answer
stringlengths 17
10.2M
|
|---|
package com.cv4j.image.util;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;
import com.cv4j.core.binary.ConnectedAreaLabel;
import com.cv4j.core.binary.MorphOpen;
import com.cv4j.core.binary.Threshold;
import com.cv4j.core.datamodel.ByteProcessor;
import com.cv4j.core.datamodel.CV4JImage;
import com.cv4j.core.datamodel.ImageProcessor;
import com.cv4j.core.datamodel.Rect;
import com.cv4j.core.datamodel.Size;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class QRCodeScanner {
public Rect findQRCodeBounding(ImageProcessor image) {
Rect rect = new Rect();
image = image.getImage().convert2Gray().getProcessor();
ByteProcessor src = ((ByteProcessor)image);
int width = src.getWidth();
int height = src.getHeight();
Threshold t = new Threshold();
t.process(src, Threshold.THRESH_VALUE, Threshold.METHOD_THRESH_BINARY_INV, 20);
MorphOpen mOpen = new MorphOpen();
byte[] data = new byte[width*height];
System.arraycopy(src.getGray(), 0, data, 0, data.length);
ByteProcessor copy = new ByteProcessor(data, width, height);
mOpen.process(src, new Size(4, 24));
saveDebugImage(src.getImage().toBitmap());
src.getImage().resetBitmap();
mOpen.process(copy, new Size(24, 4));
CV4JImage cv4JImage = new CV4JImage(width,height);
((ByteProcessor)cv4JImage.getProcessor()).putGray(copy.getGray());
saveDebugImage(cv4JImage.toBitmap());
for(int i=0; i<data.length; i++) {
int pv = src.getGray()[i]&0xff;
if(pv == 255) {
copy.getGray()[i] = (byte)255;
}
}
src.putGray(copy.getGray());
saveDebugImage(src.getImage().toBitmap());
ConnectedAreaLabel ccal = new ConnectedAreaLabel();
List<Rect> rectList = new ArrayList<>();
int[] labelMask = new int[width*height];
ccal.process(src, labelMask, rectList, true);
float w = 0;
float h = 0;
float rate = 0;
List<Rect> qrRects = new ArrayList<>();
for(Rect roi : rectList) {
w = roi.width;
h = roi.height;
rate = (float)Math.abs(w / h - 1.0);
if(rate < 0.05 && isRect(roi, labelMask, width, height)) {
qrRects.add(roi);
}
}
// find RQ code bounding
Rect[] blocks = qrRects.toArray(new Rect[0]);
if (blocks.length == 1) {
rect.x = blocks[0].x-5;
rect.y = blocks[0].y- 5;
rect.width= blocks[0].width + 10;
rect.height = blocks[0].height + 10;
}
else if (blocks.length == 3) {
for (int i = 0; i < 2; i++) {
int idx1 = blocks[i].tl().y*width + blocks[i].tl().x;
for (int j = i + 1; j < 3; j++) {
int idx2 = blocks[j].tl().y*width + blocks[j].tl().x;
if (idx2 < idx1){
Rect temp = blocks[i];
blocks[i] = blocks[j];
blocks[j] = temp;
}
}
}
rect.x = blocks[0].x - 5;
rect.y = blocks[0].y - 5;
rect.width = blocks[1].width + (blocks[1].x - blocks[0].x) + 10;
rect.height = (blocks[2].height + blocks[2].y - blocks[0].y) + 10;
} else {
rect.width = 0;
rect.height = 0;
}
return rect;
}
private boolean isRect(Rect roi, int[] labelMask, int w, int h) {
int ox = roi.x;
int oy = roi.y;
int width = roi.width;
int height = roi.height;
byte[] image = new byte[width*height];
int label = roi.labelIdx;
for(int row=oy; row<(oy + height); row++) {
for(int col=ox; col<(ox + width); col++) {
int v = labelMask[row*w + col];
if(v == label) {
image[(row - oy) * width + col - ox] = (byte)255;
}
}
}
int cx = width / 2;
int offset = 0;
if (width % 2 > 0) {
offset = 1;
}
int sum=0;
int v1=0, v2=0;
float[] data = new float[cx *height];
for(int row=0; row<height; row++) {
for(int col=0; col<cx; col++) {
v1 = image[row*width+ col]&0xff;
v2 = image[row*width+(width-1-col)]&0xff;
//sum += Math.abs(v1-v2);
data[row*cx+col] = Math.abs(v1-v2);
}
}
float[] mdev = Tools.calcMeansAndDev(data);
return (sum / 255) <= 10;
}
private void saveDebugImage(Bitmap bitmap) {
File filedir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myOcrImages");
String name = String.valueOf(System.currentTimeMillis()) + "_ocr.jpg";
File tempFile = new File(filedir.getAbsoluteFile()+File.separator, name);
FileOutputStream output = null;
try {
output = new FileOutputStream(tempFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
}catch (IOException ioe) {
Log.e("DEBUG-ERR", ioe.getMessage());
} finally {
try {
output.flush();
output.close();
} catch (IOException e) {
Log.i("DEBUG-INFO", e.getMessage());
}
}
}
}
|
package imagej.script;
import imagej.command.Command;
import imagej.module.AbstractModuleInfo;
import imagej.module.DefaultMutableModuleItem;
import imagej.module.ModuleException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import javax.script.ScriptException;
import org.scijava.Context;
import org.scijava.Contextual;
import org.scijava.ItemIO;
import org.scijava.ItemVisibility;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.util.ConversionUtils;
/**
* Metadata about a script.
*
* @author Curtis Rueden
* @author Johannes Schindelin
*/
public class ScriptInfo extends AbstractModuleInfo implements Contextual {
private static final int PARAM_CHAR_MAX = 640 * 1024; // should be enough ;-)
private final String path;
private final Reader reader;
@Parameter
private Context context;
@Parameter
private LogService log;
@Parameter
private ScriptService scriptService;
/**
* Creates a script metadata object which describes the given script file.
*
* @param context The ImageJ application context to use when populating
* service inputs.
* @param file The script file.
*/
public ScriptInfo(final Context context, final File file) {
this(context, file.getPath());
}
/**
* Creates a script metadata object which describes the given script file.
*
* @param context The ImageJ application context to use when populating
* service inputs.
* @param path Path to the script file.
*/
public ScriptInfo(final Context context, final String path) {
this(context, path, null);
}
/**
* Creates a script metadata object which describes a script provided by the
* given {@link Reader}.
*
* @param context The ImageJ application context to use when populating
* service inputs.
* @param path Pseudo-path to the script file. This file does not actually
* need to exist, but rather provides a name for the script with file
* extension.
* @param reader Reader which provides the script itself (i.e., its contents).
*/
public ScriptInfo(final Context context, final String path,
final Reader reader)
{
setContext(context);
this.path = path;
this.reader = reader;
try {
parseParameters();
addReturnValue();
}
catch (final ScriptException exc) {
log.error(exc);
}
}
// -- ScriptInfo methods --
/**
* Gets the path to the script on disk.
* <p>
* If the path doesn't actually exist on disk, then this is a pseudo-path
* merely for the purpose of naming the script with a file extension, and the
* actual script content is delivered by the {@link BufferedReader} given by
* {@link #getReader()}.
* </p>
*/
public String getPath() {
return path;
}
/**
* Gets the reader which delivers the script's content.
* <p>
* This might be null, in which case the content is stored in a file on disk
* given by {@link #getPath()}.
* </p>
*/
public Reader getReader() {
return reader;
}
/**
* Parses the script's input and output parameters.
* <p>
* ImageJ's scripting framework supports specifying @{@link Parameter}-style
* inputs and outputs in a preamble. The format is a simplified version of the
* Java @{@link Parameter} annotation syntax. The following syntaxes are
* supported:
* </p>
* <ul>
* <li>{@code // @<type> <varName>}</li>
* <li>{@code // @<type>(<attr1>=<value1>, ..., <attrN>=<valueN>) <varName>}</li>
* <li>{@code // @<IOType> <type> <varName>}</li>
* <li>{@code // @<IOType>(<attr1>=<value1>, ..., <attrN>=<valueN>) <type> <varName>}</li>
* </ul>
* <p>
* Where:
* </p>
* <ul>
* <li>{@code //} = the comment style of the scripting language, so that the
* parameter line is ignored by the script engine itself.</li>
* <li>{@code <IOType>} = one of {@code INPUT}, {@code OUTPUT}, or
* {@code BOTH}.</li>
* <li>{@code <varName>} = the name of the input or output variable.</li>
* <li>{@code <type>} = the Java {@link Class} of the variable.</li>
* <li>{@code <attr*>} = an attribute key.</li>
* <li>{@code <value*>} = an attribute value.</li>
* </ul>
* <p>
* See the @{@link Parameter} annotation for a list of valid attributes.
* </p>
* <p>
* Here are a few examples:
* </p>
* <ul>
* <li>{@code // @Dataset dataset}</li>
* <li>{@code // @double(type=OUTPUT) result}</li>
* <li>{@code // @BOTH ImageDisplay display}</li>
* <li>{@code // @INPUT(persist=false, visibility=INVISIBLE) boolean verbose}</li>
* parameters will be parsed and filled just like @{@link Parameter}
* -annotated fields in {@link Command}s.
* </ul>
*/
public void parseParameters() {
clearParameters();
try {
final BufferedReader in;
if (reader == null) {
in = new BufferedReader(new FileReader(getPath()));
}
else {
in = new BufferedReader(reader, PARAM_CHAR_MAX);
in.mark(PARAM_CHAR_MAX);
}
while (true) {
final String line = in.readLine();
if (line == null) break;
// scan for lines containing an '@' stopping at the first line
// containing at least one alphameric character but no '@'.
final int at = line.indexOf('@');
if (at >= 0) parseParam(line.substring(at + 1));
else if (line.matches(".*\\w.*")) break;
}
if (reader == null) in.close();
else in.reset();
}
catch (final IOException exc) {
log.error("Error reading script: " + path, exc);
}
catch (final ScriptException exc) {
log.error("Invalid parameter syntax for script: " + path, exc);
}
}
// -- ModuleInfo methods --
@Override
public String getDelegateClassName() {
return ScriptModule.class.getName();
}
@Override
public ScriptModule createModule() throws ModuleException {
return new ScriptModule(this);
}
// -- Contextual methods --
@Override
public Context getContext() {
return context;
}
@Override
public void setContext(final Context context) {
context.inject(this);
}
// -- Identifiable methods --
@Override
public String getIdentifier() {
return "script:" + path;
}
// -- Helper methods --
private void parseParam(final String param) throws ScriptException {
final int lParen = param.indexOf("(");
final int rParen = param.lastIndexOf(")");
if (rParen < lParen) {
throw new ScriptException("Invalid parameter: " + param);
}
if (lParen < 0) parseParam(param, parseAttrs(""));
else {
final String cutParam =
param.substring(0, lParen) + param.substring(rParen + 1);
final String attrs = param.substring(lParen + 1, rParen);
parseParam(cutParam, parseAttrs(attrs));
}
}
private void parseParam(final String param,
final HashMap<String, String> attrs) throws ScriptException
{
final String[] tokens = param.trim().split("[ \t\n]+");
checkValid(tokens.length >= 1, param);
final String typeName, varName;
if (isIOType(tokens[0])) {
// assume syntax: <IOType> <type> <varName>
checkValid(tokens.length >= 3, param);
attrs.put("type", tokens[0]);
typeName = tokens[1];
varName = tokens[2];
}
else {
// assume syntax: <type> <varName>
checkValid(tokens.length >= 2, param);
typeName = tokens[0];
varName = tokens[1];
}
final Class<?> type = scriptService.lookupClass(typeName);
addItem(varName, type, attrs);
}
/** Parses a comma-delimited list of {@code key=value} pairs into a map. */
private HashMap<String, String> parseAttrs(final String attrs)
throws ScriptException
{
// TODO: We probably want to use a real CSV parser.
final HashMap<String, String> attrsMap = new HashMap<String, String>();
for (final String token : attrs.split(",")) {
if (token.isEmpty()) continue;
final int equals = token.indexOf("=");
if (equals < 0) throw new ScriptException("Invalid attribute: " + token);
final String key = token.substring(0, equals).trim();
String value = token.substring(equals + 1).trim();
if (value.startsWith("\"") && value.endsWith("\"")) {
value = value.substring(1, value.length() - 2);
}
attrsMap.put(key, value);
}
return attrsMap;
}
private boolean isIOType(final String token) {
return ConversionUtils.convert(token, ItemIO.class) != null;
}
private void checkValid(final boolean valid, final String param)
throws ScriptException
{
if (!valid) throw new ScriptException("Invalid parameter: " + param);
}
/** Adds an output for the value returned by the script itself. */
private void addReturnValue() throws ScriptException {
final HashMap<String, String> attrs = new HashMap<String, String>();
attrs.put("type", "OUTPUT");
addItem(ScriptModule.RETURN_VALUE, Object.class, attrs);
}
private <T> void addItem(final String name, final Class<T> type,
final Map<String, String> attrs) throws ScriptException
{
final DefaultMutableModuleItem<T> item =
new DefaultMutableModuleItem<T>(this, name, type);
for (final String key : attrs.keySet()) {
final String value = attrs.get(key);
assignAttribute(item, key, value);
}
if (item.isInput()) {
inputMap().put(item.getName(), item);
inputList().add(item);
}
if (item.isOutput()) {
outputMap().put(item.getName(), item);
outputList().add(item);
}
}
private <T> void assignAttribute(final DefaultMutableModuleItem<T> item,
final String key, final String value) throws ScriptException
{
// CTR: There must be an easier way to do this.
// Just compile the thing using javac? Or parse via javascript, maybe?
if ("callback".equalsIgnoreCase(key)) {
item.setCallback(value);
}
else if ("choices".equalsIgnoreCase(key)) {
// FIXME: Regex above won't handle {a,b,c} syntax.
// item.setChoices(choices);
}
else if ("columns".equalsIgnoreCase(key)) {
item.setColumnCount(ConversionUtils.convert(value, int.class));
}
else if ("description".equalsIgnoreCase(key)) {
item.setDescription(value);
}
else if ("initializer".equalsIgnoreCase(key)) {
item.setInitializer(value);
}
else if ("type".equalsIgnoreCase(key)) {
item.setIOType(ConversionUtils.convert(value, ItemIO.class));
}
else if ("label".equalsIgnoreCase(key)) {
item.setLabel(value);
}
else if ("max".equalsIgnoreCase(key)) {
item.setMaximumValue(ConversionUtils.convert(value, item.getType()));
}
else if ("min".equalsIgnoreCase(key)) {
item.setMinimumValue(ConversionUtils.convert(value, item.getType()));
}
else if ("name".equalsIgnoreCase(key)) {
item.setName(value);
}
else if ("persist".equalsIgnoreCase(key)) {
item.setPersisted(ConversionUtils.convert(value, boolean.class));
}
else if ("persistKey".equalsIgnoreCase(key)) {
item.setPersistKey(value);
}
else if ("required".equalsIgnoreCase(key)) {
item.setRequired(ConversionUtils.convert(value, boolean.class));
}
else if ("softMax".equalsIgnoreCase(key)) {
item.setSoftMaximum(ConversionUtils.convert(value, item.getType()));
}
else if ("softMin".equalsIgnoreCase(key)) {
item.setSoftMinimum(ConversionUtils.convert(value, item.getType()));
}
else if ("stepSize".equalsIgnoreCase(key)) {
// FIXME
item.setStepSize(ConversionUtils.convert(value, Number.class));
}
else if ("visibility".equalsIgnoreCase(key)) {
item.setVisibility(ConversionUtils.convert(value, ItemVisibility.class));
}
else if ("value".equalsIgnoreCase(key)) {
item.setWidgetStyle(value);
}
else {
throw new ScriptException("Invalid attribute name: " + key);
}
}
private void clearParameters() {
inputMap().clear();
inputList().clear();
outputMap().clear();
outputList().clear();
}
}
|
package net.mgsx.kit;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map.Entry;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import com.badlogic.gdx.utils.Array;
import com.google.common.base.Predicate;
import net.mgsx.game.core.helpers.ArrayHelper;
import net.mgsx.game.core.helpers.ReflectionHelper;
import net.mgsx.game.core.meta.ClassRegistry;
public class ReflectionClassRegistry extends ClassRegistry
{
public static final String kitCore = "net.mgsx.game.core";
public static final String kitCorePlugin = "net.mgsx.game.plugins.core";
public static final String kitBehaviorTreePlugin = "net.mgsx.game.plugins.btree"; // XXX necessary to perform reflection on custom tasks ... maybe because of EntityLeafTask ...
public static final String kitPlugins = "net.mgsx.game.plugins";
public static final String behaviorTree = "com.badlogic.gdx.ai.btree";
private Reflections reflections;
public ReflectionClassRegistry(final String ...packages)
{
Collection<URL> urls = new ArrayList<URL>();
for(String url : packages){
urls.addAll(ClasspathHelper.getUrlsForPackagePrefix(url));
}
reflections = new Reflections(
new ConfigurationBuilder().filterInputsBy(new Predicate<String>() {
@Override
public boolean apply(String input) {
// executed in separate thread
boolean match = false;
for(String name : packages){
if(input.startsWith(name)){
match = true;
break;
}
}
if(match){
System.out.println("true " + input);
}else{
System.out.println("false " + input);
}
return match;
}
})
.setUrls(urls)
.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));
}
@Override
public Array<Class> getSubTypesOf(Class type) {
return ArrayHelper.array(reflections.getSubTypesOf(type));
}
@Override
public Array<Class<?>> getTypesAnnotatedWith(Class<? extends Annotation> annotation) {
return ArrayHelper.array(reflections.getTypesAnnotatedWith(annotation));
}
@Override
public Array<Class<?>> getClasses() {
Array<Class<?>> r = new Array<Class<?>>();
for(Entry<String, String> entry : reflections.getStore().get(TypeAnnotationsScanner.class).entries()){
r.add(ReflectionHelper.forName(entry.getValue()));
}
return r;
}
}
|
package com.example.db;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DbImplConfig {
@Bean
public BookRepository bookRepository() {
BookRepositoryImpl bookRepository = new BookRepositoryImpl();
bookRepository.insert(new BookEntity.Builder()
.withName("Wprowadzenie do algorytmow")
.withPrice(Price.of("120.80"))
.build()
);
bookRepository.insert(new BookEntity.Builder()
.withName("Java Podstawy")
.withPrice(Price.of("100.00"))
.build()
);
return bookRepository;
}
}
|
package nl.mpi.kinnate.export;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import nl.mpi.arbil.ui.ArbilWindowManager;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.arbil.userstorage.ArbilSessionStorage;
import nl.mpi.kinnate.KinTermSavePanel;
import nl.mpi.kinnate.ui.MainFrame;
public class ExportToR {
public void doExport(MainFrame mainFrame, KinTermSavePanel savePanel) {
// todo: modify this to use the ArbilWindowManager and update the ArbilWindowManager file select to support save file actions
JFileChooser fc = new JFileChooser();
String lastSavedFileString = ArbilSessionStorage.getSingleInstance().loadString("kinoath.ExportToR");
if (lastSavedFileString != null) {
fc.setSelectedFile(new File(lastSavedFileString));
}
fc.addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
return (file.getName().toLowerCase().endsWith(".csv"));
}
@Override
public String getDescription() {
return "Data Frame (CSV)";
}
});
int returnVal = fc.showSaveDialog(mainFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
PedigreePackageExport packageExport = new PedigreePackageExport();
ArbilSessionStorage.getSingleInstance().saveString("kinoath.ExportToR", file.getPath());
try {
FileWriter fileWriter = new FileWriter(file, false);
fileWriter.write(packageExport.createCsvContents(savePanel.getGraphEntities()));
fileWriter.close();
// ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("File saved", "Export");
} catch (IOException exception) {
ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Error, could not save file", "Export");
GuiHelper.linorgBugCatcher.logError(exception);
}
}
}
// example usage:
// install.packages()
// pid id momid dadid sex affected
// 24 1 0 0 1 1
// 24 2 0 0 2 1
// 24 3 1 2 1 2
// 24 4 0 0 2 2
// 24 5 3 4 1 3
//
// dataFrame <- read.table("~/kinship-r.csv",header=T)
// library(kinship)
// attach(dataFrame)
// pedigreeObj <- pedigree(id,momid,dadid,sex, affected)
// plot(pedigreeObj)
// Suggestion from Dan on R package to look into in detail
}
|
package co.aikar.commands;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
@SuppressWarnings("TypeParameterExplicitlyExtendsObject")
class Annotations <M extends CommandManager> extends AnnotationLookups {
public static final int NOTHING = 0;
public static final int REPLACEMENTS = 1;
public static final int LOWERCASE = 1 << 1;
public static final int UPPERCASE = 1 << 2;
public static final int NO_EMPTY = 1 << 3;
public static final int DEFAULT_EMPTY = 1 << 4;
private final M manager;
private final Map<Class<? extends Annotation>, Method> valueMethods = new IdentityHashMap<>();
private final Map<Class<? extends Annotation>, Void> noValueAnnotations = new IdentityHashMap<>();
Annotations(M manager) {
this.manager = manager;
}
String getAnnotationValue(AnnotatedElement object, Class<? extends Annotation> annoClass, int options) {
Annotation annotation = getAnnotationRecursive(object, annoClass, new HashSet<>());
String value = null;
if (annotation != null) {
Method valueMethod = valueMethods.get(annoClass);
if (noValueAnnotations.containsKey(annoClass)) {
value = "";
} else {
try {
if (valueMethod == null) {
valueMethod = annoClass.getMethod("value");
valueMethod.setAccessible(true);
valueMethods.put(annoClass, valueMethod);
}
value = (String) valueMethod.invoke(annotation);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
if (!(e instanceof NoSuchMethodException)) {
manager.log(LogLevel.ERROR, "Error getting annotation value", e);
}
noValueAnnotations.put(annoClass, null);
value = "";
}
}
}
// TODO: Aliases
if (value == null) {
if (hasOption(options, DEFAULT_EMPTY)) {
value = "";
} else {
return null;
}
}
// transforms
if (hasOption(options, REPLACEMENTS)) {
value = manager.getCommandReplacements().replace(value);
}
if (hasOption(options, LOWERCASE)) {
value = value.toLowerCase(manager.getLocales().getDefaultLocale());
} else if (hasOption(options, UPPERCASE)) {
value = value.toUpperCase(manager.getLocales().getDefaultLocale());
}
// validation
if (value.isEmpty() && hasOption(options, NO_EMPTY)) {
value = null;
}
return value;
}
private static Annotation getAnnotationRecursive(AnnotatedElement object, Class<? extends Annotation> annoClass, Collection<Annotation> checked) {
if (object.isAnnotationPresent(annoClass)) {
return object.getAnnotation(annoClass);
} else {
for (Annotation otherAnnotation : object.getDeclaredAnnotations()) {
if (!otherAnnotation.annotationType().getPackage().getName().startsWith("java.")) {
if (checked.contains(otherAnnotation)) return null;
checked.add(otherAnnotation);
final Annotation foundAnnotation = getAnnotationRecursive(otherAnnotation.annotationType(), annoClass, checked);
if (foundAnnotation != null) {
return foundAnnotation;
}
}
}
}
return null;
}
private static boolean hasOption(int options, int option) {
return (options & option) == option;
}
}
|
package com.xqbase.tuna;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;
import com.xqbase.tuna.util.ByteArrayQueue;
import com.xqbase.util.Log;
import com.xqbase.util.Time;
abstract class Attachment {
SelectionKey selectionKey;
abstract void closeChannel();
void finishClose() {
selectionKey.cancel();
closeChannel();
}
}
/**
* The encapsulation of a {@link SocketChannel} and its {@link SelectionKey},
* which corresponds to a TCP Socket.
*/
class Client extends Attachment {
private static final int STATUS_CLOSED = 0;
private static final int STATUS_IDLE = 1;
private static final int STATUS_BUSY = 2;
private static final int STATUS_DISCONNECTING = 3;
int bufferSize = Connection.MAX_BUFFER_SIZE;
int status = STATUS_IDLE;
boolean resolving = false;
ByteArrayQueue queue = new ByteArrayQueue();
Connection connection;
SocketChannel socketChannel;
Client(Connection connection) {
this.connection = connection;
connection.setHandler(new ConnectionHandler() {
@Override
public void send(byte[] b, int off, int len) {
write(b, off, len);
}
@Override
public void setBufferSize(int bufferSize) {
boolean blocked = Client.this.bufferSize == 0;
boolean toBlock = bufferSize <= 0;
Client.this.bufferSize = Math.max(0,
Math.min(bufferSize, Connection.MAX_BUFFER_SIZE));
if ((blocked ^ toBlock) && !resolving && isOpen()) {
// may be called before resolve
interestOps();
}
}
@Override
public void disconnect() {
if (status == STATUS_IDLE) {
// must be resolved
finishClose();
} else if (status == STATUS_BUSY) {
status = STATUS_DISCONNECTING;
}
}
});
}
void add(Selector selector, int ops) {
try {
selectionKey = socketChannel.register(selector, ops, this);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* registers a {@link Client} and connects to a remote address
*
* @see ConnectorImpl#connect(Connection, String, int)
* @throws IOException may throw "Network is unreachable" or "Protocol family unavailable",
* and then socketChannel will be closed, and selectionKey will not be created
*/
void connect(Selector selector, InetSocketAddress socketAddress) throws IOException {
resolving = false;
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
socketChannel.connect(socketAddress);
add(selector, SelectionKey.OP_CONNECT);
} catch (IOException e) {
// May throw "Network is unreachable" or "Protocol family unavailable",
// and then socketChannel will be closed, and selectionKey will not be created
closeChannel();
throw e;
}
}
void interestOps() {
selectionKey.interestOps((bufferSize == 0 ? 0 : SelectionKey.OP_READ) |
(status == STATUS_IDLE ? 0 : SelectionKey.OP_WRITE));
}
void write() throws IOException {
int len = queue.length();
int fromLen = len;
while (len > 0) {
int bytesWritten = socketChannel.write(ByteBuffer.wrap(queue.array(),
queue.offset(), len));
if (bytesWritten == 0) {
unblock(len, fromLen);
return;
}
len = queue.remove(bytesWritten).length();
}
unblock(len, fromLen);
if (status == STATUS_DISCONNECTING) {
finishClose();
} else {
status = STATUS_IDLE;
interestOps();
}
}
void write(byte[] b, int off, int len) {
if (status != STATUS_IDLE) {
int fromLen = queue.length();
block(queue.add(b, off, len).length(), fromLen);
return;
}
int bytesWritten;
try {
bytesWritten = socketChannel.write(ByteBuffer.wrap(b, off, len));
} catch (IOException e) {
startClose();
return;
}
if (len > bytesWritten) {
int fromLen = queue.length();
block(queue.add(b, off + bytesWritten, len - bytesWritten).length(), fromLen);
status = STATUS_BUSY;
interestOps();
}
}
void startConnect() {
status = STATUS_BUSY;
}
void finishConnect() {
InetSocketAddress local = ((InetSocketAddress) socketChannel.
socket().getLocalSocketAddress());
InetSocketAddress remote = ((InetSocketAddress) socketChannel.
socket().getRemoteSocketAddress());
connection.onConnect(new ConnectionSession(local, remote));
}
void startClose() {
if (isOpen()) {
finishClose();
// Call "close()" before "onDisconnect()"
// to avoid recursive "disconnect()".
connection.onDisconnect();
}
}
@Override
void closeChannel() {
try {
socketChannel.close();
} catch (IOException e) {}
status = STATUS_CLOSED;
}
boolean isOpen() {
return status != STATUS_CLOSED;
}
boolean isBusy() {
return status >= STATUS_IDLE;
}
private boolean blocking = false;
private void block(int len, int fromLen) {
if (fromLen > 0) {
blocking = true;
connection.onQueue(len);
}
}
private void unblock(int len, int fromLen) {
if (len == fromLen) {
return;
}
boolean fromBlocking = blocking;
if (len == 0) {
blocking = false;
}
if (fromBlocking) {
connection.onQueue(len);
}
}
}
/**
* The encapsulation of a {@link ServerSocketChannel} and its {@link SelectionKey},
* which corresponds to a TCP Server Socket
*/
class Server extends Attachment {
ServerConnection serverConnection;
ServerSocketChannel serverSocketChannel;
/**
* Opens a listening port and binds to a given address.
* @param addr - The IP address to bind and the port to listen.
* @throws IOException If an I/O error occurs when opening the port.
*/
Server(ServerConnection serverConnection,
InetSocketAddress addr) throws IOException {
this.serverConnection = serverConnection;
bind(addr);
}
void bind(InetSocketAddress addr) throws IOException {
try {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
serverSocketChannel.socket().bind(addr);
} catch (IOException e) {
closeChannel();
throw e;
}
}
@Override
void closeChannel() {
try {
serverSocketChannel.close();
} catch (IOException e) {}
}
}
class Timer implements Comparable<Timer> {
long uptime;
long id;
@Override
public int compareTo(Timer o) {
int result = Long.compare(uptime, o.uptime);
return result == 0 ? Long.compare(id, o.id) : result;
}
@Override
public String toString() {
return new Date(uptime) + "/" + id;
}
}
class Registrable {
private SelectableChannel channel;
private int interestOps;
private Attachment att;
/** @throws IOException if ServerSocket fails to Bind again */
Registrable(SelectionKey key) throws IOException {
channel = key.channel();
interestOps = key.interestOps();
att = (Attachment) key.attachment();
key.cancel(); // Need to cancel ?
if (!(att instanceof Server)) {
return;
}
// Rebuild ServerSocketChannel
Server server = (Server) att;
InetSocketAddress addr = (InetSocketAddress) server.serverSocketChannel.
socket().getLocalSocketAddress();
server.closeChannel();
server.bind(addr);
channel = server.serverSocketChannel;
}
void register(Selector selector) throws IOException {
Client client = ((Client) att);
if ((interestOps & SelectionKey.OP_CONNECT) != 0) {
// TODO Remove
client.startClose();
Log.w("Removed a Connection-Pending Channel, interestOps = " + interestOps);
return;
}
// Client may be closed by closing of Connection-Pending Channel
if (client.isOpen()) {
att.selectionKey = channel.register(selector, interestOps, att);
}
}
}
/**
* The encapsulation of {@link Selector},
* which makes {@link Client} and {@link Server} working.<p>
*/
public class ConnectorImpl implements Connector, TimerHandler, EventQueue, Executor, AutoCloseable {
private static Pattern hostName = Pattern.compile("[a-zA-Z]");
private static long nextId = 0;
private volatile Selector selector;
private boolean interrupted = false;
private byte[] buffer = new byte[Connection.MAX_BUFFER_SIZE];
private TreeMap<Timer, Runnable> timerMap = new TreeMap<>();
private ConcurrentLinkedQueue<Runnable> eventQueue = new ConcurrentLinkedQueue<>();
private ExecutorService executor = Executors.newCachedThreadPool();
{
try {
selector = Selector.open();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** @throws IOException if no IP address for the <code>host</code> could be found */
@Override
public void connect(Connection connection,
InetSocketAddress socketAddress) throws IOException {
Client client = new Client(connection);
client.startConnect();
if (!socketAddress.isUnresolved()) {
client.connect(selector, socketAddress);
return;
}
String host = socketAddress.getHostName();
int port = socketAddress.getPort();
if (host.indexOf(':') >= 0 || !hostName.matcher(host).find()) {
// Connect immediately for IPv6 or IPv4 Address
client.connect(selector,
new InetSocketAddress(InetAddress.getByName(host), port));
return;
}
client.resolving = true;
execute(() -> {
try {
// Resolve in Executor then Connect later
InetAddress addr = InetAddress.getByName(host);
invokeLater(() -> {
try {
client.connect(selector, new InetSocketAddress(addr, port));
} catch (IOException e) {
// Call "onDisconnect()" when Connecting Failure
connection.onDisconnect();
}
});
} catch (IOException e) {
// Call "onDisconnect()" when Resolving Failure
invokeLater(connection::onDisconnect);
}
});
}
@Override
public Connector.Closeable add(ServerConnection serverConnection,
InetSocketAddress socketAddress) throws IOException {
Server server = new Server(serverConnection, socketAddress);
try {
server.selectionKey = server.serverSocketChannel.
register(selector, SelectionKey.OP_ACCEPT, server);
} catch (IOException e) {
throw new RuntimeException(e);
}
return () -> {
if (server.selectionKey.isValid()) {
server.finishClose();
}
};
}
/** Consume events until interrupted */
public void doEvents() {
while (!isInterrupted()) {
Iterator<Map.Entry<Timer, Runnable>> it = timerMap.entrySet().iterator();
if (it.hasNext()) {
long timeout = it.next().getKey().uptime - System.currentTimeMillis();
doEvents(timeout > 0 ? timeout : 0);
} else {
doEvents(-1);
}
}
}
private void invokeQueue() {
long now = System.currentTimeMillis();
ArrayList<Runnable> runnables = new ArrayList<>();
Iterator<Map.Entry<Timer, Runnable>> it = timerMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Timer, Runnable> entry = it.next();
if (entry.getKey().uptime > now) {
break;
}
runnables.add(entry.getValue());
it.remove();
}
// call run() after iteration since run() may change timerMap
for (Runnable runnable : runnables) {
runnable.run();
}
Runnable runnable;
while ((runnable = eventQueue.poll()) != null) {
runnable.run();
}
}
private static boolean shortTime(long millis) {
return millis >= 0 && millis < 16;
}
private int epollCount = 0;
private void checkEpoll(long timeout, long t, int keySize) {
if (keySize > 0 || shortTime(timeout) ||
!shortTime(System.currentTimeMillis() - t) ||
!eventQueue.isEmpty() ||
Thread.currentThread().isInterrupted()) {
epollCount = 0;
return;
}
Set<SelectionKey> keys = selector.keys();
// TODO Remove: "select()" may exit immediately due to a Broken Connection ?
for (SelectionKey key : keys) {
Object att = key.attachment();
if (!(att instanceof Client)) {
continue;
}
Client client = (Client) att;
if (!client.socketChannel.isConnected() &&
!client.socketChannel.isConnectionPending()) {
Log.w("Abort Registering New Selector, timeout = " + timeout +
", t0 = " + Time.toString(t, true) + ", t1 = " +
Time.toString(System.currentTimeMillis(), true));
client.startClose();
epollCount = 0;
return;
}
}
// E-Poll Spin Detected
epollCount ++;
if (epollCount < 256) {
return;
}
epollCount = 0;
Log.w("Epoll Spin Detected, timeout = " + timeout +
", t0 = " + Time.toString(t, true) + ", t1 = " +
Time.toString(System.currentTimeMillis(), true) +
", keys = " + keys.size());
Log.w("Begin Registering New Selector " + selector + " ...");
ArrayList<Registrable> regs = new ArrayList<>();
for (SelectionKey key : keys) {
if (!key.isValid()) {
Log.w("Invaid SelectionKey Detected");
continue;
}
try {
regs.add(new Registrable(key));
} catch (IOException e) {
// Ignored if ServerSocket fails to Bind again
}
}
try {
selector.close();
} catch (IOException e) {}
try {
selector = Selector.open();
for (Registrable reg : regs) {
reg.register(selector);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
Log.w("End Registering New Selector " + selector);
}
/**
* Consumes all events raised by registered Clients and Servers,
* including network events (accept/connect/read/write) and user-defined events.<p>
*
* @param timeout Block for up to timeout milliseconds, or -1 to block indefinitely,
* or 0 without blocking.
* @return <b>true</b> if NETWORK events consumed;<br>
* <b>false</b> if no NETWORK events raised,
* whether or not user-defined events raised.<br>
*/
public boolean doEvents(long timeout) {
long t = System.currentTimeMillis();
int keySize;
try {
keySize = timeout == 0 ? selector.selectNow() :
timeout < 0 ? selector.select() : selector.select(timeout);
} catch (IOException e) {
throw new RuntimeException(e);
}
checkEpoll(timeout, t, keySize);
if (keySize == 0) {
invokeQueue();
return false;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
for (SelectionKey key : selectedKeys) {
if (!key.isValid()) {
continue;
}
if (key.isAcceptable()) {
Server server = (Server) key.attachment();
SocketChannel socketChannel;
try {
socketChannel = server.serverSocketChannel.accept();
if (socketChannel == null) {
continue;
}
socketChannel.configureBlocking(false);
} catch (IOException e) {
throw new RuntimeException(e);
}
Client client = new Client(server.serverConnection.get());
client.socketChannel = socketChannel;
client.add(selector, SelectionKey.OP_READ);
client.finishConnect();
continue;
}
Client client = (Client) key.attachment();
try {
if (key.isReadable()) {
int bytesRead = client.socketChannel.
read(ByteBuffer.wrap(buffer, 0, client.bufferSize));
if (bytesRead > 0) {
client.connection.onRecv(buffer, 0, bytesRead);
// may be closed by "onRecv"
if (!key.isValid()) {
continue;
}
} else if (bytesRead < 0) {
client.startClose();
// Disconnected, so skip onQueue and onConnect
continue;
}
}
if (key.isWritable()) {
client.write();
} else if (key.isConnectable() && client.socketChannel.finishConnect()) {
client.finishConnect();
// "onConnect()" might call "disconnect()"
if (client.isBusy()) {
client.write();
}
}
} catch (IOException e) {
client.startClose();
}
}
selectedKeys.clear();
invokeQueue();
return true;
}
@Override
public TimerHandler.Closeable postAtTime(Runnable runnable, long uptime) {
Timer timer = new Timer();
timer.uptime = uptime;
timer.id = nextId;
nextId ++;
timerMap.put(timer, runnable);
return () -> timerMap.remove(timer);
}
@Override
public void invokeLater(Runnable runnable) {
eventQueue.offer(runnable);
try {
selector.wakeup();
} catch (ClosedSelectorException e) {}
}
@Override
public void execute(Runnable runnable) {
executor.execute(runnable);
}
/**
* Interrupts {@link #doEvents()} or {@link #doEvents(long)}.<p>
* <b>Can be called outside main thread.</b>
*/
public void interrupt() {
invokeLater(() -> interrupted = true);
}
/**
* Tests whether the connector is interrupted,
* and then the "interrupted" status is cleared.
*/
public boolean isInterrupted() {
boolean interrupted_ = interrupted;
interrupted = false;
return interrupted_;
}
/**
* Unregisters, closes all <b>Client</b>s and <b>Server</b>s,
* then closes the Connector itself.
*/
@Override
public void close() {
executor.shutdown();
for (SelectionKey key : selector.keys()) {
((Attachment) key.attachment()).finishClose();
}
try {
selector.close();
} catch (IOException e) {}
}
}
|
package com.xqbase.tuna;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;
import com.xqbase.tuna.util.ByteArrayQueue;
import com.xqbase.util.Log;
import com.xqbase.util.Time;
abstract class Attachment {
SelectionKey selectionKey;
abstract void closeChannel();
void finishClose() {
selectionKey.cancel();
closeChannel();
}
}
/**
* The encapsulation of a {@link SocketChannel} and its {@link SelectionKey},
* which corresponds to a TCP Socket.
*/
class Client extends Attachment {
private static final int STATUS_CLOSED = 0;
private static final int STATUS_IDLE = 1;
private static final int STATUS_BUSY = 2;
private static final int STATUS_DISCONNECTING = 3;
int bufferSize = Connection.MAX_BUFFER_SIZE;
int status = STATUS_IDLE;
boolean resolving = false;
ByteArrayQueue queue = new ByteArrayQueue();
Connection connection;
SocketChannel socketChannel;
Client(Connection connection) {
this.connection = connection;
connection.setHandler(new ConnectionHandler() {
@Override
public void send(byte[] b, int off, int len) {
write(b, off, len);
}
@Override
public void setBufferSize(int bufferSize) {
boolean blocked = Client.this.bufferSize == 0;
boolean toBlock = bufferSize <= 0;
Client.this.bufferSize = Math.max(0,
Math.min(bufferSize, Connection.MAX_BUFFER_SIZE));
if ((blocked ^ toBlock) && !resolving && isOpen()) {
// may be called before resolve
interestOps();
}
}
@Override
public void disconnect() {
if (status == STATUS_IDLE) {
// must be resolved
finishClose();
} else if (status == STATUS_BUSY) {
status = STATUS_DISCONNECTING;
}
}
});
}
void add(Selector selector, int ops) {
try {
selectionKey = socketChannel.register(selector, ops, this);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* registers a {@link Client} and connects to a remote address
*
* @see ConnectorImpl#connect(Connection, String, int)
* @throws IOException may throw "Network is unreachable" or "Protocol family unavailable",
* and then socketChannel will be closed, and selectionKey will not be created
*/
void connect(Selector selector, InetSocketAddress socketAddress) throws IOException {
resolving = false;
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
socketChannel.connect(socketAddress);
add(selector, SelectionKey.OP_CONNECT);
} catch (IOException e) {
// May throw "Network is unreachable" or "Protocol family unavailable",
// and then socketChannel will be closed, and selectionKey will not be created
closeChannel();
throw e;
}
}
void interestOps() {
selectionKey.interestOps((bufferSize == 0 ? 0 : SelectionKey.OP_READ) |
(status == STATUS_IDLE ? 0 : SelectionKey.OP_WRITE));
}
void write() throws IOException {
int len = queue.length();
int fromLen = len;
while (len > 0) {
int bytesWritten = socketChannel.write(ByteBuffer.wrap(queue.array(),
queue.offset(), len));
if (bytesWritten == 0) {
unblock(len, fromLen);
return;
}
len = queue.remove(bytesWritten).length();
}
unblock(len, fromLen);
if (status == STATUS_DISCONNECTING) {
finishClose();
} else {
status = STATUS_IDLE;
interestOps();
}
}
void write(byte[] b, int off, int len) {
if (status != STATUS_IDLE) {
int fromLen = queue.length();
block(queue.add(b, off, len).length(), fromLen);
return;
}
int bytesWritten;
try {
bytesWritten = socketChannel.write(ByteBuffer.wrap(b, off, len));
} catch (IOException e) {
startClose();
return;
}
if (len > bytesWritten) {
int fromLen = queue.length();
block(queue.add(b, off + bytesWritten, len - bytesWritten).length(), fromLen);
status = STATUS_BUSY;
interestOps();
}
}
void startConnect() {
status = STATUS_BUSY;
}
void finishConnect() {
InetSocketAddress local = ((InetSocketAddress) socketChannel.
socket().getLocalSocketAddress());
InetSocketAddress remote = ((InetSocketAddress) socketChannel.
socket().getRemoteSocketAddress());
connection.onConnect(new ConnectionSession(local, remote));
}
void startClose() {
if (isOpen()) {
finishClose();
// Call "close()" before "onDisconnect()"
// to avoid recursive "disconnect()".
connection.onDisconnect();
}
}
@Override
void closeChannel() {
try {
socketChannel.close();
} catch (IOException e) {}
status = STATUS_CLOSED;
}
boolean isOpen() {
return status != STATUS_CLOSED;
}
boolean isBusy() {
return status >= STATUS_IDLE;
}
private boolean blocking = false;
private void block(int len, int fromLen) {
if (fromLen > 0) {
blocking = true;
connection.onQueue(len);
}
}
private void unblock(int len, int fromLen) {
if (len == fromLen) {
return;
}
boolean fromBlocking = blocking;
if (len == 0) {
blocking = false;
}
if (fromBlocking) {
connection.onQueue(len);
}
}
}
/**
* The encapsulation of a {@link ServerSocketChannel} and its {@link SelectionKey},
* which corresponds to a TCP Server Socket
*/
class Server extends Attachment {
ServerConnection serverConnection;
ServerSocketChannel serverSocketChannel;
/**
* Opens a listening port and binds to a given address.
* @param addr - The IP address to bind and the port to listen.
* @throws IOException If an I/O error occurs when opening the port.
*/
Server(ServerConnection serverConnection,
InetSocketAddress addr) throws IOException {
this.serverConnection = serverConnection;
bind(addr);
}
void bind(InetSocketAddress addr) throws IOException {
try {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
serverSocketChannel.socket().bind(addr);
} catch (IOException e) {
closeChannel();
throw e;
}
}
@Override
void closeChannel() {
try {
serverSocketChannel.close();
} catch (IOException e) {}
}
}
class Timer implements Comparable<Timer> {
long uptime;
long id;
@Override
public int compareTo(Timer o) {
int result = Long.compare(uptime, o.uptime);
return result == 0 ? Long.compare(id, o.id) : result;
}
@Override
public String toString() {
return new Date(uptime) + "/" + id;
}
}
class Registrable {
private SelectableChannel channel;
private int interestOps;
private Attachment att;
/** @throws IOException if ServerSocket fails to Bind again */
Registrable(SelectionKey key) throws IOException {
channel = key.channel();
interestOps = key.interestOps();
att = (Attachment) key.attachment();
key.cancel(); // Need to cancel ?
if (!(att instanceof Server)) {
return;
}
// Rebuild ServerSocketChannel
Server server = (Server) att;
InetSocketAddress addr = (InetSocketAddress) server.serverSocketChannel.
socket().getLocalSocketAddress();
server.closeChannel();
server.bind(addr);
channel = server.serverSocketChannel;
}
void register(Selector selector) throws IOException {
if ((interestOps & SelectionKey.OP_CONNECT) != 0) {
// TODO Remove
((Client) att).startClose();
Log.w("Removed a Connection-Pending Channel, interestOps = " + interestOps);
return;
}
// Client may be closed by closing of Connection-Pending Channel
if (att instanceof Client && !((Client) att).isOpen()) {
return;
}
att.selectionKey = channel.register(selector, interestOps, att);
}
}
/**
* The encapsulation of {@link Selector},
* which makes {@link Client} and {@link Server} working.<p>
*/
public class ConnectorImpl implements Connector, TimerHandler, EventQueue, Executor, AutoCloseable {
private static Pattern hostName = Pattern.compile("[a-zA-Z]");
private static long nextId = 0;
private volatile Selector selector;
private boolean interrupted = false;
private byte[] buffer = new byte[Connection.MAX_BUFFER_SIZE];
private TreeMap<Timer, Runnable> timerMap = new TreeMap<>();
private ConcurrentLinkedQueue<Runnable> eventQueue = new ConcurrentLinkedQueue<>();
private ExecutorService executor = Executors.newCachedThreadPool();
{
try {
selector = Selector.open();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** @throws IOException if no IP address for the <code>host</code> could be found */
@Override
public void connect(Connection connection,
InetSocketAddress socketAddress) throws IOException {
Client client = new Client(connection);
client.startConnect();
if (!socketAddress.isUnresolved()) {
client.connect(selector, socketAddress);
return;
}
String host = socketAddress.getHostName();
int port = socketAddress.getPort();
if (host.indexOf(':') >= 0 || !hostName.matcher(host).find()) {
// Connect immediately for IPv6 or IPv4 Address
client.connect(selector,
new InetSocketAddress(InetAddress.getByName(host), port));
return;
}
client.resolving = true;
execute(() -> {
try {
// Resolve in Executor then Connect later
InetAddress addr = InetAddress.getByName(host);
invokeLater(() -> {
try {
client.connect(selector, new InetSocketAddress(addr, port));
} catch (IOException e) {
// Call "onDisconnect()" when Connecting Failure
connection.onDisconnect();
}
});
} catch (IOException e) {
// Call "onDisconnect()" when Resolving Failure
invokeLater(connection::onDisconnect);
}
});
}
@Override
public Connector.Closeable add(ServerConnection serverConnection,
InetSocketAddress socketAddress) throws IOException {
Server server = new Server(serverConnection, socketAddress);
try {
server.selectionKey = server.serverSocketChannel.
register(selector, SelectionKey.OP_ACCEPT, server);
} catch (IOException e) {
throw new RuntimeException(e);
}
return () -> {
if (server.selectionKey.isValid()) {
server.finishClose();
}
};
}
/** Consume events until interrupted */
public void doEvents() {
while (!isInterrupted()) {
Iterator<Map.Entry<Timer, Runnable>> it = timerMap.entrySet().iterator();
if (it.hasNext()) {
long timeout = it.next().getKey().uptime - System.currentTimeMillis();
doEvents(timeout > 0 ? timeout : 0);
} else {
doEvents(-1);
}
}
}
private void invokeQueue() {
long now = System.currentTimeMillis();
ArrayList<Runnable> runnables = new ArrayList<>();
Iterator<Map.Entry<Timer, Runnable>> it = timerMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Timer, Runnable> entry = it.next();
if (entry.getKey().uptime > now) {
break;
}
runnables.add(entry.getValue());
it.remove();
}
// call run() after iteration since run() may change timerMap
for (Runnable runnable : runnables) {
runnable.run();
}
Runnable runnable;
while ((runnable = eventQueue.poll()) != null) {
runnable.run();
}
}
private static boolean shortTime(long millis) {
return millis >= 0 && millis < 16;
}
private int epollCount = 0;
private void checkEpoll(long timeout, long t, int keySize) {
if (keySize > 0 || shortTime(timeout) ||
!shortTime(System.currentTimeMillis() - t) ||
!eventQueue.isEmpty() ||
Thread.currentThread().isInterrupted()) {
epollCount = 0;
return;
}
Set<SelectionKey> keys = selector.keys();
// TODO Remove: "select()" may exit immediately due to a Broken Connection ?
for (SelectionKey key : keys) {
Object att = key.attachment();
if (!(att instanceof Client)) {
continue;
}
Client client = (Client) att;
if (!client.socketChannel.isConnected() &&
!client.socketChannel.isConnectionPending()) {
Log.w("Abort Registering New Selector, timeout = " + timeout +
", t0 = " + Time.toString(t, true) + ", t1 = " +
Time.toString(System.currentTimeMillis(), true));
client.startClose();
epollCount = 0;
return;
}
}
// E-Poll Spin Detected
epollCount ++;
if (epollCount < 256) {
return;
}
epollCount = 0;
Log.w("Epoll Spin Detected, timeout = " + timeout +
", t0 = " + Time.toString(t, true) + ", t1 = " +
Time.toString(System.currentTimeMillis(), true) +
", keys = " + keys.size());
Log.w("Begin Registering New Selector " + selector + " ...");
ArrayList<Registrable> regs = new ArrayList<>();
for (SelectionKey key : keys) {
if (!key.isValid()) {
Log.w("Invaid SelectionKey Detected");
continue;
}
try {
regs.add(new Registrable(key));
} catch (IOException e) {
// Ignored if ServerSocket fails to Bind again
}
}
try {
selector.close();
} catch (IOException e) {}
try {
selector = Selector.open();
for (Registrable reg : regs) {
reg.register(selector);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
Log.w("End Registering New Selector " + selector);
}
/**
* Consumes all events raised by registered Clients and Servers,
* including network events (accept/connect/read/write) and user-defined events.<p>
*
* @param timeout Block for up to timeout milliseconds, or -1 to block indefinitely,
* or 0 without blocking.
* @return <b>true</b> if NETWORK events consumed;<br>
* <b>false</b> if no NETWORK events raised,
* whether or not user-defined events raised.<br>
*/
public boolean doEvents(long timeout) {
long t = System.currentTimeMillis();
int keySize;
try {
keySize = timeout == 0 ? selector.selectNow() :
timeout < 0 ? selector.select() : selector.select(timeout);
} catch (IOException e) {
throw new RuntimeException(e);
}
checkEpoll(timeout, t, keySize);
if (keySize == 0) {
invokeQueue();
return false;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
for (SelectionKey key : selectedKeys) {
if (!key.isValid()) {
continue;
}
if (key.isAcceptable()) {
Server server = (Server) key.attachment();
SocketChannel socketChannel;
try {
socketChannel = server.serverSocketChannel.accept();
if (socketChannel == null) {
continue;
}
socketChannel.configureBlocking(false);
} catch (IOException e) {
throw new RuntimeException(e);
}
Client client = new Client(server.serverConnection.get());
client.socketChannel = socketChannel;
client.add(selector, SelectionKey.OP_READ);
client.finishConnect();
continue;
}
Client client = (Client) key.attachment();
try {
if (key.isReadable()) {
int bytesRead = client.socketChannel.
read(ByteBuffer.wrap(buffer, 0, client.bufferSize));
if (bytesRead > 0) {
client.connection.onRecv(buffer, 0, bytesRead);
// may be closed by "onRecv"
if (!key.isValid()) {
continue;
}
} else if (bytesRead < 0) {
client.startClose();
// Disconnected, so skip onQueue and onConnect
continue;
}
}
if (key.isWritable()) {
client.write();
} else if (key.isConnectable() && client.socketChannel.finishConnect()) {
client.finishConnect();
// "onConnect()" might call "disconnect()"
if (client.isBusy()) {
client.write();
}
}
} catch (IOException e) {
client.startClose();
}
}
selectedKeys.clear();
invokeQueue();
return true;
}
@Override
public TimerHandler.Closeable postAtTime(Runnable runnable, long uptime) {
Timer timer = new Timer();
timer.uptime = uptime;
timer.id = nextId;
nextId ++;
timerMap.put(timer, runnable);
return () -> timerMap.remove(timer);
}
@Override
public void invokeLater(Runnable runnable) {
eventQueue.offer(runnable);
try {
selector.wakeup();
} catch (ClosedSelectorException e) {}
}
@Override
public void execute(Runnable runnable) {
executor.execute(runnable);
}
/**
* Interrupts {@link #doEvents()} or {@link #doEvents(long)}.<p>
* <b>Can be called outside main thread.</b>
*/
public void interrupt() {
invokeLater(() -> interrupted = true);
}
/**
* Tests whether the connector is interrupted,
* and then the "interrupted" status is cleared.
*/
public boolean isInterrupted() {
boolean interrupted_ = interrupted;
interrupted = false;
return interrupted_;
}
/**
* Unregisters, closes all <b>Client</b>s and <b>Server</b>s,
* then closes the Connector itself.
*/
@Override
public void close() {
executor.shutdown();
for (SelectionKey key : selector.keys()) {
((Attachment) key.attachment()).finishClose();
}
try {
selector.close();
} catch (IOException e) {}
}
}
|
package de.otto.jlineup;
import de.otto.jlineup.browser.Browser;
import de.otto.jlineup.browser.BrowserUtils;
import de.otto.jlineup.config.JobConfig;
import de.otto.jlineup.config.Step;
import de.otto.jlineup.file.FileService;
import de.otto.jlineup.image.ImageService;
import de.otto.jlineup.report.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JLineupRunner {
private static final Logger LOG = LoggerFactory.getLogger(JLineupRunner.class);
private final JobConfig jobConfig;
private final RunStepConfig runStepConfig;
public JLineupRunner(JobConfig jobConfig, RunStepConfig runStepConfig) {
this.jobConfig = jobConfig;
this.runStepConfig = runStepConfig;
}
public boolean run() {
if (jobConfig.urls == null) {
LOG.error("No urls are configured in the config.");
return false;
}
FileService fileService = new FileService(runStepConfig);
ImageService imageService = new ImageService();
//Make sure the working dir exists
if (runStepConfig.getStep() == Step.before) {
try {
fileService.createWorkingDirectoryIfNotExists();
fileService.createOrClearReportDirectory();
fileService.createOrClearScreenshotsDirectory();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (runStepConfig.getStep() == Step.before || runStepConfig.getStep() == Step.after) {
BrowserUtils browserUtils = new BrowserUtils();
try (Browser browser = new Browser(runStepConfig, jobConfig, fileService, browserUtils)) {
browser.takeScreenshots();
} catch (Exception e) {
LOG.error("JLineup Browser Exception!", e);
return false;
}
}
try {
if (runStepConfig.getStep() == Step.after || runStepConfig.getStep() == Step.compare) {
ScreenshotsComparator screenshotsComparator = new ScreenshotsComparator(runStepConfig, jobConfig, fileService, imageService);
final Map<String, List<ScreenshotComparisonResult>> comparisonResults = screenshotsComparator.compare();
final ReportGenerator reportGenerator = new ReportGenerator();
final Report report = reportGenerator.generateReport(comparisonResults);
JSONReportWriter jsonReportWriter;
if (Utils.shouldUseLegacyReportFormat(jobConfig)) {
jsonReportWriter = new JSONReportWriter_V1(fileService);
} else {
jsonReportWriter = new JSONReportWriter_V2(fileService);
}
jsonReportWriter.writeComparisonReportAsJson(report);
final HTMLReportWriter htmlReportWriter = new HTMLReportWriter(fileService);
htmlReportWriter.writeReport(report);
final Set<Map.Entry<String, UrlReport>> entries = report.screenshotComparisonsForUrl.entrySet();
for (Map.Entry<String, UrlReport> entry : entries) {
LOG.info("Sum of screenshot differences for " + entry.getKey() + ":\n" + entry.getValue().summary.differenceSum + " (" + Math.round(entry.getValue().summary.differenceSum * 100d) + " %)");
LOG.info("Max difference of a single screenshot for " + entry.getKey() + ":\n" + entry.getValue().summary.differenceMax + " (" + Math.round(entry.getValue().summary.differenceMax * 100d) + " %)");
}
LOG.info("Sum of overall screenshot differences:\n" + report.summary.differenceSum + " (" + Math.round(report.summary.differenceSum * 100d) + " %)");
LOG.info("Max difference of a single screenshot:\n" + report.summary.differenceMax + " (" + Math.round(report.summary.differenceMax * 100d) + " %)");
if (!Utils.shouldUseLegacyReportFormat(jobConfig)) {
for (Map.Entry<String, UrlReport> entry : entries) {
//Exit with exit code 1 if at least one url report has a bigger difference than configured
if (jobConfig.urls != null && entry.getValue().summary.differenceMax > jobConfig.urls.get(entry.getKey()).maxDiff) {
LOG.info("JLineupRunner finished. There was a difference between before and after. Return code is 1.");
return false;
}
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
LOG.info("JLineupRunner run finished for step '{}'\n", runStepConfig.getStep());
return true;
}
}
|
package hudson.model.labels;
import hudson.BulkChange;
import hudson.CopyOnWrite;
import hudson.XmlFile;
import hudson.model.Action;
import hudson.model.Descriptor.FormException;
import hudson.model.Failure;
import hudson.model.Hudson;
import hudson.model.Label;
import hudson.model.Saveable;
import hudson.model.listeners.SaveableListener;
import hudson.util.DescribableList;
import hudson.util.QuotedStringTokenizer;
import hudson.util.VariableResolver;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Atomic single token label, like "foo" or "bar".
*
* @author Kohsuke Kawaguchi
* @since 1.372
*/
public class LabelAtom extends Label implements Saveable {
private DescribableList<LabelAtomProperty,LabelAtomPropertyDescriptor> properties =
new DescribableList<LabelAtomProperty,LabelAtomPropertyDescriptor>(this);
@CopyOnWrite
protected transient volatile List<Action> transientActions = new Vector<Action>();
public LabelAtom(String name) {
super(name);
load();
}
/**
* If the label contains 'unsafe' chars, escape them.
*/
@Override
public String getExpression() {
return escape(name);
}
/**
* {@inheritDoc}
*
* <p>
* Note that this method returns a read-only view of {@link Action}s.
* {@link LabelAtomProperty}s who want to add a project action
* should do so by implementing {@link LabelAtomProperty#getActions(LabelAtom)}.
*/
@Override
public synchronized List<Action> getActions() {
// add all the transient actions, too
List<Action> actions = new Vector<Action>(super.getActions());
actions.addAll(transientActions);
// return the read only list to cause a failure on plugins who try to add an action here
return Collections.unmodifiableList(actions);
}
protected void updateTransientActions() {
Vector<Action> ta = new Vector<Action>();
// add the config link
if (!getApplicablePropertyDescriptors().isEmpty()) {
// if there's no property descriptor, there's nothing interesting to configure.
ta.add(new Action() {
public String getIconFileName() {
if (Hudson.getInstance().hasPermission(Hudson.ADMINISTER))
return "setting.gif";
else
return null;
}
public String getDisplayName() {
return "Configure";
}
public String getUrlName() {
return "configure";
}
});
}
for (LabelAtomProperty p : properties)
ta.addAll(p.getActions(this));
transientActions = ta;
}
/**
* Properties associated with this label.
*/
public DescribableList<LabelAtomProperty, LabelAtomPropertyDescriptor> getProperties() {
return properties;
}
@Exported
public List<LabelAtomProperty> getPropertiesList() {
return properties.toList();
}
@Override
public boolean matches(VariableResolver<Boolean> resolver) {
return resolver.resolve(name);
}
@Override
public LabelOperatorPrecedence precedence() {
return LabelOperatorPrecedence.ATOM;
}
/*package*/ XmlFile getConfigFile() {
return new XmlFile(Hudson.XSTREAM,new File(Hudson.getInstance().root,"labels/"+name+".xml"));
}
public void save() throws IOException {
if(BulkChange.contains(this)) return;
try {
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e);
}
}
public void load() {
XmlFile file = getConfigFile();
if(file.exists()) {
try {
file.unmarshal(this);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load "+file, e);
}
}
properties.setOwner(this);
updateTransientActions();
}
/**
* Returns all the {@link LabelAtomPropertyDescriptor}s that can be potentially configured
* on this label.
*/
public List<LabelAtomPropertyDescriptor> getApplicablePropertyDescriptors() {
return LabelAtomProperty.all();
}
/**
* Accepts the update to the node configuration.
*/
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
final Hudson app = Hudson.getInstance();
app.checkPermission(Hudson.ADMINISTER);
properties.rebuild(req, req.getSubmittedForm(), getApplicablePropertyDescriptors());
updateTransientActions();
save();
// take the user back to the label top page.
rsp.sendRedirect2(".");
}
/**
* Obtains an atom by its {@linkplain #getName() name}.
*/
public static LabelAtom get(String l) {
return Hudson.getInstance().getLabelAtom(l);
}
public static boolean needsEscape(String name) {
try {
Hudson.checkGoodName(name);
// additional restricted chars
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(" ()\t\n".indexOf(ch)!=-1)
return true;
}
return false;
} catch (Failure failure) {
return true;
}
}
public static String escape(String name) {
if (needsEscape(name))
return QuotedStringTokenizer.quote(name);
return name;
}
private static final Logger LOGGER = Logger.getLogger(LabelAtom.class.getName());
}
|
package hudson.security;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import groovy.lang.Binding;
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.util.DescriptorList;
import hudson.util.PluginServletFilter;
import hudson.util.spring.BeanBuilder;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.ui.rememberme.RememberMeServices;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.dao.DataAccessException;
import javax.imageio.ImageIO;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class SecurityRealm implements Describable<SecurityRealm>, ExtensionPoint {
/**
* Creates fully-configured {@link AuthenticationManager} that performs authentication
* against the user realm. The implementation hides how such authentication manager
* is configured.
*
* <p>
* {@link AuthenticationManager} instantiation often depends on the user-specified parameters
* (for example, if the authentication is based on LDAP, the user needs to specify
* the host name of the LDAP server.) Such configuration is expected to be
* presented to the user via <tt>config.jelly</tt> and then
* captured as instance variables inside the {@link SecurityRealm} implementation.
*
* <p>
* Your {@link SecurityRealm} may also wants to alter {@link Filter} set up by
* overriding {@link #createFilter(FilterConfig)}.
*/
public abstract SecurityComponents createSecurityComponents();
/**
* {@inheritDoc}
*
* <p>
* {@link SecurityRealm} is a singleton resource in Hudson, and therefore
* it's always configured through <tt>config.jelly</tt> and never with
* <tt>global.jelly</tt>.
*/
public abstract Descriptor<SecurityRealm> getDescriptor();
/**
* Returns the URL to submit a form for the authentication.
* There's no need to override this, except for {@link LegacySecurityRealm}.
*/
public String getAuthenticationGatewayUrl() {
return "j_acegi_security_check";
}
/**
* Gets the target URL of the "login" link.
* There's no need to override this, except for {@link LegacySecurityRealm}.
* On legacy implementation this should point to "longinEntry", which
* is protected by <tt>web.xml</tt>, so that the user can be eventually authenticated
* by the container.
*/
public String getLoginUrl() {
return "login";
}
public boolean allowsSignup() {
Class clz = getClass();
return clz.getClassLoader().getResource(clz.getName().replace('.','/')+"/signup.jelly")!=null;
}
/**
* Shortcut for {@link UserDetailsService#loadUserByUsername(String)}.
*
* @throws UserMayOrMayNotExistException
* If the security realm cannot even tell if the user exists or not.
* @return
* never null.
*/
public final UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
return getSecurityComponents().userDetails.loadUserByUsername(username);
}
/**
* If this {@link SecurityRealm} supports a look up of {@link GroupDetails} by their names, override this method
* to provide the look up.
*
* <p>
* This information, when available, can be used by {@link AuthorizationStrategy}s to improve the UI and
* error diagnostics for the user.
*/
public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
throw new UserMayOrMayNotExistException(groupname);
}
/**
* {@link DefaultManageableImageCaptchaService} holder to defer initialization.
*/
private static final class CaptchaService {
private static final DefaultManageableImageCaptchaService INSTANCE = new DefaultManageableImageCaptchaService();
}
/**
* Generates a captcha image.
*/
public final void doCaptcha(StaplerRequest req, StaplerResponse rsp) throws IOException {
String id = req.getSession().getId();
rsp.setContentType("image/png");
rsp.addHeader("Cache-Control","no-cache");
ImageIO.write( CaptchaService.INSTANCE.getImageChallengeForID(id), "PNG", rsp.getOutputStream() );
}
/**
* Validates the captcha.
*/
protected final boolean validateCaptcha(String text) {
try {
String id = Stapler.getCurrentRequest().getSession().getId();
Boolean b = CaptchaService.INSTANCE.validateResponseForID(id, text);
return b!=null && b;
} catch (CaptchaServiceException e) {
LOGGER.log(Level.INFO, "Captcha validation had a problem",e);
return false;
}
}
protected static <T> T findBean(Class<T> type, ApplicationContext context) {
Map m = context.getBeansOfType(type);
switch(m.size()) {
case 0:
throw new IllegalArgumentException("No beans of "+type+" are defined");
case 1:
return type.cast(m.values().iterator().next());
default:
throw new IllegalArgumentException("Multiple beans of "+type+" are defined: "+m);
}
}
/**
* Holder for the SecurityComponents.
*/
private transient SecurityComponents securityComponents;
/**
* Use this function to get the security components, without necessarily
* recreating them.
*/
public synchronized SecurityComponents getSecurityComponents() {
if (this.securityComponents == null) {
this.securityComponents = this.createSecurityComponents();
}
return this.securityComponents;
}
/**
* Creates {@link Filter} that all the incoming HTTP requests will go through
* for authentication.
*
* <p>
* The default implementation uses {@link #getSecurityComponents()} and builds
* a standard filter chain from /WEB-INF/security/SecurityFilters.groovy.
* But subclasses can override this to completely change the filter sequence.
*
* <p>
* For other plugins that want to contribute {@link Filter}, see
* {@link PluginServletFilter}.
*
* @since 1.271
*/
public Filter createFilter(FilterConfig filterConfig) {
Binding binding = new Binding();
SecurityComponents sc = getSecurityComponents();
binding.setVariable("securityComponents", sc);
BeanBuilder builder = new BeanBuilder();
builder.parse(filterConfig.getServletContext().getResourceAsStream("/WEB-INF/security/SecurityFilters.groovy"),binding);
WebApplicationContext context = builder.createApplicationContext();
return (Filter) context.getBean("filter");
}
/**
* Singleton constant that represents "no authentication."
*/
public static final SecurityRealm NO_AUTHENTICATION = new None();
private static class None extends SecurityRealm {
public SecurityComponents createSecurityComponents() {
return new SecurityComponents(new AuthenticationManager() {
public Authentication authenticate(Authentication authentication) {
return authentication;
}
});
}
/**
* This special instance is not configurable explicitly,
* so it doesn't have a descriptor.
*/
public Descriptor<SecurityRealm> getDescriptor() {
return null;
}
/**
* We don't need any filter for this {@link SecurityRealm}.
*/
@Override
public Filter createFilter(FilterConfig filterConfig) {
return new ChainedServletFilter();
}
/**
* Maintain singleton semantics.
*/
private Object readResolve() {
return NO_AUTHENTICATION;
}
}
/**
* Just a tuple so that we can create various inter-related security related objects and
* return them all at once.
*
* <p>
* None of the fields are ever null.
*
* @see SecurityRealm#createSecurityComponents()
*/
public static final class SecurityComponents {
public final AuthenticationManager manager;
public final UserDetailsService userDetails;
public final RememberMeServices rememberMe;
public SecurityComponents() {
// we use AuthenticationManagerProxy here just as an implementation that fails all the time,
// not as a proxy. No one is supposed to use this as a proxy.
this(new AuthenticationManagerProxy());
}
public SecurityComponents(AuthenticationManager manager) {
// we use UserDetailsServiceProxy here just as an implementation that fails all the time,
// not as a proxy. No one is supposed to use this as a proxy.
this(manager,new UserDetailsServiceProxy());
}
public SecurityComponents(AuthenticationManager manager, UserDetailsService userDetails) {
this(manager,userDetails,createRememberMeService(userDetails));
}
public SecurityComponents(AuthenticationManager manager, UserDetailsService userDetails, RememberMeServices rememberMe) {
assert manager!=null && userDetails!=null && rememberMe!=null;
this.manager = manager;
this.userDetails = userDetails;
this.rememberMe = rememberMe;
}
private static RememberMeServices createRememberMeService(UserDetailsService uds) {
// create our default TokenBasedRememberMeServices, which depends on the availability of the secret key
TokenBasedRememberMeServices2 rms = new TokenBasedRememberMeServices2();
rms.setUserDetailsService(uds);
rms.setKey(Hudson.getInstance().getSecretKey());
rms.setParameter("remember_me"); // this is the form field name in login.jelly
return rms;
}
}
/**
* All registered {@link SecurityRealm} implementations.
*/
public static final DescriptorList<SecurityRealm> LIST = new DescriptorList<SecurityRealm>();
static {
LIST.load(LegacySecurityRealm.class);
LIST.load(HudsonPrivateSecurityRealm.class);
LIST.load(LDAPSecurityRealm.class);
}
private static final Logger LOGGER = Logger.getLogger(SecurityRealm.class.getName());
}
|
package io.bitsquare.user;
import io.bitsquare.app.BitsquareEnvironment;
import io.bitsquare.app.DevFlags;
import io.bitsquare.app.Version;
import io.bitsquare.btc.BitcoinNetwork;
import io.bitsquare.btc.FeePolicy;
import io.bitsquare.common.persistance.Persistable;
import io.bitsquare.locale.*;
import io.bitsquare.storage.Storage;
import javafx.beans.Observable;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.utils.MonetaryFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.*;
public final class Preferences implements Persistable {
// That object is saved to disc. We need to take care of changes to not break deserialization.
private static final long serialVersionUID = Version.LOCAL_DB_VERSION;
private static final Logger log = LoggerFactory.getLogger(Preferences.class);
public static Preferences INSTANCE;
// Deactivate mBit for now as most screens are not supporting it yet
private static final List<String> BTC_DENOMINATIONS = Arrays.asList(MonetaryFormat.CODE_BTC/*, MonetaryFormat.CODE_MBTC*/);
transient static final private ArrayList<BlockChainExplorer> blockChainExplorersTestNet = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("Blocktrail", "https:
new BlockChainExplorer("Blockexplorer", "https:
new BlockChainExplorer("Blockr.io", "https:
new BlockChainExplorer("Biteasy", "https:
));
transient static final private ArrayList<BlockChainExplorer> blockChainExplorersMainNet = new ArrayList<>(Arrays.asList(
new BlockChainExplorer("Blocktrail", "https:
new BlockChainExplorer("Tradeblock.com", "https:
new BlockChainExplorer("Blockchain.info", "https:
new BlockChainExplorer("Blockexplorer", "https:
new BlockChainExplorer("Blockr.io", "https:
new BlockChainExplorer("Biteasy", "https:
));
public static List<String> getBtcDenominations() {
return BTC_DENOMINATIONS;
}
private static Locale defaultLocale = Locale.getDefault();
//TODO test with other locales
// private static Locale defaultLocale = Locale.US;
public static Locale getDefaultLocale() {
return defaultLocale;
}
private static TradeCurrency defaultTradeCurrency = new FiatCurrency(CurrencyUtil.getCurrencyByCountryCode(CountryUtil.getDefaultCountryCode()).getCurrency().getCurrencyCode());
public static TradeCurrency getDefaultTradeCurrency() {
return defaultTradeCurrency;
}
private static boolean staticUseAnimations = true;
transient private final Storage<Preferences> storage;
transient private final BitsquareEnvironment bitsquareEnvironment;
transient private BitcoinNetwork bitcoinNetwork;
// Persisted fields
private String btcDenomination = MonetaryFormat.CODE_BTC;
private boolean useAnimations = DevFlags.STRESS_TEST_MODE ? false : true;
private final ArrayList<FiatCurrency> fiatCurrencies;
private final ArrayList<CryptoCurrency> cryptoCurrencies;
private BlockChainExplorer blockChainExplorerMainNet;
private BlockChainExplorer blockChainExplorerTestNet;
private String backupDirectory;
private boolean autoSelectArbitrators = true;
private final Map<String, Boolean> dontShowAgainMap;
private boolean tacAccepted;
// Don't remove as we don't want to break old serialized data
private boolean useTorForBitcoinJ = false;
private boolean showOwnOffersInOfferBook = true;
private Locale preferredLocale;
private TradeCurrency preferredTradeCurrency;
private long nonTradeTxFeePerKB = FeePolicy.getNonTradeFeePerKb().value;
private double maxPriceDistanceInPercent;
private boolean useInvertedMarketPrice;
private boolean useStickyMarketPrice = false;
private boolean usePercentageBasedPrice = false;
// Observable wrappers
transient private final StringProperty btcDenominationProperty = new SimpleStringProperty(btcDenomination);
transient private final BooleanProperty useAnimationsProperty = new SimpleBooleanProperty(useAnimations);
transient private final BooleanProperty useInvertedMarketPriceProperty = new SimpleBooleanProperty(useInvertedMarketPrice);
transient private final ObservableList<FiatCurrency> fiatCurrenciesAsObservable = FXCollections.observableArrayList();
transient private final ObservableList<CryptoCurrency> cryptoCurrenciesAsObservable = FXCollections.observableArrayList();
transient private final ObservableList<TradeCurrency> tradeCurrenciesAsObservable = FXCollections.observableArrayList();
// Constructor
@Inject
public Preferences(Storage<Preferences> storage, BitsquareEnvironment bitsquareEnvironment) {
log.debug("Preferences " + this);
INSTANCE = this;
this.storage = storage;
this.bitsquareEnvironment = bitsquareEnvironment;
Preferences persisted = storage.initAndGetPersisted(this);
if (persisted != null) {
setBtcDenomination(persisted.btcDenomination);
setUseAnimations(persisted.useAnimations);
setUseInvertedMarketPrice(persisted.useInvertedMarketPrice);
setFiatCurrencies(persisted.fiatCurrencies);
fiatCurrencies = new ArrayList<>(fiatCurrenciesAsObservable);
setCryptoCurrencies(persisted.cryptoCurrencies);
cryptoCurrencies = new ArrayList<>(cryptoCurrenciesAsObservable);
setBlockChainExplorerTestNet(persisted.getBlockChainExplorerTestNet());
setBlockChainExplorerMainNet(persisted.getBlockChainExplorerMainNet());
// In case of an older version without that data we set it to defaults
if (blockChainExplorerTestNet == null)
setBlockChainExplorerTestNet(blockChainExplorersTestNet.get(0));
if (blockChainExplorerMainNet == null)
setBlockChainExplorerTestNet(blockChainExplorersMainNet.get(0));
backupDirectory = persisted.getBackupDirectory();
autoSelectArbitrators = persisted.getAutoSelectArbitrators();
dontShowAgainMap = persisted.getDontShowAgainMap();
tacAccepted = persisted.getTacAccepted();
preferredLocale = persisted.getPreferredLocale();
defaultLocale = preferredLocale;
preferredTradeCurrency = persisted.getPreferredTradeCurrency();
defaultTradeCurrency = preferredTradeCurrency;
// useTorForBitcoinJ = persisted.getUseTorForBitcoinJ();
useTorForBitcoinJ = false;
useStickyMarketPrice = persisted.getUseStickyMarketPrice();
usePercentageBasedPrice = persisted.getUsePercentageBasedPrice();
showOwnOffersInOfferBook = persisted.getShowOwnOffersInOfferBook();
maxPriceDistanceInPercent = persisted.getMaxPriceDistanceInPercent();
// Backward compatible to version 0.3.6. Can be removed after a while
if (maxPriceDistanceInPercent == 0d)
maxPriceDistanceInPercent = 0.2;
try {
setNonTradeTxFeePerKB(persisted.getNonTradeTxFeePerKB());
} catch (Exception e) {
// leave default value
}
} else {
setFiatCurrencies(CurrencyUtil.getAllMainFiatCurrencies());
fiatCurrencies = new ArrayList<>(fiatCurrenciesAsObservable);
setCryptoCurrencies(CurrencyUtil.getMainCryptoCurrencies());
cryptoCurrencies = new ArrayList<>(cryptoCurrenciesAsObservable);
setBlockChainExplorerTestNet(blockChainExplorersTestNet.get(0));
setBlockChainExplorerMainNet(blockChainExplorersMainNet.get(0));
dontShowAgainMap = new HashMap<>();
preferredLocale = getDefaultLocale();
preferredTradeCurrency = getDefaultTradeCurrency();
maxPriceDistanceInPercent = 0.2;
storage.queueUpForSave();
}
this.bitcoinNetwork = bitsquareEnvironment.getBitcoinNetwork();
// Use that to guarantee update of the serializable field and to make a storage update in case of a change
btcDenominationProperty.addListener((ov) -> {
btcDenomination = btcDenominationProperty.get();
storage.queueUpForSave(2000);
});
useAnimationsProperty.addListener((ov) -> {
useAnimations = useAnimationsProperty.get();
staticUseAnimations = useAnimations;
storage.queueUpForSave(2000);
});
useInvertedMarketPriceProperty.addListener((ov) -> {
useInvertedMarketPrice = useInvertedMarketPriceProperty.get();
storage.queueUpForSave(2000);
});
fiatCurrenciesAsObservable.addListener((Observable ov) -> {
fiatCurrencies.clear();
fiatCurrencies.addAll(fiatCurrenciesAsObservable);
storage.queueUpForSave();
});
cryptoCurrenciesAsObservable.addListener((Observable ov) -> {
cryptoCurrencies.clear();
cryptoCurrencies.addAll(cryptoCurrenciesAsObservable);
storage.queueUpForSave();
});
fiatCurrenciesAsObservable.addListener((ListChangeListener<FiatCurrency>) this::updateTradeCurrencies);
cryptoCurrenciesAsObservable.addListener((ListChangeListener<CryptoCurrency>) this::updateTradeCurrencies);
tradeCurrenciesAsObservable.addAll(fiatCurrencies);
tradeCurrenciesAsObservable.addAll(cryptoCurrencies);
}
public void dontShowAgain(String key, boolean dontShowAgain) {
dontShowAgainMap.put(key, dontShowAgain);
storage.queueUpForSave(1000);
}
public void resetDontShowAgainForType() {
dontShowAgainMap.clear();
storage.queueUpForSave(1000);
}
// Setter
public void setBtcDenomination(String btcDenomination) {
this.btcDenominationProperty.set(btcDenomination);
}
public void setUseAnimations(boolean useAnimations) {
this.useAnimationsProperty.set(useAnimations);
}
public void setUseInvertedMarketPrice(boolean useInvertedMarketPrice) {
this.useInvertedMarketPriceProperty.set(useInvertedMarketPrice);
}
public void setBitcoinNetwork(BitcoinNetwork bitcoinNetwork) {
if (this.bitcoinNetwork != bitcoinNetwork)
bitsquareEnvironment.saveBitcoinNetwork(bitcoinNetwork);
this.bitcoinNetwork = bitcoinNetwork;
// We don't store the bitcoinNetwork locally as BitcoinNetwork is not serializable!
}
public void addFiatCurrency(FiatCurrency tradeCurrency) {
if (!fiatCurrenciesAsObservable.contains(tradeCurrency))
fiatCurrenciesAsObservable.add(tradeCurrency);
}
public void removeFiatCurrency(FiatCurrency tradeCurrency) {
if (tradeCurrenciesAsObservable.size() > 1) {
if (fiatCurrenciesAsObservable.contains(tradeCurrency))
fiatCurrenciesAsObservable.remove(tradeCurrency);
if (preferredTradeCurrency.equals(tradeCurrency))
setPreferredTradeCurrency(tradeCurrenciesAsObservable.get(0));
} else {
log.error("you cannot remove the last currency");
}
}
public void addCryptoCurrency(CryptoCurrency tradeCurrency) {
if (!cryptoCurrenciesAsObservable.contains(tradeCurrency))
cryptoCurrenciesAsObservable.add(tradeCurrency);
}
public void removeCryptoCurrency(CryptoCurrency tradeCurrency) {
if (tradeCurrenciesAsObservable.size() > 1) {
if (cryptoCurrenciesAsObservable.contains(tradeCurrency))
cryptoCurrenciesAsObservable.remove(tradeCurrency);
if (preferredTradeCurrency.equals(tradeCurrency))
setPreferredTradeCurrency(tradeCurrenciesAsObservable.get(0));
} else {
log.error("you cannot remove the last currency");
}
}
public void setBlockChainExplorer(BlockChainExplorer blockChainExplorer) {
if (bitcoinNetwork == BitcoinNetwork.MAINNET)
setBlockChainExplorerMainNet(blockChainExplorer);
else
setBlockChainExplorerTestNet(blockChainExplorer);
}
public void setTacAccepted(boolean tacAccepted) {
this.tacAccepted = tacAccepted;
storage.queueUpForSave();
}
public void setPreferredLocale(Locale preferredLocale) {
this.preferredLocale = preferredLocale;
defaultLocale = preferredLocale;
storage.queueUpForSave();
}
public void setPreferredTradeCurrency(TradeCurrency preferredTradeCurrency) {
if (preferredTradeCurrency != null) {
this.preferredTradeCurrency = preferredTradeCurrency;
defaultTradeCurrency = preferredTradeCurrency;
storage.queueUpForSave();
}
}
public void setNonTradeTxFeePerKB(long nonTradeTxFeePerKB) throws Exception {
if (nonTradeTxFeePerKB < Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.value)
throw new Exception("Transaction fee must be at least 5 satoshi/byte");
if (nonTradeTxFeePerKB > 500_000)
throw new Exception("Transaction fee is in the range of 10-100 satoshi/byte. Your input is above any reasonable value (>500 satoshi/byte).");
this.nonTradeTxFeePerKB = nonTradeTxFeePerKB;
FeePolicy.setNonTradeFeePerKb(Coin.valueOf(nonTradeTxFeePerKB));
storage.queueUpForSave();
}
/* public void setUseTorForBitcoinJ(boolean useTorForBitcoinJ) {
this.useTorForBitcoinJ = useTorForBitcoinJ;
storage.queueUpForSave();
}*/
public void setShowOwnOffersInOfferBook(boolean showOwnOffersInOfferBook) {
this.showOwnOffersInOfferBook = showOwnOffersInOfferBook;
storage.queueUpForSave();
}
public void setMaxPriceDistanceInPercent(double maxPriceDistanceInPercent) {
this.maxPriceDistanceInPercent = maxPriceDistanceInPercent;
storage.queueUpForSave();
}
public void setBackupDirectory(String backupDirectory) {
this.backupDirectory = backupDirectory;
storage.queueUpForSave();
}
public void setAutoSelectArbitrators(boolean autoSelectArbitrators) {
this.autoSelectArbitrators = autoSelectArbitrators;
storage.queueUpForSave();
}
public boolean flipUseInvertedMarketPrice() {
setUseInvertedMarketPrice(!getUseInvertedMarketPrice());
return getUseInvertedMarketPrice();
}
public void setUseStickyMarketPrice(boolean useStickyMarketPrice) {
this.useStickyMarketPrice = useStickyMarketPrice;
storage.queueUpForSave();
}
public void setUsePercentageBasedPrice(boolean usePercentageBasedPrice) {
this.usePercentageBasedPrice = usePercentageBasedPrice;
storage.queueUpForSave();
}
// Getter
public String getBtcDenomination() {
return btcDenominationProperty.get();
}
public StringProperty btcDenominationProperty() {
return btcDenominationProperty;
}
public boolean getUseAnimations() {
return useAnimationsProperty.get();
}
public BooleanProperty useAnimationsProperty() {
return useAnimationsProperty;
}
public static boolean useAnimations() {
return staticUseAnimations;
}
public boolean getUseInvertedMarketPrice() {
return useInvertedMarketPriceProperty.get();
}
public BooleanProperty useInvertedMarketPriceProperty() {
return useInvertedMarketPriceProperty;
}
public BitcoinNetwork getBitcoinNetwork() {
return bitcoinNetwork;
}
public ObservableList<FiatCurrency> getFiatCurrenciesAsObservable() {
return fiatCurrenciesAsObservable;
}
public ObservableList<CryptoCurrency> getCryptoCurrenciesAsObservable() {
return cryptoCurrenciesAsObservable;
}
public ObservableList<TradeCurrency> getTradeCurrenciesAsObservable() {
return tradeCurrenciesAsObservable;
}
public BlockChainExplorer getBlockChainExplorerTestNet() {
return blockChainExplorerTestNet;
}
public BlockChainExplorer getBlockChainExplorerMainNet() {
return blockChainExplorerMainNet;
}
public BlockChainExplorer getBlockChainExplorer() {
if (bitcoinNetwork == BitcoinNetwork.MAINNET)
return blockChainExplorerMainNet;
else
return blockChainExplorerTestNet;
}
public ArrayList<BlockChainExplorer> getBlockChainExplorers() {
if (bitcoinNetwork == BitcoinNetwork.MAINNET)
return blockChainExplorersMainNet;
else
return blockChainExplorersTestNet;
}
public String getBackupDirectory() {
return backupDirectory;
}
public boolean getAutoSelectArbitrators() {
return autoSelectArbitrators;
}
public Map<String, Boolean> getDontShowAgainMap() {
return dontShowAgainMap;
}
public boolean showAgain(String key) {
return !dontShowAgainMap.containsKey(key) || !dontShowAgainMap.get(key);
}
public boolean getTacAccepted() {
return tacAccepted;
}
public Locale getPreferredLocale() {
return preferredLocale;
}
public TradeCurrency getPreferredTradeCurrency() {
return preferredTradeCurrency;
}
public long getNonTradeTxFeePerKB() {
return Math.max(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.value, nonTradeTxFeePerKB);
}
public boolean getUseTorForBitcoinJ() {
return useTorForBitcoinJ;
}
public boolean getShowOwnOffersInOfferBook() {
return showOwnOffersInOfferBook;
}
public double getMaxPriceDistanceInPercent() {
return maxPriceDistanceInPercent;
}
public boolean getUseStickyMarketPrice() {
return useStickyMarketPrice;
}
public boolean getUsePercentageBasedPrice() {
return usePercentageBasedPrice;
}
// Private
private void updateTradeCurrencies(ListChangeListener.Change<? extends TradeCurrency> change) {
change.next();
if (change.wasAdded() && change.getAddedSize() == 1)
tradeCurrenciesAsObservable.add(change.getAddedSubList().get(0));
else if (change.wasRemoved() && change.getRemovedSize() == 1)
tradeCurrenciesAsObservable.remove(change.getRemoved().get(0));
}
private void setFiatCurrencies(List<FiatCurrency> currencies) {
fiatCurrenciesAsObservable.setAll(currencies);
}
private void setCryptoCurrencies(List<CryptoCurrency> currencies) {
cryptoCurrenciesAsObservable.setAll(currencies);
}
private void setBlockChainExplorerTestNet(BlockChainExplorer blockChainExplorerTestNet) {
this.blockChainExplorerTestNet = blockChainExplorerTestNet;
storage.queueUpForSave(2000);
}
private void setBlockChainExplorerMainNet(BlockChainExplorer blockChainExplorerMainNet) {
this.blockChainExplorerMainNet = blockChainExplorerMainNet;
storage.queueUpForSave(2000);
}
}
|
/*
* $Id$
* $URL$
*/
package org.subethamail.core.lists;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeSet;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RunAs;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage.RecipientType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.annotation.security.SecurityDomain;
import org.subethamail.common.ExportMessagesException;
import org.subethamail.common.ImportMessagesException;
import org.subethamail.common.MailUtils;
import org.subethamail.common.NotFoundException;
import org.subethamail.common.SearchException;
import org.subethamail.common.SubEthaMessage;
import org.subethamail.core.deliv.i.Deliverator;
import org.subethamail.core.filter.FilterRunner;
import org.subethamail.core.injector.Detacher;
import org.subethamail.core.injector.i.Injector;
import org.subethamail.core.lists.i.Archiver;
import org.subethamail.core.lists.i.ArchiverRemote;
import org.subethamail.core.lists.i.AttachmentPartData;
import org.subethamail.core.lists.i.ExportFormat;
import org.subethamail.core.lists.i.InlinePartData;
import org.subethamail.core.lists.i.ListMgr;
import org.subethamail.core.lists.i.MailData;
import org.subethamail.core.lists.i.MailSummary;
import org.subethamail.core.lists.i.SearchHit;
import org.subethamail.core.lists.i.SearchResult;
import org.subethamail.core.lists.i.TextPartData;
import org.subethamail.core.search.i.Indexer;
import org.subethamail.core.search.i.SimpleHit;
import org.subethamail.core.search.i.SimpleResult;
import org.subethamail.core.util.PersonalBean;
import org.subethamail.core.util.Transmute;
import org.subethamail.entity.Attachment;
import org.subethamail.entity.Mail;
import org.subethamail.entity.MailingList;
import org.subethamail.entity.Person;
import org.subethamail.entity.i.Permission;
import org.subethamail.entity.i.PermissionException;
import com.sun.mail.util.LineInputStream;
/**
* Implementation of the Archiver interface.
*
* @author Jeff Schnitzer
* @author Scott Hernandez
*/
@Stateless(name="Archiver")
@SecurityDomain("subetha")
@PermitAll
@RunAs("siteAdmin")
@WebService(name="Archiver", targetNamespace="http://ws.subethamail.org/", serviceName="ArchiverService")
@SOAPBinding(style=SOAPBinding.Style.RPC)
public class ArchiverBean extends PersonalBean implements Archiver, ArchiverRemote
{
@EJB Deliverator deliverator;
@EJB FilterRunner filterRunner;
@EJB Detacher detacher;
@EJB ListMgr listManager;
@EJB Injector injector;
@EJB Indexer indexer;
private static Log log = LogFactory.getLog(ArchiverBean.class);
@Resource(mappedName="java:/Mail") private Session mailSession;
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#sendTo(java.lang.Long, String email)
*/
@WebMethod
public void sendTo(Long mailId, String email) throws NotFoundException
{
this.deliverator.deliverToEmail(mailId, email);
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#getThreads(java.lang.Long)
*/
@WebMethod
public List<MailSummary> getThreads(Long listId, int skip, int count) throws NotFoundException, PermissionException
{
Person me = this.getMe();
// Are we allowed to view archives?
MailingList list = this.getListFor(listId, Permission.VIEW_ARCHIVES, me);
List<Mail> mails = this.em.findMailByList(listId, skip, count);
// This is fun. Assemble the thread relationships.
SortedSet<Mail> roots = new TreeSet<Mail>();
for (Mail mail: mails)
{
Mail parent = mail;
while (parent.getParent() != null)
parent = parent.getParent();
roots.add(parent);
}
// Figure out if we're allowed to see emails
boolean showEmail = list.getPermissionsFor(me).contains(Permission.VIEW_ADDRESSES);
// Now generate the entire summary
return Transmute.mailSummaries(roots, showEmail, null);
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#search(java.lang.Long, java.lang.String, int, int)
*/
@WebMethod
public SearchResult search(Long listId, String query, int skip, int count) throws NotFoundException, PermissionException, SearchException
{
Person me = this.getMe();
// Are we allowed to view archives?
MailingList list = this.getListFor(listId, Permission.VIEW_ARCHIVES, me);
SimpleResult simpleResult = this.indexer.search(listId, query, skip, count);
List<SearchHit> hits = new ArrayList<SearchHit>(simpleResult.getHits().size());
// Since there might be deleted mail in the results, let's do a partial attempt
// to reduce the total number when we know about specific deleted mail. The number
// is not exact, of course, because there may be more deleted mail on different
// pages of search results. But at least the number isn't obviously wrong for
// small result sets.
int totalResults = simpleResult.getTotal();
for (SimpleHit simpleHit: simpleResult.getHits())
{
// Note that there might be deleted mail in the hits, so be careful
Mail mail = this.em.find(Mail.class, simpleHit.getId());
if (mail != null)
{
hits.add(new SearchHit(
mail.getId(),
mail.getSubject(),
list.getPermissionsFor(me).contains(Permission.VIEW_ADDRESSES)
? mail.getFromAddress().getAddress() : null,
mail.getFromAddress().getPersonal(),
mail.getSentDate(),
simpleHit.getScore()
));
}
else
{
totalResults
}
}
return new SearchResult(totalResults, hits);
}
/* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#countMailByList(java.lang.Long)
*/
@WebMethod
public int countMailByList(Long listId)
{
return this.em.countMailByList(listId);
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#getMessage(java.lang.Long, OutputStream)
*/
public void writeMessage(Long mailId, OutputStream stream) throws NotFoundException, PermissionException
{
Mail mail = this.getMailFor(mailId, Permission.VIEW_ARCHIVES);
try
{
writeMessage(mail, stream);
}
catch (Exception e)
{
if (log.isDebugEnabled()) log.debug("exception getting mail#" + mailId + "\n" + e.toString());
}
}
/**
* Writes a message out to the stream. First current filters are applied, and then message is written.
*
* @param msg The message to write
* @param stream The stream to write to
*/
private void writeMessage(Mail mail, OutputStream stream) throws MessagingException, IOException
{
SubEthaMessage msg = new SubEthaMessage(this.mailSession, mail.getContent());
this.filterRunner.onArchiveRender(msg, mail);
this.detacher.attach(msg);
msg.writeTo(stream);
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#writeAttachment(java.lang.Long, java.io.OutputStream)
*/
public void writeAttachment(Long attachmentId, OutputStream stream) throws NotFoundException, PermissionException
{
Attachment a = this.em.get(Attachment.class, attachmentId);
a.getMail().getList().checkPermission(getMe(), Permission.VIEW_ARCHIVES);
Blob data = a.getContent();
try
{
BufferedInputStream bis = new BufferedInputStream(data.getBinaryStream());
int stuff;
while ((stuff = bis.read()) >= 0)
stream.write(stuff);
}
catch (SQLException ex)
{
throw new RuntimeException(ex);
}
catch (IOException ex)
{
throw new RuntimeException(ex);
}
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#getAttachmentContentType(java.lang.Long)
*/
@WebMethod
public String getAttachmentContentType(Long attachmentId) throws NotFoundException, PermissionException
{
Attachment a = this.em.get(Attachment.class, attachmentId);
a.getMail().getList().checkPermission(getMe(), Permission.VIEW_ARCHIVES);
return a.getContentType();
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#getMail(java.lang.Long)
*/
@WebMethod
public MailData getMail(Long mailId) throws NotFoundException, PermissionException
{
Person me = this.getMe();
// Are we allowed to view archives?
Mail mail = this.getMailFor(mailId, Permission.VIEW_ARCHIVES, me);
// Figure out if we're allowed to see emails
boolean showEmail = mail.getList().getPermissionsFor(me).contains(Permission.VIEW_ADDRESSES);
MailData data = this.makeMailData(mail, showEmail);
Mail root = mail;
while (root.getParent() != null)
root = root.getParent();
// This trick inserts us into the thread hierarchy we create.
data.setThreadRoot(Transmute.mailSummary(root, showEmail, data));
return data;
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#importMessages(Long, InputStream)
*/
public int importMessages(Long listId, InputStream mboxStream) throws NotFoundException, PermissionException, ImportMessagesException
{
MailingList list = this.getListFor(listId, Permission.IMPORT_MESSAGES);
try
{
LineInputStream in = new LineInputStream(mboxStream);
String line = null;
String fromLine = null;
String envelopeSender = null;
ByteArrayOutputStream buf = null;
Date fallbackDate = new Date();
int count = 0;
for (line = in.readLine(); line != null; line = in.readLine())
{
if (line.indexOf("From ") == 0)
{
if (buf != null)
{
byte[] bytes = buf.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
Date sent = this.injector.importMessage(list.getId(), envelopeSender, bin, true, fallbackDate);
if (sent != null)
fallbackDate = sent;
count++;
}
fromLine = line;
envelopeSender = MailUtils.getMboxFrom(fromLine);
buf = new ByteArrayOutputStream();
}
else if (buf != null)
{
byte[] bytes = MailUtils.decodeMboxFrom(line).getBytes();
buf.write(bytes, 0, bytes.length);
buf.write(10);
}
}
if (buf != null)
{
byte[] bytes = buf.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
this.injector.importMessage(list.getId(), envelopeSender, bin, true, fallbackDate);
count++;
}
return count;
}
catch (IOException ex)
{
throw new ImportMessagesException(ex);
}
}
/**
* Makes the base mail data. Doesn't set the threadRoot.
*/
protected MailData makeMailData(Mail raw, boolean showEmail) throws NotFoundException
{
try
{
InternetAddress addy = raw.getFromAddress();
SubEthaMessage msg = new SubEthaMessage(this.mailSession, raw.getContent());
List<InlinePartData> inlineParts = new ArrayList<InlinePartData>();
List<AttachmentPartData> attachmentParts = new ArrayList<AttachmentPartData>();
for (Part part: msg.getParts())
{
String contentType = part.getContentType();
if (contentType.startsWith(SubEthaMessage.DETACHMENT_MIME_TYPE))
{
//we need the orig Content-Type before the message was munged
contentType = part.getHeader(SubEthaMessage.HDR_ORIGINAL_CONTENT_TYPE)[0];
//put back the orig Content-Type
part.setHeader(SubEthaMessage.HDR_CONTENT_TYPE, contentType);
String name = part.getFileName();
// just in case we are working with something that isn't
// C-D: attachment; filename=""
if (name == null || name.length() == 0)
name = MailUtils.getNameFromContentType(contentType);
Long id = (Long) part.getContent();
//TODO: Set the correct size. This should be the size of the Attachment.content (Blob)
AttachmentPartData apd = new AttachmentPartData(id, contentType, name, 0);
attachmentParts.add(apd);
}
else
{
// not an attachment cause it isn't stored as a detached part.
Object content = part.getContent();
String name = part.getFileName();
// just in case we are working with something that isn't
// C-D: attachment; filename=""
if (name == null || name.length() == 0)
name = MailUtils.getNameFromContentType(contentType);
InlinePartData ipd;
if (content instanceof String)
{
ipd = new TextPartData((String)content, part.getContentType(), name, part.getSize());
}
else
{
ipd = new InlinePartData(content, part.getContentType(), name, part.getSize());
}
inlineParts.add(ipd);
}
}
return new MailData(
raw.getId(),
raw.getSubject(),
showEmail ? addy.getAddress() : null,
addy.getPersonal(),
raw.getSentDate(),
Transmute.mailSummaries(raw.getReplies(), showEmail, null),
raw.getList().getId(),
inlineParts,
attachmentParts);
}
catch (MessagingException ex)
{
// Should be impossible since everything was already run through
// JavaMail when the data was imported.
throw new RuntimeException(ex);
}
catch (IOException ex)
{
// Ditto
throw new RuntimeException(ex);
}
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#deleteMail(java.lang.Long)
*/
@WebMethod
public Long deleteMail(Long mailId) throws NotFoundException, PermissionException
{
Mail mail = this.getMailFor(mailId, Permission.DELETE_ARCHIVES);
// Make all the children belong to the parent
Mail parent = mail.getParent();
if (parent != null)
parent.getReplies().remove(mail);
for (Mail child: mail.getReplies())
{
child.setParent(parent);
if (parent != null)
parent.getReplies().add(child);
}
mail.getReplies().clear();
this.em.remove(mail);
// TODO: figure out how to remove it from the search index
return mail.getList().getId();
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#post(java.lang.String, java.lang.Long, java.lang.String, java.lang.String)
*/
public void post(String fromAddress, Long listId, String subject, String body) throws NotFoundException, PermissionException
{
Person me = this.getMe();
if (me == null)
throw new IllegalStateException("Must be logged in");
MailingList toList = this.getListFor(listId, Permission.POST, me);
if (me.getEmailAddress(fromAddress) == null)
throw new IllegalArgumentException("Not one of your addresses");
try
{
// Craft a new message
SubEthaMessage sm = craftMessage(toList, fromAddress, me.getName(), subject, body, false);
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(8192);
sm.writeTo(tmpStream);
this.injector.inject(fromAddress, toList.getEmail(), tmpStream.toByteArray());
}
catch (MessagingException ex) { throw new RuntimeException(ex); }
catch (IOException ex) { throw new RuntimeException(ex); }
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#reply(java.lang.String, java.lang.Long, java.lang.String, java.lang.String)
*/
public Long reply(String fromAddress, Long msgId, String subject, String body) throws NotFoundException, PermissionException
{
Person me = this.getMe();
if (me == null)
throw new IllegalStateException("Must be logged in");
Mail mail = this.getMailFor(msgId, Permission.POST, me);
MailingList toList = mail.getList();
if (me.getEmailAddress(fromAddress) == null)
throw new IllegalArgumentException("Not one of your addresses");
try
{
// Craft a new message
SubEthaMessage sm = craftMessage(toList, fromAddress, me.getName(), subject, body, true);
String inReplyTo = mail.getMessageId();
if (inReplyTo != null && inReplyTo.length() > 0)
sm.setHeader("In-Reply-To", inReplyTo);
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(8192);
sm.writeTo(tmpStream);
this.injector.inject(fromAddress, toList.getEmail(), tmpStream.toByteArray());
}
catch (MessagingException ex) { throw new RuntimeException(ex); }
catch (IOException ex) { throw new RuntimeException(ex); }
return toList.getId();
}
private SubEthaMessage craftMessage(MailingList toList, String fromAddress, String fromName, String subject, String body, boolean reply)
throws MessagingException, IOException
{
Session session = Session.getDefaultInstance(new Properties());
SubEthaMessage sm = new SubEthaMessage(session);
sm.setFrom(new InternetAddress(fromAddress, fromName));
sm.setRecipient(RecipientType.TO, new InternetAddress(toList.getEmail()));;
sm.setSubject(subject);
sm.setContent(body, "text/plain");
return sm;
}
/* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#exportMessages(java.lang.Long[], org.subethamail.core.lists.i.ExportFormat, java.io.OutputStream)
*/
public void exportMessages(Long[] msgIds, ExportFormat format, OutputStream outStream) throws NotFoundException, PermissionException, ExportMessagesException
{
if(ExportFormat.XML.equals(format))
throw new ExportMessagesException("The XML format is supported, for now.");
ZipOutputStream zipOutputStream = null;
if(ExportFormat.RFC2822DIRECTORY.equals(format))
{
CheckedOutputStream checksum = new CheckedOutputStream(outStream, new Adler32());
zipOutputStream = new ZipOutputStream(new BufferedOutputStream(checksum));
}
try
{
for (int i = 0; i < msgIds.length; i++)
{
Long msgId = msgIds[i];
Mail mail = this.getMailFor(msgId, Permission.VIEW_ARCHIVES);
switch (format)
{
case RFC2822DIRECTORY:
ZipEntry entry = new ZipEntry(msgId.toString() + ".eml");
entry.setComment("Message from " + mail.getFrom() + " for list " + mail.getList().getEmail());
entry.setTime(mail.getArrivalDate().getTime());
zipOutputStream.putNextEntry(entry);
writeMessage(mail, zipOutputStream);
zipOutputStream.closeEntry();
break;
case MBOX:
outStream.write(("FROM_ " + mail.getFrom()).getBytes());
outStream.write("\r\n".getBytes());
writeMessage(mail, outStream);
outStream.write("\r\n\r\n".getBytes());
break;
default:
throw new ExportMessagesException("Unsupported Format!" + format.toString());
// break;
}
}
switch (format)
{
case RFC2822DIRECTORY:
zipOutputStream.close();
break;
}
}
catch (Exception e)
{
throw new ExportMessagesException("Error:" + e.getMessage());
}
}
/* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#exportList(java.lang.Long, org.subethamail.core.lists.i.ExportFormat, java.io.OutputStream)
*/
public void exportList(Long listId, ExportFormat format, OutputStream outStream) throws NotFoundException, PermissionException, ExportMessagesException
{
List<Mail> mails = this.em.findMailByList(listId, 0, Integer.MAX_VALUE);
Stack<Long> mailIds = new Stack<Long>();
for (Mail mail : mails)
{
mailIds.add(mail.getId());
}
exportMessages(mailIds.toArray(new Long[] {}), format, outStream);
}
}
|
package hudson.model;
import junit.framework.TestCase;
import java.util.Random;
/**
* @author Stephen Connolly
*/
public class ResourceListTest extends TestCase {
private Resource a1, a2, a3, a4, a;
private Resource b1, b2, b3, b4, b;
private Resource c1, c2, c3, c4, c;
private Resource d, e, f;
private int fWriteCount;
private Random entropy;
private ResourceList x;
private ResourceList y;
private ResourceList z;
public void setUp() {
entropy = new Random();
a = new Resource("A" + entropy.nextLong());
a1 = new Resource(a, "A" + entropy.nextLong());
a2 = new Resource(a, "A" + entropy.nextLong());
a3 = new Resource(a, "A" + entropy.nextLong());
a4 = new Resource(a, "A" + entropy.nextLong());
b = new Resource("B" + entropy.nextLong());
b1 = new Resource(b, "B" + entropy.nextLong());
b2 = new Resource(b, "B" + entropy.nextLong());
b3 = new Resource(b, "B" + entropy.nextLong());
b4 = new Resource(b, "B" + entropy.nextLong());
c = new Resource(null, "C" + entropy.nextLong(), 3);
c1 = new Resource(c, "C" + entropy.nextLong(), 3);
c2 = new Resource(c, "C" + entropy.nextLong(), 3);
c3 = new Resource(c, "C" + entropy.nextLong(), 3);
c4 = new Resource(c, "C" + entropy.nextLong(), 3);
d = new Resource("D" + entropy.nextLong());
e = new Resource(null, "E" + entropy.nextLong());
fWriteCount = 5 + entropy.nextInt(100);
f = new Resource(null, "F" + entropy.nextLong(), 5);
x = new ResourceList();
y = new ResourceList();
z = new ResourceList();
}
public void testEmptyLists() throws Exception {
z.r(a);
ResourceList w = new ResourceList();
w.w(a);
assertFalse("Empty vs Empty", x.isCollidingWith(y));
assertFalse("Empty vs Empty", y.isCollidingWith(x));
assertFalse("Empty vs Read", x.isCollidingWith(z));
assertFalse("Read vs Empty", z.isCollidingWith(x));
assertFalse("Empty vs Write", x.isCollidingWith(w));
assertFalse("Write vs Empty", w.isCollidingWith(x));
}
public void testSimpleR() throws Exception {
x.r(a);
y.r(b);
z.r(a);
assertFalse("Read-Read", x.isCollidingWith(y));
assertFalse("Read-Read", y.isCollidingWith(x));
assertFalse("Read-Read", x.isCollidingWith(z));
assertFalse("Read-Read", z.isCollidingWith(x));
assertFalse("Read-Read", z.isCollidingWith(y));
assertFalse("Read-Read", y.isCollidingWith(z));
}
public void testSimpleRW() throws Exception {
x.r(a);
y.r(b);
z.w(a);
assertFalse("Read-Read different resources", x.isCollidingWith(y));
assertFalse("Read-Read different resources", y.isCollidingWith(x));
assertTrue("Read-Write same resource", x.isCollidingWith(z));
assertTrue("Read-Write same resource", z.isCollidingWith(x));
assertFalse("Read-Write different resources", z.isCollidingWith(y));
assertFalse("Read-Write different resources", y.isCollidingWith(z));
}
public void testSimpleW() throws Exception {
x.w(a);
y.w(b);
z.w(a);
assertFalse(x.isCollidingWith(y));
assertFalse(y.isCollidingWith(x));
assertTrue(x.isCollidingWith(z));
assertTrue(z.isCollidingWith(x));
assertFalse(z.isCollidingWith(y));
assertFalse(y.isCollidingWith(z));
ResourceList w = x.union(y);
assertTrue(w.isCollidingWith(z));
assertTrue(z.isCollidingWith(w));
ResourceList v = new ResourceList();
v.w(a1);
assertTrue(w.isCollidingWith(v));
assertTrue(z.isCollidingWith(w));
}
public void testParentChildR() throws Exception {
x.r(a1);
x.r(a2);
y.r(a3);
y.r(a4);
z.r(a);
assertFalse("Reads should never conflict", x.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(x));
assertFalse("Reads should never conflict", x.isCollidingWith(z));
assertFalse("Reads should never conflict", z.isCollidingWith(x));
assertFalse("Reads should never conflict", z.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(z));
}
public void testParentChildW() throws Exception {
x.w(a1);
x.w(a2);
y.w(a3);
y.w(a4);
z.w(a);
assertFalse("Sibling resources should not conflict", x.isCollidingWith(y));
assertFalse("Sibling resources should not conflict", y.isCollidingWith(x));
assertTrue("Taking parent resource assumes all children are taken too", x.isCollidingWith(z));
assertTrue("Taking parent resource assumes all children are taken too", z.isCollidingWith(x));
assertTrue("Taking parent resource assumes all children are taken too", z.isCollidingWith(y));
assertTrue("Taking parent resource assumes all children are taken too", y.isCollidingWith(z));
}
public void testParentChildR3() throws Exception {
x.r(c1);
x.r(c2);
y.r(c3);
y.r(c4);
z.r(c);
assertFalse("Reads should never conflict", x.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(x));
assertFalse("Reads should never conflict", x.isCollidingWith(z));
assertFalse("Reads should never conflict", z.isCollidingWith(x));
assertFalse("Reads should never conflict", z.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(z));
}
public void testParentChildW3() throws Exception {
x.w(c1);
x.w(c2);
y.w(c3);
y.w(c4);
z.w(c);
assertFalse("Sibling resources should not conflict", x.isCollidingWith(y));
assertFalse("Sibling resources should not conflict", y.isCollidingWith(x));
assertFalse("Using less than the limit of child resources should not be a problem", x.isCollidingWith(z));
assertFalse("Using less than the limit of child resources should not be a problem", z.isCollidingWith(x));
assertFalse("Using less than the limit of child resources should not be a problem", z.isCollidingWith(y));
assertFalse("Using less than the limit of child resources should not be a problem", y.isCollidingWith(z));
ResourceList w = x.union(y);
assertFalse("Using less than the limit of child resources should not be a problem", w.isCollidingWith(z));
assertFalse("Using less than the limit of child resources should not be a problem", z.isCollidingWith(w));
assertFalse("Total count = 2, limit is 3", w.isCollidingWith(x));
assertFalse("Total count = 2, limit is 3", x.isCollidingWith(w));
ResourceList v = x.union(x); // write count is two
assertFalse("Total count = 3, limit is 3", v.isCollidingWith(x));
assertFalse("Total count = 3, limit is 3", x.isCollidingWith(v));
v = v.union(x); // write count is three
assertTrue("Total count = 4, limit is 3", v.isCollidingWith(x));
assertTrue("Total count = 4, limit is 3", x.isCollidingWith(v));
}
public void testMultiWrite1() throws Exception {
y.w(e);
for (int i = 0; i < fWriteCount; i++) {
assertTrue("Total = W" + (i + 1) + ", Limit = W1", x.isCollidingWith(y));
assertTrue("Total = W" + (i + 1) + ", Limit = W1", y.isCollidingWith(x));
x.w(e);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertTrue("Total = W" + (i + fWriteCount) + ", Limit = W1", x.isCollidingWith(y));
assertTrue("Total = W" + (i + fWriteCount) + ", Limit = W1", y.isCollidingWith(x));
x.w(e);
}
}
public void testMultiWriteN() throws Exception {
y.w(f);
for (int i = 0; i < fWriteCount; i++) {
assertFalse("Total = W" + (i + 1) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertFalse("Total = W" + (i + 1) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
x.w(f);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertTrue("Total = W" + (fWriteCount + i) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertTrue("Total = W" + (fWriteCount + i) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
x.w(f);
}
}
public void testMultiRead1() throws Exception {
y.r(e);
for (int i = 0; i < fWriteCount; i++) {
assertFalse("Total = R" + (i + 1) + ", Limit = W1", x.isCollidingWith(y));
assertFalse("Total = R" + (i + 1) + ", Limit = W1", y.isCollidingWith(x));
x.r(e);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertFalse("Total = R" + (i + fWriteCount) + ", Limit = W1", x.isCollidingWith(y));
assertFalse("Total = R" + (i + fWriteCount) + ", Limit = W1", y.isCollidingWith(x));
x.r(e);
}
}
public void testMultiReadN() throws Exception {
y.r(f);
for (int i = 0; i < fWriteCount; i++) {
assertFalse("Total = R" + (i + 1) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertFalse("Total = R" + (i + 1) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
x.r(f);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertFalse("Total = R" + (fWriteCount + i) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertFalse("Total = R" + (fWriteCount + i) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
x.r(f);
}
}
}
|
package imagej.ui;
import imagej.InstantiableException;
import imagej.command.CommandService;
import imagej.data.display.ImageDisplay;
import imagej.display.Display;
import imagej.display.DisplayService;
import imagej.display.event.DisplayActivatedEvent;
import imagej.display.event.DisplayCreatedEvent;
import imagej.display.event.DisplayDeletedEvent;
import imagej.display.event.DisplayUpdatedEvent;
import imagej.event.EventHandler;
import imagej.event.EventService;
import imagej.event.StatusService;
import imagej.log.LogService;
import imagej.menu.MenuService;
import imagej.options.OptionsService;
import imagej.platform.AppService;
import imagej.platform.PlatformService;
import imagej.platform.event.AppQuitEvent;
import imagej.plugin.Parameter;
import imagej.plugin.Plugin;
import imagej.plugin.PluginInfo;
import imagej.plugin.PluginService;
import imagej.service.AbstractService;
import imagej.service.Service;
import imagej.thread.ThreadService;
import imagej.tool.ToolService;
import imagej.ui.DialogPrompt.MessageType;
import imagej.ui.DialogPrompt.OptionType;
import imagej.ui.DialogPrompt.Result;
import imagej.ui.viewer.DisplayViewer;
import imagej.ui.viewer.DisplayWindow;
import imagej.ui.viewer.ImageDisplayViewer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Default service for handling ImageJ user interfaces.
*
* @author Curtis Rueden
*/
@Plugin(type = Service.class)
public final class DefaultUIService extends AbstractService implements
UIService
{
@Parameter
private LogService log;
@Parameter
private EventService eventService;
@Parameter
private StatusService statusService;
@Parameter
private ThreadService threadService;
@Parameter
private PlatformService platformService;
@Parameter
private PluginService pluginService;
@Parameter
private CommandService commandService;
@Parameter
private MenuService menuService;
@Parameter
private ToolService toolService;
@Parameter
private OptionsService optionsService;
@Parameter
private AppService appService;
/**
* A list of extant display viewers. It's needed in order to find the viewer
* associated with a display.
*/
private List<DisplayViewer<?>> displayViewers;
/** List of available user interfaces, ordered by priority. */
private List<UserInterface> uiList;
/** Map of available user interfaces, keyed off their names. */
private Map<String, UserInterface> uiMap;
/** The default user interface to use, if one is not explicitly specified. */
private UserInterface defaultUI;
private boolean activationInvocationPending = false;
// -- UIService methods --
@Override
public LogService getLog() {
return log;
}
@Override
public ThreadService getThreadService() {
return threadService;
}
@Override
public EventService getEventService() {
return eventService;
}
@Override
public StatusService getStatusService() {
return statusService;
}
@Override
public PlatformService getPlatformService() {
return platformService;
}
@Override
public PluginService getPluginService() {
return pluginService;
}
@Override
public CommandService getCommandService() {
return commandService;
}
@Override
public MenuService getMenuService() {
return menuService;
}
@Override
public ToolService getToolService() {
return toolService;
}
@Override
public OptionsService getOptionsService() {
return optionsService;
}
@Override
public AppService getAppService() {
return appService;
}
@Override
public void addUI(final UserInterface ui) {
addUI(null, ui);
}
@Override
public void addUI(final String name, final UserInterface ui) {
// add to UI list
uiList.add(ui);
// add to UI map
uiMap.put(ui.getClass().getName(), ui);
if (name != null && !name.isEmpty()) uiMap.put(name, ui);
}
@Override
public void createUI() {
final UserInterface ui = getDefaultUI();
if (ui == null) {
throw new IllegalStateException("No UIs available.");
}
createUI(ui);
}
@Override
public void createUI(final String name) {
final UserInterface ui = uiMap.get(name);
if (ui == null) {
throw new IllegalArgumentException("No such user interface: " + name);
}
createUI(ui);
}
@Override
public void createUI(final UserInterface ui) {
log.info("Launching user interface: " + ui.getClass().getName());
ui.show();
}
@Override
public boolean isVisible() {
final UserInterface ui = getDefaultUI();
if (ui == null) {
throw new IllegalStateException("No UIs available.");
}
return ui.isVisible();
}
@Override
public boolean isVisible(final String name) {
final UserInterface ui = uiMap.get(name);
if (ui == null) {
throw new IllegalArgumentException("No such user interface: " + name);
}
return ui.isVisible();
}
@Override
public UserInterface getDefaultUI() {
return defaultUI;
}
@Override
public void setDefaultUI(final UserInterface ui) {
defaultUI = ui;
}
@Override
public UserInterface getUI(final String name) {
return uiMap.get(name);
}
@Override
public List<UserInterface> getAvailableUIs() {
return Collections.unmodifiableList(uiList);
}
@Override
public List<UserInterface> getVisibleUIs() {
final ArrayList<UserInterface> uis = new ArrayList<UserInterface>();
for (final UserInterface ui : uiList) {
if (ui.isVisible()) uis.add(ui);
}
return uis;
}
@Override
public DisplayViewer<?> getDisplayViewer(final Display<?> display) {
for (final DisplayViewer<?> displayViewer : displayViewers) {
if (displayViewer.getDisplay() == display) return displayViewer;
}
log.warn("No viewer found for display: '" + display.getName() + "'");
return null;
}
@Override
public ImageDisplayViewer getImageDisplayViewer(final ImageDisplay display) {
for (final DisplayViewer<?> displayViewer : displayViewers) {
if (displayViewer.getDisplay() == display)
if (displayViewer instanceof ImageDisplayViewer)
return (ImageDisplayViewer) displayViewer;
}
log.warn("No image viewer found for display: '" + display.getName() + "'");
return null;
}
@Override
public OutputWindow createOutputWindow(final String title) {
final UserInterface ui = getDefaultUI();
if (ui == null) return null;
return ui.newOutputWindow(title);
}
@Override
public DialogPrompt.Result showDialog(final String message) {
return showDialog(message, getContext().getTitle());
}
@Override
public Result showDialog(String message, MessageType messageType) {
return showDialog(message, getContext().getTitle(), messageType);
}
@Override
public Result showDialog(String message, MessageType messageType,
OptionType optionType)
{
return showDialog(message, getContext().getTitle(), messageType, optionType);
}
@Override
public DialogPrompt.Result showDialog(final String message,
final String title)
{
return showDialog(message, title,
DialogPrompt.MessageType.INFORMATION_MESSAGE);
}
@Override
public DialogPrompt.Result showDialog(final String message,
final String title, final DialogPrompt.MessageType messageType)
{
return showDialog(message, title, messageType,
DialogPrompt.OptionType.DEFAULT_OPTION);
}
@Override
public DialogPrompt.Result showDialog(final String message,
final String title, final DialogPrompt.MessageType messageType,
final DialogPrompt.OptionType optionType)
{
final UserInterface ui = getDefaultUI();
if (ui == null) return null;
final DialogPrompt dialogPrompt =
ui.dialogPrompt(message, title, messageType, optionType);
return dialogPrompt.prompt();
}
@Override
public void showContextMenu(final String menuRoot, final Display<?> display,
final int x, final int y)
{
final UserInterface ui = getDefaultUI();
if (ui == null) return;
ui.showContextMenu(menuRoot, display, x, y);
}
// -- Service methods --
@Override
public void initialize() {
displayViewers = new ArrayList<DisplayViewer<?>>();
uiList = new ArrayList<UserInterface>();
uiMap = new HashMap<String, UserInterface>();
discoverUIs();
subscribeToEvents(eventService);
}
// -- Event handlers --
/**
* Called when a display is created. This is the magical place where the
* display model is connected with the real UI.
*/
@EventHandler
protected void onEvent(final DisplayCreatedEvent e) {
final Display<?> display = e.getObject();
@SuppressWarnings({ "rawtypes", "unchecked" })
final List<PluginInfo<DisplayViewer<?>>> viewers = (List)
pluginService.getPluginsOfType(DisplayViewer.class);
for (final UserInterface ui : getVisibleUIs()) {
DisplayViewer<?> displayViewer = null;
for (final PluginInfo<DisplayViewer<?>> info : viewers) {
// check that viewer can actually handle the given display
try {
final DisplayViewer<?> viewer = info.createInstance();
viewer.setContext(getContext());
viewer.setPriority(info.getPriority());
if (!viewer.canView(display)) continue;
if (!viewer.isCompatible(ui)) continue;
displayViewer = viewer;
break; // found a suitable viewer; move on to the next UI
}
catch (final InstantiableException exc) {
log.warn("Failed to create instance of " + info.getClassName(), exc);
}
}
if (displayViewer == null) {
log.warn("For UI '" + ui.getClass().getName() +
"': no suitable viewer for display");
}
else {
final DisplayWindow displayWindow =
getDefaultUI().createDisplayWindow(display);
displayViewer.view(displayWindow, display);
displayWindow.setTitle(display.getName());
displayViewers.add(displayViewer);
displayWindow.showDisplay(true);
}
}
}
/**
* Called when a display is deleted. The display viewer is not removed
* from the list of viewers until after this returns.
*/
@EventHandler
protected void onEvent(final DisplayDeletedEvent e) {
final Display<?> display = e.getObject();
final DisplayViewer<?> displayViewer = getDisplayViewer(display);
if (displayViewer != null) {
displayViewer.onDisplayDeletedEvent(e);
displayViewers.remove(displayViewer);
}
}
/** Called when a display is updated. */
@EventHandler
protected void onEvent(final DisplayUpdatedEvent e) {
final Display<?> display = e.getDisplay();
final DisplayViewer<?> displayViewer = getDisplayViewer(display);
if (displayViewer != null) {
displayViewer.onDisplayUpdatedEvent(e);
}
}
/**
* Called when a display is activated.
* <p>
* The goal here is to eventually synchronize the window activation state with
* the display activation state if the display activation state changed
* programmatically. We queue a call on the UI thread to activate the display
* viewer of the currently active window.
* </p>
*/
@EventHandler
protected void onEvent(final DisplayActivatedEvent e) {
// CTR FIXME: Verify whether this threading logic is really necessary.
if (activationInvocationPending) return;
activationInvocationPending = true;
threadService.queue(new Runnable() {
@Override
public void run() {
final DisplayService displayService =
e.getContext().getService(DisplayService.class);
final Display<?> activeDisplay = displayService.getActiveDisplay();
if (activeDisplay != null) {
final DisplayViewer<?> displayViewer =
getDisplayViewer(activeDisplay);
if (displayViewer != null) displayViewer.onDisplayActivatedEvent(e);
}
activationInvocationPending = false;
}
});
}
@EventHandler
protected void onEvent(@SuppressWarnings("unused") final AppQuitEvent event) {
// FIXME: Why only the default one? Move to AbstractUserInterface!
final UserInterface ui = getDefaultUI();
ui.saveLocation();
}
// -- Helper methods --
/** Discovers available user interfaces. */
private void discoverUIs() {
final List<PluginInfo<UserInterface>> infos =
pluginService.getPluginsOfType(UserInterface.class);
for (final PluginInfo<UserInterface> info : infos) {
try {
// instantiate user interface
final UserInterface ui = info.createInstance();
ui.setContext(getContext());
ui.setPriority(info.getPriority());
log.info("Discovered user interface: " + ui.getClass().getName());
addUI(info.getName(), ui);
}
catch (final InstantiableException e) {
log.warn("Invalid user interface: " + info.getClassName(), e);
}
}
// check system property for explicit UI preference
final String uiProp = System.getProperty(UI_PROPERTY);
final UserInterface ui = uiMap.get(uiProp);
if (ui != null) {
// set the default UI to the one provided by the system property
setDefaultUI(ui);
}
else if (uiList.size() > 0) {
// set the default UI to the one with the highest priority
setDefaultUI(uiList.get(0));
}
}
@Override
public boolean isDefaultUI(final String name) {
return getDefaultUI() == getUI(name);
}
}
|
package cl.fatman.capital.fund;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.log4j.Logger;
import java.util.List;
public class PersistenceData {
private static final PersistenceData INSTANCE = new PersistenceData();
private EntityManagerFactory entityManagerFactory;
static final Logger logger = Logger.getLogger(PersistenceData.class);
private PersistenceData() {
}
public static PersistenceData getInstance() {
return INSTANCE;
}
public void setUp() {
logger.debug("setUp()");
try {
logger.debug("Creating EntityManagerFactory.");
entityManagerFactory = Persistence.createEntityManagerFactory("cl.fatman.capital.fund.jpa");
logger.debug("EntityManagerFactory successfully created.");
}
catch (Exception e) {
logger.error("Problem in the EntityManagerFactory creation.", e);
}
}
public void tearDown() {
logger.debug("tearDown()");
try {
logger.debug("Closing the EntityManagerFactory.");
entityManagerFactory.close();
logger.debug("EntityManagerFactory successfully closed.");
}
catch (Exception e) {
logger.error("Problem in the EntityManagerFactory closing.", e);
}
}
public void insertObjectList(List<?> objectList) {
logger.debug("insertObjectList(List<?> objectList)");
EntityManager entityManager = null;
try {
logger.debug("Creating a new EntityManager.");
entityManager = entityManagerFactory.createEntityManager();
logger.debug("Beginning a new transaction.");
entityManager.getTransaction().begin();
for (Object object: objectList) {
logger.debug("Saving object.");
entityManager.persist(object);
}
logger.debug("Committing and closing the transaction.");
entityManager.getTransaction().commit();
logger.debug("Object list successfully stored.");
}
catch (Exception e) {
if (entityManager != null && entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
logger.debug("Finish transaction rollback.");
}
logger.error("Problem storing the object list.", e);
}
finally {
if (entityManager != null && entityManager.isOpen()) {
entityManager.close();
logger.debug("EntityManager closed.");
}
}
}
public List<?> selectAllObjects(String fromTable, Class<?> resultClass) {
logger.debug("selectAllObjects()");
List<?> resultList = null;
EntityManager entityManager = null;
try {
logger.debug("Opening a new EntityManager.");
entityManager = entityManagerFactory.createEntityManager();
logger.debug("Beginning a new transaction.");
entityManager.getTransaction().begin();
logger.debug("Executing query: " + fromTable);
resultList = entityManager.createQuery(fromTable, resultClass).getResultList();
logger.debug("Committing and closing the transaction.");
entityManager.getTransaction().commit();
logger.debug("Object list retrieved successfully.");
}
catch (Exception e) {
if (entityManager != null && entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
logger.error("Finish transaction rollback.");
}
logger.error("Problem retrieving object list.", e);
resultList = null;
}
finally {
if (entityManager != null && entityManager.isOpen()) {
entityManager.close();
logger.debug("EntityManager closed.");
}
}
return resultList;
}
public List<?> getFundByType(FundType type) {
logger.debug("selectFundByType(FundType type)");
List<?> resultList = null;
EntityManager entityManager = null;
try {
logger.debug("Opening a new EntityManager.");
entityManager = entityManagerFactory.createEntityManager();
logger.debug("Beginning a new transaction.");
entityManager.getTransaction().begin();
logger.debug("Executing query: get_fund_by_type");
Query query = entityManager.createNamedQuery("get_fund_by_type");
query.setParameter("type", type);
resultList = query.getResultList();
logger.debug("Committing and closing the transaction.");
entityManager.getTransaction().commit();
logger.debug("Object list retrieved successfully.");
}
catch (Exception e) {
if (entityManager != null && entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
logger.debug("Finish transaction rollback.");
}
logger.error("Problem retrieving Fund object.", e);
resultList = null;
}
finally {
if (entityManager != null && entityManager.isOpen()) {
entityManager.close();
logger.debug("EntityManager closed.");
}
}
return resultList;
}
public List<?> getUpdateDate() {
logger.debug("getUpdateDate()");
List<?> resultList = null;
EntityManager entityManager = null;
try {
logger.debug("Opening a new EntityManager.");
entityManager = entityManagerFactory.createEntityManager();
logger.debug("Beginning a new transaction.");
entityManager.getTransaction().begin();
logger.debug("Executing query: get_update_date");
Query query = entityManager.createNamedQuery("get_update_date");
resultList = query.getResultList();
logger.debug("Committing and closing the transaction.");
entityManager.getTransaction().commit();
logger.debug("Object list retrieved successfully.");
}
catch (Exception e) {
if (entityManager != null && entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
logger.debug("Finish transaction rollback.");
}
logger.error("Problem retrieving Fund object.", e);
resultList = null;
}
finally {
if (entityManager != null && entityManager.isOpen()) {
entityManager.close();
logger.debug("EntityManager closed.");
}
}
return resultList;
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app;
import static processing.app.I18n._;
import java.io.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import processing.app.helpers.PreferencesMap;
/**
* run/stop/etc buttons for the ide
*/
public class EditorToolbar extends JComponent implements MouseInputListener, KeyListener {
/** Rollover titles for each button. */
static final String title[] = {
_("Verify"), _("Upload"), _("New"), _("Open"), _("Save"), _("Serial Monitor"), _("Logic Analyzer"), _("Papilio Loader"), _("Virtual Instruments") , _("New Papilio Project"), _("Load Circuit"), _("View Circuit"), _("Edit Circuit")
};
/** Titles for each button when the shift key is pressed. */
static final String titleShift[] = {
_("Verify"), _("Upload Using Programmer"), _("New Editor Window"), _("Open in Another Window"), _("Save"), _("Serial Monitor")
};
/** Titles for each button when the control key is pressed. */
static final String titleControl[] = {
"Verify", "Upload To Memory", "New", "Open", "Save", "Serial Monitor"
};
static final int BUTTON_COUNT = title.length;
/** Width of each toolbar button. */
static final int BUTTON_WIDTH = 27;
/** Height of each toolbar button. */
static final int BUTTON_HEIGHT = 32;
/** The amount of space between groups of buttons on the toolbar. */
static final int BUTTON_GAP = 10;
/** Size of the button image being chopped up. */
static final int BUTTON_IMAGE_SIZE = 33;
static final int RUN = 0;
static final int EXPORT = 1;
static final int NEW = 2;
static final int OPEN = 3;
static final int SAVE = 4;
static final int SERIAL = 5;
//dhia
static final int OLS = 6;
static final int PAPILIO = 7;
static final int VIRTUAL_INSTRUMENTS = 8;
static final int NEW_PROJECT = 9;
static final int LOAD_CIRCUIT = 10;
static final int VIEW_CIRCUIT = 11;
static final int EDIT_CIRCUIT = 12;
static final int INACTIVE = 0;
static final int ROLLOVER = 1;
static final int ACTIVE = 2;
Editor editor;
Image offscreen;
int width, height;
Color bgcolor;
static Image[][] buttonImages;
int currentRollover;
JPopupMenu popup;
JMenu menu;
int buttonCount;
int[] state = new int[BUTTON_COUNT];
Image[] stateImage;
int which[]; // mapping indices to implementation
int x1[], x2[];
int y1, y2;
Font statusFont;
Color statusColor;
boolean shiftPressed, controlPressed;
public EditorToolbar(Editor editor, JMenu menu) {
this.editor = editor;
this.menu = menu;
buttonCount = 0;
which = new int[BUTTON_COUNT];
//which[buttonCount++] = NOTHING;
which[buttonCount++] = RUN;
which[buttonCount++] = EXPORT;
which[buttonCount++] = NEW;
which[buttonCount++] = OPEN;
which[buttonCount++] = SAVE;
which[buttonCount++] = SERIAL;
//dhia
which[buttonCount++] = OLS;
which[buttonCount++] = PAPILIO;
which[buttonCount++] = VIRTUAL_INSTRUMENTS;
which[buttonCount++] = NEW_PROJECT;
which[buttonCount++] = LOAD_CIRCUIT;
which[buttonCount++] = VIEW_CIRCUIT;
which[buttonCount++] = EDIT_CIRCUIT;
currentRollover = -1;
bgcolor = Theme.getColor("buttons.bgcolor");
statusFont = Theme.getFont("buttons.status.font");
statusColor = Theme.getColor("buttons.status.color");
addMouseListener(this);
addMouseMotionListener(this);
}
protected void loadButtons() {
Image allButtons = Base.getThemeImage("buttons.gif", this);
buttonImages = new Image[BUTTON_COUNT][3];
for (int i = 0; i < BUTTON_COUNT; i++) {
if (i == 6) //skip the tools for now
i = 9;
for (int state = 0; state < 3; state++) {
Image image = createImage(BUTTON_WIDTH, BUTTON_HEIGHT);
Graphics g = image.getGraphics();
g.drawImage(allButtons,
-(i*BUTTON_IMAGE_SIZE) - 3,
(-2 + state)*BUTTON_IMAGE_SIZE, null);
buttonImages[i][state] = image;
}
}
}
@Override
public void paintComponent(Graphics screen) {
// this data is shared by all EditorToolbar instances
if (buttonImages == null) {
loadButtons();
}
// this happens once per instance of EditorToolbar
if (stateImage == null) {
state = new int[buttonCount];
stateImage = new Image[buttonCount];
for (int i = 0; i < buttonCount; i++) {
setState(i, INACTIVE, false);
}
y1 = 0;
y2 = BUTTON_HEIGHT;
x1 = new int[buttonCount];
x2 = new int[buttonCount];
}
Dimension size = getSize();
if ((offscreen == null) ||
(size.width != width) || (size.height != height)) {
offscreen = createImage(size.width, size.height);
width = size.width;
height = size.height;
int offsetX = 3;
for (int i = 0; i < buttonCount; i++) {
if (i == 6) //skip the tools for now
i = 9;
x1[i] = offsetX;
if (i == 2 || i == 6 || i == 9 || i ==10) x1[i] += BUTTON_GAP;
x2[i] = x1[i] + BUTTON_WIDTH;
offsetX = x2[i];
}
// Serial button must be on the right
x1[SERIAL] = width - BUTTON_WIDTH - 14;
x2[SERIAL] = width - 14;
// x1[DHIA] = width - BUTTON_WIDTH - 60;
// x2[DHIA] = width - 60;
}
Graphics g = offscreen.getGraphics();
g.setColor(bgcolor); //getBackground());
g.fillRect(0, 0, width, height);
for (int i = 0; i < buttonCount; i++) {
g.drawImage(stateImage[i], x1[i], y1, null);
}
g.setColor(statusColor);
g.setFont(statusFont);
/*
// if i ever find the guy who wrote the java2d api, i will hurt him.
*
* whereas I love the Java2D API. --jdf. lol.
*
Graphics2D g2 = (Graphics2D) g;
FontRenderContext frc = g2.getFontRenderContext();
float statusW = (float) statusFont.getStringBounds(status, frc).getWidth();
float statusX = (getSize().width - statusW) / 2;
g2.drawString(status, statusX, statusY);
*/
if (currentRollover != -1) {
int statusY = (BUTTON_HEIGHT + g.getFontMetrics().getAscent()) / 2;
String status = controlPressed ? titleControl[currentRollover] :
shiftPressed ? titleShift[currentRollover] : title[currentRollover];
if (currentRollover != SERIAL)
//by dhia
//g.drawString(status, (buttonCount-1) * BUTTON_WIDTH + 10 * BUTTON_GAP, statusY);
g.drawString(status, (buttonCount-5) * BUTTON_WIDTH + 10 * BUTTON_GAP, statusY);
else {
int statusX = x1[SERIAL] - BUTTON_GAP;
statusX -= g.getFontMetrics().stringWidth(status);
g.drawString(status, statusX, statusY);
}
}
screen.drawImage(offscreen, 0, 0, null);
if (!isEnabled()) {
screen.setColor(new Color(0,0,0,100));
screen.fillRect(0, 0, getWidth(), getHeight());
}
}
public void mouseMoved(MouseEvent e) {
if (!isEnabled())
return;
// mouse events before paint();
if (state == null) return;
if (state[OPEN] != INACTIVE) {
// avoid flicker, since there will probably be an update event
setState(OPEN, INACTIVE, false);
}
handleMouse(e);
}
public void mouseDragged(MouseEvent e) { }
public void handleMouse(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if (currentRollover != -1) {
if ((x > x1[currentRollover]) && (y > y1) &&
(x < x2[currentRollover]) && (y < y2)) {
return;
} else {
setState(currentRollover, INACTIVE, true);
currentRollover = -1;
}
}
int sel = findSelection(x, y);
if (sel == -1) return;
if (state[sel] != ACTIVE) {
setState(sel, ROLLOVER, true);
currentRollover = sel;
}
}
private int findSelection(int x, int y) {
// if app loads slowly and cursor is near the buttons
// when it comes up, the app may not have time to load
if ((x1 == null) || (x2 == null)) return -1;
for (int i = 0; i < buttonCount; i++) {
if ((y > y1) && (x > x1[i]) &&
(y < y2) && (x < x2[i])) {
//System.out.println("sel is " + i);
return i;
}
}
return -1;
}
private void setState(int slot, int newState, boolean updateAfter) {
state[slot] = newState;
stateImage[slot] = buttonImages[which[slot]][newState];
if (updateAfter) {
repaint();
}
}
public void mouseEntered(MouseEvent e) {
handleMouse(e);
}
public void mouseExited(MouseEvent e) {
// if the popup menu for is visible, don't register this,
// because the popup being set visible will fire a mouseExited() event
if ((popup != null) && popup.isVisible()) return;
if (state[OPEN] != INACTIVE) {
setState(OPEN, INACTIVE, true);
}
handleMouse(e);
}
int wasDown = -1;
public void mousePressed(MouseEvent e) {
// jdf
if (!isEnabled())
return;
final int x = e.getX();
final int y = e.getY();
int sel = findSelection(x, y);
///if (sel == -1) return false;
if (sel == -1) return;
currentRollover = -1;
PreferencesMap prefs = Preferences.getMap();
prefs.putAll(Base.getBoardPreferences());
switch (sel) {
case RUN:
editor.handleRun(false);
break;
// case STOP:
// editor.handleStop();
// break;
case OPEN:
popup = menu.getPopupMenu();
popup.show(EditorToolbar.this, x, y);
break;
case NEW:
if (shiftPressed) {
try {
editor.base.handleNew();
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
editor.base.handleNewReplace();
}
break;
case SAVE:
editor.handleSave(false);
break;
case EXPORT:
if (e.isShiftDown())
editor.handleExport(Editor.uploadUsingProgrammer);
else if (e.isControlDown())
editor.handleExport(Editor.uploadToMemory);
else
editor.handleExport(Editor.uploadNormal);
break;
case SERIAL:
editor.handleSerial();
break;
//by dhia
case PAPILIO:
Base.openURL(_("tools://Papilio_Loader.sh"));
break;
case OLS:
Base.openURL(_("tools://Logic_Analyzer.sh"));
break;
case VIRTUAL_INSTRUMENTS:
Base.openURL(_("tools://Logic_Analyzer.sh"));
break;
case NEW_PROJECT:
try {
String pslPath = Base.getExamplesPath();
File f1 = new File(pslPath+"/Template_PSL_Base/Template_PSL_Base.ino");
Editor newproj = Base.activeEditor.base.handleOpen(f1);
newproj.handlesaveAtStart(false);
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case LOAD_CIRCUIT:
File fileBit = getLibraryFile("#define\\s+circuit", "bit.file");
File fileSch = getLibraryFile("#define\\s+circuit", "sch.file");
if (fileBit.exists()) {
long dateSch = fileSch.lastModified();
long dateBitfile = fileBit.lastModified();
long currentTime = java.lang.System.currentTimeMillis();
if ((dateSch > (currentTime - 86400000)) && (dateSch > dateBitfile)) //If the schematic has been modified in the last 24 hours and the schematic is newer then bit file.
Base.showMessage("Warning!", "The Xilinx Schematic file is newer then the BitFile that contains the circuit. Did you forget to run \"Generate Programming File\" after modifying the circuit?");
Base.openURL("file://" + fileBit.toString());
}
else
Base.showMessage("Not Found", "Sorry, no bit file found in the libraries or project directory.");
break;
case VIEW_CIRCUIT:
File filePdf = getLibraryFile("#define\\s+circuit", "pdf.file");
File fileBit2 = getLibraryFile("#define\\s+circuit", "bit.file");
if (filePdf.exists()) {
long datePDF = filePdf.lastModified();
long dateBit = fileBit2.lastModified();
if (dateBit > datePDF)
Base.showMessage("Warning!", "The circuit defined by the bit file is newer then the view in this PDF file. This view of the circuit may not be correct, please edit the circuit for an accurate view.");
Base.openURL("file://" + filePdf.toString());
}
else
Base.showMessage("Not Found", "Sorry, no schematic pdf file found in the libraries or project directory.");
break;
case EDIT_CIRCUIT:
File fileXise = getLibraryFile("#define\\s+circuit", "xise.file");
if (fileXise.exists()){
//Base.openURL("file://" + fileXise.toString());
if (fileXise.toString().startsWith(Base.getActiveSketchPath()))
Base.openURL("file://" + fileXise.toString());
else {
Base.showMessage("Library File", "This is a library circuit, it cannot be edited directly. Please save to a new location to edit.");
Base.activeEditor.handleSaveAs();
try {
Base.copyDir(fileXise.getParentFile(), new File(Base.getActiveSketchPath()+"/circuit") );
} catch (IOException ie) { }
String text = editor.getText();
String pattern = "#define\\s+circuit\\s+";
Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = r.matcher(text);
if (m.find()) {
String newText = m.replaceAll("//#define circuit ");
editor.setText(newText);
editor.handleSave(false);
}
//Base.showMessage("Saved", "Don't forget to remove the \"#define circuit\" statement before editing the circuit.");
}
}
else
Base.showMessage("Not Found", "Sorry, no Xilinx ISE project file found in the libraries or project directory.");
break;
}
}
private File getLibraryFile(String keyWord, String prefKey) {
//Remove the whitespace and search for a newline to rule out commented out keywords.
String keyWordVal = getKeyWord(keyWord);
PreferencesMap prefs = Preferences.getMap();
prefs.putAll(Base.getBoardPreferences());
String prefFile = prefs.get(prefKey);
File libFile = null;
List <File> libraryFolders = Base.getLibrariesPath();
for (File libRoot : libraryFolders ) {
File[] libFiles = libRoot.listFiles();
if (libFiles != null) {
for (File lib : libFiles) {
if (lib.isDirectory()) {
if (lib.getName().toLowerCase().equals(keyWordVal)) {
libFile = new File(lib.getPath() + "/" + prefFile);
}
}
}
}
}
//Default to local sketch directory if there is no library file
if (libFile == null)
libFile = new File(Base.getActiveSketchPath() + "/" + prefFile);
return libFile;
}
private String getKeyWord(String keyword) {
String result = null;
String text = editor.getText();
String editorLines[] = text.split("\\r?\\n");
String pattern = "^\\s*" + keyword + "\\s+([^\\s]+).*$";
Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
for (String line : editorLines){
Matcher m = r.matcher(line);
if (m.find()) {
result = m.group(1).toString();
result = result.toLowerCase();
return result;
}
}
return result;
}
public void mouseClicked(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
/**
* Set a particular button to be active.
*/
public void activate(int what) {
if (buttonImages != null) {
setState(what, ACTIVE, true);
}
}
/**
* Set a particular button to be active.
*/
public void deactivate(int what) {
if (buttonImages != null) {
setState(what, INACTIVE, true);
}
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
public Dimension getMinimumSize() {
return new Dimension((BUTTON_COUNT + 1)*BUTTON_WIDTH, BUTTON_HEIGHT);
}
public Dimension getMaximumSize() {
return new Dimension(3000, BUTTON_HEIGHT);
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
shiftPressed = true;
repaint();
}
if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
controlPressed = true;
repaint();
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
shiftPressed = false;
repaint();
}
if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
controlPressed = false;
repaint();
}
}
public void keyTyped(KeyEvent e) { }
}
|
package claw.wani.x2t.translator;
import claw.shenron.transformation.DependentTransformationGroup;
import claw.shenron.transformation.IndependentTransformationGroup;
import claw.shenron.transformation.Transformation;
import claw.shenron.transformation.TransformationGroup;
import claw.shenron.translator.Translator;
import claw.tatsu.analysis.topology.DirectedGraph;
import claw.tatsu.analysis.topology.TopologicalSort;
import claw.tatsu.common.Message;
import claw.tatsu.xcodeml.exception.IllegalDirectiveException;
import claw.tatsu.xcodeml.exception.IllegalTransformationException;
import claw.tatsu.xcodeml.xnode.common.Xcode;
import claw.tatsu.xcodeml.xnode.common.XcodeProgram;
import claw.tatsu.xcodeml.xnode.common.Xnode;
import claw.wani.language.ClawPragma;
import claw.wani.transformation.internal.OpenAccContinuation;
import claw.wani.transformation.ll.caching.Kcaching;
import claw.wani.transformation.ll.directive.DirectivePrimitive;
import claw.wani.transformation.ll.loop.*;
import claw.wani.transformation.ll.utility.ArrayToFctCall;
import claw.wani.transformation.ll.utility.UtilityRemove;
import claw.wani.transformation.sca.ModelData;
import claw.wani.transformation.sca.Sca;
import claw.wani.transformation.sca.ScaForward;
import claw.wani.x2t.configuration.Configuration;
import claw.wani.x2t.configuration.GroupConfiguration;
import org.w3c.dom.Element;
import java.util.*;
/**
* ClawTranslator stores all transformation groups applied during the
* translation.
*
* @author clementval
*/
public class ClawTranslator implements Translator {
// Hold all transformation groups
private final Map<Class, TransformationGroup> _tGroups;
// Hold cross-transformation elements
private final Map<Element, Object> _crossTransformationTable;
private final Map<ClawDirectiveKey, ClawPragma> _blockDirectives;
private int _transformationCounter = 0;
/**
* ClawTranslator ctor. Creates the transformation groups needed for the CLAW
* transformation and order the accordingly to their interpretation order.
*/
public ClawTranslator() {
/*
* Use LinkedHashMap to be able to iterate through the map
* entries with the insertion order.
*/
_tGroups = new LinkedHashMap<>();
for(GroupConfiguration g : Configuration.get().getGroups()) {
switch(g.getType()) {
case DEPENDENT:
_tGroups.put(g.getTransformationClass(),
new DependentTransformationGroup(g.getName()));
break;
case INDEPENDENT:
_tGroups.put(g.getTransformationClass(),
new IndependentTransformationGroup(g.getName()));
break;
}
}
// Internal transformations not specified by default configuration or user
_tGroups.put(OpenAccContinuation.class,
new IndependentTransformationGroup("internal-open-acc-continuation"));
_crossTransformationTable = new HashMap<>();
_blockDirectives = new Hashtable<>();
}
@Override
public void generateTransformation(XcodeProgram xcodeml, Xnode pragma)
throws IllegalTransformationException, IllegalDirectiveException
{
// Analyze the raw pragma with the CLAW language parser
ClawPragma analyzedPragma = ClawPragma.analyze(pragma);
// Create transformation object based on the directive
switch(analyzedPragma.getDirective()) {
case ARRAY_TO_CALL:
addTransformation(xcodeml, new ArrayToFctCall(analyzedPragma));
break;
case KCACHE:
addTransformation(xcodeml, new Kcaching(analyzedPragma));
break;
case LOOP_FUSION:
addTransformation(xcodeml, new LoopFusion(analyzedPragma));
break;
case LOOP_INTERCHANGE:
addTransformation(xcodeml, new LoopInterchange(analyzedPragma));
break;
case LOOP_EXTRACT:
addTransformation(xcodeml, new LoopExtraction(analyzedPragma));
break;
case LOOP_HOIST:
HandleBlockDirective(xcodeml, analyzedPragma);
break;
case ARRAY_TRANSFORM:
HandleBlockDirective(xcodeml, analyzedPragma);
break;
case REMOVE:
HandleBlockDirective(xcodeml, analyzedPragma);
break;
case SCA:
if(analyzedPragma.hasForwardClause()) {
addTransformation(xcodeml, new ScaForward(analyzedPragma));
} else {
addTransformation(xcodeml, new Sca(analyzedPragma));
}
break;
case MODEL_DATA:
HandleBlockDirective(xcodeml, analyzedPragma);
break;
case PRIMITIVE:
addTransformation(xcodeml, new DirectivePrimitive(analyzedPragma));
break;
case IF_EXTRACT:
addTransformation(xcodeml, new IfExtract(analyzedPragma));
break;
// driver handled directives
case IGNORE:
case VERBATIM:
case NO_DEP:
break;
default:
throw new IllegalDirectiveException(null, "Unrecognized CLAW directive",
pragma.lineNo());
}
}
@Override
public void finalize(XcodeProgram xcodeml)
throws IllegalTransformationException
{
// Clean up block transformation map
for(Map.Entry<ClawDirectiveKey, ClawPragma> entry :
_blockDirectives.entrySet()) {
createBlockDirectiveTransformation(xcodeml, entry.getValue(), null);
}
reorderTransformations();
}
/**
* Associate correctly the start and end directive to form blocks.
*
* @param xcodeml Current translation unit.
* @param analyzedPragma Analyzed pragma object to be handle.
*/
private void HandleBlockDirective(XcodeProgram xcodeml,
ClawPragma analyzedPragma)
throws IllegalDirectiveException, IllegalTransformationException
{
int depth = analyzedPragma.getPragma().depth();
ClawDirectiveKey crtRemoveKey =
new ClawDirectiveKey(analyzedPragma.getDirective(), depth);
if(analyzedPragma.isEndPragma()) { // start block directive
if(!_blockDirectives.containsKey(crtRemoveKey)) {
throw new
IllegalDirectiveException(analyzedPragma.getDirective().name(),
"Invalid Claw directive (end with no start)",
analyzedPragma.getPragma().lineNo());
} else {
createBlockDirectiveTransformation(xcodeml,
_blockDirectives.get(crtRemoveKey), analyzedPragma);
_blockDirectives.remove(crtRemoveKey);
}
} else { // end block directive
if(_blockDirectives.containsKey(crtRemoveKey)) {
createBlockDirectiveTransformation(xcodeml,
_blockDirectives.get(crtRemoveKey), null);
}
_blockDirectives.remove(crtRemoveKey);
_blockDirectives.put(crtRemoveKey, analyzedPragma);
}
}
/**
* Create a new block transformation object according to its start directive.
*
* @param xcodeml Current translation unit.
* @param begin Begin directive which starts the block.
* @param end End directive which ends the block.
*/
private void createBlockDirectiveTransformation(XcodeProgram xcodeml,
ClawPragma begin,
ClawPragma end)
throws IllegalTransformationException
{
if(begin == null || !begin.isApplicableToCurrentTarget()) {
return;
}
switch(begin.getDirective()) {
case REMOVE:
addTransformation(xcodeml, new UtilityRemove(begin, end));
break;
case ARRAY_TRANSFORM:
addTransformation(xcodeml, new ArrayTransform(begin, end));
break;
case LOOP_HOIST:
addTransformation(xcodeml, new LoopHoist(begin, end));
break;
case MODEL_DATA:
addTransformation(xcodeml, new ModelData(begin, end));
}
}
/**
* Add transformation in the correct group.
*
* @param xcodeml Current translation unit.
* @param t Transformation to be added.
*/
public void addTransformation(XcodeProgram xcodeml, Transformation t)
throws IllegalTransformationException
{
if(t.getDirective() != null
&& t.getDirective() instanceof ClawPragma
&& !((ClawPragma) t.getDirective()).isApplicableToCurrentTarget())
{
return;
}
if(t.analyze(xcodeml, this)) {
if(_tGroups.containsKey(t.getClass())) {
_tGroups.get(t.getClass()).add(t);
}
} else if(t.abortOnFailedAnalysis()) {
throw new IllegalTransformationException(
"Analysis for transformation failed. " +
"See errors for more information.",
t.getDirective().getPragma().lineNo());
}
}
@Override
public boolean isHandledPragma(Xnode pragma) {
return ClawPragma.startsWithClaw(pragma);
}
private void reorderTransformations() {
if(getGroups().containsKey(ScaForward.class)) {
TransformationGroup tg = getGroups().get(ScaForward.class);
if(tg.count() <= 1) {
return;
}
DirectedGraph<Transformation> dg = new DirectedGraph<>();
Map<String, List<Transformation>> fctMap = new HashMap<>();
for(Transformation t : tg.getTransformations()) {
ScaForward p = (ScaForward) t;
dg.addNode(p);
if(fctMap.containsKey(p.getCallingFctName())) {
List<Transformation> tList = fctMap.get(p.getCallingFctName());
tList.add(p);
} else {
List<Transformation> tList = new ArrayList<>();
tList.add(p);
fctMap.put(p.getCallingFctName(), tList);
}
}
for(Transformation t : tg.getTransformations()) {
ScaForward p = (ScaForward) t;
if(p.getCalledFctName() != null) {
if(fctMap.containsKey(p.getCalledFctName())) {
List<Transformation> tList = fctMap.get(p.getCalledFctName());
for(Transformation end : tList) {
dg.addEdge(p, end);
}
}
}
}
List<Transformation> ordered =
TopologicalSort.sort(TopologicalSort.reverseGraph(dg));
tg.setTransformations(ordered);
}
}
public void generateAdditionalTransformation(ClawPragma claw,
XcodeProgram xcodeml, Xnode stmt)
throws IllegalTransformationException
{
// Order doesn't matter
applyFusionClause(claw, xcodeml, stmt);
applyInterchangeClause(claw, xcodeml, stmt);
}
/**
* Generate loop interchange transformation if the clause is present in the
* directive.
*
* @param claw ClawPragma object that tells encapsulates all
* information about the current directives and its
* clauses.
* @param xcodeml Current XcodeML program.
* @param stmt Statement on which the transformation is attached. Must
* be a FdoStatement for the loop interchange
* transformation.
*/
private void applyInterchangeClause(ClawPragma claw, XcodeProgram xcodeml,
Xnode stmt)
throws IllegalTransformationException
{
if(claw.hasInterchangeClause() && stmt.opcode() == Xcode.F_DO_STATEMENT) {
Xnode p = xcodeml.createNode(Xcode.F_PRAGMA_STATEMENT);
stmt.insertBefore(p);
ClawPragma l = ClawPragma.createLoopInterchangeLanguage(claw, p);
LoopInterchange interchange = new LoopInterchange(l);
addTransformation(xcodeml, interchange);
Message.debug("Loop interchange added: " + claw.getIndexes());
}
}
/**
* Generate loop fusion transformation if the clause is present in the
* directive.
*
* @param claw ClawPragma object that tells encapsulates all
* information about the current directives and its
* clauses.
* @param xcodeml Current XcodeML program.
* @param stmt Statement on which the transformation is attached. Must
* be a FdoStatement for the loop fusion transformation.
*/
private void applyFusionClause(ClawPragma claw, XcodeProgram xcodeml,
Xnode stmt)
throws IllegalTransformationException
{
if(claw.hasFusionClause() && stmt.opcode() == Xcode.F_DO_STATEMENT) {
ClawPragma l = ClawPragma.createLoopFusionLanguage(claw);
addTransformation(xcodeml, new LoopFusion(stmt, l));
Message.debug("Loop fusion added: " + claw.getGroupValue());
}
}
/**
* @see Translator#getGroups()
*/
public Map<Class, TransformationGroup> getGroups() {
return _tGroups;
}
/**
* Get the next extraction counter value.
*
* @return Transformation counter value.
*/
public int getNextTransformationCounter() {
return _transformationCounter++;
}
/**
* Get a stored element from a previous transformation.
*
* @param key Key to use to retrieve the element.
* @return The stored element if present. Null otherwise.
*/
public Object hasElement(Xnode key) {
if(_crossTransformationTable.containsKey(key.element())) {
return _crossTransformationTable.get(key.element());
}
return null;
}
/**
* Store a Xnode from a transformation for a possible usage in another
* transformation. If a key is already present, the element is overwritten.
*
* @param key The element acting as a key.
* @param value The element to be stored.
*/
public void storeElement(Xnode key, Object value) {
_crossTransformationTable.remove(key.element());
_crossTransformationTable.put(key.element(), value);
}
}
|
package ai.grakn.client;
import ai.grakn.Grakn;
import ai.grakn.GraknGraph;
import ai.grakn.GraknSession;
import ai.grakn.GraknTxType;
import ai.grakn.concept.EntityType;
import ai.grakn.concept.ResourceType;
import ai.grakn.graql.Graql;
import ai.grakn.graql.InsertQuery;
import ai.grakn.test.EngineContext;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.SystemOutRule;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import static ai.grakn.graql.Graql.var;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.argThat;
import static java.util.stream.Stream.generate;
import static org.mockito.Mockito.*;
public class LoaderClientTest {
private GraknSession session;
@Rule
public final SystemOutRule systemOut = new SystemOutRule().enableLog();
@ClassRule
public static final EngineContext engine = EngineContext.startInMemoryServer();
@Before
public void setupSession(){
this.session = engine.factoryWithNewKeyspace();
}
@Test
public void whenSingleQueryLoadedAndTaskCompletionFunctionThrowsError_ErrorIsLogged(){
// Create a LoaderClient with a callback that will fail
LoaderClient loader = loader();
loader.setTaskCompletionConsumer((json) -> assertTrue("Testing Log failure",false));
// Load some queries
generate(this::query).limit(1).forEach(loader::add);
// Wait for queries to finish
loader.waitToFinish();
// Verify that the logger received the failed log message
assertThat(systemOut.getLog(), containsString("error in callback"));
}
@Test
public void whenSingleQueryLoaded_TaskCompletionExecutesExactlyOnce(){
AtomicInteger tasksCompleted = new AtomicInteger(0);
// Create a LoaderClient with a callback that will fail
LoaderClient loader = loader();
loader.setTaskCompletionConsumer((json) -> tasksCompleted.incrementAndGet());
// Load some queries
generate(this::query).limit(1).forEach(loader::add);
// Wait for queries to finish
loader.waitToFinish();
// Verify that the logger received the failed log message
assertEquals(1, tasksCompleted.get());
}
@Test
public void whenSending50InsertQueries_50EntitiesAreLoadedIntoGraph() {
LoaderClient loader = loader();
generate(this::query).limit(100).forEach(loader::add);
loader.waitToFinish();
try (GraknGraph graph = session.open(GraknTxType.READ)) {
assertEquals(100, graph.getEntityType("name_tag").instances().size());
}
}
@Test
public void whenSending100QueriesWithBatchSize20_EachBatchHas20Queries() {
LoaderClient loader = loader();
loader.setBatchSize(20);
generate(this::query).limit(100).forEach(loader::add);
loader.waitToFinish();
verify(loader, times(5)).sendQueriesToLoader(argThat(insertQueries -> insertQueries.size() == 20));
}
@Test
public void whenSending90QueriesWithBatchSize20_TheLastBatchHas10Queries(){
LoaderClient loader = loader();
loader.setBatchSize(20);
generate(this::query).limit(90).forEach(loader::add);
loader.waitToFinish();
verify(loader, times(4)).sendQueriesToLoader(argThat(insertQueries -> insertQueries.size() == 20));
verify(loader, times(1)).sendQueriesToLoader(argThat(insertQueries -> insertQueries.size() == 10));
}
@Test
public void whenSending20QueriesWith1ActiveTask_OnlyOneBatchIsActiveAtOnce() throws Exception {
LoaderClient loader = loader();
loader.setNumberActiveTasks(1);
loader.setBatchSize(5);
generate(this::query).limit(20).forEach(loader::add);
loader.waitToFinish();
try (GraknGraph graph = session.open(GraknTxType.READ)) {
assertEquals(20, graph.getEntityType("name_tag").instances().size());
}
}
@Test
public void whenEngineRESTFailsWhileLoadingWithRetryTrue_LoaderRetriesAndWaits() throws Exception {
AtomicInteger tasksCompletedWithoutError = new AtomicInteger(0);
LoaderClient loader = loader();
loader.setRetryPolicy(true);
loader.setBatchSize(5);
loader.setTaskCompletionConsumer((json) -> {
if(json != null){
tasksCompletedWithoutError.incrementAndGet();
}
});
for(int i = 0; i < 20; i++){
loader.add(query());
if(i%10 == 0) {
engine.server().stopHTTP();
engine.server().startHTTP();
}
}
loader.waitToFinish();
assertEquals(4, tasksCompletedWithoutError.get());
}
// TODO: Run this test in a more deterministic way (mocking endpoints?)
@Test
public void whenEngineRESTFailsWhileLoadingWithRetryFalse_LoaderDoesNotWait() throws Exception {
AtomicInteger tasksCompletedWithoutError = new AtomicInteger(0);
AtomicInteger tasksCompletedWithError = new AtomicInteger(0);
LoaderClient loader = loader();
loader.setRetryPolicy(false);
loader.setBatchSize(5);
loader.setTaskCompletionConsumer((json) -> {
if (json != null) {
tasksCompletedWithoutError.incrementAndGet();
} else {
tasksCompletedWithError.incrementAndGet();
}
});
for(int i = 0; i < 20; i++){
loader.add(query());
if(i%10 == 0) {
engine.server().stopHTTP();
engine.server().startHTTP();
}
}
loader.waitToFinish();
assertThat(tasksCompletedWithoutError.get(), lessThanOrEqualTo(4));
assertThat(tasksCompletedWithoutError.get() + tasksCompletedWithError.get(), equalTo(4));
}
private LoaderClient loader(){
// load ontology
try(GraknGraph graph = session.open(GraknTxType.WRITE)){
EntityType nameTag = graph.putEntityType("name_tag");
ResourceType<String> nameTagString = graph.putResourceType("name_tag_string", ResourceType.DataType.STRING);
ResourceType<String> nameTagId = graph.putResourceType("name_tag_id", ResourceType.DataType.STRING);
nameTag.resource(nameTagString);
nameTag.resource(nameTagId);
graph.admin().commitNoLogs();
return spy(new LoaderClient(graph.getKeyspace(), Grakn.DEFAULT_URI));
}
}
private InsertQuery query(){
return Graql.insert(
var().isa("name_tag")
.has("name_tag_string", UUID.randomUUID().toString())
.has("name_tag_id", UUID.randomUUID().toString()));
}
}
|
package app.hongs.serv.common;
import app.hongs.HongsUnchecked;
import java.util.regex.Pattern;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
*
* @author Hongs
*/
public class SessFiller extends HttpServletRequestWrapper {
private Sesion ses;
private String sid;
private static final Pattern SIDFMT = Pattern.compile("^[a-zA-Z0-9\\-]{1,32}$");
public SessFiller(HttpServletRequest request, String sid) {
super(request);
// ID , 400
if (sid != null && sid.length() != 0
&& !SIDFMT.matcher(sid).matches()) {
throw new HongsUnchecked(0x1100, "Session ID must be 1 to 32 alphanumeric or '-'.");
}
this.sid = sid;
}
/**
* HttpSession
*
* @return
*/
@Override
public HttpSession getSession() {
return getSession(true);
}
/**
* HttpSession
* @param add
* @return
*/
@Override
public HttpSession getSession(boolean add) {
if (ses != null) {
return ses;
}
if (sid != null) {
ses = Sesion.getSesion(sid);
if (ses == null) {
if (add == true) {
ses = new Sesion(sid);
ses.setServletContext(getServletContext());
}
} else {
sid = ses.getId ( );
ses.setServletContext(getServletContext());
}
} else {
if (add == true) {
ses = new Sesion( );
sid = ses.getId ( );
ses.setServletContext(getServletContext());
}
}
return ses;
}
}
|
package uk.ac.ox.oucs.vle.proxy;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.email.api.EmailService;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.portal.api.PortalService;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.user.api.UserNotDefinedException;
import uk.ac.ox.oucs.vle.AdditionalUserDetails;
import uk.ac.ox.oucs.vle.SakaiProxy;
import uk.ac.ox.oucs.vle.UserProxy;
/**
* This is the actual Sakai proxy which talks to the Sakai services.
* @author buckett
*
*/
public class SakaiProxyImpl implements SakaiProxy {
private final static Log log = LogFactory.getLog(SakaiProxyImpl.class);
private UserDirectoryService userService;
private EmailService emailService;
private EventTrackingService eventService;
private ToolManager toolManager;
private ServerConfigurationService serverConfigurationService;
private SiteService siteService;
private PortalService portalService;
private AdditionalUserDetails additionalUserDetails;
private String fromAddress;
public void setUserService(UserDirectoryService userService) {
this.userService = userService;
}
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}
public void setEventService(EventTrackingService eventService) {
this.eventService = eventService;
}
public void setToolManager(ToolManager toolManager) {
this.toolManager = toolManager;
}
public void setSiteService(SiteService siteService) {
this.siteService = siteService;
}
public void setPortalService(PortalService portalService) {
this.portalService = portalService;
}
public void setAdditionalUserDetails(AdditionalUserDetails additionalUserDetails) {
this.additionalUserDetails = additionalUserDetails;
}
public void setServerConfigurationService(ServerConfigurationService serverConfigurationService) {
this.serverConfigurationService = serverConfigurationService;
}
public void init() {
if (fromAddress == null) {
fromAddress = serverConfigurationService.getString("course-signup.from", null);
}
}
public UserProxy getCurrentUser() {
User sakaiUser = userService.getCurrentUser();
UserProxy user = wrapUserProxy(sakaiUser);
return user;
}
public UserProxy findUserById(String id) {
try {
return wrapUserProxy(userService.getUser(id));
} catch (UserNotDefinedException unde) {
return null;
}
}
public UserProxy findStudentById(String id) {
try {
return wrapStudentProxy(userService.getUser(id));
} catch (UserNotDefinedException unde) {
return null;
}
}
public UserProxy findUserByEmail(String email) {
Collection<User> users = userService.findUsersByEmail(email);
if (users.size() == 0) {
return null;
} else {
if (users.size() > 1) {
log.warn("More than one user found with email: "+ email);
}
return wrapUserProxy(users.iterator().next());
}
}
public UserProxy findUserByEid(String eid) {
try {
return wrapUserProxy(userService.getUserByAid(eid));
} catch (UserNotDefinedException unde) {
return null;
}
}
public void sendEmail(String to, String subject, String body) {
String from = fromAddress;
if (from == null) {
from = getCurrentUser().getEmail();
}
emailService.send(
from, // from address
to, // to address
subject, // subject
body, // message body
null, // header to string
null, // Reply to string
null // Additional headers
);
}
public void logEvent(String resourceId, String eventType, String placementId) {
Placement placement = getPlacement(placementId);
String context = placement.getContext();
String resource = "/coursesignup/group/"+ resourceId;
Event event = eventService.newEvent(eventType, resource, context, false, NotificationService.NOTI_OPTIONAL);
eventService.post(event);
}
/**
* Just get the current placement.
* @return The current placement.
* @throws RunTimeException If there isn't a current placement, this happens
* when a request comes through that isn't processed by the portal.
*/
public Placement getPlacement(String placementId) {
Placement placement = null;
if (null == placementId) {
placement = toolManager.getCurrentPlacement();
} else {
placement = siteService.findTool(placementId);
}
if (placement == null) {
throw new RuntimeException("No current tool placement set.");
}
return placement;
}
@SuppressWarnings("unchecked")
private UserProxy wrapUserProxy(User sakaiUser) {
if(sakaiUser == null) {
return null;
}
List<String> units = sakaiUser.getProperties().getPropertyList("units");
return new UserProxy(sakaiUser.getId(), sakaiUser.getEid(),
sakaiUser.getFirstName(), sakaiUser.getLastName(), sakaiUser.getDisplayName(),
sakaiUser.getEmail(),
sakaiUser.getDisplayId(),
sakaiUser.getProperties().getProperty("oakOSSID"),
sakaiUser.getProperties().getProperty("yearOfStudy"),
sakaiUser.getProperties().getProperty("oakStatus"),
sakaiUser.getProperties().getProperty("primaryOrgUnit"),
null,
(units == null)?Collections.EMPTY_LIST:units);
}
private UserProxy wrapStudentProxy(User sakaiUser) {
if(sakaiUser == null) {
return null;
}
List<String> units = sakaiUser.getProperties().getPropertyList("units");
return new UserProxy(sakaiUser.getId(), sakaiUser.getEid(),
sakaiUser.getFirstName(), sakaiUser.getLastName(), sakaiUser.getDisplayName(),
sakaiUser.getEmail(),
sakaiUser.getDisplayId(),
sakaiUser.getProperties().getProperty("oakOSSID"),
sakaiUser.getProperties().getProperty("yearOfStudy"),
sakaiUser.getProperties().getProperty("oakStatus"),
sakaiUser.getProperties().getProperty("primaryOrgUnit"),
additionalUserDetails.getDegreeProgram(sakaiUser.getEid()),
(units == null)?Collections.EMPTY_LIST:units);
}
public String getConfirmUrl(String signupId) {
return getConfirmUrl(signupId, null);
}
public String getConfirmUrl(String signupId, String placementId) {
return getUrl("/static/pending.jsp#"+ signupId, placementId);
}
public String getDirectUrl(String courseId) {
return getUrl("/static/browse.jsp?openCourse="+ courseId);
}
public String getApproveUrl(String signupId) {
return getApproveUrl(signupId, null);
}
public String getApproveUrl(String signupId, String placementId) {
return getUrl("/static/approve.jsp#"+ signupId, placementId);
}
public String getAdvanceUrl(String signupId, String status, String placementId) {
String urlSafe = encode(signupId+"$"+status+"$"+getPlacement(placementId).getId());
return serverConfigurationService.getServerUrl() +
"/course-signup/rest/signup/advance/"+urlSafe;
}
public String encode(String uncoded) {
byte[] encrypted = encrypt(uncoded);
String base64String = new String(Base64.encodeBase64(encrypted));
return base64String.replace('+','-').replace('/','_');
}
public String uncode(String encoded) {
String base64String = encoded.replace('-','+').replace('_','/');
byte[] encrypted = Base64.decodeBase64(base64String.getBytes());
return decrypt(encrypted);
}
public String getMyUrl() {
return getMyUrl(null);
}
public String getMyUrl(String placementId) {
return getUrl("/static/my.jsp", placementId);
}
private String getUrl(String toolState) {
return getUrl(toolState, null);
}
private String getUrl(String toolState, String placementId) {
Placement currentPlacement = getPlacement(placementId);
//String siteId = currentPlacement.getContext();
ToolConfiguration toolConfiguration = siteService.findTool(currentPlacement.getId());
String pageUrl = toolConfiguration.getContainingPage().getUrl();
Map<String, String[]> encodedToolState = portalService.encodeToolState(currentPlacement.getId(), toolState);
StringBuilder params = new StringBuilder();
for (Entry<String, String[]> entry : encodedToolState.entrySet()) {
for(String value: entry.getValue()) {
params.append("&");
params.append(entry.getKey());
params.append("=");
params.append(URLEncoder.encode(value));
}
}
if (params.length() > 0) {
pageUrl += "?"+ params.substring(1); // Trim the leading &
}
return pageUrl;
}
protected String getSecretKey() {
return serverConfigurationService.getString("aes.secret.key", "se1?r2eFM8rC5u2K");
}
protected byte[] encrypt(String string) {
SecretKeySpec skeySpec = new SecretKeySpec(getSecretKey().getBytes(), "AES");
try {
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] bytes = cipher.doFinal(string.getBytes());
return bytes;
} catch (Exception e) {
System.out.println("encrypt Exception ["+e.getLocalizedMessage()+"]");
}
return null;
}
protected String decrypt(byte[] bytes) {
SecretKeySpec skeySpec = new SecretKeySpec(getSecretKey().getBytes(), "AES");
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(bytes);
return new String(original);
} catch (Exception e) {
System.out.println("decrypt Exception ["+e.getLocalizedMessage()+"]");
}
return null;
}
}
|
package net.iaeste.iws.ejb;
import net.iaeste.iws.api.enums.exchange.OfferState;
import net.iaeste.iws.api.exceptions.IWSException;
import net.iaeste.iws.persistence.ExchangeDao;
import net.iaeste.iws.persistence.entities.exchange.OfferEntity;
import net.iaeste.iws.persistence.entities.exchange.OfferGroupEntity;
import net.iaeste.iws.persistence.jpa.ExchangeJpaDao;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.TimerService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Singleton
public class ScheduleJobsBean {
private static final Logger log = LoggerFactory.getLogger(ScheduleJobsBean.class);
private EntityManager iwsEntityManager = null;
private ExchangeDao exchangeDao = null;
@Resource
private TimerService timerService;
private final Object lock = new Object();
private boolean processExpiredOfferIsRunning = false;
/**
* Setter for the JNDI injected persistence context. This allows us to also
* test the code, by invoking these setters on the instantiated Object.
*
* @param iwsEntityManager Transactional Entity Manager instance
*/
@PersistenceContext(unitName = "iwsDatabase")
public void setIwsEntityManager(final EntityManager iwsEntityManager) {
this.iwsEntityManager = iwsEntityManager;
}
/**
* {@inheritDoc}
*/
@PostConstruct
public void postConstruct() {
log.info("post construct");
exchangeDao = new ExchangeJpaDao(iwsEntityManager);
}
//for local testing
//@Schedule(second = "*/30", minute = "*", hour = "*", info="Every 30 seconds")
//for server
//@Schedule(second = "0", minute = "1", hour = "0", info = "Every day at 0:01 AM (server time)", persistent = false)
private void processExpiredOffers() {
log.info("processExpiredOffers started at " + new DateTime());
final boolean run;
synchronized (lock) {
if (!processExpiredOfferIsRunning) {
run = true;
processExpiredOfferIsRunning = true;
} else {
run = false;
}
}
if (run) {
// We invcoke the logic in a try-finally block, so we can switch of
// the processing regardlessly of the outcome
try {
// Now we invoke the actual logic, outside of the sync block,
// as to not block anything
runExpiredOfferProcessing();
} finally {
// Now the worker has completed the job, we can set the
// processing flag back to false, so another instance can start
synchronized (lock) {
processExpiredOfferIsRunning = false;
}
}
}
log.info("processExpiredOffers ended at " + new DateTime());
}
private void runExpiredOfferProcessing() {
try {
final List<OfferEntity> offers = exchangeDao.findExpiredOffers(new Date());
final List<Long> ids = new ArrayList<>(offers.size());
for (final OfferEntity offer : offers) {
ids.add(offer.getId());
}
final List<OfferGroupEntity> offerGroups = exchangeDao.findInfoForSharedOffers(ids);
final Map<Long, List<OfferGroupEntity>> sharingInfo = prepareOfferGroupMap(ids, offerGroups);
final List<Long> removeOfferGroup = new ArrayList<>();
final List<Long> closeOfferGroup = new ArrayList<>();
for (final Long id : ids) {
for (final OfferGroupEntity offerGroup : sharingInfo.get(id)) {
if (offerGroup.getHasApplication()) {
closeOfferGroup.add(offerGroup.getId());
} else {
removeOfferGroup.add(offerGroup.getId());
}
}
}
exchangeDao.updateOfferState(ids, OfferState.EXPIRED);
exchangeDao.deleteOfferGroup(removeOfferGroup);
exchangeDao.updateOfferGroupState(closeOfferGroup, OfferState.CLOSED);
} catch (IllegalArgumentException | IWSException e) {
log.error("Error in processing expired offers", e);
}
}
private Map<Long, List<OfferGroupEntity>> prepareOfferGroupMap(final List<Long> ids, final List<OfferGroupEntity> offerGroups) {
final Map<Long, List<OfferGroupEntity>> result = new HashMap<>(ids.size());
for (final Long id : ids) {
result.put(id, new ArrayList<OfferGroupEntity>());
}
for (final OfferGroupEntity offerGroup : offerGroups) {
result.get(offerGroup.getOffer().getId()).add(offerGroup);
}
return result;
}
}
|
package com.izforge.izpack.util;
import java.awt.event.KeyEvent;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import jline.console.ConsoleReader;
import jline.console.completer.FileNameCompleter;
import jline.internal.Log;
/**
* I/O streams to support prompting and keyboard input from the console.
*
* @author Tim Anderson
*/
public class Console
{
private static final Logger logger = Logger.getLogger(Console.class.getName());
/**
* Console reader.
*/
private ConsoleReader consoleReader;
/**
* Check if consoleReader failed to load.
*/
private boolean consoleReaderFailed = false;
/**
* File name completer allows for tab completion on files and directories.
*/
private final FileNameCompleter fileNameCompleter = new FileNameCompleter();
/**
* Input stream.
*/
private BufferedReader in;
/**
* Output stream.
*/
private PrintWriter out;
/**
* Constructs a <tt>Console</tt> with <tt>System.in</tt> and <tt>System.out</tt> as the I/O streams.
*/
public Console()
{
this(System.in, System.out);
}
/**
* Constructs a <tt>Console</tt>.
*
* @param in the input stream
* @param out the output stream
*/
public Console(InputStream in, OutputStream out)
{
try
{
Log.setOutput(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException
{
}
}));
this.consoleReader = new ConsoleReader("IzPack", in, out, null);
this.out = new PrintWriter(consoleReader.getOutput(), true);
}
catch (Throwable t)
{
consoleReaderFailed = true;
this.out = new PrintWriter(out, true);
this.in = new BufferedReader(new InputStreamReader(in));
logger.log(Level.SEVERE, "Cannot initialize the console reader. Default to regular input stream.", t);
}
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return
* followed immediately by a linefeed.
*
* @return a String containing the contents of the line, not including any line-termination characters, or
* null if the end of the stream has been reached
* @throws IOException if an I/O error occurs
*/
public String readLine() throws IOException
{
if (consoleReaderFailed)
{
return in.readLine();
}
else
{
return consoleReader.readLine();
}
}
/**
* Prints a message to the console.
*
* @param message the message to print
*/
public void print(String message)
{
out.print(message);
out.flush();
}
/**
* Prints a new line.
*/
public void println()
{
out.println();
}
/**
* Prints a message to the console with a new line.
*
* @param message the message to print
*/
public void println(String message)
{
out.println(message);
}
/**
* Displays a prompt and waits for numeric input.
*
* @param prompt the prompt to display
* @param min the minimum allowed value
* @param max the maximum allowed value
* @param eof the value to return if end of stream is reached
* @return a value in the range of <tt>from..to</tt>, or <tt>eof</tt> if the end of stream is reached
*/
public int prompt(String prompt, int min, int max, int eof)
{
return prompt(prompt, min, max, min - 1, eof);
}
/**
* Displays a prompt and waits for numeric input.
*
* @param prompt the prompt to display
* @param min the minimum allowed value
* @param max the maximum allowed value
* @param defaultValue the default value to use, if no input is entered. Use a value {@code < min} if there is no
* default
* @param eof the value to return if end of stream is reached
* @return a value in the range of <tt>from..to</tt>, or <tt>eof</tt> if the end of stream is reached
*/
public int prompt(String prompt, int min, int max, int defaultValue, int eof)
{
int result = min - 1;
try
{
do
{
println(prompt);
String value = readLine();
if (value != null)
{
value = value.trim();
if (value.equals("") && defaultValue >= min)
{
// use the default value
result = defaultValue;
break;
}
try
{
result = Integer.valueOf(value);
}
catch (NumberFormatException ignore)
{
// loop round to try again
}
}
else
{
// end of stream
result = eof;
break;
}
}
while (result < min || result > max);
}
catch (IOException e)
{
logger.log(Level.WARNING, e.getMessage(), e);
result = eof;
}
return result;
}
/**
* Displays a prompt and waits for input.
* Allows auto completion of files and directories.
* Except a path to a file or directory.
* Ensure to expand the tilde character to the user's home directory.
* If the input ends with a file separator we will trim it to keep consistency.
*
* @param prompt the prompt to display
* @param eof the value to return if end of stream is reached
* @return the input value or <tt>eof</tt> if the end of stream is reached
*/
public String promptLocation(String prompt, String eof)
{
return promptLocation(prompt, "", eof);
}
/**
* Displays a prompt and waits for input.
* Allows auto completion of files and directories.
* Except a path to a file or directory.
* Ensure to expand the tilde character to the user's home directory.
* If the input ends with a file separator we will trim it to keep consistency.
* TODO: Perhaps have file separator at the end for directories and no file separator at the end for files
*
* @param prompt the prompt to display
* @param defaultValue the default value to use, if no input is entered
* @param eof the value to return if end of stream is reached
* @return the input value or {@code eof} if the end of stream is reached
*/
public String promptLocation(String prompt, String defaultValue, String eof)
{
if (consoleReaderFailed)
{
return prompt(prompt, defaultValue, eof);
}
String result;
consoleReader.addCompleter(fileNameCompleter);
println(prompt);
try
{
while ((result = consoleReader.readLine().trim()) != null)
{
if (result.startsWith("~"))
{
result = result.replace("~", System.getProperty("user.home"));
}
if (result.endsWith(File.separator) && result.length() > 1)
{
result = result.substring(0, result.length()-1);
}
if (result.isEmpty())
{
result = defaultValue;
}
break;
}
}
catch (IOException e)
{
result = eof;
logger.log(Level.WARNING, e.getMessage(), e);
}
finally
{
consoleReader.removeCompleter(fileNameCompleter);
}
return result;
}
/**
* Displays a prompt and waits for input.
* Expects a password, characters with be mased with the echoCharacter "*"
* @param prompt the prompt to display
* @param eof the value to return if end of stream is reached
* @return the input value or <tt>eof</tt> if the end of stream is reached
*/
public String promptPassword(String prompt, String eof)
{
return promptPassword(prompt, "", eof);
}
/**
* Displays a prompt and waits for input.
* Expects a password, characters with be mased with the echoCharacter "*"
*
* @param prompt the prompt to display
* @param defaultValue the default value to use, if no input is entered
* @param eof the value to return if end of stream is reached
* @return the input value or {@code eof} if the end of stream is reached
*/
public String promptPassword(String prompt, String defaultValue, String eof)
{
if (consoleReaderFailed)
{
return prompt(prompt, defaultValue, eof);
}
int ch;
String result = "";
String backspace = "\b \b";
String echoCharacter = "*";
StringBuilder stringBuilder = new StringBuilder();
println(prompt);
boolean submitted = false;
try
{
while(!submitted)
{
switch (ch = consoleReader.readCharacter())
{
case -1:
case '\n':
case '\r':
println("");
result = stringBuilder.toString();
submitted = true;
break;
case KeyEvent.VK_BACK_SPACE:
case KeyEvent.VK_DELETE:
if (stringBuilder.length() > 0)
{
print(backspace);
stringBuilder.setLength(stringBuilder.length() - 1);
}
break;
default:
print(echoCharacter);
stringBuilder.append((char) ch);
}
}
}
catch (IOException e)
{
result = eof;
logger.log(Level.WARNING, e.getMessage(), e);
}
if(result.isEmpty())
{
result = defaultValue;
}
return result;
}
/**
* Displays a prompt and waits for input.
*
* @param prompt the prompt to display
* @param eof the value to return if end of stream is reached
* @return the input value or <tt>eof</tt> if the end of stream is reached
*/
public String prompt(String prompt, String eof)
{
return prompt(prompt, "", eof);
}
/**
* Displays a prompt and waits for input.
*
* @param prompt the prompt to display
* @param defaultValue the default value to use, if no input is entered
* @param eof the value to return if end of stream is reached
* @return the input value or {@code eof} if the end of stream is reached
*/
public String prompt(String prompt, String defaultValue, String eof)
{
String result;
try
{
println(prompt);
result = readLine();
if (result == null)
{
result = eof;
}
else if (result.equals(""))
{
result = defaultValue;
}
}
catch (IOException e)
{
result = eof;
logger.log(Level.WARNING, e.getMessage(), e);
}
return result;
}
/**
* Prompts for a value from a set of values.
*
* @param prompt the prompt to display
* @param values the valid values
* @param eof the value to return if end of stream is reached
* @return the input value or <tt>eof</tt> if the end of stream is reached
*/
public String prompt(String prompt, String[] values, String eof)
{
while (true)
{
String input = prompt(prompt, eof);
if (input == null || input.equals(eof))
{
return input;
}
else
{
for (String value : values)
{
if (value.equalsIgnoreCase(input))
{
return value;
}
}
}
}
}
public void useDefaultInput()
{
consoleReaderFailed = true;
}
}
|
package com.youtube.vitess.client;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.UnsignedLong;
import com.google.protobuf.ByteString;
import com.youtube.vitess.client.cursor.Cursor;
import com.youtube.vitess.client.cursor.SimpleCursor;
import com.youtube.vitess.proto.Query;
import com.youtube.vitess.proto.Query.BindVariable;
import com.youtube.vitess.proto.Query.BoundQuery;
import com.youtube.vitess.proto.Query.QueryResult;
import com.youtube.vitess.proto.Vtgate.BoundKeyspaceIdQuery;
import com.youtube.vitess.proto.Vtgate.BoundShardQuery;
import com.youtube.vitess.proto.Vtgate.ExecuteEntityIdsRequest.EntityId;
import com.youtube.vitess.proto.Vtrpc.RPCError;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLInvalidAuthorizationSpecException;
import java.sql.SQLNonTransientException;
import java.sql.SQLRecoverableException;
import java.sql.SQLSyntaxErrorException;
import java.sql.SQLTimeoutException;
import java.sql.SQLTransientException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Proto contains methods for working with Vitess protobuf messages.
*/
public class Proto {
private static final int MAX_DECIMAL_UNIT = 30;
public static void checkError(RPCError error) throws SQLException {
if (error != null) {
int errno = getErrno(error.getMessage());
String sqlState = getSQLState(error.getMessage());
switch (error.getCode()) {
case SUCCESS:
break;
case BAD_INPUT:
throw new SQLSyntaxErrorException(error.toString(), sqlState, errno);
case DEADLINE_EXCEEDED:
throw new SQLTimeoutException(error.toString(), sqlState, errno);
case INTEGRITY_ERROR:
throw new SQLIntegrityConstraintViolationException(error.toString(), sqlState, errno);
case TRANSIENT_ERROR:
throw new SQLTransientException(error.toString(), sqlState, errno);
case UNAUTHENTICATED:
throw new SQLInvalidAuthorizationSpecException(error.toString(), sqlState, errno);
case NOT_IN_TX:
throw new SQLRecoverableException(error.toString(), sqlState, errno);
default:
throw new SQLNonTransientException("Vitess RPC error: " + error.toString(), sqlState,
errno);
}
}
}
/**
* Extracts the MySQL errno from a Vitess error message, if any.
*
* <p>
* If no errno information is found, it returns {@code 0}.
*/
public static int getErrno(@Nullable String errorMessage) {
if (errorMessage == null) {
return 0;
}
int tagPos = errorMessage.indexOf("(errno ");
if (tagPos == -1) {
return 0;
}
int start = tagPos + "(errno ".length();
if (start >= errorMessage.length()) {
return 0;
}
int end = errorMessage.indexOf(')', start);
if (end == -1) {
return 0;
}
try {
return Integer.parseInt(errorMessage.substring(start, end));
} catch (NumberFormatException e) {
return 0;
}
}
/**
* Extracts the SQLSTATE from a Vitess error message, if any.
*
* <p>
* If no SQLSTATE information is found, it returns {@code ""}.
*/
public static String getSQLState(@Nullable String errorMessage) {
if (errorMessage == null) {
return "";
}
int tagPos = errorMessage.indexOf("(sqlstate ");
if (tagPos == -1) {
return "";
}
int start = tagPos + "(sqlstate ".length();
if (start >= errorMessage.length()) {
return "";
}
int end = errorMessage.indexOf(')', start);
if (end == -1) {
return "";
}
return errorMessage.substring(start, end);
}
public static BindVariable buildBindVariable(Object value) {
if (value instanceof BindVariable) {
return (BindVariable) value;
}
BindVariable.Builder builder = BindVariable.newBuilder();
if (value instanceof Iterable<?>) {
// List Bind Vars
Iterator<?> itr = ((Iterable<?>) value).iterator();
if (!itr.hasNext()) {
throw new IllegalArgumentException("Can't pass empty list as list bind variable.");
}
builder.setType(Query.Type.TUPLE);
while (itr.hasNext()) {
TypedValue tval = new TypedValue(itr.next());
builder.addValues(Query.Value.newBuilder().setType(tval.type).setValue(tval.value).build());
}
} else {
TypedValue tval = new TypedValue(value);
builder.setType(tval.type);
builder.setValue(tval.value);
}
return builder.build();
}
public static EntityId buildEntityId(byte[] keyspaceId, Object value) {
TypedValue tval = new TypedValue(value);
return EntityId.newBuilder().setKeyspaceId(ByteString.copyFrom(keyspaceId)).setType(tval.type)
.setValue(tval.value).build();
}
/**
* bindQuery creates a BoundQuery from query and vars.
*/
public static BoundQuery bindQuery(String query, Map<String, ?> vars) {
BoundQuery.Builder boundQueryBuilder = BoundQuery.newBuilder().setSql(query);
if (vars != null) {
for (Map.Entry<String, ?> entry : vars.entrySet()) {
boundQueryBuilder.putBindVariables(entry.getKey(), buildBindVariable(entry.getValue()));
}
}
return boundQueryBuilder.build();
}
/**
* bindShardQuery creates a BoundShardQuery.
*/
public static BoundShardQuery bindShardQuery(String keyspace, Iterable<String> shards,
BoundQuery query) {
return BoundShardQuery.newBuilder().setKeyspace(keyspace).addAllShards(shards).setQuery(query)
.build();
}
/**
* bindShardQuery creates a BoundShardQuery.
*/
public static BoundShardQuery bindShardQuery(String keyspace, Iterable<String> shards,
String query, Map<String, ?> vars) {
return bindShardQuery(keyspace, shards, bindQuery(query, vars));
}
/**
* bindKeyspaceIdQuery creates a BoundKeyspaceIdQuery.
*/
public static BoundKeyspaceIdQuery bindKeyspaceIdQuery(String keyspace,
Iterable<byte[]> keyspaceIds, BoundQuery query) {
return BoundKeyspaceIdQuery.newBuilder().setKeyspace(keyspace)
.addAllKeyspaceIds(Iterables.transform(keyspaceIds, BYTE_ARRAY_TO_BYTE_STRING))
.setQuery(query).build();
}
/**
* bindKeyspaceIdQuery creates a BoundKeyspaceIdQuery.
*/
public static BoundKeyspaceIdQuery bindKeyspaceIdQuery(String keyspace,
Iterable<byte[]> keyspaceIds, String query, Map<String, ?> vars) {
return bindKeyspaceIdQuery(keyspace, keyspaceIds, bindQuery(query, vars));
}
public static List<Cursor> toCursorList(List<QueryResult> queryResults) {
ImmutableList.Builder<Cursor> builder = new ImmutableList.Builder<Cursor>();
for (QueryResult queryResult : queryResults) {
builder.add(new SimpleCursor(queryResult));
}
return builder.build();
}
public static final Function<byte[], ByteString> BYTE_ARRAY_TO_BYTE_STRING =
new Function<byte[], ByteString>() {
@Override
public ByteString apply(byte[] from) {
return ByteString.copyFrom(from);
}
};
public static final Function<Map.Entry<byte[], ?>, EntityId> MAP_ENTRY_TO_ENTITY_KEYSPACE_ID =
new Function<Map.Entry<byte[], ?>, EntityId>() {
@Override
public EntityId apply(Map.Entry<byte[], ?> entry) {
return buildEntityId(entry.getKey(), entry.getValue());
}
};
/**
* Represents a type and value in the type system used in query.proto.
*/
protected static class TypedValue {
Query.Type type;
ByteString value;
TypedValue(Object value) {
if (value == null) {
this.type = Query.Type.NULL_TYPE;
this.value = ByteString.EMPTY;
} else if (value instanceof String) {
// String
this.type = Query.Type.VARCHAR;
this.value = ByteString.copyFromUtf8((String) value);
} else if (value instanceof byte[]) {
// Bytes
this.type = Query.Type.VARBINARY;
this.value = ByteString.copyFrom((byte[]) value);
} else if (value instanceof Integer || value instanceof Long || value instanceof Short
|| value instanceof Byte) {
// Int32, Int64, Short, Byte
this.type = Query.Type.INT64;
this.value = ByteString.copyFromUtf8(value.toString());
} else if (value instanceof UnsignedLong) {
// Uint64
this.type = Query.Type.UINT64;
this.value = ByteString.copyFromUtf8(value.toString());
} else if (value instanceof Float || value instanceof Double) {
// Float, Double
this.type = Query.Type.FLOAT64;
this.value = ByteString.copyFromUtf8(value.toString());
} else if (value instanceof Boolean) {
// Boolean
this.type = Query.Type.INT64;
this.value = ByteString.copyFromUtf8(((boolean) value) ? "1" : "0");
} else if (value instanceof BigDecimal) {
// BigDecimal
BigDecimal bigDecimal = (BigDecimal) value;
if (bigDecimal.scale() > MAX_DECIMAL_UNIT) {
// MySQL only supports scale up to 30.
bigDecimal = bigDecimal.setScale(MAX_DECIMAL_UNIT, BigDecimal.ROUND_HALF_UP);
}
this.type = Query.Type.DECIMAL;
this.value = ByteString.copyFromUtf8(bigDecimal.toPlainString());
} else {
throw new IllegalArgumentException(
"unsupported type for Query.Value proto: " + value.getClass());
}
}
}
}
|
package com.microsoft.bond;
import com.microsoft.bond.helpers.ArgumentHelper;
import com.microsoft.bond.protocol.*;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Partially implements the {@link BondType} contract for generated Bond struct data types.
* Leaves the rest of implementation details to generated subclasses specific to the struct type,
* which are generated private classes nested within the struct classes.
* @param <TStruct> the class of the struct value
*/
// This API is consumed by codegen, which static analysis isn't aware of.
@SuppressWarnings({"unused", "WeakerAccess"})
public abstract class StructBondType<TStruct extends BondSerializable>
extends BondType<TStruct> implements StructMetadata {
// The registry of all loaded struct type builders, for generic and non-generic generated struct types.
// Entries are added by static initializeBondType methods of the generated struct types which is called
// by the static class initializer and can also be called manually if the static class initializer hasn't
// completed yet (which happens with circular class dependencies).
// This registry's purpose is to provide an alternative solution to obtain a type descriptor for a struct
// type, that can be used when executing generated code initializing fields of struct type descriptors.
// An alternative solution is necessary since the user-facing solution of accessing public static fields
// BOND_TYPE doesn't work when running as part of initialization of a generated class (the static fields
// may not be set yet). Thus, there are two approaches to get a Bond type descriptor for a user-defined
// generated struct:
// 1. [public-facing API used by all user code] Use the public static field BOND_TYPE which is:
// (a) The type descriptor, for struct types that do not declare generic type parameters. or
// (b) A builder of type descriptor that takes generic type arguments and returns an instance
// of the type descriptor, for struct types that declare generic type parameters.
// 2. [private API used only by generated initialization code] Use the protected method getStructType
// that returns the type descriptor given the Class and generic type arguments (empty for non-generic
// types. This method relies on the registry of struct type builders, and will initialize the class
// (thus executing its registration) if necessary.
// Note that #2 doesn't distinguish between generic and non-generic types, by abstracting the type builder
// for all types, with empty generic type argument list for non-generic types. On the contrary, #1 has
// that distinction since it's intended for public API and needs to be convenient (i.e. it's not elegant
// to ask client code to "build" an invariant non-generic type).
private static final ConcurrentHashMap<
Class<? extends BondSerializable>,
StructBondTypeBuilder<? extends BondSerializable>> structTypeBuilderRegistry =
new ConcurrentHashMap<
Class<? extends BondSerializable>,
StructBondTypeBuilder<? extends BondSerializable>>();
private static final String BOND_TYPE_INITIALIZATION_METHOD_NAME = "initializeBondType";
// The global initialization lock, used to initialize type descriptors.
// Global locking is necessary to avoid deadlocks when multiple threads initialize generated classes
// that reference each other. The contention for this lock is generally not expected to be a problem because:
// 1. A lock is acquired only once per type descriptor object when it is actually initialized. This is
// achieved by double-checked locking in the ensureInitialized method.
// 2. Due to type caching, there is at most one lock acqusition for each type (or each specialization of
// a generic type), which is constrained by the application. Note that temporary type descriptors
// are used only to lookup the cached equivalent and are themselves not initialized.
private static final Object initializationLock = new Object();
// set by the constructor (part of the object identity)
private final GenericTypeSpecialization genericTypeSpecialization;
private final int precomputedHashCode;
// set by the initialization method instead of the constructor since may have cyclic dependencies
private StructBondType<? super TStruct> baseStructType;
private StructField<?>[] structFields;
// indicates whether this instance is initialized, thread-safe (atomic) read and write from/to memory
private volatile boolean isInitialized = false;
// indicates whether this instance is currently being initialized by the thread holding the global lock;
// the flag is used to prevent a thread from re-entering initialization method due to cyclic references
private boolean isCurrentlyInitializing = false;
/**
* Used by generated subclasses to instantiate the type descriptor.
*
* @param genericTypeSpecialization specialization of a generic struct or null if not a generic struct
*/
protected StructBondType(GenericTypeSpecialization genericTypeSpecialization) {
this.genericTypeSpecialization = genericTypeSpecialization;
precomputedHashCode = this.getClass().hashCode() +
(genericTypeSpecialization == null ? 0 : genericTypeSpecialization.hashCode());
}
/**
* Used by generated subclasses to initialize the base struct reference and fields of the type descriptor.
* Field types (including fields of the base struct) may refer back to the declaring struct which causes
* cyclic dependencies, and therefore this initialization is separated from the constructor.
*
* @param baseStructType the type descriptor of the base struct or null if it doesn't exist
* @param structFields an array of descriptors of the declared fields of the struct (excluding inherited)
*/
protected final void initializeBaseAndFields(
StructBondType<? super TStruct> baseStructType,
StructField<?>... structFields) {
this.baseStructType = baseStructType;
this.structFields = structFields;
}
/**
* Called from generated code to make sure the type descriptor is initialized.
*/
protected final void ensureInitialized() {
// double-checked locking to make sure initialization happens only one in a single thread;
// the contention is restricted since there is at most one initialization per each distinct
// non-generic struct type or per each distinct specialization of a generic struct type
if (!this.isInitialized) {
synchronized (initializationLock) {
if (!this.isInitialized) {
// enter initialization only if not already initializing by the current thread
// (which already holds the lock and hence can be the only initializing thread)
if (!this.isCurrentlyInitializing) {
try {
// mark this object as currently being initialized, so that this thread
// does not re-enter initialization when there is a cyclic type reference
this.isCurrentlyInitializing = true;
// initialize (call generated method which initializes struct type fields
// and then calls initializeBaseAndFields) and mark this instance as
// initialized (using a volatile variable), so that from this point on
// every thread will skip initialization and lock acquisition
this.initialize();
this.isInitialized = true;
} finally {
// clean up after the current thread so that if the initialize method
// threw an exception and the object was not successfully initialized
// then some other thread can still try to initialize
// Please note that the initialize methods do not throw any exceptions
// under normal circumstances, and if they throw something then it is
// almost certainly a fatal error (e.g. OutOfMemory or ThreadDeath).
this.isCurrentlyInitializing = false;
}
}
}
}
}
}
/**
* Implemented by generated subclasses to initialize the type descriptor, speficially initialize the
* fields and then call {@link #initializeBaseAndFields(StructBondType, StructField[])}.
*/
protected abstract void initialize();
/**
* Used by generated subclasses to serialize declared fields of this struct, excluding inherited fields.
*
* @param context contains the runtime context of the serialization
* @param value the value to serialize from
* @throws IOException if an I/O error occurred
*/
protected abstract void serializeStructFields(
SerializationContext context, TStruct value) throws IOException;
/**
* Used by generated subclasses to deserialize declared fields of this struct, excluding inherited fields.
*
* @param context contains the runtime context of the deserialization
* @param value the value to deserialize into
* @throws IOException if an I/O error occurred
*/
protected abstract void deserializeStructFields(
TaggedDeserializationContext context, TStruct value) throws IOException;
/**
* Used by generated subclasses to deserialize declared fields of this struct, excluding inherited fields.
*
* @param context contains the runtime context of the deserialization
* @param value the value to deserialize into
* @throws IOException if an I/O error occurred
*/
protected abstract void deserializeStructFields(
UntaggedDeserializationContext context, TStruct value) throws IOException;
/**
* Used by generated subclasses to initialize declared fields of this struct, excluding inherited fields.
*
* @param value the value to initialize
*/
protected abstract void initializeStructFields(TStruct value);
/**
* Used by generated subclasses to memberwise-copy declared fields of this struct, excluding inherited fields.
*
* @param fromValue the value to copy from
* @param toValue the value to copy to
*/
protected abstract void cloneStructFields(TStruct fromValue, TStruct toValue);
/**
* Gets the generic specialization or null if not generic struct.
*
* @return the generic specialization or null if not generic struct
*/
protected final GenericTypeSpecialization getGenericSpecialization() {
return this.genericTypeSpecialization;
}
/**
* Gets the descriptor of the base struct type.
*
* @return the type descriptor of the base struct or null if there is no base struct
*/
public final StructBondType<? super TStruct> getBaseStructType() {
return this.baseStructType;
}
/**
* Gets an array containing the descriptors of the struct fields.
*
* @return an array containing the descriptors of the struct fields
*/
public final StructField<?>[] geStructFields() {
return this.structFields.clone();
}
/**
* Builds a new {@link SchemaDef} instance describing the schema of this struct.
*
* @return a new schema definition instance
*/
public final SchemaDef buildSchemaDef() {
SchemaDef schemaDef = new SchemaDef();
HashMap<StructBondType<?>, StructDefOrdinalTuple> typeDefMap =
new HashMap<StructBondType<?>, StructDefOrdinalTuple>();
schemaDef.root = this.createSchemaTypeDef(typeDefMap);
StructDef[] tempArray = new StructDef[typeDefMap.size()];
for (Map.Entry<StructBondType<?>, StructDefOrdinalTuple> e : typeDefMap.entrySet()) {
StructDefOrdinalTuple structDefInfo = e.getValue();
tempArray[structDefInfo.ordinal] = structDefInfo.structDef;
}
schemaDef.structs.addAll(Arrays.asList(tempArray));
return schemaDef;
}
@Override
public final String getName() {
// rely on generated class
return this.getValueClass().getSimpleName();
}
@Override
public final String getQualifiedName() {
// rely on generated class
return this.getValueClass().getName();
}
@Override
public final BondDataType getBondDataType() {
return BondDataType.BT_STRUCT;
}
@Override
public final boolean isNullableType() {
return false;
}
@Override
public final boolean isGenericType() {
return this.genericTypeSpecialization != null;
}
@Override
public final BondType<?>[] getGenericTypeArguments() {
return this.genericTypeSpecialization != null ?
this.genericTypeSpecialization.genericTypeArguments.clone() : null;
}
@Override
public final Class<TStruct> getPrimitiveValueClass() {
return null;
}
@Override
protected final TStruct newDefaultValue() {
return this.newInstance();
}
@Override
protected final TStruct cloneValue(TStruct value) {
TStruct clonedValue = this.newInstance();
StructBondType<? super TStruct> currentStructType = this;
while (currentStructType != null) {
currentStructType.cloneStructFields(value, clonedValue);
currentStructType = currentStructType.baseStructType;
}
return clonedValue;
}
/**
* Instantiates a new instance of this struct type.
*
* @return new struct instance
*/
public abstract TStruct newInstance();
/**
* Returns a value indicating whether this type is a subtype of (or the same as) the argument type.
*
* @param other the argument type
* @return true if this type is the same type or a subtype of the argument type
*/
public final boolean isSubtypeOf(StructBondType<?> other) {
ArgumentHelper.ensureNotNull(other, "other");
StructBondType<?> currentType = this;
while (currentType != null) {
if (currentType.equals(other)) {
return true;
}
currentType = currentType.baseStructType;
}
return false;
}
@Override
protected final void serializeValue(SerializationContext context, TStruct value) throws IOException {
this.verifyNonNullableValueIsNotSetToNull(value);
context.writer.writeStructBegin(this);
if (this.baseStructType != null) {
this.baseStructType.serializeValueAsBase(context, value);
}
this.serializeStructFields(context, value);
context.writer.writeStructEnd();
}
private void serializeValueAsBase(
SerializationContext context, TStruct value) throws IOException {
if (this.baseStructType != null) {
this.baseStructType.serializeValueAsBase(context, value);
}
context.writer.writeBaseBegin(this);
this.serializeStructFields(context, value);
context.writer.writeBaseEnd();
}
@Override
protected final TStruct deserializeValue(TaggedDeserializationContext context) throws IOException {
TStruct value = this.newDefaultValue();
context.reader.readStructBegin();
if (this.baseStructType != null) {
this.baseStructType.deserializeValueAsBase(context, value);
}
this.deserializeStructFields(context, value);
context.reader.readStructEnd();
return value;
}
@Override
protected final TStruct deserializeValue(UntaggedDeserializationContext context) throws IOException {
TStruct value = this.newDefaultValue();
if (this.baseStructType != null) {
this.baseStructType.deserializeValueAsBase(context, value);
}
this.deserializeStructFields(context, value);
return value;
}
private void deserializeValueAsBase(
TaggedDeserializationContext context, TStruct value) throws IOException {
if (this.baseStructType != null) {
this.baseStructType.deserializeValueAsBase(context, value);
}
context.reader.readBaseBegin();
this.deserializeStructFields(context, value);
context.reader.readBaseEnd();
}
private void deserializeValueAsBase(
UntaggedDeserializationContext context, TStruct value) throws IOException {
if (this.baseStructType != null) {
this.baseStructType.deserializeValueAsBase(context, value);
}
this.deserializeStructFields(context, value);
}
@Override
protected final void serializeField(
SerializationContext context,
TStruct value,
StructField<TStruct> field) throws IOException {
this.verifySerializedNonNullableFieldIsNotSetToNull(value, field);
// struct fields are never omitted
context.writer.writeFieldBegin(BondDataType.BT_STRUCT, field.getId(), field);
try {
this.serializeValue(context, value);
} catch (InvalidBondDataException e) {
// throws
Throw.raiseStructFieldSerializationError(false, field, e, null);
}
context.writer.writeFieldEnd();
}
@Override
protected final TStruct deserializeField(
TaggedDeserializationContext context,
StructField<TStruct> field) throws IOException {
// a struct value may be deserialized only from BT_STRUCT
if (context.readFieldResult.type.value != BondDataType.BT_STRUCT.value) {
// throws
Throw.raiseFieldTypeIsNotCompatibleDeserializationError(context.readFieldResult.type, field);
}
TStruct value = null;
try {
value = this.deserializeValue(context);
} catch (InvalidBondDataException e) {
// throws
Throw.raiseStructFieldSerializationError(true, field, e, null);
}
return value;
}
@Override
public final int hashCode() {
return this.precomputedHashCode;
}
@Override
public final boolean equals(Object obj) {
if (obj instanceof StructBondType<?>) {
StructBondType<?> that = (StructBondType<?>) obj;
return this.precomputedHashCode == that.precomputedHashCode &&
this.getClass().equals(that.getClass()) &&
(this.genericTypeSpecialization == null ?
that.genericTypeSpecialization == null :
this.genericTypeSpecialization.equals(that.genericTypeSpecialization));
} else {
return false;
}
}
/**
* Serializes an object into the given protocol writer.
*
* @param obj the object to serialize
* @param writer the protocol writer to write into
* @throws IOException if an I/O error occurred
*/
void serialize(TStruct obj, ProtocolWriter writer) throws IOException {
// first pass
if (writer instanceof TwoPassProtocolWriter) {
ProtocolWriter firstPassWriter = ((TwoPassProtocolWriter) writer).getFirstPassWriter();
if (firstPassWriter != null) {
SerializationContext firstPassContext = new SerializationContext(firstPassWriter);
this.serializeValue(firstPassContext, obj);
}
}
// second pass
SerializationContext context = new SerializationContext(writer);
this.serializeValue(context, obj);
}
/**
* Deserializes an object from the given tagged protocol reader.
*
* @param reader the protocol reader to read from
* @return deserialized object
* @throws IOException if an I/O error occurred
*/
TStruct deserialize(TaggedProtocolReader reader) throws IOException {
TaggedDeserializationContext context = new TaggedDeserializationContext(reader);
return this.deserializeValue(context);
}
/**
* Deserializes an object from the given untagged protocol reader.
*
* @param reader the protocol reader to read from
* @return deserialized object
* @throws IOException if an I/O error occurred
*/
TStruct deserialize(UntaggedProtocolReader reader) throws IOException {
UntaggedDeserializationContext context = new UntaggedDeserializationContext(reader);
return this.deserializeValue(context);
}
@Override
final TypeDef createSchemaTypeDef(HashMap<StructBondType<?>, StructDefOrdinalTuple> structDefMap) {
// first need to get the struct def info since need to reference it by the ordinal
StructDefOrdinalTuple structDefInfo = structDefMap.get(this);
if (structDefInfo == null) {
// struct def wasn't created yet, create one and associate with the current struct in the map;
int nextOrdinal = structDefMap.size();
StructDef structDef = new StructDef();
structDefInfo = new StructDefOrdinalTuple(structDef, nextOrdinal);
// the struct def instance that is associated in the map with the current struct type is not yet
// initialized, but any descendants that use this struct will reference the same struct def instance
structDefMap.put(this, structDefInfo);
this.initializeSchemaStructDef(structDef, structDefMap);
}
TypeDef typeDef = new TypeDef();
typeDef.id = this.getBondDataType();
typeDef.struct_def = (short) structDefInfo.ordinal;
return typeDef;
}
/**
* Codegen helper method that tries to read a field from payload and indicates whether there is a field to read.
*
* @param context contains the runtime context of the deserialization
* @return true if there are more fields to read
* @throws IOException if an I/O error occurred
*/
protected static boolean readField(TaggedDeserializationContext context) throws IOException {
context.reader.readFieldBegin(context.readFieldResult);
int statusValue = context.readFieldResult.type.value;
return statusValue != BondDataType.BT_STOP.value && statusValue != BondDataType.BT_STOP_BASE.value;
}
private void initializeSchemaStructDef(
StructDef structDef, HashMap<StructBondType<?>, StructDefOrdinalTuple> structDefMap) {
structDef.metadata.name = this.getName();
structDef.metadata.qualified_name = this.getFullName();
if (this.baseStructType != null) {
structDef.base_def = this.baseStructType.createSchemaTypeDef(structDefMap);
}
for (StructField<?> field : this.structFields) {
FieldDef fieldDef = new FieldDef();
fieldDef.metadata.name = field.name;
fieldDef.metadata.modifier = field.modifier;
initializeSchemaVariantWithDefaultValue(fieldDef.metadata.default_value, field);
fieldDef.id = field.id;
fieldDef.type = field.fieldType.createSchemaTypeDef(structDefMap);
}
}
private void initializeSchemaVariantWithDefaultValue(Variant variant, StructField field) {
variant.nothing = field.isDefaultNothing();
switch (field.fieldType.getBondDataType().value) {
case BondDataType.Values.BT_UINT8:
case BondDataType.Values.BT_UINT16:
case BondDataType.Values.BT_UINT32:
case BondDataType.Values.BT_UINT64:
variant.uint_value = ((Number) field.getDefaultValue()).longValue();
break;
case BondDataType.Values.BT_INT8:
case BondDataType.Values.BT_INT16:
case BondDataType.Values.BT_INT32:
case BondDataType.Values.BT_INT64:
variant.int_value = ((Number) field.getDefaultValue()).longValue();
break;
case BondDataType.Values.BT_BOOL:
// bool is piggy-backing on the int value
variant.int_value = (Boolean) field.getDefaultValue() ? 1 : 0;
break;
case BondDataType.Values.BT_FLOAT:
case BondDataType.Values.BT_DOUBLE:
variant.double_value = ((Number) field.getDefaultValue()).doubleValue();
break;
case BondDataType.Values.BT_STRING:
variant.string_value = (String) field.getDefaultValue();
break;
case BondDataType.Values.BT_WSTRING:
variant.wstring_value = (String) field.getDefaultValue();
break;
default:
// the default is null for structs and containers
break;
}
}
/**
* Registers a struct type builder from generated code.
*
* @param clazz the struct class
* @param structTypeBuilder type builder for the given struct type
* @param <TStruct> the Bond struct value class
*/
protected static <TStruct extends BondSerializable> void registerStructType(
Class<TStruct> clazz, StructBondTypeBuilder<TStruct> structTypeBuilder) {
structTypeBuilderRegistry.putIfAbsent(clazz, structTypeBuilder);
}
/**
* Gets a type descriptor for a struct represented by a particular generated class.
* This method is used when initializing struct type descriptors, so that a particular
* type descriptor may access a type descriptor of another type. This method is the only
* accessor to a struct type descriptor that is used in generated code when initializing
* struct type descriptors (generic type arguments, the base, or fields) and since the
* type descriptor is returns is always initialized, there's the invariant condition that
* all cached struct type descriptors are initialized.
*
* @param clazz the struct class
* @param genericTypeArguments the generic type arguments in the declaration order
* @return a type descriptor instance
*/
protected static StructBondType<? extends BondSerializable> getStructType(
Class<? extends BondSerializable> clazz,
BondType<?>... genericTypeArguments) {
StructBondTypeBuilder<?> structTypeBuilder = structTypeBuilderRegistry.get(clazz);
if (structTypeBuilder == null) {
// the type builder is not found in the registry, which could be due to the following two reasons:
// 1. The type builder class hasn't been registered yet, which means that the struct class
// (whose generated static initializer does this registration) hasn't been initialized yet, or
// 2. The struct class was not generated by the same code generator, which should never happen
// since this method is protected and intended to be called only from generated code
try {
// Class initialization may not be enough since the class may already be in the middle of
// initialization, where is needed to initialize a referenced class that had a circular
// reference back to it. Therefore, call the static initialization method
Method typeInitMethod = clazz.getMethod(BOND_TYPE_INITIALIZATION_METHOD_NAME);
typeInitMethod.invoke(null);
} catch (Exception e) {
// if there is an error, then the class implemenation is invalid
throw new RuntimeException(
"Unexpected program state: invalid struct implementation: " + clazz.getName(),
e);
}
// at this point the class initialization should register the struct type builder;
// if it's still not registered then the struct class initialization is not doing what
// it should (although the initialization method exists and was successfully invoked),
// so the conclusion is that it's not generated per our expectations
structTypeBuilder = structTypeBuilderRegistry.get(clazz);
if (structTypeBuilder == null) {
throw new RuntimeException(
"Unexpected program state: invalid struct implementation: " + clazz.getName());
}
}
// make sure the generic type argument count matches the expected count;
// since this should be called only be generated code, this must be always the case
if (structTypeBuilder.getGenericTypeParameterCount() != genericTypeArguments.length) {
throw new RuntimeException(
"Unexpected program state: generic argument count mismatch: " + clazz.getName() +
", expected: " + structTypeBuilder.getGenericTypeParameterCount() +
", actual: " + genericTypeArguments.length);
}
// build, cache, and initialize the type descriptor
return structTypeBuilder.getInitializedFromCache(genericTypeArguments);
}
/**
* Responsible for building and caching Bond struct types with generic type parameters. Please note
* that a {@link StructBondType} instance for a generic type can exist only when all generic type
* parameters are bound. This class is responsible for this binding: it takes the generic type
* arguments and instantiates a new {@link StructBondType} instance representing a specialization
* of the generic type. As a special case, it can instantiate new type descriptors for non-generic
* types (for which the list of generic type arguments is null).
*
* @param <TStruct> the class of the struct value
*/
protected static abstract class StructBondTypeBuilder<TStruct extends BondSerializable> {
/**
* Gets the number of generic type parameters or (as a special case) 0 for non-generic types.
*
* @return the number of generic type parameters
*/
public abstract int getGenericTypeParameterCount();
/**
* Creates a new instance of type descriptor that is neither initialized nor cached. This instance
* is used to locate the cached instance (or will be cached itself if no cached instance exists yet).
*
* @param genericTypeArguments generic type arguments
* @return new uninitialized uncached type descriptor instance
*/
protected abstract StructBondType<TStruct> buildNewInstance(BondType<?>[] genericTypeArguments);
/**
* Returns an initialized instance of the struct type descriptor from the cache,
* building/caching/initializing it if necessary.
*
* @param genericTypeArguments generic type arguments
* @return new initialized type descriptor instance (cached)
*/
public final StructBondType<TStruct> getInitializedFromCache(BondType<?>... genericTypeArguments) {
StructBondType<TStruct> cacheKey = this.buildNewInstance(genericTypeArguments);
StructBondType<TStruct> cachedType = (StructBondType<TStruct>) getCachedType(cacheKey);
cachedType.ensureInitialized();
return cachedType;
}
}
/**
* A descriptor of a single field in a struct declaration that encapsulates the details
* of that field behavior such as initialization, serialization and deserialization.
* This class is the root of the class hierarchy for various Bond types (primitives and objects)
* as well as for whether the field defaults to "nothing" (i.e. needs a "Something" wrapper).
* The purpose of this class hierarchy is that field initialization/serialization/deserialization
* code can just call initialize/serialize/deserialize method without any regard to the field type,
* which is setup in the struct type descriptor's {@see StructBondType#initialize} method.
*
* @param <TField> the class of the field value, using corresponding wrappers for primitive types
*/
protected static abstract class StructField<TField> implements FieldMetadata {
// accessed by subclasses
final StructBondType<?> structType;
final BondType<TField> fieldType;
final short id;
final String name;
final Modifier modifier;
// restrict subclasses to nested classes only
private StructField(
StructBondType<?> structType,
BondType<TField> fieldType,
int id,
String name,
Modifier modifier) {
this.structType = structType;
this.fieldType = fieldType;
this.id = (short) id;
this.name = name;
this.modifier = modifier;
}
/**
* Gets the declaring struct type descriptor.
*
* @return the declaring struct type descriptor
*/
public final StructBondType<?> getStructType() {
return this.structType;
}
/**
* Gets the field type descriptor.
*
* @return the field type descriptor
*/
public final BondType<TField> getFieldType() {
return this.fieldType;
}
@Override
public final short getId() {
return this.id;
}
@Override
public final String getName() {
return this.name;
}
@Override
public final Modifier getModifier() {
return this.modifier;
}
@Override
public abstract TField getDefaultValue();
/**
* Codegen helper to verify deserialized field.
*
* @param isFieldSet a boolean tracking whether the field was set during deserialization
* @return true if the argument is false and the field needs to be set to the default value
* @throws InvalidBondDataException if the field is required and was not set
*/
public final boolean verifyDeserialized(boolean isFieldSet) throws InvalidBondDataException {
if (!isFieldSet && this.modifier.value == Modifier.Required.value) {
// throws
Throw.raiseRequiredStructFieldIsMissingDeserializationError(this);
}
// indicate to the generated code that the field needs to be set to the default value
return !isFieldSet;
}
final void verifyFieldWasNotYetDeserialized(
boolean wasAlreadyDeserialized) throws InvalidBondDataException {
if (wasAlreadyDeserialized) {
Throw.raiseStructFieldIsPresentMoreThanOnceDeserializationError(this);
}
}
final boolean isOptional() {
return this.modifier.value == Modifier.Optional.value;
}
}
/**
* Implements the {@link StructField} contract for fields of general object data types
* (i.e. any field that is not of a Java primitive type, string, or an enum) that are
* not defaulting to "nothing". Since these field types cannot have explicit default
* values, there is no constructor that takes a default value.
*/
protected static final class ObjectStructField<TField> extends StructField<TField> {
public ObjectStructField(
StructBondType<?> structType,
BondType<TField> fieldType,
int id,
String name,
Modifier modifier) {
super(structType, fieldType, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final TField getDefaultValue() {
return this.initialize();
}
public final TField initialize() {
return this.fieldType.newDefaultValue();
}
public final TField clone(TField value) {
return this.fieldType.cloneValue(value);
}
public final void serialize(
SerializationContext context, TField value) throws IOException {
this.fieldType.serializeField(context, value, this);
}
public final TField deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return this.fieldType.deserializeField(context, this);
}
public final TField deserialize(UntaggedDeserializationContext context) throws IOException {
return this.fieldType.deserializeValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of general object data types
* (i.e. any field that is not of a Java primitive type, string, or an enum) that are
* defaulting to "nothing". The default value for such fields is null (meaning "nothing").
*/
protected static final class SomethingObjectStructField<TField> extends StructField<TField> {
public SomethingObjectStructField(
StructBondType<?> structType,
BondType<TField> fieldType,
int id,
String name,
Modifier modifier) {
super(structType, fieldType, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final TField getDefaultValue() {
return null;
}
public final SomethingObject<TField> initialize() {
return null;
}
public final SomethingObject<TField> clone(SomethingObject<TField> value) {
return value == null ? null : Something.wrap(this.fieldType.cloneValue(value.value));
}
public final void serialize(
SerializationContext context, SomethingObject<TField> value) throws IOException {
this.fieldType.serializeSomethingField(context, value, this);
}
public final SomethingObject<TField> deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return this.fieldType.deserializeSomethingField(context, this);
}
public final SomethingObject<TField> deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(this.fieldType.deserializeValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the uint8 primitive data type
* that are not defaulting to "nothing".
*/
protected static final class UInt8StructField extends StructField<Byte> {
private final byte defaultValue;
public UInt8StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
byte defaultValue) {
super(structType, BondTypes.UINT8, id, name, modifier);
this.defaultValue = defaultValue;
}
public UInt8StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, UInt8BondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Byte getDefaultValue() {
// box
return this.initialize();
}
public final byte initialize() {
return this.defaultValue;
}
public final byte clone(byte value) {
return value;
}
public final void serialize(
SerializationContext context, byte value) throws IOException {
UInt8BondType.serializePrimitiveField(context, value, this);
}
public final byte deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return UInt8BondType.deserializePrimitiveField(context, this);
}
public final byte deserialize(UntaggedDeserializationContext context) throws IOException {
return UInt8BondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the uint8 primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingUInt8StructField extends StructField<Byte> {
public SomethingUInt8StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.UINT8, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Byte getDefaultValue() {
return null;
}
public final SomethingByte initialize() {
return null;
}
public final SomethingByte clone(SomethingByte value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingByte value) throws IOException {
UInt8BondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingByte deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return UInt8BondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingByte deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(UInt8BondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the uint16 primitive data type
* that are not defaulting to "nothing".
*/
protected static final class UInt16StructField extends StructField<Short> {
private final short defaultValue;
public UInt16StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
short defaultValue) {
super(structType, BondTypes.UINT16, id, name, modifier);
this.defaultValue = defaultValue;
}
public UInt16StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, UInt16BondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Short getDefaultValue() {
// box
return this.initialize();
}
public final short initialize() {
return this.defaultValue;
}
public final short clone(short value) {
return value;
}
public final void serialize(
SerializationContext context, short value) throws IOException {
UInt16BondType.serializePrimitiveField(context, value, this);
}
public final short deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return UInt16BondType.deserializePrimitiveField(context, this);
}
public final short deserialize(UntaggedDeserializationContext context) throws IOException {
return UInt16BondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the uint16 primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingUInt16StructField extends StructField<Short> {
public SomethingUInt16StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.UINT16, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Short getDefaultValue() {
return null;
}
public final SomethingShort initialize() {
return null;
}
public final SomethingShort clone(SomethingShort value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingShort value) throws IOException {
UInt16BondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingShort deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return UInt16BondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingShort deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(UInt16BondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the uint32 primitive data type
* that are not defaulting to "nothing".
*/
protected static final class UInt32StructField extends StructField<Integer> {
private final int defaultValue;
public UInt32StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
int defaultValue) {
super(structType, BondTypes.UINT32, id, name, modifier);
this.defaultValue = defaultValue;
}
public UInt32StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, UInt32BondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Integer getDefaultValue() {
// box
return this.initialize();
}
public final int initialize() {
return this.defaultValue;
}
public final int clone(int value) {
return value;
}
public final void serialize(
SerializationContext context, int value) throws IOException {
UInt32BondType.serializePrimitiveField(context, value, this);
}
public final int deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return UInt32BondType.deserializePrimitiveField(context, this);
}
public final int deserialize(UntaggedDeserializationContext context) throws IOException {
return UInt32BondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the uint32 primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingUInt32StructField extends StructField<Integer> {
public SomethingUInt32StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.UINT32, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Integer getDefaultValue() {
return null;
}
public final SomethingInteger initialize() {
return null;
}
public final SomethingInteger clone(SomethingInteger value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingInteger value) throws IOException {
UInt32BondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingInteger deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return UInt32BondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingInteger deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(UInt32BondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the uint64 primitive data type
* that are not defaulting to "nothing".
*/
protected static final class UInt64StructField extends StructField<Long> {
private final long defaultValue;
public UInt64StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
long defaultValue) {
super(structType, BondTypes.UINT64, id, name, modifier);
this.defaultValue = defaultValue;
}
public UInt64StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, UInt64BondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Long getDefaultValue() {
// box
return this.initialize();
}
public final long initialize() {
return this.defaultValue;
}
public final long clone(long value) {
return value;
}
public final void serialize(
SerializationContext context, long value) throws IOException {
UInt64BondType.serializePrimitiveField(context, value, this);
}
public final long deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return UInt64BondType.deserializePrimitiveField(context, this);
}
public final long deserialize(UntaggedDeserializationContext context) throws IOException {
return UInt64BondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the uint64 primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingUInt64StructField extends StructField<Long> {
public SomethingUInt64StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.UINT64, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Long getDefaultValue() {
return null;
}
public final SomethingLong initialize() {
return null;
}
public final SomethingLong clone(SomethingLong value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingLong value) throws IOException {
UInt64BondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingLong deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return UInt64BondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingLong deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(UInt64BondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the int8 primitive data type
* that are not defaulting to "nothing".
*/
protected static final class Int8StructField extends StructField<Byte> {
private final byte defaultValue;
public Int8StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
byte defaultValue) {
super(structType, BondTypes.INT8, id, name, modifier);
this.defaultValue = defaultValue;
}
public Int8StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, Int8BondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Byte getDefaultValue() {
// box
return this.initialize();
}
public final byte initialize() {
return this.defaultValue;
}
public final byte clone(byte value) {
return value;
}
public final void serialize(
SerializationContext context, byte value) throws IOException {
Int8BondType.serializePrimitiveField(context, value, this);
}
public final byte deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return Int8BondType.deserializePrimitiveField(context, this);
}
public final byte deserialize(UntaggedDeserializationContext context) throws IOException {
return Int8BondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the int8 primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingInt8StructField extends StructField<Byte> {
public SomethingInt8StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.INT8, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Byte getDefaultValue() {
return null;
}
public final SomethingByte initialize() {
return null;
}
public final SomethingByte clone(SomethingByte value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingByte value) throws IOException {
Int8BondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingByte deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return Int8BondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingByte deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(Int8BondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the int16 primitive data type
* that are not defaulting to "nothing".
*/
protected static final class Int16StructField extends StructField<Short> {
private final short defaultValue;
public Int16StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
short defaultValue) {
super(structType, BondTypes.INT16, id, name, modifier);
this.defaultValue = defaultValue;
}
public Int16StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, Int16BondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Short getDefaultValue() {
// box
return this.initialize();
}
public final short initialize() {
return this.defaultValue;
}
public final short clone(short value) {
return value;
}
public final void serialize(
SerializationContext context, short value) throws IOException {
Int16BondType.serializePrimitiveField(context, value, this);
}
public final short deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return Int16BondType.deserializePrimitiveField(context, this);
}
public final short deserialize(UntaggedDeserializationContext context) throws IOException {
return Int16BondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the int16 primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingInt16StructField extends StructField<Short> {
public SomethingInt16StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.INT16, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Short getDefaultValue() {
return null;
}
public final SomethingShort initialize() {
return null;
}
public final SomethingShort clone(SomethingShort value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingShort value) throws IOException {
Int16BondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingShort deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return Int16BondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingShort deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(Int16BondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the int32 primitive data type
* that are not defaulting to "nothing".
*/
protected static final class Int32StructField extends StructField<Integer> {
private final int defaultValue;
public Int32StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
int defaultValue) {
super(structType, BondTypes.INT32, id, name, modifier);
this.defaultValue = defaultValue;
}
public Int32StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, Int32BondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Integer getDefaultValue() {
// box
return this.initialize();
}
public final int initialize() {
return this.defaultValue;
}
public final int clone(int value) {
return value;
}
public final void serialize(
SerializationContext context, int value) throws IOException {
Int32BondType.serializePrimitiveField(context, value, this);
}
public final int deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return Int32BondType.deserializePrimitiveField(context, this);
}
public final int deserialize(UntaggedDeserializationContext context) throws IOException {
return Int32BondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the int32 primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingInt32StructField extends StructField<Integer> {
public SomethingInt32StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.INT32, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Integer getDefaultValue() {
return null;
}
public final SomethingInteger initialize() {
return null;
}
public final SomethingInteger clone(SomethingInteger value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingInteger value) throws IOException {
Int32BondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingInteger deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return Int32BondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingInteger deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(Int32BondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the int64 primitive data type
* that are not defaulting to "nothing".
*/
protected static final class Int64StructField extends StructField<Long> {
private final long defaultValue;
public Int64StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
long defaultValue) {
super(structType, BondTypes.INT64, id, name, modifier);
this.defaultValue = defaultValue;
}
public Int64StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, Int64BondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Long getDefaultValue() {
// box
return this.initialize();
}
public final long initialize() {
return this.defaultValue;
}
public final long clone(long value) {
return value;
}
public final void serialize(
SerializationContext context, long value) throws IOException {
Int64BondType.serializePrimitiveField(context, value, this);
}
public final long deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return Int64BondType.deserializePrimitiveField(context, this);
}
public final long deserialize(UntaggedDeserializationContext context) throws IOException {
return Int64BondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the int64 primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingInt64StructField extends StructField<Long> {
public SomethingInt64StructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.INT64, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Long getDefaultValue() {
return null;
}
public final SomethingLong initialize() {
return null;
}
public final SomethingLong clone(SomethingLong value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingLong value) throws IOException {
Int64BondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingLong deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return Int64BondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingLong deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(Int64BondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the bool primitive data type
* that are not defaulting to "nothing".
*/
protected static final class BoolStructField extends StructField<Boolean> {
private final boolean defaultValue;
public BoolStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
boolean defaultValue) {
super(structType, BondTypes.BOOL, id, name, modifier);
this.defaultValue = defaultValue;
}
public BoolStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, BoolBondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Boolean getDefaultValue() {
// box
return this.initialize();
}
public final boolean initialize() {
return this.defaultValue;
}
public final boolean clone(boolean value) {
return value;
}
public final void serialize(
SerializationContext context, boolean value) throws IOException {
BoolBondType.serializePrimitiveField(context, value, this);
}
public final boolean deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return BoolBondType.deserializePrimitiveField(context, this);
}
public final boolean deserialize(UntaggedDeserializationContext context) throws IOException {
return BoolBondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the bool primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingBoolStructField extends StructField<Boolean> {
public SomethingBoolStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.BOOL, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Boolean getDefaultValue() {
return null;
}
public final SomethingBoolean initialize() {
return null;
}
public final SomethingBoolean clone(SomethingBoolean value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingBoolean value) throws IOException {
BoolBondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingBoolean deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return BoolBondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingBoolean deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(BoolBondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the float primitive data type
* that are not defaulting to "nothing".
*/
protected static final class FloatStructField extends StructField<Float> {
private final float defaultValue;
public FloatStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
float defaultValue) {
super(structType, BondTypes.FLOAT, id, name, modifier);
this.defaultValue = defaultValue;
}
public FloatStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, FloatBondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Float getDefaultValue() {
// box
return this.initialize();
}
public final float initialize() {
return this.defaultValue;
}
public final float clone(float value) {
return value;
}
public final void serialize(
SerializationContext context, float value) throws IOException {
FloatBondType.serializePrimitiveField(context, value, this);
}
public final float deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return FloatBondType.deserializePrimitiveField(context, this);
}
public final float deserialize(UntaggedDeserializationContext context) throws IOException {
return FloatBondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the float primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingFloatStructField extends StructField<Float> {
public SomethingFloatStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.FLOAT, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Float getDefaultValue() {
return null;
}
public final SomethingFloat initialize() {
return null;
}
public final SomethingFloat clone(SomethingFloat value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingFloat value) throws IOException {
FloatBondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingFloat deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return FloatBondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingFloat deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(FloatBondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the double primitive data type
* that are not defaulting to "nothing".
*/
protected static final class DoubleStructField extends StructField<Double> {
private final double defaultValue;
public DoubleStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
double defaultValue) {
super(structType, BondTypes.DOUBLE, id, name, modifier);
this.defaultValue = defaultValue;
}
public DoubleStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, DoubleBondType.DEFAULT_VALUE_AS_PRIMITIVE);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final Double getDefaultValue() {
// box
return this.initialize();
}
public final double initialize() {
return this.defaultValue;
}
public final double clone(double value) {
return value;
}
public final void serialize(
SerializationContext context, double value) throws IOException {
DoubleBondType.serializePrimitiveField(context, value, this);
}
public final double deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return DoubleBondType.deserializePrimitiveField(context, this);
}
public final double deserialize(UntaggedDeserializationContext context) throws IOException {
return DoubleBondType.deserializePrimitiveValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the double primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingDoubleStructField extends StructField<Double> {
public SomethingDoubleStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.DOUBLE, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final Double getDefaultValue() {
return null;
}
public final SomethingDouble initialize() {
return null;
}
public final SomethingDouble clone(SomethingDouble value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingDouble value) throws IOException {
DoubleBondType.serializePrimitiveSomethingField(context, value, this);
}
public final SomethingDouble deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return DoubleBondType.deserializePrimitiveSomethingField(context, this);
}
public final SomethingDouble deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(DoubleBondType.deserializePrimitiveValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the string primitive data type
* that are not defaulting to "nothing".
*/
protected static final class StringStructField extends StructField<String> {
private final String defaultValue;
public StringStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
String defaultValue) {
super(structType, BondTypes.STRING, id, name, modifier);
this.defaultValue = defaultValue;
}
// used by codegen
public StringStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, StringBondType.DEFAULT_VALUE_AS_OBJECT);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final String getDefaultValue() {
return this.initialize();
}
public final String initialize() {
return this.defaultValue;
}
public final String clone(String value) {
return value;
}
public final void serialize(
SerializationContext context, String value) throws IOException {
this.fieldType.serializeField(context, value, this);
}
public final String deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return this.fieldType.deserializeField(context, this);
}
public final String deserialize(UntaggedDeserializationContext context) throws IOException {
return this.fieldType.deserializeValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the string primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingStringStructField extends StructField<String> {
public SomethingStringStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.STRING, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final String getDefaultValue() {
return null;
}
public final SomethingObject<String> initialize() {
return null;
}
public final SomethingObject<String> clone(SomethingObject<String> value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingObject<String> value) throws IOException {
this.fieldType.serializeSomethingField(context, value, this);
}
public final SomethingObject<String> deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return this.fieldType.deserializeSomethingField(context, this);
}
public final SomethingObject<String> deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(this.fieldType.deserializeValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the string primitive data type
* that are not defaulting to "nothing".
*/
protected static final class WStringStructField extends StructField<String> {
private final String defaultValue;
public WStringStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier,
String defaultValue) {
super(structType, BondTypes.WSTRING, id, name, modifier);
this.defaultValue = defaultValue;
}
// used by codegen
public WStringStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
this(structType, id, name, modifier, WStringBondType.DEFAULT_VALUE_AS_OBJECT);
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final String getDefaultValue() {
return this.initialize();
}
public final String initialize() {
return this.defaultValue;
}
public final String clone(String value) {
return value;
}
public final void serialize(
SerializationContext context, String value) throws IOException {
this.fieldType.serializeField(context, value, this);
}
public final String deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return this.fieldType.deserializeField(context, this);
}
public final String deserialize(UntaggedDeserializationContext context) throws IOException {
return this.fieldType.deserializeValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the string primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingWStringStructField extends StructField<String> {
// used by codegen
public SomethingWStringStructField(
StructBondType<?> structType,
int id,
String name,
Modifier modifier) {
super(structType, BondTypes.WSTRING, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final String getDefaultValue() {
return null;
}
public final SomethingObject<String> initialize() {
return null;
}
public final SomethingObject<String> clone(SomethingObject<String> value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingObject<String> value) throws IOException {
this.fieldType.serializeSomethingField(context, value, this);
}
public final SomethingObject<String> deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return this.fieldType.deserializeSomethingField(context, this);
}
public final SomethingObject<String> deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(this.fieldType.deserializeValue(context));
}
}
/**
* Implements the {@link StructField} contract for fields of the string primitive data type
* that are not defaulting to "nothing".
*/
protected static final class EnumStructField<TEnum extends BondEnum<TEnum>> extends StructField<TEnum> {
private final TEnum defaultValue;
public EnumStructField(
StructBondType<?> structType,
EnumBondType<TEnum> fieldType,
int id,
String name,
Modifier modifier,
TEnum defaultValue) {
super(structType, fieldType, id, name, modifier);
this.defaultValue = defaultValue;
}
public EnumStructField(
StructBondType<?> structType,
EnumBondType<TEnum> fieldType,
int id,
String name,
Modifier modifier) {
this(structType, fieldType, id, name, modifier, fieldType.newDefaultValue());
}
@Override
public final boolean isDefaultNothing() {
return false;
}
@Override
public final TEnum getDefaultValue() {
return this.initialize();
}
public final TEnum initialize() {
return this.defaultValue;
}
public final TEnum clone(TEnum value) {
return value;
}
public final void serialize(
SerializationContext context, TEnum value) throws IOException {
this.fieldType.serializeField(context, value, this);
}
public final TEnum deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return this.fieldType.deserializeField(context, this);
}
public final TEnum deserialize(UntaggedDeserializationContext context) throws IOException {
return this.fieldType.deserializeValue(context);
}
}
/**
* Implements the {@link StructField} contract for fields of the string primitive data type
* that are defaulting to "nothing".
*/
protected static final class SomethingEnumStructField<TEnum extends BondEnum<TEnum>> extends StructField<TEnum> {
// used by codegen
public SomethingEnumStructField(
StructBondType<?> structType,
EnumBondType<TEnum> fieldType,
int id,
String name,
Modifier modifier) {
super(structType, fieldType, id, name, modifier);
}
@Override
public final boolean isDefaultNothing() {
return true;
}
@Override
public final TEnum getDefaultValue() {
return null;
}
public final SomethingObject<TEnum> initialize() {
return null;
}
public final SomethingObject<TEnum> clone(SomethingObject<TEnum> value) {
return value == null ? null : Something.wrap(value.value);
}
public final void serialize(
SerializationContext context, SomethingObject<TEnum> value) throws IOException {
this.fieldType.serializeSomethingField(context, value, this);
}
public final SomethingObject<TEnum> deserialize(
TaggedDeserializationContext context, boolean wasAlreadyDeserialized) throws IOException {
this.verifyFieldWasNotYetDeserialized(wasAlreadyDeserialized);
return this.fieldType.deserializeSomethingField(context, this);
}
public final SomethingObject<TEnum> deserialize(UntaggedDeserializationContext context) throws IOException {
return Something.wrap(this.fieldType.deserializeValue(context));
}
}
}
|
package com.carmanconsulting.akka;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.Terminated;
import akka.actor.UntypedActor;
import org.junit.Test;
public class StoppingTest extends AkkaTestCase {
// Other Methods
@Test
public void testStopMethod() {
ActorRef echo = system().actorOf(Props.create(EchoAndStop.class), "echo");
watch(echo);
echo.tell("Hello", testActor());
expectMsg("Hello");
expectMsgClass(Terminated.class);
}
// Inner Classes
public static class EchoAndStop extends UntypedActor {
@Override
public void onReceive(Object message) throws Exception {
sender().tell(message, self());
context().stop(self());
}
}
}
|
package com.mgmtp.jfunk.unit;
import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.mgmtp.jfunk.common.JFunkConstants;
import com.mgmtp.jfunk.core.module.TestModule;
import com.mgmtp.jfunk.core.reporting.Reporter;
import com.mgmtp.jfunk.core.scripting.ScriptContext;
/**
* Allows "jFunk scripting" in unit tests. An instance of this class can be injected into a unit
* test class.
*
* @author rnaegele
*/
@Singleton
@ThreadSafe
public final class JFunkRunner {
private final Provider<ScriptContext> scriptContextProvider;
/**
* Creates a new instance.
*
* @param scriptContextProvider
* provides the correctly scoped {@link ScriptContext}
*/
@Inject
JFunkRunner(final Provider<ScriptContext> scriptContextProvider) {
this.scriptContextProvider = scriptContextProvider;
}
/**
* @see ScriptContext#copyFormEntry(String, String, String, String)
*/
public void copyFormEntry(final String srcDataSetKey, final String srcKey, final String destDataSetKey, final String destKey) {
scriptContextProvider.get().copyFormEntry(srcDataSetKey, srcKey, destDataSetKey, destKey);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#load(String, boolean)
*/
public void load(final String propertiesFile, final boolean preserveExisting) {
scriptContextProvider.get().load(propertiesFile, preserveExisting);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#generate(String)
* @deprecated use {@link #prepareNextDataSet(String)}
*/
@Deprecated
public void generate(final String dataSetKey) {
scriptContextProvider.get().generate(dataSetKey);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#prepareNextDataSet(String)
*/
public void prepareNextDataSet(final String dataSetKey) {
scriptContextProvider.get().prepareNextDataSet(dataSetKey);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#registerReporter(Reporter)
*/
public Reporter registerReporter(final Reporter reporter) {
return scriptContextProvider.get().registerReporter(reporter);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#get(String)
*/
public String get(final String configKey) {
return scriptContextProvider.get().get(configKey);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#resetFixedData(String, String)
*/
public void resetFixedData() {
scriptContextProvider.get().resetFixedData(null, null);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#resetFixedData(String, String)
*/
public void resetFixedData(final String dataSetKey) {
scriptContextProvider.get().resetFixedData(dataSetKey, null);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#resetFixedData(String, String)
*/
public void resetFixedData(final String dataSetKey, final String entryKey) {
scriptContextProvider.get().resetFixedData(dataSetKey, entryKey);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#run(String)
*/
public void run(final String testModuleClassName) {
scriptContextProvider.get().run(testModuleClassName);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#run(TestModule)
*/
public void run(final TestModule testModule) {
scriptContextProvider.get().run(testModule);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#run(TestModule)
*/
public void runModule() {
ScriptContext scriptContext = scriptContextProvider.get();
scriptContext.run(scriptContext.get("${" + JFunkConstants.TESTMODULE_CLASS + "}"));
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#resetDataSource()
*/
public void resetDataSource() {
scriptContextProvider.get().resetDataSource();
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#setFormEntry(String, String, String)
*/
public void setFormEntry(final String dataSetKey, final String entryKey, final String value) {
scriptContextProvider.get().setFormEntry(dataSetKey, entryKey, value);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#set(String, String)
*/
public void set(final String key, final String value) {
scriptContextProvider.get().set(key, value);
}
/**
* @see com.mgmtp.jfunk.core.scripting.ScriptContext#setNow(String, String)
*/
public void setNow(final String key, final String value) {
scriptContextProvider.get().setNow(key, value);
}
}
|
package com.github.aha.poc.junit5;
import static com.github.aha.poc.junit5.SpyingTests.Greeting.GreetingService.WELCOME;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import lombok.Getter;
@DisplayName("Examples of spying tests")
public class SpyingTests {
@Nested
class Greeting {
@Test
@DisplayName("should use service in standard way")
void regularUsage() {
HelloService service = new HelloService();
assertThat(service.sayGreeting()).isEqualTo("Welcome and Hello");
assertThat(service.generalGreeting).isEqualTo(WELCOME);
}
@Test
@DisplayName("should mock inherited method in spied class")
void mockInheritedMethod() {
HelloService spiedService = Mockito.spy(new HelloService());
Mockito.doNothing().when((HelloService) spiedService).initGreeting();
assertThat(spiedService.sayGreeting()).isEqualTo("Hello");
assertThat(spiedService.generalGreeting).isEmpty();
}
abstract class GreetingService {
static final String WELCOME = "Welcome and ";
String generalGreeting = "";
public String sayGreeting() {
initGreeting();
return getGreeting();
}
protected abstract String getGreeting();
void initGreeting() {
generalGreeting = WELCOME;
}
}
class HelloService extends GreetingService {
@Override
protected String getGreeting() {
return generalGreeting + "Hello";
}
}
}
@Nested
class Calculator {
@Test
@DisplayName("should use service in standard way")
void regularUsage() {
IntCalc service = new IntCalc();
assertThat(service.add(5)).isEqualTo(5);
assertThat(service.add(3)).isEqualTo(8);
assertThat(service.add(4)).isEqualTo(0);
}
@Test
@DisplayName("should mock inherited method in spied class")
void mockInheritedMethod() {
IntCalc spiedService = Mockito.spy(new IntCalc());
Mockito.doNothing().when((IntCalc) spiedService).initValue();
assertThat(spiedService.add(5)).isEqualTo(5);
assertThat(spiedService.add(3)).isEqualTo(8);
assertThat(spiedService.add(4)).isEqualTo(12);
}
abstract class AbstractCalc<V extends Number> {
@Getter
V value;
int count = 0;
{
initValue();
}
public V add(V addition) {
value = addValue(value, addition);
checkCount();
return value;
}
abstract void initValue();
abstract V addValue(V value2, V addition);
private void checkCount() {
count++;
if (count % 3 == 0) {
initValue();
}
}
}
class IntCalc extends AbstractCalc<Integer> {
@Override
protected Integer addValue(Integer currentValue, Integer addition) {
return currentValue + addition;
}
@Override
void initValue() {
value = 0;
}
}
}
}
|
package gui;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import sun.java2d.pipe.SpanShapeRenderer.Simple;
import system.PFSystem;
import domainobjects.DateRange;
import domainobjects.ExpenseFilter;
import domainobjects.IDSet;
import domainobjects.Money;
import domainobjects.MoneyRange;
import domainobjects.PayTo;
import domainobjects.PaymentMethod;
import domainobjects.SetOperation;
import domainobjects.SimpleDate;
public class FilterCreation implements IDialog
{
protected Shell shell;
private Button dateFilterCheck;
private DateTime lowerDateSelect;
private DateTime upperDateSelect;
private Button amountFilterCheck;
private Text upperAmountText;
private Text lowerAmountText;
private Button paymentFilterCheck;
private Button cashRadio;
private Button creditRadio;
private Button debitRadio;
private Button otherRadio;
private Button labelFilterCheck;
private Button selectLabelsButton;
private Button payToFilterCheck;
private Button selectPayToButton;
private Button expenseAllRadio;
private Button expenseSomeRadio;
private ExpenseFilter outputFilter = null;
private Table labelTable;
private Table payToTable;
private TableColumn tblclmnId;
private TableColumn tblclmnLabel;
private TableColumn tblclmnId_1;
private TableColumn tblclmnName;
private TableColumn tblclmnBranch;
private Composite composite_5;
/**
* Open the window.
* @wbp.parser.entryPoint
*
*/
public Object open()
{
Display display =Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
return outputFilter;
}
protected void createContents()
{
shell = new Shell(SWT.SYSTEM_MODAL | SWT.DIALOG_TRIM);
shell.setSize(767, 719);
shell.setText("Filter Creation");
composite_5 = new Composite(shell, SWT.NONE);
composite_5.setBounds(0, 0, 761, 679);
Composite composite = new Composite(composite_5, SWT.NONE);
composite.setBounds(10, 10, 733, 52);
dateFilterCheck = new Button(composite, SWT.CHECK);
dateFilterCheck.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final boolean isSelected = dateFilterCheck.getSelection();
lowerDateSelect.setEnabled(isSelected);
upperDateSelect.setEnabled(isSelected);
}
});
dateFilterCheck.setBounds(10, 10, 132, 25);
dateFilterCheck.setText("Filter by date");
lowerDateSelect = new DateTime(composite, SWT.BORDER);
lowerDateSelect.setEnabled(false);
lowerDateSelect.setBounds(467, 10, 125, 33);
upperDateSelect = new DateTime(composite, SWT.BORDER);
upperDateSelect.setEnabled(false);
upperDateSelect.setBounds(598, 10, 125, 33);
Composite composite_1 = new Composite(composite_5, SWT.NONE);
composite_1.setBounds(10, 68, 733, 50);
amountFilterCheck = new Button(composite_1, SWT.CHECK);
amountFilterCheck.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final boolean isSelected = amountFilterCheck.getSelection();
lowerAmountText.setEnabled(isSelected);
upperAmountText.setEnabled(isSelected);
}
});
amountFilterCheck.setText("Filter by amount");
amountFilterCheck.setBounds(10, 10, 159, 25);
upperAmountText = new Text(composite_1, SWT.BORDER);
upperAmountText.setEnabled(false);
upperAmountText.setText("$0.00");
upperAmountText.setBounds(600, 7, 123, 31);
lowerAmountText = new Text(composite_1, SWT.BORDER);
lowerAmountText.setEnabled(false);
lowerAmountText.setText("$0.00");
lowerAmountText.setBounds(471, 7, 123, 31);
Composite composite_2 = new Composite(composite_5, SWT.NONE);
composite_2.setBounds(10, 124, 733, 73);
paymentFilterCheck = new Button(composite_2, SWT.CHECK);
paymentFilterCheck.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final boolean isSelected = paymentFilterCheck.getSelection();
cashRadio.setEnabled(isSelected);
debitRadio.setEnabled(isSelected);
creditRadio.setEnabled(isSelected);
otherRadio.setEnabled(isSelected);
}
});
paymentFilterCheck.setText("Filter by payment");
paymentFilterCheck.setBounds(10, 39, 167, 25);
Group group = new Group(composite_2, SWT.NONE);
group.setBounds(403, 10, 320, 54);
cashRadio = new Button(group, SWT.RADIO);
cashRadio.setEnabled(false);
cashRadio.setSelection(true);
cashRadio.setText("Cash");
cashRadio.setBounds(10, 26, 67, 25);
creditRadio = new Button(group, SWT.RADIO);
creditRadio.setEnabled(false);
creditRadio.setText("Credit");
creditRadio.setBounds(161, 26, 76, 25);
debitRadio = new Button(group, SWT.RADIO);
debitRadio.setEnabled(false);
debitRadio.setText("Debit");
debitRadio.setBounds(83, 26, 72, 25);
otherRadio = new Button(group, SWT.RADIO);
otherRadio.setEnabled(false);
otherRadio.setText("Other");
otherRadio.setBounds(243, 26, 74, 25);
Composite composite_3 = new Composite(composite_5, SWT.NONE);
composite_3.setBounds(10, 203, 733, 201);
labelFilterCheck = new Button(composite_3, SWT.CHECK);
labelFilterCheck.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final boolean isSelected = labelFilterCheck.getSelection();
labelTable.setEnabled(isSelected);
selectLabelsButton.setEnabled(isSelected);
expenseAllRadio.setEnabled(isSelected);
expenseSomeRadio.setEnabled(isSelected);
}
});
labelFilterCheck.setText("Filter by labels");
labelFilterCheck.setBounds(10, 10, 142, 25);
selectLabelsButton = new Button(composite_3, SWT.NONE);
selectLabelsButton.setEnabled(false);
selectLabelsButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
IDialog selection = new LabelSelection();
IDSet labels = (IDSet)selection.open();
labelTable.removeAll();
final int totalLabels = labels.getSize();
for(int i = 0; i < totalLabels; i++)
{
final int id = labels.getValue(i);
final domainobjects.Label label = (domainobjects.Label)PFSystem.getCurrent().getLabelSystem().getDataByID(id);
// add each label to the list
TableItem labelItem = new TableItem(labelTable, SWT.NONE);
labelItem.setText(0, "" + id);
labelItem.setText(1, label.getLabelName());
}
}
});
selectLabelsButton.setBounds(10, 158, 125, 28);
selectLabelsButton.setText("Select Labels");
Group grpLabelSet = new Group(composite_3, SWT.NONE);
grpLabelSet.setText("Expense Must Have");
grpLabelSet.setBounds(533, 44, 190, 108);
expenseAllRadio = new Button(grpLabelSet, SWT.RADIO);
expenseAllRadio.setEnabled(false);
expenseAllRadio.setBounds(10, 34, 49, 25);
expenseAllRadio.setText("All");
expenseSomeRadio = new Button(grpLabelSet, SWT.RADIO);
expenseSomeRadio.setEnabled(false);
expenseSomeRadio.setSelection(true);
expenseSomeRadio.setText("Some");
expenseSomeRadio.setBounds(10, 65, 75, 25);
labelTable = new Table(composite_3, SWT.BORDER | SWT.FULL_SELECTION);
labelTable.setBounds(10, 44, 517, 108);
labelTable.setHeaderVisible(true);
labelTable.setLinesVisible(true);
tblclmnId = new TableColumn(labelTable, SWT.NONE);
tblclmnId.setWidth(100);
tblclmnId.setText("ID");
tblclmnLabel = new TableColumn(labelTable, SWT.NONE);
tblclmnLabel.setWidth(100);
tblclmnLabel.setText("Label");
Composite composite_4 = new Composite(composite_5, SWT.NONE);
composite_4.setBounds(10, 410, 733, 225);
payToFilterCheck = new Button(composite_4, SWT.CHECK);
payToFilterCheck.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final boolean isSelected = payToFilterCheck.getSelection();
payToTable.setEnabled(isSelected);
selectPayToButton.setEnabled(isSelected);
}
});
payToFilterCheck.setText("Filter by pay to");
payToFilterCheck.setBounds(10, 10, 148, 25);
selectPayToButton = new Button(composite_4, SWT.NONE);
selectPayToButton.setEnabled(false);
selectPayToButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
IDialog selection = new PaytoSelection();
final int payToID = (int)selection.open();
payToTable.removeAll();
PayTo payTo = (PayTo)PFSystem.getCurrent().getPayToSystem().getDataByID(payToID);
// set the payTo id
TableItem paytoItem = new TableItem(payToTable, SWT.NONE);
paytoItem.setText("" + payToID);
paytoItem.setText(1, payTo.getPayToName());
paytoItem.setText(2, payTo.getPayToBranch());
}
});
selectPayToButton.setBounds(10, 189, 125, 28);
selectPayToButton.setText("Select Pay To");
payToTable = new Table(composite_4, SWT.BORDER | SWT.FULL_SELECTION);
payToTable.setBounds(10, 44, 713, 139);
payToTable.setHeaderVisible(true);
payToTable.setLinesVisible(true);
tblclmnId_1 = new TableColumn(payToTable, SWT.NONE);
tblclmnId_1.setWidth(100);
tblclmnId_1.setText("ID");
tblclmnName = new TableColumn(payToTable, SWT.NONE);
tblclmnName.setWidth(100);
tblclmnName.setText("Name");
tblclmnBranch = new TableColumn(payToTable, SWT.NONE);
tblclmnBranch.setWidth(100);
tblclmnBranch.setText("Branch");
Button filterButton = new Button(composite_5, SWT.NONE);
filterButton.setBounds(649, 641, 94, 28);
filterButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
closeWithReturn(generateFilterFromGUI());
}
});
filterButton.setText("Filter");
Button cancelButton = new Button(composite_5, SWT.NONE);
cancelButton.setBounds(10, 641, 94, 28);
cancelButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
closeWithReturn(null);
}
});
cancelButton.setText("Cancel");
}
private ExpenseFilter generateFilterFromGUI()
{
ExpenseFilter output = new ExpenseFilter();
if(dateFilterCheck.getSelection())
{
output.assignDateRange(getDateRange());
}
if(amountFilterCheck.getSelection())
{
output.assignMoneyRange(getMoneyRange());
}
if(paymentFilterCheck.getSelection())
{
output.assignmentPaymentMethod(getPaymentMethod());
}
if(labelFilterCheck.getSelection())
{
output.assignLabels(getLabelSet(), getSetOperation());
}
if(payToFilterCheck.getSelection())
{
output.assignPayTo(getPayToSet());
}
return output;
}
private DateRange getDateRange()
{
SimpleDate lower = SimpleDate.Now();
lower.setYear(lowerDateSelect.getYear());
lower.setMonth(lowerDateSelect.getMonth());
lower.setDay(lowerDateSelect.getDay());
SimpleDate upper = SimpleDate.Now();
upper.setYear(upperDateSelect.getYear());
upper.setMonth(upperDateSelect.getMonth());
upper.setDay(upperDateSelect.getDay());
return new DateRange(lower, upper);
}
private MoneyRange getMoneyRange()
{
Money lower = Money.fromString(lowerAmountText.getText());
Money upper = Money.fromString(upperAmountText.getText());
return new MoneyRange(lower, upper);
}
private PaymentMethod getPaymentMethod()
{
if(cashRadio.getSelection())
{
return PaymentMethod.CASH;
}
else if(debitRadio.getSelection())
{
return PaymentMethod.DEBIT;
}
else if(creditRadio.getSelection())
{
return PaymentMethod.CREDIT;
}
else
{
return PaymentMethod.OTHER;
}
}
private IDSet getLabelSet()
{
return GUIHelper.getLabelIDSetFromTable(labelTable);
}
private SetOperation getSetOperation()
{
if(expenseAllRadio.getSelection())
{
return SetOperation.INTERSECTION;
}
else
{
return SetOperation.UNION;
}
}
private IDSet getPayToSet()
{
final int id = Integer.parseInt(payToTable.getItem(0).getText(0));
return IDSet.createFromValue(id);
}
private void closeWithReturn(ExpenseFilter filter)
{
assert filter == null || filter != outputFilter; // do not set the filter to itself
outputFilter = filter;
shell.close();
}
}
|
package com.meltmedia.cadmium.cli;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.meltmedia.cadmium.core.git.GitService;
import com.meltmedia.cadmium.status.Status;
import com.meltmedia.cadmium.status.StatusMember;
@Parameters(commandDescription = "Instructs a site to update its content.")
public class UpdateCommand {
private final Logger log = LoggerFactory.getLogger(getClass());
@Parameter(names="--branch", description="The branch that you are updating", required=true)
private String branch;
@Parameter(names="--revision", description="The revision that you are updating to", required=true)
private String revision;
@Parameter(names="--site", description="The site that is to be updated", required=true)
private String site;
@Parameter(names="--comment", description="The comment for the history", required=true)
private String comment;
@Parameter(names="--force", description="Force the update", required=false)
private String force;
public static final String JERSEY_ENDPOINT = "/system/update";
public void execute() throws ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
String url = site + JERSEY_ENDPOINT;
log.debug("site + JERSEY_ENDPOINT = {}", url);
System.out.println("Getting status of ["+site+"]");
try {
Status siteStatus = CloneCommand.getSiteStatus(site);
boolean branchSame = true;
boolean revisionSame = true;
boolean forceUpdate = false;
String currentRevision = siteStatus.getRevision();
String currentBranch = siteStatus.getBranch();
if(force != null) {
forceUpdate = true;
}
if(!branch.trim().equals(currentBranch.trim())) {
//update the branch to requested branch
branch = currentBranch.trim();
branchSame = false;
}
if(revision.trim().equals(currentRevision.trim())) {
//update the branch to requested branch
revision = currentRevision.trim();
revisionSame = false;
}
if( branchSame && revisionSame && !forceUpdate) {
System.out.println("The site [" + site + "] is already on branch [" + branch + "] and revision [" + revision + "].");
}
else {
HttpPost post = new HttpPost(url);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("branch", branch.trim()));
nvps.add(new BasicNameValuePair("rev", revision.trim()));
nvps.add(new BasicNameValuePair("comment", comment.trim()));
post.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
HttpResponse response = client.execute(post);
System.out.println(response.toString());
}
}
catch (Exception e) {
System.err.println("Failed to updated site [" + site + "] to branch [" + branch + "] and revision [" + revision + "].");
}
}
}
|
package com.microsoft.rest;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.primitives.Primitives;
import com.google.common.reflect.TypeToken;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
/**
* Validates user provided parameters are not null if they are required.
*/
public final class Validator {
/**
* Hidden constructor for utility class.
*/
private Validator() { }
public static void validate(Object parameter) throws IllegalArgumentException {
// Validation of top level payload is done outside
if (parameter == null) {
return;
}
Class parameterType = parameter.getClass();
TypeToken<?> parameterToken = TypeToken.of(parameterType);
if (Primitives.isWrapperType(parameterType)) {
parameterToken = parameterToken.unwrap();
}
if (parameterToken.isPrimitive()
|| parameterType.isEnum()
|| parameterToken.isAssignableFrom(LocalDate.class)
|| parameterToken.isAssignableFrom(DateTime.class)
|| parameterToken.isAssignableFrom(String.class)
|| parameterToken.isAssignableFrom(DateTimeRfc1123.class)
|| parameterToken.isAssignableFrom(Period.class)) {
return;
}
for (Class<?> c : parameterToken.getTypes().classes().rawTypes()) {
// Ignore checks for Object type.
if (c.isAssignableFrom(Object.class)) {
continue;
}
for (Field field : c.getDeclaredFields()) {
field.setAccessible(true);
int mod = field.getModifiers();
// Skip static fields since we don't have any, skip final fields since users can't modify them
if (Modifier.isFinal(mod) || Modifier.isStatic(mod)) {
continue;
}
JsonProperty annotation = field.getAnnotation(JsonProperty.class);
// Skip read-only properties (WRITE_ONLY)
if (annotation != null && annotation.access().equals(JsonProperty.Access.WRITE_ONLY)) {
continue;
}
Object property;
try {
property = field.get(parameter);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
if (property == null) {
if (annotation != null && annotation.required()) {
throw new IllegalArgumentException(field.getName() + " is required and cannot be null.");
}
} else {
try {
Class<?> propertyType = property.getClass();
if (TypeToken.of(List.class).isAssignableFrom(propertyType)) {
List<?> items = (List<?>) property;
for (Object item : items) {
Validator.validate(item);
}
}
else if (TypeToken.of(Map.class).isAssignableFrom(propertyType)) {
Map<?, ?> entries = (Map<?, ?>) property;
for (Map.Entry<?, ?> entry : entries.entrySet()) {
Validator.validate(entry.getKey());
Validator.validate(entry.getValue());
}
}
else if (parameterType != propertyType) {
Validator.validate(property);
}
} catch (IllegalArgumentException ex) {
if (ex.getCause() == null) {
// Build property chain
throw new IllegalArgumentException(field.getName() + "." + ex.getMessage());
} else {
throw ex;
}
}
}
}
}
}
}
|
package com.sendwithus;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import com.sendwithus.exception.SendWithUsException;
/**
* POJO encapsulating parameters for SendWithUs "send" API calls.
*/
public class SendWithUsSendRequest
{
private String emailId = null;
private Map<String, Object> recipient = null;
private Map<String, Object> emailData = null;
private Map<String, Object>[] ccRecipients = null;
private Map<String, Object>[] bccRecipients = null;
private Map<String, Object> sender = null;
private String[] tags = null;
private Map<String, String> inline = null;
private String[] attachmentPaths = null;
private String espAccount = null;
private String versionName = null;
private String locale = null;
private Map<String, String> headers = null;
public SendWithUsSendRequest()
{
}
/**
* @return HashMap of request parameters for "send" API call
* @throws SendWithUsException
*/
public Map<String, Object> asMap() throws SendWithUsException
{
Map<String, Object> sendParams = new HashMap<String, Object>();
sendParams.put("email_id", emailId);
sendParams.put("recipient", recipient);
sendParams.put("email_data", emailData);
// sender is optional
if (sender != null)
{
sendParams.put("sender", sender);
}
// cc is optional
if ((ccRecipients != null) && (ccRecipients.length > 0))
{
sendParams.put("cc", ccRecipients);
}
// bcc is optional
if ((bccRecipients != null) && (bccRecipients.length > 0))
{
sendParams.put("bcc", bccRecipients);
}
if ((attachmentPaths != null) && (attachmentPaths.length > 0))
{
ArrayList<HashMap<String, String>> files = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < attachmentPaths.length; i++)
{
try
{
File file = new File(attachmentPaths[i]);
byte[] byteArray = FileUtils.readFileToByteArray(file);
byte[] encodedBytes = Base64.encodeBase64(byteArray);
HashMap<String, String> file_map = new HashMap<String, String>();
file_map.put("id",
FilenameUtils.getName(attachmentPaths[i]));
file_map.put("data", new String(encodedBytes));
files.add(file_map);
}
catch (IOException e)
{
throw new SendWithUsException("Caught IOException", e);
}
}
sendParams.put("files", files);
}
if ((tags != null) && (tags.length > 0))
{
sendParams.put("tags", tags);
}
if (inline != null)
{
sendParams.put("inline", inline);
}
if (espAccount != null)
{
sendParams.put("esp_account", espAccount);
}
if (versionName != null)
{
sendParams.put("version_name", versionName);
}
if (locale != null)
{
sendParams.put("locale", locale);
}
if (headers != null)
{
sendParams.put("headers", headers);
}
return sendParams;
}
public SendWithUsSendRequest setEmailId(String emailId)
{
this.emailId = emailId;
return this;
}
public SendWithUsSendRequest setRecipient(Map<String, Object> recipient)
{
this.recipient = recipient;
return this;
}
public SendWithUsSendRequest setEmailData(Map<String, Object> emailData)
{
this.emailData = emailData;
return this;
}
public SendWithUsSendRequest setCcRecipients(
Map<String, Object>[] ccRecipients)
{
this.ccRecipients = ccRecipients;
return this;
}
public SendWithUsSendRequest setBccRecipients(
Map<String, Object>[] bccRecipients)
{
this.bccRecipients = bccRecipients;
return this;
}
public SendWithUsSendRequest setSender(Map<String, Object> sender)
{
this.sender = sender;
return this;
}
public SendWithUsSendRequest setTags(String[] tags)
{
this.tags = tags;
return this;
}
public SendWithUsSendRequest setInline(Map<String, String> inline)
{
this.inline = inline;
return this;
}
public SendWithUsSendRequest setAttachmentPaths(String[] attachmentPaths)
{
this.attachmentPaths = attachmentPaths;
return this;
}
public SendWithUsSendRequest setEspAccount(String espAccount)
{
this.espAccount = espAccount;
return this;
}
public SendWithUsSendRequest setVersionName(String versionName)
{
this.versionName = versionName;
return this;
}
public SendWithUsSendRequest setLocale(String locale)
{
this.locale = locale;
return this;
}
public SendWithUsSendRequest setHeaders(Map<String, String> headers)
{
this.headers = headers;
return this;
}
}
|
package classycle.graph;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
/**
* A processor which extracts the strong components of a directed graph.
* A strong component is a maximal strongly connected subgraph of a
* directed graph. The implementation is based on Tarjan's algorithm.
*
* @author Franz-Josef Elmer
*/
public class StrongComponentProcessor extends GraphProcessor {
private final boolean _calculateAttributes;
private int _counter;
private Stack _vertexStack = new Stack();
private Vector _strongComponents = new Vector();
private Hashtable _vertexToComponents = new Hashtable();
private StrongComponent[] _graph;
/**
* Creates an instance.
* @param calculateAttributes If <tt>true</tt> the attributes of the
* strong components will be calculated. Otherwise not.
*/
public StrongComponentProcessor(boolean calculateAttributes) {
_calculateAttributes = calculateAttributes;
}
/**
* Returns the result of {@link #deepSearchFirst}.
*/
public StrongComponent[] getStrongComponents() {
return _graph;
}
protected void initializeProcessing(Vertex[] graph) {
_counter = 0;
_vertexStack.setSize(0);
_strongComponents.setSize(0);
_vertexToComponents.clear();
}
protected void processBefore(Vertex vertex) {
final AtomicVertex atomicVertex = castAsAtomicVertex(vertex);
atomicVertex.setOrder(_counter);
atomicVertex.setLow(_counter++);
_vertexStack.push(atomicVertex);
}
protected void processArc(Vertex tail, Vertex head) {
final AtomicVertex t = castAsAtomicVertex(tail);
final AtomicVertex h = castAsAtomicVertex(head);
if (h.isGraphVertex()) {
if (!h.isVisited()) {
process(h);
t.setLow(Math.min(t.getLow(), h.getLow()));
} else if (h.getOrder() < t.getOrder() && _vertexStack.contains(h)) {
t.setLow(Math.min(t.getLow(), h.getOrder()));
}
}
}
protected void processAfter(Vertex vertex) {
final AtomicVertex atomicVertex = castAsAtomicVertex(vertex);
if (atomicVertex.getLow() == atomicVertex.getOrder()) {
StrongComponent component = new StrongComponent();
while (!_vertexStack.isEmpty()
&& ((AtomicVertex) _vertexStack.peek()).getOrder()
>= atomicVertex.getOrder()) {
AtomicVertex vertexOfComponent = (AtomicVertex) _vertexStack.pop();
component.addVertex(vertexOfComponent);
_vertexToComponents.put(vertexOfComponent, component);
}
_strongComponents.addElement(component);
}
}
/**
* Adds all arcs to the strong components. There is an arc from a strong
* component to another one if there is at least one arc from a vertex
* of one component to a vertex the other one.
*/
protected void finishProcessing(Vertex[] graph) {
_graph = new StrongComponent[_strongComponents.size()];
for (int i = 0; i < _graph.length; i++) {
_graph[i] = (StrongComponent) _strongComponents.elementAt(i);
if (_calculateAttributes) {
_graph[i].calculateAttributes();
}
}
Enumeration keys = _vertexToComponents.keys();
while (keys.hasMoreElements()) {
AtomicVertex vertex = (AtomicVertex) keys.nextElement();
StrongComponent tail = (StrongComponent) _vertexToComponents.get(vertex);
for (int i = 0, n = vertex.getNumberOfOutgoingArcs(); i < n; i++) {
AtomicVertex h = (AtomicVertex) vertex.getHeadVertex(i);
if (h.isGraphVertex()) {
StrongComponent head = (StrongComponent) _vertexToComponents.get(h);
if (head != tail) {
tail.addOutgoingArcTo(head);
}
}
}
}
}
private AtomicVertex castAsAtomicVertex(Vertex vertex) {
if (vertex instanceof AtomicVertex) {
return (AtomicVertex) vertex;
} else {
throw new IllegalArgumentException(
vertex + " is not an instance of AtomicVertex");
}
}
} //class
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.*;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class MainRobot extends IterativeRobot {
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
RobotActuators.initialize();
RobotSensors.initialize();
RobotDrive.initialize();
//RobotPickUp.initialize();
//RobotDrive.initialize();
//RobotShoot.initialize();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
//runCompressor();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
runCompressor();
// RobotDrive.update();
// RobotDrive.driveStraight(0.5);
RobotDrive.update();
// RobotDrive.test();
// RobotDrive.drive(0.5, 1);
RobotDrive.joystickDrive(); //HOLD X -> HIGH GEAR, HOLD Y -> STOP
/*RobotShoot.update();
boolean shoot = RobotSensors.ballReadyToLiftLim.get(); //this is just for testing 3rd switch
//System.out.println("this is the value of shoot: " + shoot);
if (shoot) {
RobotShoot.testShooter();
}*/
//RobotPickUp.update();
//RobotPickUp.test(false, false, true);
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
}
private void runCompressor() {
if (!RobotSensors.pressureSwitch.get()) {
RobotActuators.compressor.set(Relay.Value.kOn);
System.out.println("Setting the compressor to ON");
} else {
RobotActuators.compressor.set(Relay.Value.kOff);
}
System.out.println("runCompressor finished");
}
}
|
package org.intermine.bio.gbrowse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryCollectionReference;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.bio.postprocess.PostProcessOperationsTask;
import org.intermine.bio.postprocess.PostProcessUtil;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.proxy.ProxyCollection;
import org.intermine.util.DynamicUtil;
import org.intermine.util.TypeUtil;
import org.flymine.model.genomic.Analysis;
import org.flymine.model.genomic.CDS;
import org.flymine.model.genomic.Chromosome;
import org.flymine.model.genomic.ChromosomeBand;
import org.flymine.model.genomic.ComputationalAnalysis;
import org.flymine.model.genomic.ComputationalResult;
import org.flymine.model.genomic.Evidence;
import org.flymine.model.genomic.Exon;
import org.flymine.model.genomic.Gene;
import org.flymine.model.genomic.LocatedSequenceFeature;
import org.flymine.model.genomic.Location;
import org.flymine.model.genomic.MRNA;
import org.flymine.model.genomic.NcRNA;
import org.flymine.model.genomic.Sequence;
import org.flymine.model.genomic.Synonym;
import org.flymine.model.genomic.Transcript;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
/**
* A Task for creating GFF and FASTA files for use by GBrowse. Only those features that are
* located on a Chromosome are written.
* @author Kim Rutherford
*/
public class WriteGFFTask extends Task
{
protected static final Logger LOG = Logger.getLogger(WriteGFFTask.class);
private String alias;
private File destinationDirectory;
/**
* Set the ObjectStore alias to read from
* @param alias name of the ObjectStore
*/
public void setAlias(String alias) {
this.alias = alias;
}
/**
* Set the name of the directory where the GFF and FASTA files should be created.
* @param destinationDirectory the directory for creating new files in.
*/
public void setDest(File destinationDirectory) {
this.destinationDirectory = destinationDirectory;
}
/**
* {@inheritDoc}
*/
public void execute() throws BuildException {
if (destinationDirectory == null) {
throw new BuildException("dest attribute is not set");
}
if (alias == null) {
throw new BuildException("alias attribute is not set");
}
ObjectStore os = null;
try {
os = ObjectStoreFactory.getObjectStore(alias);
writeGFF(os);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new BuildException(e);
}
}
/**
* Create a GFF and FASTA files for the objects in the given ObjectStore, suitable for reading
* by GBrowse.
* @param os the ObjectStore to read from
* @throws ObjectStoreException if the is a problem with the ObjectStore
* @throws IOException if there is a problem while writing
*/
void writeGFF(ObjectStore os)
throws ObjectStoreException, IOException {
Results results =
PostProcessUtil.findLocationAndObjects(os, Chromosome.class,
LocatedSequenceFeature.class, false);
results.setBatchSize(2000);
Iterator resIter = results.iterator();
PrintWriter gffWriter = null;
// a Map of object classes to counts
Map objectCounts = null;
// Map from Transcript to Location (on Chromosome)
Map seenTranscripts = new HashMap();
// Map from exon to Location (on Chromosome)
Map seenTranscriptParts = new HashMap();
// the last Chromosome seen
Integer currentChrId = null;
Chromosome currentChr = null;
Map synonymMap = null;
Map evidenceMap = null;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Integer resultChrId = (Integer) rr.get(0);
LocatedSequenceFeature feature = (LocatedSequenceFeature) rr.get(1);
Location loc = (Location) rr.get(2);
// TODO XXX FIXME - see #628
if (feature instanceof ChromosomeBand) {
continue;
}
try {
if (TypeUtil.isInstanceOf(feature,
"org.flymine.model.genomic.ArtificialDeletion")) {
try {
if (TypeUtil.getFieldValue(feature, "available") != Boolean.TRUE) {
// write only the available deletions because there are too many
// ArtificialDeletions for GBrowse to work well
continue;
}
} catch (IllegalAccessException e) {
throw new RuntimeException("can't access 'available' field in: " + feature);
}
}
} catch (ClassNotFoundException e) {
// ignore - ArtificialDeletion is not in the model
}
if (feature instanceof CDS) {
// writeTranscriptsAndExons() for use by the processed_transcript
// aggregator
continue;
}
// special case for stemcellmine
if (feature.getChromosome() == null) {
continue;
}
if (feature.getChromosome().getIdentifier() == null) {
continue;
}
if (currentChrId == null || !currentChrId.equals(resultChrId)) {
if (currentChrId != null) {
writeTranscriptsAndExons(gffWriter, currentChr, seenTranscripts,
seenTranscriptParts, synonymMap, evidenceMap);
seenTranscripts = new HashMap();
seenTranscriptParts = new HashMap();
}
synonymMap = makeSynonymMap(os, resultChrId);
evidenceMap = makeEvidenceMap(os, resultChrId);
currentChr = (Chromosome) os.getObjectById(resultChrId);
if (currentChr == null) {
throw new RuntimeException("get null from getObjectById()");
}
if (currentChr.getIdentifier() == null) {
LOG.error("chromosome has no identifier: " + currentChr);
continue;
}
if (currentChr.getOrganism() == null) {
LOG.error("chromosome has no organism: " + currentChr);
continue;
}
if (currentChr.getOrganism().getAbbreviation() == null
|| !currentChr.getIdentifier().endsWith("_random")
&& !currentChr.getIdentifier().equals("M")
&& !currentChr.getOrganism().getAbbreviation().equals("MM")
&& !currentChr.getOrganism().getAbbreviation().equals("MD")
&& !currentChr.getOrganism().getAbbreviation().equals("CF")
&& !currentChr.getOrganism().getAbbreviation().equals("RN")) {
writeChromosomeFasta(currentChr);
File gffFile = chromosomeGFFFile(currentChr);
if (gffWriter != null) {
gffWriter.close();
}
gffWriter = new PrintWriter(new FileWriter(gffFile));
List synonymList = (List) synonymMap.get(currentChr.getId());
List evidenceList = (List) evidenceMap.get(currentChr.getId());
writeFeature(gffWriter, currentChr, currentChr, null,
chromosomeFileNamePrefix(currentChr),
"chromosome",
"Chromosome", null, synonymList, evidenceList, currentChr.getId());
objectCounts = new HashMap();
currentChrId = resultChrId;
}
}
// process Transcripts but not tRNAs
// we can't just check for MRNA because the Transcripts of Pseudogenes aren't MRNAs
if (feature instanceof Transcript && !(feature instanceof NcRNA)) {
seenTranscripts.put(feature, loc);
}
if (feature instanceof Exon
// || feature instanceof FivePrimeUTR || feature instanceof ThreePrimeUTR
) {
seenTranscriptParts.put(feature, loc);
}
if (currentChr.getOrganism().getAbbreviation() == null
|| !currentChr.getIdentifier().endsWith("_random")
&& !currentChr.getIdentifier().equals("M")
&& !currentChr.getOrganism().getAbbreviation().equals("MM")
&& !currentChr.getOrganism().getAbbreviation().equals("CF")
&& !currentChr.getOrganism().getAbbreviation().equals("MD")
&& !currentChr.getOrganism().getAbbreviation().equals("RN")) {
String identifier = feature.getIdentifier();
String featureType = getFeatureName(feature);
if (identifier == null) {
identifier = featureType + "_" + objectCounts.get(feature.getClass());
}
List synonymList = (List) synonymMap.get(feature.getId());
List evidenceList = (List) evidenceMap.get(feature.getId());
Map extraAttributes = new HashMap();
if (feature instanceof ChromosomeBand) {
ArrayList indexList = new ArrayList();
indexList.add(objectCounts.get(feature.getClass()));
extraAttributes.put("Index", indexList);
}
writeFeature(gffWriter, currentChr, feature, loc,
identifier,
featureType.toLowerCase(), featureType, extraAttributes,
synonymList, evidenceList, feature.getId());
}
incrementCount(objectCounts, feature);
}
// special case for t1dmine/stemcellmine
if (!currentChr.getIdentifier().endsWith("_random")
&& !currentChr.getIdentifier().equals("M")
&& currentChr.getOrganism().getAbbreviation() != null
&& !currentChr.getOrganism().getAbbreviation().equals("MM")
&& !currentChr.getOrganism().getAbbreviation().equals("MD")
&& !currentChr.getOrganism().getAbbreviation().equals("RN")) {
writeTranscriptsAndExons(gffWriter, currentChr, seenTranscripts,
seenTranscriptParts, synonymMap, evidenceMap);
}
gffWriter.close();
}
private String getFeatureName(LocatedSequenceFeature feature) {
Class bioEntityClass = feature.getClass();
Set classes = DynamicUtil.decomposeClass(bioEntityClass);
StringBuffer nameBuffer = new StringBuffer();
Iterator iter = classes.iterator();
while (iter.hasNext()) {
Class thisClass = (Class) iter.next();
if (nameBuffer.length() > 0) {
nameBuffer.append("_");
} else {
nameBuffer.append(TypeUtil.unqualifiedName(thisClass.getName()));
}
}
return nameBuffer.toString();
}
private void writeTranscriptsAndExons(PrintWriter gffWriter, Chromosome chr,
Map seenTranscripts, Map seenTranscriptParts,
Map synonymMap, Map evidenceMap) {
Iterator transcriptIter = seenTranscripts.keySet().iterator();
while (transcriptIter.hasNext()) {
// we can't just use MRNA here because the Transcripts of a pseudogene are Transcripts,
// but aren't MRNAs
Transcript transcript = (Transcript) transcriptIter.next();
Gene gene = transcript.getGene();
if (gene == null) {
continue;
}
Location transcriptLocation = (Location) seenTranscripts.get(transcript);
String transcriptFeatureType = "mRNA";
Map geneNameAttributeMap = new HashMap();
ArrayList geneNameList = new ArrayList();
geneNameList.add(gene.getIdentifier());
geneNameAttributeMap.put("Gene", geneNameList);
List synonymList = (List) synonymMap.get(transcript.getId());
if (synonymList == null) {
synonymList = new ArrayList();
}
if (transcript instanceof MRNA) {
// special case for CDS objects - display them as MRNA as GBrowse uses the CDS class
// for displaying MRNAs
Iterator cdsIter = ((MRNA) transcript).getcDSs().iterator();
while (cdsIter.hasNext()) {
CDS cds = (CDS) cdsIter.next();
synonymList.add(makeIdString(cds.getId()));
}
}
List evidenceList = (List) evidenceMap.get(transcript.getId());
writeFeature(gffWriter, chr, transcript, transcriptLocation, transcript.getIdentifier(),
transcriptFeatureType, "mRNA", geneNameAttributeMap, synonymList,
evidenceList, transcript.getId());
Collection exons = transcript.getExons();
ProxyCollection exonsResults = (ProxyCollection) exons;
// exon collections are small enough that optimisation just slows things down
exonsResults.setNoOptimise();
exonsResults.setNoExplain();
Iterator exonIter = exons.iterator();
while (exonIter.hasNext()) {
Exon exon = (Exon) exonIter.next();
Location exonLocation = (Location) seenTranscriptParts.get(exon);
List exonSynonymValues = (List) synonymMap.get(exon.getId());
List exonEvidence = (List) evidenceMap.get(exon.getId());
writeFeature(gffWriter, chr, exon, exonLocation, transcript.getIdentifier(),
"CDS", "mRNA", null, exonSynonymValues, exonEvidence,
transcript.getId());
}
}
}
private void incrementCount(Map objectCounts, Object object) {
if (objectCounts.containsKey(object.getClass())) {
int oldCount = ((Integer) objectCounts.get(object.getClass())).intValue();
objectCounts.put(object.getClass(), new Integer(oldCount + 1));
} else {
objectCounts.put(object.getClass(), new Integer(1));
}
}
/**
* @param bioEntity the obejct to write
* @param chromosomeLocation the location of the object on the chromosome
* @param featureType the type (third output column) to be used when writing - null means create
* the featureType automatically from the java class name on the object to write
* @param idType the type tag to use when storing the ID in the attributes Map - null means use
* the featureType
* @param flyMineId
* @param synonymValues a List of synonyms for this feature
* @param evidenceList a List of evidence objects for this feature
*/
private void writeFeature(PrintWriter gffWriter, Chromosome chr,
LocatedSequenceFeature bioEntity, Location chromosomeLocation,
String identifier,
String featureType, String idType, Map extraAttributes,
List synonymValues, List evidenceList, Integer flyMineId) {
StringBuffer lineBuffer = new StringBuffer();
lineBuffer.append(chromosomeFileNamePrefix(chr)).append("\t");
String source = ".";
if (evidenceList != null) {
Iterator evidenceIter = evidenceList.iterator();
while (evidenceIter.hasNext()) {
Evidence evidence = (Evidence) evidenceIter.next();
if (evidence instanceof ComputationalResult) {
Analysis analysis = ((ComputationalResult) evidence).getAnalysis();
if (analysis instanceof ComputationalAnalysis) {
source = ((ComputationalAnalysis) analysis).getAlgorithm();
}
}
}
}
lineBuffer.append(source).append("\t");
lineBuffer.append(featureType).append("\t");
if (chromosomeLocation == null && bioEntity == chr) {
// special case for Chromosome location
lineBuffer.append(1).append("\t").append(chr.getLength()).append("\t");
} else {
lineBuffer.append(chromosomeLocation.getStart()).append("\t");
lineBuffer.append(chromosomeLocation.getEnd()).append("\t");
}
lineBuffer.append(0).append("\t");
if (chromosomeLocation == null) {
lineBuffer.append(".");
} else {
if (chromosomeLocation.getStrand().equals("1")) {
lineBuffer.append("+");
} else {
if (chromosomeLocation.getStrand().equals("-1")) {
lineBuffer.append("-");
} else {
lineBuffer.append(".");
}
}
}
lineBuffer.append("\t");
if (chromosomeLocation == null) {
lineBuffer.append(".");
} else {
if (chromosomeLocation.getPhase() == null) {
lineBuffer.append(".");
} else {
lineBuffer.append(chromosomeLocation.getPhase());
}
}
lineBuffer.append("\t");
Map attributes = new LinkedHashMap();
List identifiers = new ArrayList();
identifiers.add(identifier);
attributes.put(idType, identifiers);
ArrayList flyMineIDs = new ArrayList();
flyMineIDs.add(makeIdString(flyMineId));
attributes.put("FlyMineInternalID", flyMineIDs.clone());
List allIds = (List) flyMineIDs.clone();
if (synonymValues != null) {
Iterator synonymIter = synonymValues.iterator();
while (synonymIter.hasNext()) {
String thisSynonymValue = (String) synonymIter.next();
if (!allIds.contains(thisSynonymValue)) {
allIds.add(thisSynonymValue);
}
}
}
attributes.put("Alias", allIds);
if (extraAttributes != null) {
Iterator extraAttributesIter = extraAttributes.keySet().iterator();
while (extraAttributesIter.hasNext()) {
String key = (String) extraAttributesIter.next();
attributes.put(key, extraAttributes.get(key));
}
}
try {
if (TypeUtil.isInstanceOf(bioEntity, "org.flymine.model.genomic.PCRProduct")) {
Boolean fieldValue;
try {
fieldValue = (Boolean) TypeUtil.getFieldValue(bioEntity, "promoter");
} catch (IllegalAccessException e) {
throw new RuntimeException("can't access 'promoter' field in: " + bioEntity);
}
ArrayList promoterFlagList = new ArrayList();
promoterFlagList.add(fieldValue.toString());
attributes.put("promoter", promoterFlagList);
}
} catch (ClassNotFoundException e) {
// ignore - PCRProduct is not in the model
}
try {
if (TypeUtil.isInstanceOf(bioEntity, "org.flymine.model.genomic.ArtificialDeletion")) {
Boolean fieldValue;
try {
fieldValue = (Boolean) TypeUtil.getFieldValue(bioEntity, "available");
} catch (IllegalAccessException e) {
throw new RuntimeException("can't access 'available' field in: " + bioEntity);
}
if (fieldValue != null) {
ArrayList availableFlagList = new ArrayList();
availableFlagList.add(fieldValue.toString());
attributes.put("available", availableFlagList);
}
}
} catch (ClassNotFoundException e) {
// ignore - ArtificialDeletion is not in the model
}
lineBuffer.append(stringifyAttributes(attributes));
gffWriter.println(lineBuffer.toString());
}
private String makeIdString(Integer id) {
return "FlyMineInternalID_" + id;
}
/**
* Return a String representation of the attributes Map. Taken from BioJava's
* SimpleGFFRecord.java
* @param attMap the Map of attributes
* @return a String representation of the attributes
*/
static String stringifyAttributes(Map attMap) {
StringBuffer sBuff = new StringBuffer();
Iterator ki = attMap.keySet().iterator();
while (ki.hasNext()) {
String key = (String) ki.next();
List values = (List) attMap.get(key);
if (values.size() == 0) {
sBuff.append(key);
sBuff.append(";");
} else {
for (Iterator vi = values.iterator(); vi.hasNext();) {
sBuff.append(key);
String value = (String) vi.next();
sBuff.append(" \"" + value + "\"");
if (ki.hasNext() || vi.hasNext()) {
sBuff.append(";");
}
if (vi.hasNext()) {
sBuff.append(" ");
}
}
}
if (ki.hasNext()) {
sBuff.append(" ");
}
}
return sBuff.toString();
}
/**
* Make a Map from LocatedSequenceFeature ID to List of Synonym values (Strings) for
* LocatedSequenceFeature objects located on the chromosome with the given ID.
* @param os the ObjectStore to read from
* @param chromosomeId the chromosome ID of the LocatedSequenceFeature objects to examine
* @return a Map from id to synonym List
* @throws ObjectStoreException
*/
private Map makeSynonymMap(ObjectStore os, Integer chromosomeId) throws ObjectStoreException {
Query q = new Query();
q.setDistinct(true);
QueryClass qcEnt = new QueryClass(LocatedSequenceFeature.class);
QueryField qfEnt = new QueryField(qcEnt, "id");
q.addFrom(qcEnt);
q.addToSelect(qfEnt);
QueryClass qcSyn = new QueryClass(Synonym.class);
QueryField qfSyn = new QueryField(qcSyn, "value");
q.addFrom(qcSyn);
q.addToSelect(qfSyn);
QueryClass qcLoc = new QueryClass(Location.class);
q.addFrom(qcLoc);
QueryClass qcChr = new QueryClass(Chromosome.class);
QueryField qfChr = new QueryField(qcChr, "id");
q.addFrom(qcChr);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference col = new QueryCollectionReference(qcEnt, "synonyms");
ContainsConstraint cc1 = new ContainsConstraint(col, ConstraintOp.CONTAINS, qcSyn);
cs.addConstraint(cc1);
QueryValue chrIdQueryValue = new QueryValue(chromosomeId);
SimpleConstraint sc = new SimpleConstraint(qfChr, ConstraintOp.EQUALS, chrIdQueryValue);
cs.addConstraint(sc);
QueryObjectReference ref1 = new QueryObjectReference(qcLoc, "subject");
ContainsConstraint cc2 = new ContainsConstraint(ref1, ConstraintOp.CONTAINS, qcEnt);
cs.addConstraint(cc2);
QueryObjectReference ref2 = new QueryObjectReference(qcLoc, "object");
ContainsConstraint cc3 = new ContainsConstraint(ref2, ConstraintOp.CONTAINS, qcChr);
cs.addConstraint(cc3);
q.setConstraint(cs);
Set indexesToCreate = new HashSet();
indexesToCreate.add(qfEnt);
indexesToCreate.add(qfSyn);
((ObjectStoreInterMineImpl) os).precompute(q, indexesToCreate,
PostProcessOperationsTask.PRECOMPUTE_CATEGORY);
Results res = os.execute(q);
res.setBatchSize(50000);
Iterator resIter = res.iterator();
Map returnMap = new HashMap();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Integer bioEntityId = (Integer) rr.get(0);
String synonymValue = (String) rr.get(1);
List synonymValues = (List) returnMap.get(bioEntityId);
if (synonymValues == null) {
synonymValues = new ArrayList();
returnMap.put(bioEntityId, synonymValues);
}
synonymValues.add(synonymValue);
}
return returnMap;
}
/**
* Make a Map from LocatedSequenceFeature ID to List of Evidence objects for
* LocatedSequenceFeature objects located on the chromosome with the given ID.
* @param os the ObjectStore to read from
* @param chromosomeId the chromosome ID of the LocatedSequenceFeature objects to examine
* @return a Map from id to Evidence List
* @throws ObjectStoreException
*/
private Map makeEvidenceMap(ObjectStore os, Integer chromosomeId)
throws ObjectStoreException {
Query q = new Query();
q.setDistinct(true);
QueryClass qcEnt = new QueryClass(LocatedSequenceFeature.class);
QueryField qfEnt = new QueryField(qcEnt, "id");
q.addFrom(qcEnt);
q.addToSelect(qfEnt);
QueryClass qcEvidence = new QueryClass(Evidence.class);
q.addFrom(qcEvidence);
q.addToSelect(qcEvidence);
QueryClass qcLoc = new QueryClass(Location.class);
q.addFrom(qcLoc);
QueryClass qcChr = new QueryClass(Chromosome.class);
QueryField qfChr = new QueryField(qcChr, "id");
q.addFrom(qcChr);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference col = new QueryCollectionReference(qcEnt, "evidence");
ContainsConstraint cc1 = new ContainsConstraint(col, ConstraintOp.CONTAINS, qcEvidence);
cs.addConstraint(cc1);
QueryValue chrIdQueryValue = new QueryValue(chromosomeId);
SimpleConstraint sc = new SimpleConstraint(qfChr, ConstraintOp.EQUALS, chrIdQueryValue);
cs.addConstraint(sc);
QueryObjectReference ref1 = new QueryObjectReference(qcLoc, "subject");
ContainsConstraint cc2 = new ContainsConstraint(ref1, ConstraintOp.CONTAINS, qcEnt);
cs.addConstraint(cc2);
QueryObjectReference ref2 = new QueryObjectReference(qcLoc, "object");
ContainsConstraint cc3 = new ContainsConstraint(ref2, ConstraintOp.CONTAINS, qcChr);
cs.addConstraint(cc3);
q.setConstraint(cs);
Set indexesToCreate = new HashSet();
indexesToCreate.add(qfEnt);
((ObjectStoreInterMineImpl) os).precompute(q, indexesToCreate,
PostProcessOperationsTask.PRECOMPUTE_CATEGORY);
Results res = os.execute(q);
res.setBatchSize(50000);
Iterator resIter = res.iterator();
Map returnMap = new HashMap();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Integer bioEntityId = (Integer) rr.get(0);
Evidence evidence = (Evidence) rr.get(1);
List idEvidence = (List) returnMap.get(bioEntityId);
if (idEvidence == null) {
idEvidence = new ArrayList();
returnMap.put(bioEntityId, idEvidence);
}
idEvidence.add(evidence);
}
return returnMap;
}
private void writeChromosomeFasta(Chromosome chr)
throws IOException, IllegalArgumentException {
Sequence chromosomeSequence = chr.getSequence();
if (chromosomeSequence == null) {
LOG.warn("cannot find any sequence for chromosome " + chr.getIdentifier());
} else {
String residues = chromosomeSequence.getResidues();
if (residues == null) {
LOG.warn("cannot find any sequence residues for chromosome "
+ chr.getIdentifier());
} else {
FileOutputStream fileStream =
new FileOutputStream(chromosomeFastaFile(chr));
PrintStream printStream = new PrintStream(fileStream);
printStream.println(">" + chromosomeFileNamePrefix(chr));
// code from BioJava's FastaFormat class:
int length = residues.length();
for (int pos = 0; pos < length; pos += 60) {
int end = Math.min(pos + 60, length);
printStream.println(residues.substring(pos, end));
}
printStream.close();
fileStream.close();
}
}
}
private File chromosomeFastaFile(Chromosome chr) {
return new File(destinationDirectory, chromosomeFileNamePrefix(chr) + ".fa");
}
private File chromosomeGFFFile(Chromosome chr) {
return new File(destinationDirectory, chromosomeFileNamePrefix(chr) + ".gff");
}
private String chromosomeFileNamePrefix(Chromosome chr) {
return chr.getOrganism().getGenus() + "_"
+ chr.getOrganism().getSpecies().replaceAll(" ", "_")
+ "_chr_" + chr.getIdentifier();
}
}
|
package net.bither.bitherj.core;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import net.bither.bitherj.crypto.ECKey;
import net.bither.bitherj.crypto.EncryptedData;
import net.bither.bitherj.crypto.KeyCrypterException;
import net.bither.bitherj.crypto.PasswordSeed;
import net.bither.bitherj.crypto.hd.DeterministicKey;
import net.bither.bitherj.crypto.hd.HDKeyDerivation;
import net.bither.bitherj.crypto.mnemonic.MnemonicCode;
import net.bither.bitherj.crypto.mnemonic.MnemonicException;
import net.bither.bitherj.db.AbstractDb;
import net.bither.bitherj.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
public class HDMKeychain {
public static interface HDMFetchRemotePublicKeys{
void completeRemotePublicKeys(CharSequence password, ArrayList<HDMAddress.Pubs> partialPubs);
}
public static interface HDMFetchRemoteAddresses {
List<HDMAddress.Pubs> getRemoteExistsPublicKeys(CharSequence password);
}
public static interface HDMAddressChangeDelegate {
public void hdmAddressAdded(HDMAddress address);
}
private static final Logger log = LoggerFactory.getLogger(HDMKeychain.class);
private transient byte[] seed;
private ArrayList<HDMAddress> allCompletedAddresses;
private Collection<HDMAddress> addressesInUse;
private Collection<HDMAddress> addressesTrashed;
private int hdSeedId;
private boolean isFromXRandom;
private HDMAddressChangeDelegate addressChangeDelegate;
// Create With Random
public HDMKeychain(SecureRandom random, CharSequence password) {
isFromXRandom = random.getClass().getCanonicalName().indexOf("XRandom") >= 0;
seed = new byte[32];
random.nextBytes(seed);
EncryptedData encryptedSeed = new EncryptedData(seed, password);
wipeSeed();
hdSeedId = AbstractDb.addressProvider.addHDKey(encryptedSeed.toEncryptedString(), isFromXRandom);
allCompletedAddresses = new ArrayList<HDMAddress>();
}
// From DB
public HDMKeychain(int seedId) {
this.hdSeedId = seedId;
allCompletedAddresses = new ArrayList<HDMAddress>();
initFromDb();
}
// Import
public HDMKeychain(EncryptedData encryptedSeed, boolean isFromXRandom ,CharSequence password, HDMFetchRemoteAddresses fetchDelegate) throws HDMBitherIdNotMatchException, MnemonicException.MnemonicLengthException {
seed = encryptedSeed.decrypt(password);
allCompletedAddresses = new ArrayList<HDMAddress>();
List<HDMAddress.Pubs> pubs = fetchDelegate.getRemoteExistsPublicKeys(password);
if(pubs.size() > 0){
try {
DeterministicKey root = externalChainRoot(password);
byte[] pubDerived = root.deriveSoftened(0).getPubKey();
byte[] pubFetched = pubs.get(0).hot;
root.wipe();
if(!Arrays.equals(pubDerived, pubFetched)){
wipeSeed();
throw new HDMBitherIdNotMatchException();
}
} catch (MnemonicException.MnemonicLengthException e) {
wipeSeed();
throw e;
}
}
wipeSeed();
ArrayList<HDMAddress> as = new ArrayList<HDMAddress>();
for (HDMAddress.Pubs p : pubs) {
as.add(new HDMAddress(p, this));
}
this.hdSeedId = AbstractDb.addressProvider.addHDKey(encryptedSeed.toEncryptedString(), isFromXRandom);
AbstractDb.addressProvider.completeHDMAddresses(getHdSeedId(), as);
allCompletedAddresses.addAll(as);
}
public int prepareAddresses(int count, CharSequence password, byte[] coldExternalRootPub){
DeterministicKey externalRootHot;
DeterministicKey externalRootCold = HDKeyDerivation.createMasterPubKeyFromExtendedBytes(coldExternalRootPub);
try {
externalRootHot = externalChainRoot(password);
externalRootHot.clearPrivateKey();
} catch (MnemonicException.MnemonicLengthException e) {
return 0;
}
ArrayList<HDMAddress.Pubs> pubs = new ArrayList<HDMAddress.Pubs>();
for (int i = AbstractDb.addressProvider.maxHDMAddressPubIndex(getHdSeedId()) + 1;
pubs.size() < count;
i++) {
HDMAddress.Pubs p = new HDMAddress.Pubs();
try {
p.hot = externalRootHot.deriveSoftened(i).getPubKey();
p.cold = externalRootCold.deriveSoftened(i).getPubKey();
pubs.add(p);
} catch (Exception e) {
e.printStackTrace();
}
}
AbstractDb.addressProvider.prepareHDMAddresses(getHdSeedId(), pubs);
if (externalRootHot != null) {
externalRootHot.wipe();
}
if (externalRootCold != null) {
externalRootCold.wipe();
}
return pubs.size();
}
public List<HDMAddress> completeAddresses(int count, CharSequence password, HDMFetchRemotePublicKeys fetchDelegate) {
int uncompletedAddressCount = uncompletedAddressCount();
if(uncompletedAddressCount < count){
throw new RuntimeException("Not enough uncompleted allCompletedAddresses " + count + "/" + uncompletedAddressCount + " : " + getHdSeedId());
}
ArrayList<HDMAddress> as = new ArrayList<HDMAddress>();
synchronized (allCompletedAddresses) {
ArrayList<HDMAddress.Pubs> pubs = AbstractDb.addressProvider.getUncompletedHDMAddressPubs(getHdSeedId(), count);
try {
fetchDelegate.completeRemotePublicKeys(password, pubs);
for (HDMAddress.Pubs p : pubs) {
as.add(new HDMAddress(p, this));
}
AbstractDb.addressProvider.completeHDMAddresses(getHdSeedId(), as);
} catch (Exception e) {
e.printStackTrace();
return as;
}
if(addressChangeDelegate != null){
for(HDMAddress a : as){
addressChangeDelegate.hdmAddressAdded(a);
}
}
allCompletedAddresses.addAll(as);
}
return as;
}
public List<HDMAddress> getAddresses() {
synchronized (allCompletedAddresses) {
if(addressesInUse == null){
addressesInUse = Collections2.filter(allCompletedAddresses, new Predicate<HDMAddress>() {
@Override
public boolean apply(@Nullable HDMAddress input) {
return !input.isTrashed();
}
});
}
return new ArrayList<HDMAddress>(addressesInUse);
}
}
public List<HDMAddress> getTrashedAddresses(){
synchronized (allCompletedAddresses){
if(addressesTrashed == null){
addressesTrashed = Collections2.filter(allCompletedAddresses, new Predicate<HDMAddress>() {
@Override
public boolean apply(@Nullable HDMAddress input) {
return input.isTrashed();
}
});
}
return new ArrayList<HDMAddress>(addressesTrashed);
}
}
public DeterministicKey externalChainRoot(CharSequence password) throws MnemonicException.MnemonicLengthException {
DeterministicKey master = masterKey(password);
DeterministicKey purpose = master.deriveHardened(44);
DeterministicKey coinType = purpose.deriveHardened(0);
DeterministicKey account = coinType.deriveHardened(0);
DeterministicKey external = account.deriveSoftened(0);
master.wipe();
purpose.wipe();
coinType.wipe();
account.wipe();
return external;
}
public byte[] getExternalChainRootPubExtended(CharSequence password) throws MnemonicException.MnemonicLengthException{
DeterministicKey ex = externalChainRoot(password);
byte[] pub = ex.getPubKeyExtended();
ex.wipe();
return pub;
}
public String getExternalChainRootPubExtendedAsHex(CharSequence password) throws MnemonicException.MnemonicLengthException{
return Utils.bytesToHexString(getExternalChainRootPubExtended(password));
}
private DeterministicKey masterKey(CharSequence password) throws MnemonicException.MnemonicLengthException {
long begin = System.currentTimeMillis();
MnemonicCode mnemonic = MnemonicCode.instance();
decryptSeed(password);
byte[] s = mnemonic.toSeed(mnemonic.toMnemonic(seed), "");
wipeSeed();
DeterministicKey master = HDKeyDerivation.createMasterPrivateKey(s);
Utils.wipeBytes(s);
log.info("hdm keychain decrypt time: {}", System.currentTimeMillis() - begin);
return master;
}
public DeterministicKey getExternalKey(int index, CharSequence password){
try {
DeterministicKey externalChainRoot = externalChainRoot(password);
DeterministicKey key = externalChainRoot.deriveSoftened(index);
externalChainRoot.wipe();
return key;
}catch (Exception e){
throw new RuntimeException(e);
}
}
public int getCurrentMaxAddressIndex(){
synchronized (allCompletedAddresses) {
int max = Integer.MIN_VALUE;
for (HDMAddress address : allCompletedAddresses) {
if (address.getIndex() > max) {
max = address.getIndex();
}
}
return max;
}
}
private void initFromDb(){
isFromXRandom = AbstractDb.addressProvider.isHDSeedFromXRandom(getHdSeedId());
initAddressesFromDb();
}
private void initAddressesFromDb(){
synchronized (allCompletedAddresses){
List<HDMAddress> addrs = AbstractDb.addressProvider.getHDMAddressInUse(this);
if(addrs != null) {
allCompletedAddresses.addAll(addrs);
}
}
}
public int getHdSeedId(){
return hdSeedId;
}
public int uncompletedAddressCount(){
return AbstractDb.addressProvider.uncompletedHDMAddressCount(getHdSeedId());
}
public HDMAddressChangeDelegate getAddressChangeDelegate() {
return addressChangeDelegate;
}
public void setAddressChangeDelegate(HDMAddressChangeDelegate addressChangeDelegate) {
this.addressChangeDelegate = addressChangeDelegate;
}
public boolean isFromXRandom(){
return isFromXRandom;
}
public void decryptSeed(CharSequence password) throws KeyCrypterException{
if(hdSeedId <= 0){
return;
}
String encrypted = getEncryptedSeed();
if(!Utils.isEmpty(encrypted)){
seed = new EncryptedData(encrypted).decrypt(password);
}
}
public String getEncryptedSeed(){
return AbstractDb.addressProvider.getEncryptSeed(hdSeedId);
}
public void changePassword(CharSequence oldPassword, CharSequence newPassword){
decryptSeed(oldPassword);
AbstractDb.addressProvider.setEncryptSeed(getHdSeedId(), new EncryptedData(seed, newPassword).toEncryptedString());
wipeSeed();
}
public List<String> getSeedWords(CharSequence password) throws MnemonicException.MnemonicLengthException {
decryptSeed(password);
List<String> words = MnemonicCode.instance().toMnemonic(seed);
wipeSeed();
return words;
}
public void wipeSeed(){
Utils.wipeBytes(seed);
}
public PasswordSeed createPasswordSeed(CharSequence password){
String encrypted = AbstractDb.addressProvider.getEncryptSeed(hdSeedId);
byte[] priv = new EncryptedData(encrypted).decrypt(password);
ECKey k = new ECKey(priv, null);
String address = k.toAddress();
Utils.wipeBytes(priv);
k.clearPrivateKey();
return new PasswordSeed(address, encrypted);
}
public static final class HDMBitherIdNotMatchException extends RuntimeException{
public static final String msg = "HDM BitherId Not Match";
public HDMBitherIdNotMatchException(){
super(msg);
}
}
}
|
package com.browseengine.bobo.api;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FilterIndexReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.ReaderUtil;
import com.browseengine.bobo.facets.FacetHandler;
/**
* bobo browse index reader
*
*/
public class BoboIndexReader extends FilterIndexReader
{
private static final String SPRING_CONFIG = "bobo.spring";
private static Logger logger = Logger.getLogger(BoboIndexReader.class);
protected Map<String, FacetHandler<?>> _facetHandlerMap;
protected Collection<FacetHandler<?>> _facetHandlers;
protected WorkArea _workArea;
protected IndexReader _srcReader;
protected BoboIndexReader[] _subReaders = null;
protected int[] _starts = null;
private final Map<String,Object> _facetDataMap = new HashMap<String,Object>();
private final ThreadLocal<Map<String,Object>> _runtimeFacetDataMap = new ThreadLocal<Map<String,Object>>()
{
protected Map<String,Object> initialValue() { return new HashMap<String,Object>(); }
};
/**
* Constructor
*
* @param reader
* Index reader
* @throws IOException
*/
public static BoboIndexReader getInstance(IndexReader reader) throws IOException
{
return BoboIndexReader.getInstance(reader, null, new WorkArea());
}
public static BoboIndexReader getInstance(IndexReader reader, WorkArea workArea) throws IOException
{
return BoboIndexReader.getInstance(reader, null, workArea);
}
/**
* Constructor.
*
* @param reader
* index reader
* @param facetHandlers
* List of facet handlers
* @throws IOException
*/
public static BoboIndexReader getInstance(IndexReader reader,
Collection<FacetHandler<?>> facetHandlers) throws IOException
{
return BoboIndexReader.getInstance(reader, facetHandlers, new WorkArea());
}
public static BoboIndexReader getInstance(IndexReader reader,
Collection<FacetHandler<?>> facetHandlers,
WorkArea workArea) throws IOException
{
BoboIndexReader boboReader = new BoboIndexReader(reader, facetHandlers, workArea);
boboReader.facetInit();
return boboReader;
}
public static BoboIndexReader getInstanceAsSubReader(IndexReader reader) throws IOException
{
return getInstanceAsSubReader(reader, null, new WorkArea());
}
public static BoboIndexReader getInstanceAsSubReader(IndexReader reader,
Collection<FacetHandler<?>> facetHandlers) throws IOException
{
return getInstanceAsSubReader(reader, facetHandlers, new WorkArea());
}
public static BoboIndexReader getInstanceAsSubReader(IndexReader reader,
Collection<FacetHandler<?>> facetHandlers,
WorkArea workArea) throws IOException
{
BoboIndexReader boboReader = new BoboIndexReader(reader, facetHandlers, workArea, false);
boboReader.facetInit();
return boboReader;
}
public IndexReader getInnerReader()
{
return in;
}
public Object getFacetData(String name){
return _facetDataMap.get(name);
}
public Object putFacetData(String name,Object data){
return _facetDataMap.put(name, data);
}
public Object getRuntimeFacetData(String name)
{
Map<String,Object> map = _runtimeFacetDataMap.get();
if(map == null) return null;
return map.get(name);
}
public Object putRuntimeFacetData(String name,Object data)
{
Map<String,Object> map = _runtimeFacetDataMap.get();
if(map == null)
{
map = new HashMap<String,Object>();
_runtimeFacetDataMap.set(map);
}
return map.put(name, data);
}
public void clearRuntimeFacetData()
{
_runtimeFacetDataMap.set(null);
}
@Override
protected void doClose() throws IOException
{
_facetDataMap.clear();
if(_srcReader != null) _srcReader.close();
super.doClose();
}
@Override
protected void doCommit(Map commitUserData) throws IOException
{
if(_srcReader != null) _srcReader.flush(commitUserData);
}
@Override
protected void doDelete(int n) throws CorruptIndexException, IOException
{
if(_srcReader != null) _srcReader.deleteDocument(n);
}
private void loadFacetHandler(String name,
Set<String> loaded,
Set<String> visited,
WorkArea workArea) throws IOException
{
FacetHandler<?> facetHandler = _facetHandlerMap.get(name);
if (facetHandler != null && !loaded.contains(name))
{
visited.add(name);
Set<String> dependsOn = facetHandler.getDependsOn();
if (dependsOn.size() > 0)
{
Iterator<String> iter = dependsOn.iterator();
while (iter.hasNext())
{
String f = iter.next();
if (name.equals(f))
continue;
if (!loaded.contains(f))
{
if (visited.contains(f))
{
throw new IOException("Facet handler dependency cycle detected, facet handler: "
+ name + " not loaded");
}
loadFacetHandler(f, loaded, visited, workArea);
}
if (!loaded.contains(f))
{
throw new IOException("unable to load facet handler: " + f);
}
facetHandler.putDependedFacetHandler(_facetHandlerMap.get(f));
}
}
long start = System.currentTimeMillis();
facetHandler.loadFacetData(this, workArea);
long end = System.currentTimeMillis();
if (logger.isDebugEnabled()){
StringBuffer buf = new StringBuffer();
buf.append("facetHandler loaded: ").append(name).append(", took: ").append(end-start).append(" ms");
logger.debug(buf.toString());
}
loaded.add(name);
}
}
private void loadFacetHandlers(WorkArea workArea, Set<String> toBeRemoved)
{
Set<String> loaded = new HashSet<String>();
Set<String> visited = new HashSet<String>();
for(String name : _facetHandlerMap.keySet())
{
try
{
loadFacetHandler(name, loaded, visited, workArea);
}
catch (Exception ioe)
{
toBeRemoved.add(name);
logger.error("facet load failed: " + name + ": " + ioe.getMessage(), ioe);
}
}
for(String name : toBeRemoved)
{
_facetHandlerMap.remove(name);
}
}
private static IndexReader[] createSubReaders(IndexReader reader, WorkArea workArea) throws IOException
{
List<IndexReader> readerList = new ArrayList<IndexReader>();
ReaderUtil.gatherSubReaders(readerList, reader);
IndexReader[] subReaders = (IndexReader[])readerList.toArray(new IndexReader[readerList.size()]);
BoboIndexReader[] boboReaders;
if(subReaders != null && subReaders.length > 0)
{
boboReaders = new BoboIndexReader[subReaders.length];
for(int i = 0; i < subReaders.length; i++)
{
boboReaders[i] = new BoboIndexReader(subReaders[i], null, workArea, false);
}
}
else
{
boboReaders = new BoboIndexReader[]{ new BoboIndexReader(reader, null, workArea, false) };
}
return boboReaders;
}
@Override
public Directory directory()
{
return (_subReaders != null ? _subReaders[0].directory() : super.directory());
}
protected void initialize(Collection<FacetHandler<?>> facetHandlers) throws IOException
{
if (facetHandlers == null) // try to load from index
{
Directory idxDir = directory();
if (idxDir != null && idxDir instanceof FSDirectory)
{
FSDirectory fsDir = (FSDirectory) idxDir;
File file = fsDir.getFile();
facetHandlers = new ArrayList<FacetHandler<?>>();
}
else
{
facetHandlers = new ArrayList<FacetHandler<?>>();
}
}
_facetHandlers = facetHandlers;
_facetHandlerMap = new HashMap<String, FacetHandler<?>>();
for (FacetHandler<?> facetHandler : facetHandlers)
{
_facetHandlerMap.put(facetHandler.getName(), facetHandler);
}
}
protected BoboIndexReader(IndexReader reader,
Collection<FacetHandler<?>> facetHandlers,
WorkArea workArea) throws IOException
{
this(reader, facetHandlers, workArea, true);
_srcReader = reader;
}
protected BoboIndexReader(IndexReader reader,
Collection<FacetHandler<?>> facetHandlers,
WorkArea workArea,
boolean useSubReaders) throws IOException
{
super(useSubReaders ? new MultiReader(createSubReaders(reader, workArea), false) : reader);
if(useSubReaders)
{
BoboIndexReader[] subReaders = (BoboIndexReader[])in.getSequentialSubReaders();
if(subReaders != null && subReaders.length > 0)
{
_subReaders = subReaders;
int maxDoc = 0;
_starts = new int[_subReaders.length + 1];
for (int i = 0; i < _subReaders.length; i++)
{
if(facetHandlers != null) _subReaders[i].setFacetHandlers(facetHandlers);
_starts[i] = maxDoc;
maxDoc += _subReaders[i].maxDoc();
}
_starts[_subReaders.length] = maxDoc;
}
}
_facetHandlers = facetHandlers;
_workArea = workArea;
}
protected void facetInit() throws IOException
{
facetInit(new HashSet<String>());
}
protected void facetInit(Set<String> toBeRemoved) throws IOException
{
initialize(_facetHandlers);
if(_subReaders == null)
{
loadFacetHandlers(_workArea, toBeRemoved);
}
else
{
for(BoboIndexReader r : _subReaders)
{
r.facetInit(toBeRemoved);
}
for(String name : toBeRemoved)
{
_facetHandlerMap.remove(name);
}
}
}
protected void setFacetHandlers(Collection<FacetHandler<?>> facetHandlers)
{
_facetHandlers = facetHandlers;
}
/**
* @deprecated use {@link org.apache.lucene.search.MatchAllDocsQuery} instead.
* @return query that matches all docs in the index
*/
public Query getFastMatchAllDocsQuery()
{
return new MatchAllDocsQuery();
}
/**
* Utility method to dump out all fields (name and terms) for a given index.
*
* @param outFile
* File to dump to.
* @throws IOException
*/
public void dumpFields(File outFile) throws IOException
{
FileWriter writer = null;
try
{
writer = new FileWriter(outFile);
PrintWriter out = new PrintWriter(writer);
Set<String> fieldNames = getFacetNames();
for (String fieldName : fieldNames)
{
TermEnum te = terms(new Term(fieldName, ""));
out.write(fieldName + ":\n");
while (te.next())
{
Term term = te.term();
if (!fieldName.equals(term.field()))
{
break;
}
out.write(term.text() + "\n");
}
out.write("\n\n");
}
}
finally
{
if (writer != null)
{
writer.close();
}
}
}
/**
* Gets all the facet field names
*
* @return Set of facet field names
*/
public Set<String> getFacetNames()
{
return _facetHandlerMap.keySet();
}
/**
* Gets a facet handler
*
* @param fieldname
* name
* @return facet handler
*/
public FacetHandler<?> getFacetHandler(String fieldname)
{
return _facetHandlerMap.get(fieldname);
}
@Override
public IndexReader[] getSequentialSubReaders() {
return _subReaders;
}
/**
* Gets the facet handler map
*
* @return facet handler map
*/
public Map<String, FacetHandler<?>> getFacetHandlerMap()
{
return _facetHandlerMap;
}
public void rewrap(IndexReader in){
if(_subReaders != null)
{
throw new UnsupportedOperationException("this BoboIndexReader has subreaders");
}
super.in = in;
}
@Override
public Document document(int docid) throws IOException
{
if(_subReaders != null)
{
int readerIndex = readerIndex(docid, _starts, _subReaders.length);
BoboIndexReader subReader = _subReaders[readerIndex];
return subReader.document(docid - _starts[readerIndex]);
}
else
{
Document doc = super.document(docid);
Collection<FacetHandler<?>> facetHandlers = _facetHandlerMap.values();
for (FacetHandler<?> facetHandler : facetHandlers)
{
String[] vals = facetHandler.getFieldValues(this,docid);
if (vals != null)
{
for (String val : vals)
{
doc.add(new Field(facetHandler.getName(),
val,
Field.Store.NO,
Field.Index.NOT_ANALYZED));
}
}
}
return doc;
}
}
private static int readerIndex(int n, int[] starts, int numSubReaders)
{
int lo = 0;
int hi = numSubReaders - 1;
while (hi >= lo)
{
int mid = (lo + hi) >>> 1;
int midValue = starts[mid];
if (n < midValue)
hi = mid - 1;
else if (n > midValue)
lo = mid + 1;
else
{
while (mid+1 < numSubReaders && starts[mid+1] == midValue)
{
mid++;
}
return mid;
}
}
return hi;
}
/**
* Work area for loading
*/
public static class WorkArea
{
private HashMap<Class<?>, Object> map = new HashMap<Class<?>, Object>();
@SuppressWarnings("unchecked")
public <T> T get(Class<T> cls)
{
T obj = (T) map.get(cls);
return obj;
}
public void put(Object obj)
{
map.put(obj.getClass(), obj);
}
public void clear()
{
map.clear();
}
}
}
|
package hudson.model;
import hudson.search.SearchFactory;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.Stapler;
import javax.servlet.ServletException;
import java.io.IOException;
import hudson.search.SearchableModelObject;
import hudson.search.Search;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchIndex;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* {@link ModelObject} with some convenience methods.
*
* @author Kohsuke Kawaguchi
*/
public abstract class AbstractModelObject implements SearchableModelObject {
/**
* Displays the error in a page.
*/
protected final void sendError(Exception e, StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
req.setAttribute("exception", e);
sendError(e.getMessage(),req,rsp);
}
protected final void sendError(Exception e) throws ServletException, IOException {
sendError(e,Stapler.getCurrentRequest(),Stapler.getCurrentResponse());
}
protected final void sendError(String message, StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
req.setAttribute("message",message);
rsp.forward(this,"error",req);
}
/**
* @param pre
* If true, the message is put in a PRE tag.
*/
protected final void sendError(String message, StaplerRequest req, StaplerResponse rsp, boolean pre) throws ServletException, IOException {
req.setAttribute("message",message);
if(pre)
req.setAttribute("pre",true);
rsp.forward(this,"error",req);
}
protected final void sendError(String message) throws ServletException, IOException {
sendError(message,Stapler.getCurrentRequest(),Stapler.getCurrentResponse());
}
/**
* Convenience method to verify that the current request is a POST request.
*
* @deprecated
* Use {@link RequirePOST} on your method.
*/
protected final void requirePOST() throws ServletException {
StaplerRequest req = Stapler.getCurrentRequest();
if (req==null) return; // invoked outside the context of servlet
String method = req.getMethod();
if(!method.equalsIgnoreCase("POST"))
throw new ServletException("Must be POST, Can't be "+method);
}
/**
* Default implementation that returns empty index.
*/
protected SearchIndexBuilder makeSearchIndex() {
return new SearchIndexBuilder().addAllAnnotations(this);
}
public final SearchIndex getSearchIndex() {
return makeSearchIndex().make();
}
public Search getSearch() {
for (SearchFactory sf : SearchFactory.all()) {
Search s = sf.createFor(this);
if (s!=null)
return s;
}
return new Search();
}
/**
* Default implementation that returns the display name.
*/
public String getSearchName() {
return getDisplayName();
}
}
|
package com.novoda.downloadmanager.lib;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.util.Pair;
import com.novoda.downloadmanager.notifications.NotificationVisibility;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
/**
* This class contains all the information necessary to request a new download. The URI is the
* only required parameter.
* <p/>
* Note that the default download destination is a shared volume where the system might delete
* your file if it needs to reclaim space for system use. If this is a problem, use a location
* on external storage (see {@link #setDestinationUri(java.net.URI)}.
*/
public class Request {
/**
* Bit flag for {@link #setAllowedNetworkTypes} corresponding to
* {@link android.net.ConnectivityManager#TYPE_MOBILE}.
*/
public static final int NETWORK_MOBILE = 1 << 0;
/**
* Bit flag for {@link #setAllowedNetworkTypes} corresponding to
* {@link android.net.ConnectivityManager#TYPE_WIFI}.
*/
public static final int NETWORK_WIFI = 1 << 1;
/**
* Bit flag for {@link #setAllowedNetworkTypes} corresponding to
* {@link android.net.ConnectivityManager#TYPE_BLUETOOTH}.
*/
public static final int NETWORK_BLUETOOTH = 1 << 2;
private final List<Pair<String, String>> requestHeaders = new ArrayList<>();
private URI uri;
private URI destinationUri;
private CharSequence title = "";
private CharSequence description = "";
private String mimeType;
private int allowedNetworkTypes = ~0; // default to all network types allowed
private boolean roamingAllowed = true;
private boolean meteredAllowed = true;
private boolean isVisibleInDownloadsUi = true;
private boolean scannable = false;
private String notificationExtras;
private String bigPictureUrl = "";
private long batchId = -1L;
private String extraData;
private boolean alwaysResume;
private boolean allowTarUpdates;
private boolean noIntegrity;
/**
* if a file is designated as a MediaScanner scannable file, the following value is
* stored in the database column {@link DownloadContract.Downloads#COLUMN_MEDIA_SCANNED}.
*/
static final int SCANNABLE_VALUE_YES = 0;
// value of 1 is stored in the above column by DownloadProvider after it is scanned by
// MediaScanner
/**
* if a file is designated as a file that should not be scanned by MediaScanner,
* the following value is stored in the database column
* {@link DownloadContract.Downloads#COLUMN_MEDIA_SCANNED}.
*/
static final int SCANNABLE_VALUE_NO = 2;
/**
* can take any of the following values: {@link NotificationVisibility#HIDDEN}
* {@link NotificationVisibility#ACTIVE_OR_COMPLETE}, {@link NotificationVisibility#ONLY_WHEN_ACTIVE},
* {@link NotificationVisibility#ONLY_WHEN_COMPLETE}
*/
private int notificationVisibility = NotificationVisibility.ONLY_WHEN_ACTIVE;
/**
* @param uri the HTTP Uri to download.
* @deprecated use {@link #Request(java.net.URI)}
*/
@Deprecated
public Request(Uri uri) {
this(uri.toString());
}
/**
* @param uri the HTTP URI to download.
*/
public Request(URI uri) {
validateUriScheme(uri.toString(), uri.getScheme());
this.uri = uri;
}
Request(String uriString) {
URI uri = URI.create(uriString);
validateUriScheme(uri.toString(), uri.getScheme());
this.uri = uri;
}
private void validateUriScheme(String uri, String scheme) {
if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
}
}
@Deprecated
public Request setDestinationUri(Uri uri) {
destinationUri = URI.create(uri.toString());
return this;
}
public Request setDestinationUri(URI uri) {
destinationUri = uri;
return this;
}
public Request setDestinationInExternalFilesDir(String dirType, String subPath) {
final File file = GlobalState.getContext().getExternalFilesDir(dirType);
if (file == null) {
throw new IllegalStateException("Failed to get external storage files directory");
} else if (file.exists()) {
if (!file.isDirectory()) {
throw new IllegalStateException(file.getAbsolutePath() + " already exists and is not a directory");
}
} else {
if (!file.mkdirs()) {
throw new IllegalStateException("Unable to create directory: " + file.getAbsolutePath());
}
}
setDestinationFromBase(file, subPath);
return this;
}
public Request setDestinationInInternalFilesDir(String dirType, String subPath) {
final File file = new File(GlobalState.getContext().getFilesDir(), dirType);
if (file.exists()) {
if (!file.isDirectory()) {
throw new IllegalStateException(file.getAbsolutePath() + " already exists and is not a directory");
}
} else {
if (!file.mkdirs()) {
throw new IllegalStateException("Unable to create directory: " + file.getAbsolutePath());
}
}
setDestinationFromBase(file, subPath);
return this;
}
public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
File file = Environment.getExternalStoragePublicDirectory(dirType);
if (file == null) {
throw new IllegalStateException("Failed to get external storage public directory");
} else if (file.exists()) {
if (!file.isDirectory()) {
throw new IllegalStateException(file.getAbsolutePath() + " already exists and is not a directory");
}
} else {
if (!file.mkdirs()) {
throw new IllegalStateException("Unable to create directory: " + file.getAbsolutePath());
}
}
setDestinationFromBase(file, subPath);
return this;
}
private void setDestinationFromBase(File base, String subPath) {
if (subPath == null) {
throw new NullPointerException("subPath cannot be null");
}
destinationUri = new File(base, subPath).toURI();
}
/**
* If the file to be downloaded is to be scanned by MediaScanner, this method
* should be called before {@link DownloadManager#enqueue(Request)} is called.
*/
public void allowScanningByMediaScanner() {
scannable = true;
}
/**
* Always attempt to resume the download, regardless of whether the server returns
* a Etag header or not. **CAUTION** if the file has changed then this flag will
* result in undefined behaviour.
*/
public Request alwaysAttemptResume() {
alwaysResume = true;
return this;
}
/**
* Automatically pause the download when reaching the end of the file instead of writing the last bytes to disk.
* This allows for a resume of the download against an updated tar file.
* If used this also sets {@code alwaysAttemptResume()}
*/
public Request allowTarUpdates() {
allowTarUpdates = true;
alwaysAttemptResume();
return this;
}
/**
* When a ETag header is present, the application should check the integrity of the
* downloaded file, otherwise the current download won't be able to be resumed
*/
public Request applicationChecksFileIntegrity() {
noIntegrity = true;
return this;
}
public Request addRequestHeader(String header, String value) {
if (header == null) {
throw new NullPointerException("header cannot be null");
}
if (header.contains(":")) {
throw new IllegalArgumentException("header may not contain ':'");
}
if (value == null) {
value = "";
}
requestHeaders.add(Pair.create(header, value));
return this;
}
/**
* Set the title of this download, to be displayed in notifications (if enabled). If no
* title is given, a default one will be assigned based on the download filename, once the
* download starts.
*
* @return this object
*/
public Request setTitle(CharSequence title) {
this.title = title;
return this;
}
/**
* Set a description of this download, to be displayed in notifications (if enabled)
*
* @return this object
*/
public Request setDescription(CharSequence description) {
this.description = description;
return this;
}
/**
* Set a drawable url that will be used for the Big Picture Style
*
* @param bigPictureUrl the drawable resource id
* @return this object
*/
public Request setBigPictureUrl(String bigPictureUrl) {
this.bigPictureUrl = bigPictureUrl;
return this;
}
/**
* Set the ID of the batch that this request belongs to
*
* @param batchId the batch id
* @return this object
*/
Request setBatchId(long batchId) {
this.batchId = batchId;
return this;
}
public Request setMimeType(String mimeType) {
this.mimeType = mimeType;
return this;
}
@Deprecated
public Request setShowRunningNotification(boolean show) {
return (show) ? setNotificationVisibility(NotificationVisibility.ONLY_WHEN_ACTIVE) : setNotificationVisibility(NotificationVisibility.HIDDEN);
}
public Request setNotificationVisibility(int visibility) {
notificationVisibility = visibility;
return this;
}
/**
* Restrict the types of networks over which this download may proceed.
* By default, all network types are allowed. Consider using
* {@link #setAllowedOverMetered(boolean)} instead, since it's more
* flexible.
*
* @param flags any combination of the NETWORK_* bit flags.
* @return this object
*/
public Request setAllowedNetworkTypes(int flags) {
allowedNetworkTypes = flags;
return this;
}
/**
* Set whether this download may proceed over a roaming connection. By default, roaming is
* allowed.
*
* @param allowed whether to allow a roaming connection to be used
* @return this object
*/
public Request setAllowedOverRoaming(boolean allowed) {
roamingAllowed = allowed;
return this;
}
/**
* Set whether this download may proceed over a metered network
* connection. By default, metered networks are allowed.
*
* @see android.net.ConnectivityManager#isActiveNetworkMetered()
*/
public Request setAllowedOverMetered(boolean allow) {
meteredAllowed = allow;
return this;
}
/**
* Set whether this download should be displayed in the system's Downloads UI. True by
* default.
*
* @param isVisible whether to display this download in the Downloads UI
* @return this object
*/
public Request setVisibleInDownloadsUi(boolean isVisible) {
isVisibleInDownloadsUi = isVisible;
return this;
}
/**
* @param extra data that will be passed to you in the Intent on download completion.
*/
public Request setNotificationExtra(String extra) {
notificationExtras = extra;
return this;
}
/**
* @param extra data you want to save alongside your download so you can query it later.
*/
public Request setExtraData(String extra) {
extraData = extra;
return this;
}
long getBatchId() {
return batchId;
}
/**
* @return ContentValues to be passed to DownloadProvider.insert()
*/
ContentValues toContentValues() {
ContentValues values = new ContentValues();
assert uri != null;
values.put(DownloadContract.Downloads.COLUMN_URI, uri.toString());
if (destinationUri != null) {
values.put(DownloadContract.Downloads.COLUMN_DESTINATION, DownloadsDestination.DESTINATION_FILE_URI);
values.put(DownloadContract.Downloads.COLUMN_FILE_NAME_HINT, destinationUri.toString());
} else {
values.put(
DownloadContract.Downloads.COLUMN_DESTINATION,
DownloadsDestination.DESTINATION_CACHE_PARTITION_PURGEABLE
);
}
// is the file supposed to be media-scannable?
values.put(DownloadContract.Downloads.COLUMN_MEDIA_SCANNED, (scannable) ? SCANNABLE_VALUE_YES : SCANNABLE_VALUE_NO);
if (!requestHeaders.isEmpty()) {
encodeHttpHeaders(values);
}
putIfNonNull(values, DownloadContract.Downloads.COLUMN_MIME_TYPE, mimeType);
values.put(DownloadContract.Downloads.COLUMN_ALLOWED_NETWORK_TYPES, allowedNetworkTypes);
values.put(DownloadContract.Downloads.COLUMN_ALLOW_ROAMING, roamingAllowed);
values.put(DownloadContract.Downloads.COLUMN_ALLOW_METERED, meteredAllowed);
values.put(DownloadContract.Downloads.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, isVisibleInDownloadsUi);
values.put(DownloadContract.Downloads.COLUMN_NOTIFICATION_EXTRAS, notificationExtras);
values.put(DownloadContract.Downloads.COLUMN_BATCH_ID, batchId);
values.put(DownloadContract.Downloads.COLUMN_EXTRA_DATA, extraData);
values.put(DownloadContract.Downloads.COLUMN_ALWAYS_RESUME, alwaysResume);
values.put(DownloadContract.Downloads.COLUMN_ALLOW_TAR_UPDATES, allowTarUpdates);
values.put(DownloadContract.Downloads.COLUMN_NO_INTEGRITY, noIntegrity);
return values;
}
private void encodeHttpHeaders(ContentValues values) {
int index = 0;
for (Pair<String, String> header : requestHeaders) {
String headerString = header.first + ": " + header.second;
values.put(DownloadContract.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
index++;
}
}
private void putIfNonNull(ContentValues contentValues, String key, Object value) {
if (value != null) {
contentValues.put(key, value.toString());
}
}
RequestBatch asBatch() {
RequestBatch requestBatch = new RequestBatch.Builder()
.withTitle(title.toString())
.withDescription(description.toString())
.withBigPictureUrl(bigPictureUrl)
.withVisibility(notificationVisibility)
.build();
requestBatch.addRequest(this);
return requestBatch;
}
String getDestinationPath() {
return destinationUri.getPath();
}
}
|
package io.bitsquare.locale;
import io.bitsquare.user.Preferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.stream.Collectors;
public class CurrencyUtil {
private static final Logger log = LoggerFactory.getLogger(CurrencyUtil.class);
private static final List<FiatCurrency> allSortedFiatCurrencies = createAllSortedFiatCurrenciesList();
private static List<FiatCurrency> createAllSortedFiatCurrenciesList() {
Set<FiatCurrency> set = CountryUtil.getAllCountries().stream()
.map(country -> getCurrencyByCountryCode(country.code))
.collect(Collectors.toSet());
List<FiatCurrency> list = new ArrayList<>(set);
list.sort(TradeCurrency::compareTo);
return list;
}
public static List<FiatCurrency> getAllSortedFiatCurrencies() {
return allSortedFiatCurrencies;
}
public static List<FiatCurrency> getAllMainFiatCurrencies() {
List<FiatCurrency> list = new ArrayList<>();
// Top traded currencies
list.add(new FiatCurrency("USD"));
list.add(new FiatCurrency("EUR"));
list.add(new FiatCurrency("GBP"));
list.add(new FiatCurrency("CAD"));
list.add(new FiatCurrency("AUD"));
list.add(new FiatCurrency("RUB"));
list.add(new FiatCurrency("INR"));
list.sort(TradeCurrency::compareTo);
TradeCurrency defaultTradeCurrency = getDefaultTradeCurrency();
FiatCurrency defaultFiatCurrency = defaultTradeCurrency instanceof FiatCurrency ? (FiatCurrency) defaultTradeCurrency : null;
if (defaultFiatCurrency != null && list.contains(defaultFiatCurrency)) {
list.remove(defaultTradeCurrency);
list.add(0, defaultFiatCurrency);
}
return list;
}
private static final List<CryptoCurrency> allSortedCryptoCurrencies = createAllSortedCryptoCurrenciesList();
public static List<CryptoCurrency> getAllSortedCryptoCurrencies() {
return allSortedCryptoCurrencies;
}
// Don't make a PR for adding a coin but follow the steps described here:
public static List<CryptoCurrency> createAllSortedCryptoCurrenciesList() {
final List<CryptoCurrency> result = new ArrayList<>();
result.add(new CryptoCurrency("AIB", "Advanced Internet Blocks"));
result.add(new CryptoCurrency("ANC", "Anoncoin"));
result.add(new CryptoCurrency("ANTI", "Anti"));
result.add(new CryptoCurrency("ARCO", "AquariusCoin"));
result.add(new CryptoCurrency("ARG", "Argentum"));
result.add(new CryptoCurrency("REP", "Augur", true));
result.add(new CryptoCurrency("BATL", "Battlestars"));
result.add(new CryptoCurrency("BIGUP", "BigUp"));
result.add(new CryptoCurrency("BITAUD", "BitAUD", true));
result.add(new CryptoCurrency("BITCHF", "BitCHF", true));
result.add(new CryptoCurrency("BITCNY", "BitCNY", true));
result.add(new CryptoCurrency("BITEUR", "BitEUR", true));
result.add(new CryptoCurrency("BITGBP", "BitGBP", true));
result.add(new CryptoCurrency("BITHKD", "BitHKD", true));
result.add(new CryptoCurrency("BITNZD", "BitNZD", true));
result.add(new CryptoCurrency("BITSEK", "BitSEK", true));
result.add(new CryptoCurrency("BITSGD", "BitSGD", true));
result.add(new CryptoCurrency("GBYTE", "Byte"));
result.add(new CryptoCurrency("SYNQ", "BitSYNQ"));
result.add(new CryptoCurrency("BTS", "BitShares"));
result.add(new CryptoCurrency("BITUSD", "BitUSD", true));
result.add(new CryptoCurrency("BLK", "Blackcoin"));
result.add(new CryptoCurrency("BURST", "Burstcoin"));
result.add(new CryptoCurrency("CLAM", "Clams"));
result.add(new CryptoCurrency("CLOAK", "CloakCoin"));
result.add(new CryptoCurrency("CMT", "Comet"));
result.add(new CryptoCurrency("XCP", "Counterparty"));
result.add(new CryptoCurrency("CRBIT", "Creditbit"));
result.add(new CryptoCurrency("CRW", "Crown"));
result.add(new CryptoCurrency("CBX", "Crypto Bullion"));
result.add(new CryptoCurrency("DNET", "DarkNet"));
result.add(new CryptoCurrency("DIBC", "DIBCOIN"));
result.add(new CryptoCurrency("DASH", "Dash"));
result.add(new CryptoCurrency("DCR", "Decred"));
result.add(new CryptoCurrency("DGB", "Digibyte"));
result.add(new CryptoCurrency("DRS", "Digital Rupees"));
result.add(new CryptoCurrency("DGD", "DigixDAO Tokens", true));
result.add(new CryptoCurrency("DOGE", "Dogecoin"));
result.add(new CryptoCurrency("DMC", "DynamicCoin"));
result.add(new CryptoCurrency("EMC", "Emercoin"));
result.add(new CryptoCurrency("EURT", "EUR Tether"));
result.add(new CryptoCurrency("ESP", "Espers"));
result.add(new CryptoCurrency("ENT", "Eternity"));
result.add(new CryptoCurrency("ETH", "Ether"));
result.add(new CryptoCurrency("ETC", "Ether Classic"));
result.add(new CryptoCurrency("ERC", "Europecoin"));
result.add(new CryptoCurrency("EGC", "EverGreenCoin"));
result.add(new CryptoCurrency("FCT", "Factom"));
result.add(new CryptoCurrency("FAIR", "FairCoin"));
result.add(new CryptoCurrency("FLO", "FlorinCoin"));
result.add(new CryptoCurrency("GAME", "GameCredits"));
result.add(new CryptoCurrency("GEMZ", "Gemz"));
result.add(new CryptoCurrency("GRC", "Gridcoin"));
result.add(new CryptoCurrency("GRS", "Groestlcoin"));
result.add(new CryptoCurrency("NLG", "Gulden"));
result.add(new CryptoCurrency("HODL", "HOdlcoin"));
result.add(new CryptoCurrency("HNC", "HunCoin"));
result.add(new CryptoCurrency("IOC", "I/O Coin"));
result.add(new CryptoCurrency("IOP", "Fermat"));
result.add(new CryptoCurrency("JPYT", "JPY Tether"));
result.add(new CryptoCurrency("JBS", "Jumbucks"));
result.add(new CryptoCurrency("LBC", "LBRY Credits"));
result.add(new CryptoCurrency("LTBC", "LTBcoin"));
result.add(new CryptoCurrency("LSK", "Lisk"));
result.add(new CryptoCurrency("LTC", "Litecoin"));
result.add(new CryptoCurrency("MAID", "MaidSafeCoin"));
result.add(new CryptoCurrency("MKR", "Maker", true));
result.add(new CryptoCurrency("MXT", "MarteXcoin"));
result.add(new CryptoCurrency("MOIN", "Moin"));
result.add(new CryptoCurrency("XMR", "Monero"));
result.add(new CryptoCurrency("MT", "Mycelium Token", true));
result.add(new CryptoCurrency("XMY", "Myriadcoin"));
result.add(new CryptoCurrency("NAV", "Nav Coin"));
result.add(new CryptoCurrency("XEM", "NEM"));
result.add(new CryptoCurrency("NEVA", "Nevacoin"));
result.add(new CryptoCurrency("NMC", "Namecoin"));
result.add(new CryptoCurrency("NBT", "NuBits"));
result.add(new CryptoCurrency("NSR", "NuShares"));
result.add(new CryptoCurrency("NXT", "Nxt"));
result.add(new CryptoCurrency("OK", "OKCash"));
result.add(new CryptoCurrency("OMNI", "Omni"));
result.add(new CryptoCurrency("OPAL", "Opal"));
result.add(new CryptoCurrency("PASC", "Pascal Coin"));
result.add(new CryptoCurrency("PPC", "Peercoin"));
result.add(new CryptoCurrency("PINK", "Pinkcoin"));
result.add(new CryptoCurrency("PIVX", "PIVX"));
result.add(new CryptoCurrency("XPTX", "PlatinumBar"));
result.add(new CryptoCurrency("PLU", "Plutons", true));
result.add(new CryptoCurrency("POST", "PostCoin"));
result.add(new CryptoCurrency("POT", "PotCoin"));
result.add(new CryptoCurrency("XPM", "Primecoin"));
result.add(new CryptoCurrency("RADS", "Radium"));
result.add(new CryptoCurrency("REALEST", "RealEst. Coin"));
result.add(new CryptoCurrency("RDD", "ReddCoin"));
result.add(new CryptoCurrency("XRP", "Ripple"));
result.add(new CryptoCurrency("SFSC", "Safe FileSystem Coin"));
result.add(new CryptoCurrency("STEEM", "STEEM"));
result.add(new CryptoCurrency("SDC", "ShadowCash"));
result.add(new CryptoCurrency("SHIFT", "Shift"));
result.add(new CryptoCurrency("SC", "Siacoin"));
result.add(new CryptoCurrency("SF", "Siafund"));
result.add(new CryptoCurrency("SIB", "Sibcoin"));
result.add(new CryptoCurrency("SMLY", "Smileycoin"));
result.add(new CryptoCurrency("SLR", "SolarCoin"));
result.add(new CryptoCurrency("STEEMUSD", "Steem Dollars", true));
result.add(new CryptoCurrency("XLM", "Stellar Lumens"));
result.add(new CryptoCurrency("SJCX", "StorjcoinX"));
result.add(new CryptoCurrency("STRAT", "Stratis"));
result.add(new CryptoCurrency("SWT", "Swarm City Token"));
result.add(new CryptoCurrency("SYNX", "Syndicate"));
result.add(new CryptoCurrency("AMP", "Synereo", true));
result.add(new CryptoCurrency("TRI", "Triangles"));
result.add(new CryptoCurrency("USDT", "USD Tether"));
result.add(new CryptoCurrency("UNO", "Unobtanium"));
result.add(new CryptoCurrency("VCN", "VCoin"));
result.add(new CryptoCurrency("VPN", "VPNCoin"));
result.add(new CryptoCurrency("XVG", "Verge"));
result.add(new CryptoCurrency("VRC", "VeriCoin"));
result.add(new CryptoCurrency("WDC", "Worldcoin"));
result.add(new CryptoCurrency("WAVES", "Waves"));
result.add(new CryptoCurrency("XAUR", "Xaurum"));
result.add(new CryptoCurrency("YACC", "YACCoin"));
result.add(new CryptoCurrency("YBC", "YbCoin"));
result.add(new CryptoCurrency("ZEC", "Zcash"));
result.add(new CryptoCurrency("XZC", "Zcoin"));
result.sort(TradeCurrency::compareTo);
return result;
}
public static List<CryptoCurrency> getMainCryptoCurrencies() {
final List<CryptoCurrency> result = new ArrayList<>();
result.add(new CryptoCurrency("XMR", "Monero"));
result.add(new CryptoCurrency("ZEC", "Zcash"));
result.add(new CryptoCurrency("SC", "Siacoin"));
result.add(new CryptoCurrency("ETH", "Ether"));
result.add(new CryptoCurrency("ETC", "Ether Classic"));
result.add(new CryptoCurrency("STEEM", "STEEM"));
result.add(new CryptoCurrency("MT", "Mycelium Token", true));
result.add(new CryptoCurrency("REP", "Augur", true));
result.add(new CryptoCurrency("FLO", "FlorinCoin"));
result.add(new CryptoCurrency("LTC", "Litecoin"));
result.add(new CryptoCurrency("DASH", "Dash"));
result.add(new CryptoCurrency("NMC", "Namecoin"));
result.add(new CryptoCurrency("NBT", "NuBits"));
result.add(new CryptoCurrency("DOGE", "Dogecoin"));
result.add(new CryptoCurrency("NXT", "Nxt"));
result.add(new CryptoCurrency("BTS", "BitShares"));
result.sort(TradeCurrency::compareTo);
return result;
}
/**
* @return Sorted list of SEPA currencies with EUR as first item
*/
private static Set<TradeCurrency> getSortedSEPACurrencyCodes() {
return CountryUtil.getAllSepaCountries().stream()
.map(country -> getCurrencyByCountryCode(country.code))
.collect(Collectors.toSet());
}
// At OKPay you can exchange internally those currencies
public static List<TradeCurrency> getAllOKPayCurrencies() {
ArrayList<TradeCurrency> currencies = new ArrayList<>(Arrays.asList(
new FiatCurrency("EUR"),
new FiatCurrency("USD"),
new FiatCurrency("GBP"),
new FiatCurrency("CHF"),
new FiatCurrency("RUB"),
new FiatCurrency("PLN"),
new FiatCurrency("JPY"),
new FiatCurrency("CAD"),
new FiatCurrency("AUD"),
new FiatCurrency("CZK"),
new FiatCurrency("NOK"),
new FiatCurrency("SEK"),
new FiatCurrency("DKK"),
new FiatCurrency("HRK"),
new FiatCurrency("HUF"),
new FiatCurrency("NZD"),
new FiatCurrency("RON"),
new FiatCurrency("TRY"),
new FiatCurrency("ZAR"),
new FiatCurrency("HKD"),
new FiatCurrency("CNY")
));
currencies.sort(TradeCurrency::compareTo);
return currencies;
}
public static boolean isFiatCurrency(String currencyCode) {
try {
return currencyCode != null && !currencyCode.isEmpty() && !isCryptoCurrency(currencyCode) && Currency.getInstance(currencyCode) != null;
} catch (Throwable t) {
return false;
}
}
public static Optional<FiatCurrency> getFiatCurrency(String currencyCode) {
return allSortedFiatCurrencies.stream().filter(e -> e.getCode().equals(currencyCode)).findAny();
}
@SuppressWarnings("WeakerAccess")
public static boolean isCryptoCurrency(String currencyCode) {
return getCryptoCurrency(currencyCode).isPresent();
}
public static Optional<CryptoCurrency> getCryptoCurrency(String currencyCode) {
return getAllSortedCryptoCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findAny();
}
public static Optional<TradeCurrency> getTradeCurrency(String currencyCode) {
Optional<FiatCurrency> fiatCurrencyOptional = getFiatCurrency(currencyCode);
if (isFiatCurrency(currencyCode) && fiatCurrencyOptional.isPresent()) {
return Optional.of(fiatCurrencyOptional.get());
} else {
Optional<CryptoCurrency> cryptoCurrencyOptional = getCryptoCurrency(currencyCode);
if (isCryptoCurrency(currencyCode) && cryptoCurrencyOptional.isPresent()) {
return Optional.of(cryptoCurrencyOptional.get());
} else {
return Optional.empty();
}
}
}
public static FiatCurrency getCurrencyByCountryCode(String countryCode) {
return new FiatCurrency(Currency.getInstance(new Locale(LanguageUtil.getDefaultLanguage(), countryCode)).getCurrencyCode());
}
public static String getNameByCode(String currencyCode) {
if (isCryptoCurrency(currencyCode))
return getCryptoCurrency(currencyCode).get().getName();
else
try {
return Currency.getInstance(currencyCode).getDisplayName(Preferences.getDefaultLocale());
} catch (Throwable t) {
log.debug("No currency name available " + t.getMessage());
return currencyCode;
}
}
public static String getNameAndCode(String currencyCode) {
return getNameByCode(currencyCode) + " (" + currencyCode + ")";
}
public static TradeCurrency getDefaultTradeCurrency() {
return Preferences.getDefaultTradeCurrency();
}
}
|
package lucee.runtime.debug;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.res.util.ResourceSnippet;
import lucee.commons.io.res.util.ResourceSnippetsMap;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.StringUtil;
import lucee.runtime.Component;
import lucee.runtime.Page;
import lucee.runtime.PageContext;
import lucee.runtime.PageContextImpl;
import lucee.runtime.PageSource;
import lucee.runtime.PageSourceImpl;
import lucee.runtime.config.Config;
import lucee.runtime.config.ConfigImpl;
import lucee.runtime.config.ConfigWebImpl;
import lucee.runtime.db.SQL;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.CatchBlock;
import lucee.runtime.exp.DatabaseException;
import lucee.runtime.exp.PageException;
import lucee.runtime.exp.PageExceptionImpl;
import lucee.runtime.op.Caster;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.DebugQueryColumn;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Query;
import lucee.runtime.type.QueryColumn;
import lucee.runtime.type.QueryImpl;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.dt.DateTimeImpl;
import lucee.runtime.type.query.QueryResult;
import lucee.runtime.type.util.KeyConstants;
import lucee.runtime.type.util.ListUtil;
/**
* Class to debug the application
*/
public final class DebuggerImpl implements Debugger {
private static final long serialVersionUID = 3957043879267494311L;
private static final Collection.Key IMPLICIT_ACCESS = KeyImpl.intern("implicitAccess");
private static final Collection.Key GENERIC_DATA = KeyImpl.intern("genericData");
private static final Collection.Key PAGE_PARTS = KeyImpl.intern("pageParts");
// private static final Collection.Key OUTPUT_LOG= KeyImpl.intern("outputLog");
private static final int MAX_PARTS = 100;
private Map<String, DebugEntryTemplateImpl> entries = new HashMap<String, DebugEntryTemplateImpl>();
private Map<String, DebugEntryTemplatePartImpl> partEntries;
private ResourceSnippetsMap snippetsMap = new ResourceSnippetsMap(1024, 128);
private List<QueryEntry> queries = new ArrayList<QueryEntry>();
private List<DebugTimerImpl> timers = new ArrayList<DebugTimerImpl>();
private List<DebugTraceImpl> traces = new ArrayList<DebugTraceImpl>();
private List<DebugDump> dumps = new ArrayList<DebugDump>();
private List<CatchBlock> exceptions = new ArrayList<CatchBlock>();
private Map<String, ImplicitAccessImpl> implicitAccesses = new HashMap<String, ImplicitAccessImpl>();
private boolean output = true;
private long lastEntry;
private long lastTrace;
private Array historyId = new ArrayImpl();
private Array historyLevel = new ArrayImpl();
private long starttime = System.currentTimeMillis();
private DebugOutputLog outputLog;
private Map<String, Map<String, List<String>>> genericData;
final static Comparator DEBUG_ENTRY_TEMPLATE_COMPARATOR = new DebugEntryTemplateComparator();
final static Comparator DEBUG_ENTRY_TEMPLATE_PART_COMPARATOR = new DebugEntryTemplatePartComparator();
private static final Key CACHE_TYPE = KeyImpl.init("cacheType");
@Override
public void reset() {
entries.clear();
if(partEntries != null)
partEntries.clear();
queries.clear();
implicitAccesses.clear();
if(genericData != null)
genericData.clear();
timers.clear();
traces.clear();
dumps.clear();
exceptions.clear();
historyId.clear();
historyLevel.clear();
output = true;
outputLog = null;
}
public DebuggerImpl() {
}
@Override
public DebugEntryTemplate getEntry(PageContext pc, PageSource source) {
return getEntry(pc, source, null);
}
@Override
public DebugEntryTemplate getEntry(PageContext pc, PageSource source, String key) {
lastEntry = System.currentTimeMillis();
String src = DebugEntryTemplateImpl.getSrc(source == null ? "" : source.getDisplayPath(), key);
DebugEntryTemplateImpl de = entries.get(src);
if(de != null) {
de.countPP();
historyId.appendEL(de.getId());
historyLevel.appendEL(Caster.toInteger(pc.getCurrentLevel()));
return de;
}
de = new DebugEntryTemplateImpl(source, key);
entries.put(src, de);
historyId.appendEL(de.getId());
historyLevel.appendEL(Caster.toInteger(pc.getCurrentLevel()));
return de;
}
@Override
public DebugEntryTemplatePart getEntry(PageContext pc, PageSource source, int startPos, int endPos) {
String src = DebugEntryTemplatePartImpl.getSrc(source == null ? "" : source.getDisplayPath(), startPos, endPos);
DebugEntryTemplatePartImpl de = null;
if(partEntries != null) {
de = partEntries.get(src);
if(de != null) {
de.countPP();
return de;
}
}
else {
partEntries = new HashMap<String, DebugEntryTemplatePartImpl>();
}
ResourceSnippet snippet = snippetsMap.getSnippet(source, startPos, endPos, ((PageContextImpl)pc).getResourceCharset().name());
de = new DebugEntryTemplatePartImpl(source, startPos, endPos, snippet.getStartLine(), snippet.getEndLine(), snippet.getContent());
partEntries.put(src, de);
return de;
}
private ArrayList<DebugEntryTemplate> toArray() {
ArrayList<DebugEntryTemplate> arrPages = new ArrayList<DebugEntryTemplate>(entries.size());
Iterator<String> it = entries.keySet().iterator();
while(it.hasNext()) {
DebugEntryTemplate page = entries.get(it.next());
page.resetQueryTime();
arrPages.add(page);
}
Collections.sort(arrPages, DEBUG_ENTRY_TEMPLATE_COMPARATOR);
// Queries
int len = queries.size();
QueryEntry entry;
for (int i = 0; i < len; i++) {
entry = queries.get(i);
String path = entry.getSrc();
Object o = entries.get(path);
if(o != null) {
DebugEntryTemplate oe = (DebugEntryTemplate)o;
oe.updateQueryTime(entry.getExecutionTime());
}
}
return arrPages;
}
public static boolean debugQueryUsage(PageContext pageContext, QueryResult qr) {
if(pageContext.getConfig().debug() && qr instanceof Query) {
if(((ConfigWebImpl)pageContext.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_QUERY_USAGE)) {
((Query)qr).enableShowQueryUsage();
return true;
}
}
return false;
}
public static boolean debugQueryUsage(PageContext pageContext, Query qry) {
if(pageContext.getConfig().debug() && qry instanceof Query) {
if(((ConfigWebImpl)pageContext.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_QUERY_USAGE)) {
qry.enableShowQueryUsage();
return true;
}
}
return false;
}
private String _toString(long value) {
if(value <= 0)
return "0";
return String.valueOf(value);
}
private String _toString(int value) {
if(value <= 0)
return "0";
return String.valueOf(value);
}
@Override
public void addQuery(Query query, String datasource, String name, SQL sql, int recordcount, PageSource src, int time) {
addQuery(query, datasource, name, sql, recordcount, src, (long)time);
}
@Override
public void addQuery(Query query, String datasource, String name, SQL sql, int recordcount, PageSource src, long time) {
String path = "";
if(src != null)
path = src.getDisplayPath();
queries.add(new QueryResultEntryImpl((QueryResult)query, datasource, name, sql, recordcount, path, time));
}
public void addQuery(QueryResult qr, String datasource, String name, SQL sql, int recordcount, PageSource src, long time) {
String path = "";
if(src != null)
path = src.getDisplayPath();
queries.add(new QueryResultEntryImpl(qr, datasource, name, sql, recordcount, path, time));
}
@Override
public void setOutput(boolean output) {
this.output = output;
}
@Override
public List<QueryEntry> getQueries() {
return queries;
}
@Override
public void writeOut(PageContext pc) throws IOException {
// stop();
if(!output)
return;
String addr = pc.getHttpServletRequest().getRemoteAddr();
lucee.runtime.config.DebugEntry debugEntry = ((ConfigImpl)pc.getConfig()).getDebugEntry(addr, null);
// no debug File
if(debugEntry == null) {
// pc.forceWrite(pc.getConfig().getDefaultDumpWriter().toString(pc,toDumpData(pc, 9999,DumpUtil.toDumpProperties()),true));
return;
}
Struct args = new StructImpl();
args.setEL(KeyConstants._custom, debugEntry.getCustom());
try {
args.setEL(KeyConstants._debugging, pc.getDebugger().getDebuggingData(pc));
}
catch (PageException e1) {
}
try {
String path = debugEntry.getPath();
PageSource[] arr = ((PageContextImpl)pc).getPageSources(path);
Page p = PageSourceImpl.loadPage(pc, arr, null);
// patch for old path
String fullname = debugEntry.getFullname();
if(p == null) {
if(path != null) {
boolean changed = false;
if(path.endsWith("/Modern.cfc") || path.endsWith("\\Modern.cfc")) {
path = "/lucee-server-context/admin/debug/Modern.cfc";
fullname = "lucee-server-context.admin.debug.Modern";
changed = true;
}
else if(path.endsWith("/Classic.cfc") || path.endsWith("\\Classic.cfc")) {
path = "/lucee-server-context/admin/debug/Classic.cfc";
fullname = "lucee-server-context.admin.debug.Classic";
changed = true;
}
else if(path.endsWith("/Comment.cfc") || path.endsWith("\\Comment.cfc")) {
path = "/lucee-server-context/admin/debug/Comment.cfc";
fullname = "lucee-server-context.admin.debug.Comment";
changed = true;
}
if(changed)
pc.write(
"<span style='color:red'>Please update your debug template defintions in the Lucee admin by going into the detail view and hit the \"update\" button.</span>");
}
arr = ((PageContextImpl)pc).getPageSources(path);
p = PageSourceImpl.loadPage(pc, arr);
}
pc.addPageSource(p.getPageSource(), true);
try {
Component c = pc.loadComponent(fullname);
c.callWithNamedValues(pc, "output", args);
} finally {
pc.removeLastPageSource(true);
}
}
catch (PageException e) {
pc.handlePageException(e);
}
}
@Override
public Struct getDebuggingData(PageContext pc) throws DatabaseException {
return getDebuggingData(pc, false);
}
@Override
public Struct getDebuggingData(PageContext pc, boolean addAddionalInfo) throws DatabaseException {
Struct debugging = new StructImpl();
// datasources
debugging.setEL(KeyConstants._datasources, ((ConfigImpl)pc.getConfig()).getDatasourceConnectionPool().meta());
// queries
List<QueryEntry> queries = getQueries();
Struct qryExe = new StructImpl();
ListIterator<QueryEntry> qryIt = queries.listIterator();
Collection.Key[] cols = new Collection.Key[] { KeyConstants._name, KeyConstants._time, KeyConstants._sql, KeyConstants._src, KeyConstants._count,
KeyConstants._datasource, KeyConstants._usage, CACHE_TYPE };
String[] types = new String[] { "VARCHAR", "DOUBLE", "VARCHAR", "VARCHAR", "DOUBLE", "VARCHAR", "ANY", "VARCHAR" };
Query qryQueries = null;
try {
qryQueries = new QueryImpl(cols, types, queries.size(), "query");
}
catch (DatabaseException e) {
qryQueries = new QueryImpl(cols, queries.size(), "query");
}
int row = 0;
try {
QueryEntry qe;
while(qryIt.hasNext()) {
row++;
qe = qryIt.next();
qryQueries.setAt(KeyConstants._name, row, qe.getName() == null ? "" : qe.getName());
qryQueries.setAt(KeyConstants._time, row, Long.valueOf(qe.getExecutionTime()));
qryQueries.setAt(KeyConstants._sql, row, qe.getSQL().toString());
qryQueries.setAt(KeyConstants._src, row, qe.getSrc());
qryQueries.setAt(KeyConstants._count, row, Integer.valueOf(qe.getRecordcount()));
qryQueries.setAt(KeyConstants._datasource, row, qe.getDatasource());
qryQueries.setAt(CACHE_TYPE, row, qe.getCacheType());
Struct usage = getUsage(qe);
if(usage != null)
qryQueries.setAt(KeyConstants._usage, row, usage);
Object o = qryExe.get(KeyImpl.init(qe.getSrc()), null);
if(o == null)
qryExe.setEL(KeyImpl.init(qe.getSrc()), Long.valueOf(qe.getExecutionTime()));
else
qryExe.setEL(KeyImpl.init(qe.getSrc()), Long.valueOf(((Long)o).longValue() + qe.getExecutionTime()));
}
}
catch (PageException dbe) {
}
// Pages
// src,load,app,query,total
row = 0;
ArrayList<DebugEntryTemplate> arrPages = toArray();
int len = arrPages.size();
Query qryPage = new QueryImpl(new Collection.Key[] { KeyConstants._id, KeyConstants._count, KeyConstants._min, KeyConstants._max, KeyConstants._avg,
KeyConstants._app, KeyConstants._load, KeyConstants._query, KeyConstants._total, KeyConstants._src }, len, "query");
try {
DebugEntryTemplate de;
// PageSource ps;
for (int i = 0; i < len; i++) {
row++;
de = arrPages.get(i);
// ps = de.getPageSource();
qryPage.setAt(KeyConstants._id, row, de.getId());
qryPage.setAt(KeyConstants._count, row, _toString(de.getCount()));
qryPage.setAt(KeyConstants._min, row, _toString(de.getMin()));
qryPage.setAt(KeyConstants._max, row, _toString(de.getMax()));
qryPage.setAt(KeyConstants._avg, row, _toString(de.getExeTime() / de.getCount()));
qryPage.setAt(KeyConstants._app, row, _toString(de.getExeTime() - de.getQueryTime()));
qryPage.setAt(KeyConstants._load, row, _toString(de.getFileLoadTime()));
qryPage.setAt(KeyConstants._query, row, _toString(de.getQueryTime()));
qryPage.setAt(KeyConstants._total, row, _toString(de.getFileLoadTime() + de.getExeTime()));
qryPage.setAt(KeyConstants._src, row, de.getSrc());
}
}
catch (PageException dbe) {
}
// Pages Parts
List<DebugEntryTemplatePart> filteredPartEntries = null;
boolean hasParts = partEntries != null && !partEntries.isEmpty() && !arrPages.isEmpty();
int qrySize = 0;
if(hasParts) {
String slowestTemplate = arrPages.get(0).getPath();
filteredPartEntries = new ArrayList();
java.util.Collection<DebugEntryTemplatePartImpl> col = partEntries.values();
for (DebugEntryTemplatePart detp : col) {
if(detp.getPath().equals(slowestTemplate))
filteredPartEntries.add(detp);
}
qrySize = Math.min(filteredPartEntries.size(), MAX_PARTS);
}
Query qryPart = new QueryImpl(
new Collection.Key[] { KeyConstants._id, KeyConstants._count, KeyConstants._min, KeyConstants._max, KeyConstants._avg, KeyConstants._total,
KeyConstants._path, KeyConstants._start, KeyConstants._end, KeyConstants._startLine, KeyConstants._endLine, KeyConstants._snippet },
qrySize, "query");
if(hasParts) {
row = 0;
Collections.sort(filteredPartEntries, DEBUG_ENTRY_TEMPLATE_PART_COMPARATOR);
DebugEntryTemplatePart[] parts = new DebugEntryTemplatePart[qrySize];
if(filteredPartEntries.size() > MAX_PARTS)
parts = filteredPartEntries.subList(0, MAX_PARTS).toArray(parts);
else
parts = filteredPartEntries.toArray(parts);
try {
DebugEntryTemplatePart de;
// PageSource ps;
for (int i = 0; i < parts.length; i++) {
row++;
de = parts[i];
qryPart.setAt(KeyConstants._id, row, de.getId());
qryPart.setAt(KeyConstants._count, row, _toString(de.getCount()));
qryPart.setAt(KeyConstants._min, row, _toString(de.getMin()));
qryPart.setAt(KeyConstants._max, row, _toString(de.getMax()));
qryPart.setAt(KeyConstants._avg, row, _toString(de.getExeTime() / de.getCount()));
qryPart.setAt(KeyConstants._start, row, _toString(de.getStartPosition()));
qryPart.setAt(KeyConstants._end, row, _toString(de.getEndPosition()));
qryPart.setAt(KeyConstants._total, row, _toString(de.getExeTime()));
qryPart.setAt(KeyConstants._path, row, de.getPath());
if(de instanceof DebugEntryTemplatePartImpl) {
qryPart.setAt(KeyConstants._startLine, row, _toString(((DebugEntryTemplatePartImpl)de).getStartLine()));
qryPart.setAt(KeyConstants._endLine, row, _toString(((DebugEntryTemplatePartImpl)de).getEndLine()));
qryPart.setAt(KeyConstants._snippet, row, ((DebugEntryTemplatePartImpl)de).getSnippet());
}
}
}
catch (PageException dbe) {
}
}
// exceptions
len = exceptions == null ? 0 : exceptions.size();
Array arrExceptions = new ArrayImpl();
if(len > 0) {
Iterator<CatchBlock> it = exceptions.iterator();
row = 0;
while(it.hasNext()) {
arrExceptions.appendEL(it.next());
}
}
// generic data
Query qryGenData = new QueryImpl(new Collection.Key[] { KeyConstants._category, KeyConstants._name, KeyConstants._value }, 0, "query");
Map<String, Map<String, List<String>>> genData = getGenericData();
if(genData != null && genData.size() > 0) {
Iterator<Entry<String, Map<String, List<String>>>> it = genData.entrySet().iterator();
Entry<String, Map<String, List<String>>> e;
Iterator<Entry<String, List<String>>> itt;
Entry<String, List<String>> ee;
String cat;
int r;
List<String> list;
Object val;
while(it.hasNext()) {
e = it.next();
cat = e.getKey();
itt = e.getValue().entrySet().iterator();
while(itt.hasNext()) {
ee = itt.next();
r = qryGenData.addRow();
list = ee.getValue();
if(list.size() == 1)
val = list.get(0);
else
val = ListUtil.listToListEL(list, ", ");
qryGenData.setAtEL(KeyConstants._category, r, cat);
qryGenData.setAtEL(KeyConstants._name, r, ee.getKey());
qryGenData.setAtEL(KeyConstants._value, r, val);
}
}
}
// output log
// Query qryOutputLog=getOutputText();
// timers
len = timers == null ? 0 : timers.size();
Query qryTimers = new QueryImpl(new Collection.Key[] { KeyConstants._label, KeyConstants._time, KeyConstants._template }, len, "timers");
if(len > 0) {
try {
Iterator<DebugTimerImpl> it = timers.iterator();
DebugTimer timer;
row = 0;
while(it.hasNext()) {
timer = it.next();
row++;
qryTimers.setAt(KeyConstants._label, row, timer.getLabel());
qryTimers.setAt(KeyConstants._template, row, timer.getTemplate());
qryTimers.setAt(KeyConstants._time, row, Caster.toDouble(timer.getTime()));
}
}
catch (PageException dbe) {
}
}
// dumps
len = dumps == null ? 0 : dumps.size();
if(!((ConfigImpl)pc.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_DUMP))
len = 0;
Query qryDumps = new QueryImpl(new Collection.Key[] { KeyConstants._output, KeyConstants._template, KeyConstants._line }, len, "dumps");
if(len > 0) {
try {
Iterator<DebugDump> it = dumps.iterator();
DebugDump dd;
row = 0;
while(it.hasNext()) {
dd = it.next();
row++;
qryDumps.setAt(KeyConstants._output, row, dd.getOutput());
if(!StringUtil.isEmpty(dd.getTemplate()))
qryDumps.setAt(KeyConstants._template, row, dd.getTemplate());
if(dd.getLine() > 0)
qryDumps.setAt(KeyConstants._line, row, new Double(dd.getLine()));
}
}
catch (PageException dbe) {
}
}
// traces
len = traces == null ? 0 : traces.size();
if(!((ConfigImpl)pc.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_TRACING))
len = 0;
Query qryTraces = new QueryImpl(new Collection.Key[] { KeyConstants._type, KeyConstants._category, KeyConstants._text, KeyConstants._template,
KeyConstants._line, KeyConstants._action, KeyConstants._varname, KeyConstants._varvalue, KeyConstants._time }, len, "traces");
if(len > 0) {
try {
Iterator<DebugTraceImpl> it = traces.iterator();
DebugTraceImpl trace;
row = 0;
while(it.hasNext()) {
trace = it.next();
row++;
qryTraces.setAt(KeyConstants._type, row, DebugTraceImpl.toType(trace.getType(), "INFO"));
if(!StringUtil.isEmpty(trace.getCategory()))
qryTraces.setAt(KeyConstants._category, row, trace.getCategory());
if(!StringUtil.isEmpty(trace.getText()))
qryTraces.setAt(KeyConstants._text, row, trace.getText());
if(!StringUtil.isEmpty(trace.getTemplate()))
qryTraces.setAt(KeyConstants._template, row, trace.getTemplate());
if(trace.getLine() > 0)
qryTraces.setAt(KeyConstants._line, row, new Double(trace.getLine()));
if(!StringUtil.isEmpty(trace.getAction()))
qryTraces.setAt(KeyConstants._action, row, trace.getAction());
if(!StringUtil.isEmpty(trace.getVarName()))
qryTraces.setAt(KeyImpl.init("varname"), row, trace.getVarName());
if(!StringUtil.isEmpty(trace.getVarValue()))
qryTraces.setAt(KeyImpl.init("varvalue"), row, trace.getVarValue());
qryTraces.setAt(KeyConstants._time, row, new Double(trace.getTime()));
}
}
catch (PageException dbe) {
}
}
// scope access
len = implicitAccesses == null ? 0 : implicitAccesses.size();
Query qryImplicitAccesseses = new QueryImpl(
new Collection.Key[] { KeyConstants._template, KeyConstants._line, KeyConstants._scope, KeyConstants._count, KeyConstants._name }, len,
"implicitAccess");
if(len > 0) {
try {
Iterator<ImplicitAccessImpl> it = implicitAccesses.values().iterator();
ImplicitAccessImpl das;
row = 0;
while(it.hasNext()) {
das = it.next();
row++;
qryImplicitAccesseses.setAt(KeyConstants._template, row, das.getTemplate());
qryImplicitAccesseses.setAt(KeyConstants._line, row, new Double(das.getLine()));
qryImplicitAccesseses.setAt(KeyConstants._scope, row, das.getScope());
qryImplicitAccesseses.setAt(KeyConstants._count, row, new Double(das.getCount()));
qryImplicitAccesseses.setAt(KeyConstants._name, row, das.getName());
}
}
catch (PageException dbe) {
}
}
Query history = new QueryImpl(new Collection.Key[] {}, 0, "history");
try {
history.addColumn(KeyConstants._id, historyId);
history.addColumn(KeyConstants._level, historyLevel);
}
catch (PageException e) {
}
if(addAddionalInfo) {
debugging.setEL(KeyConstants._cgi, pc.cgiScope());
}
debugging.setEL(KeyImpl.init("starttime"), new DateTimeImpl(starttime, false));
debugging.setEL(KeyConstants._id, pc.getId());
debugging.setEL(KeyConstants._pages, qryPage);
debugging.setEL(PAGE_PARTS, qryPart);
debugging.setEL(KeyConstants._queries, qryQueries);
debugging.setEL(KeyConstants._timers, qryTimers);
debugging.setEL(KeyConstants._traces, qryTraces);
debugging.setEL("dumps", qryDumps);
debugging.setEL(IMPLICIT_ACCESS, qryImplicitAccesseses);
debugging.setEL(GENERIC_DATA, qryGenData);
// debugging.setEL(OUTPUT_LOG,qryOutputLog);
debugging.setEL(KeyConstants._history, history);
debugging.setEL(KeyConstants._exceptions, arrExceptions);
return debugging;
}
private static Struct getUsage(QueryEntry qe) throws PageException {
Query qry = qe.getQry();
QueryColumn c;
DebugQueryColumn dqc;
outer: if(qry != null) {
Struct usage = null;
Collection.Key[] columnNames = qry.getColumnNames();
Collection.Key columnName;
for (int i = 0; i < columnNames.length; i++) {
columnName = columnNames[i];
c = qry.getColumn(columnName);
if(!(c instanceof DebugQueryColumn))
break outer;
dqc = (DebugQueryColumn)c;
if(usage == null)
usage = new StructImpl();
usage.setEL(columnName, Caster.toBoolean(dqc.isUsed()));
}
return usage;
}
return null;
}
@Override
public DebugTimer addTimer(String label, long time, String template) {
DebugTimerImpl t;
timers.add(t = new DebugTimerImpl(label, time, template));
return t;
}
@Override
public DebugTrace addTrace(int type, String category, String text, PageSource ps, String varName, String varValue) {
long _lastTrace = (traces.isEmpty()) ? lastEntry : lastTrace;
lastTrace = System.currentTimeMillis();
DebugTraceImpl t = new DebugTraceImpl(type, category, text, ps == null ? "unknown template" : ps.getDisplayPath(), SystemUtil.getCurrentContext().line,
"", varName, varValue, lastTrace - _lastTrace);
traces.add(t);
return t;
}
public DebugDump addDump(PageSource ps, String dump) {
DebugDump dt = new DebugDumpImpl(ps.getDisplayPath(), SystemUtil.getCurrentContext().line, dump);
dumps.add(dt);
return dt;
}
@Override
public DebugTrace addTrace(int type, String category, String text, String template, int line, String action, String varName, String varValue) {
long _lastTrace = (traces.isEmpty()) ? lastEntry : lastTrace;
lastTrace = System.currentTimeMillis();
DebugTraceImpl t = new DebugTraceImpl(type, category, text, template, line, action, varName, varValue, lastTrace - _lastTrace);
traces.add(t);
return t;
}
@Override
public DebugTrace[] getTraces() {
return getTraces(ThreadLocalPageContext.get());
}
@Override
public DebugTrace[] getTraces(PageContext pc) {
if(pc != null && ((ConfigImpl)pc.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_TRACING))
return traces.toArray(new DebugTrace[traces.size()]);
return new DebugTrace[0];
}
@Override
public void addException(Config config, PageException pe) {
if(exceptions.size() > 1000)
return;
try {
exceptions.add(((PageExceptionImpl)pe).getCatchBlock(config));
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
@Override
public CatchBlock[] getExceptions() {
return exceptions.toArray(new CatchBlock[exceptions.size()]);
}
public void init(Config config) {
this.starttime = System.currentTimeMillis() + config.getTimeServerOffset();
}
@Override
public void addImplicitAccess(String scope, String name) {
if(implicitAccesses.size() > 1000)
return;
try {
SystemUtil.TemplateLine tl = SystemUtil.getCurrentContext();
String key = tl + ":" + scope + ":" + name;
ImplicitAccessImpl dsc = implicitAccesses.get(key);
if(dsc != null)
dsc.inc();
else
implicitAccesses.put(key, new ImplicitAccessImpl(scope, name, tl.template, tl.line));
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
@Override
public ImplicitAccess[] getImplicitAccesses(int scope, String name) {
return implicitAccesses.values().toArray(new ImplicitAccessImpl[implicitAccesses.size()]);
}
public void setOutputLog(DebugOutputLog outputLog) {
this.outputLog = outputLog;
}
public DebugTextFragment[] getOutputTextFragments() {
return this.outputLog.getFragments();
}
public Query getOutputText() throws DatabaseException {
DebugTextFragment[] fragments = outputLog.getFragments();
int len = fragments == null ? 0 : fragments.length;
Query qryOutputLog = new QueryImpl(new Collection.Key[] { KeyConstants._line, KeyConstants._template, KeyConstants._text }, len, "query");
if(len > 0) {
for (int i = 0; i < fragments.length; i++) {
qryOutputLog.setAtEL(KeyConstants._line, i + 1, fragments[i].getLine());
qryOutputLog.setAtEL(KeyConstants._template, i + 1, fragments[i].getTemplate());
qryOutputLog.setAtEL(KeyConstants._text, i + 1, fragments[i].getText());
}
}
return qryOutputLog;
}
public void resetTraces() {
traces.clear();
}
@Override
public void addGenericData(String labelCategory, Map<String, String> data) {
// init generic data if necessary
if(genericData == null)
genericData = new ConcurrentHashMap<String, Map<String, List<String>>>();
// category
Map<String, List<String>> cat = genericData.get(labelCategory);
if(cat == null)
genericData.put(labelCategory, cat = new ConcurrentHashMap<String, List<String>>());
// data
Iterator<Entry<String, String>> it = data.entrySet().iterator();
Entry<String, String> e;
List<String> entry;
while(it.hasNext()) {
e = it.next();
entry = cat.get(e.getKey());
if(entry == null) {
cat.put(e.getKey(), entry = new ArrayList<String>());
}
entry.add(e.getValue());
}
}
/*
* private List<String> createAndFillList(Map<String, List<String>> cat) { Iterator<List<String>> it = cat.values().iterator(); int size=0;
* while(it.hasNext()){ size=it.next().size(); break; } ArrayList<String> list = new ArrayList<String>();
*
* // fill with empty values to be on the same level as other columns for(int i=0;i<size;i++)list.add("");
*
* return list; }
*/
@Override
public Map<String, Map<String, List<String>>> getGenericData() {
return genericData;
}
}
final class DebugEntryTemplateComparator implements Comparator<DebugEntryTemplate> {
@Override
public int compare(DebugEntryTemplate de1, DebugEntryTemplate de2) {
long result = ((de2.getExeTime() + de2.getFileLoadTime()) - (de1.getExeTime() + de1.getFileLoadTime()));
// we do this additional step to try to avoid ticket LUCEE-2076
return result > 0L ? 1 : (result < 0L ? -1 : 0);
}
}
final class DebugEntryTemplatePartComparator implements Comparator<DebugEntryTemplatePart> {
@Override
public int compare(DebugEntryTemplatePart de1, DebugEntryTemplatePart de2) {
long result = de2.getExeTime() - de1.getExeTime();
// we do this additional step to try to avoid ticket LUCEE-2076
return result > 0L ? 1 : (result < 0L ? -1 : 0);
}
}
|
package bisq.asset.coins;
import bisq.asset.Coin;
import bisq.asset.RegexAddressValidator;
public class Noir extends Coin {
public Noir() {
super("Noir", "NOR", new RegexAddressValidator("^[Z][_A-z0-9]*([_A-z0-9])*$"));
}
}
|
package lucee.runtime.config;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import lucee.commons.io.IOUtil;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.compress.ZipUtil;
import lucee.commons.io.log.LogUtil;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.filter.ExtensionResourceFilter;
import lucee.commons.io.res.util.FileWrapper;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.StringUtil;
import lucee.commons.lang.SystemOut;
import lucee.runtime.Info;
import lucee.runtime.extension.RHExtension;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.type.util.ListUtil;
import lucee.commons.io.log.Log;
import lucee.commons.io.res.filter.ResourceFilter;
public class DeployHandler {
private static final ResourceFilter ALL_EXT = new ExtensionResourceFilter(new String[]{".lex",".lar"});
public static void deploy(Config config){
synchronized (config) {
Resource dir = getDeployDirectory(config);
int ma = Info.getMajorVersion();
int mi = Info.getMinorVersion();
if(!dir.exists()) {
if(ma>4 || ma==4 && mi>1) {// FUTURE remove the if contition
dir.mkdirs();
}
return;
}
Resource[] children = dir.listResources(ALL_EXT);
Resource child;
String ext;
for(int i=0;i<children.length;i++){
child=children[i];
try {
// Lucee archives
ext=ResourceUtil.getExtension(child, null);
if("lar".equalsIgnoreCase(ext)) {
deployArchive(config,child);
}
// Lucee Extensions
else if("lex".equalsIgnoreCase(ext))
deployExtension(config, child);
}
catch (ZipException e) {
SystemOut.printDate(config.getErrWriter(),ExceptionUtil.getStacktrace(e, true));
}
catch (IOException e) {
SystemOut.printDate(config.getErrWriter(),ExceptionUtil.getStacktrace(e, true));
}
}
}
}
public static Resource getDeployDirectory(Config config) {
return config.getConfigDir().getRealResource("deploy");
}
private static void deployArchive(Config config,Resource archive) throws ZipException, IOException {
Log logger = ((ConfigImpl)config).getLog("deploy");
String type=null,virtual=null,name=null;
boolean readOnly,topLevel,hidden,physicalFirst;
short inspect;
InputStream is = null;
ZipFile file=null;
try {
file=new ZipFile(FileWrapper.toFile(archive));
ZipEntry entry = file.getEntry("META-INF/MANIFEST.MF");
// no manifest
if(entry==null) {
logger.log(Log.LEVEL_ERROR,"archive","cannot deploy Lucee Archive ["+archive+"], file is to old, the file does not have a MANIFEST.");
moveToFailedFolder(archive);
return;
}
is = file.getInputStream(entry);
Manifest manifest = new Manifest(is);
Attributes attr = manifest.getMainAttributes();
//id = unwrap(attr.getValue("mapping-id"));
type = unwrap(attr.getValue("mapping-type"));
virtual = unwrap(attr.getValue("mapping-virtual-path"));
name = ListUtil.trim(virtual, "/");
readOnly = Caster.toBooleanValue(unwrap(attr.getValue("mapping-readonly")),false);
topLevel = Caster.toBooleanValue(unwrap(attr.getValue("mapping-top-level")),false);
inspect = ConfigWebUtil.inspectTemplate(unwrap(attr.getValue("mapping-inspect")), ConfigImpl.INSPECT_UNDEFINED);
if(inspect==ConfigImpl.INSPECT_UNDEFINED) {
Boolean trusted = Caster.toBoolean(unwrap(attr.getValue("mapping-trusted")),null);
if(trusted!=null) {
if(trusted.booleanValue()) inspect=ConfigImpl.INSPECT_NEVER;
else inspect=ConfigImpl.INSPECT_ALWAYS;
}
}
hidden = Caster.toBooleanValue(unwrap(attr.getValue("mapping-hidden")),false);
physicalFirst = Caster.toBooleanValue(unwrap(attr.getValue("mapping-physical-first")),false);
}
finally{
IOUtil.closeEL(is);
ZipUtil.close(file);
}
Resource trgDir = config.getConfigDir().getRealResource("archives").getRealResource(type).getRealResource(name);
Resource trgFile = trgDir.getRealResource(archive.getName());
trgDir.mkdirs();
// delete existing files
try {
ResourceUtil.deleteContent(trgDir, null);
ResourceUtil.moveTo(archive, trgFile,true);
logger.log(Log.LEVEL_INFO,"archive","add "+type+" mapping ["+virtual+"] with archive ["+trgFile.getAbsolutePath()+"]");
if("regular".equalsIgnoreCase(type))
ConfigWebAdmin.updateMapping((ConfigImpl)config,virtual, null, trgFile.getAbsolutePath(), "archive", inspect, topLevel);
else if("cfc".equalsIgnoreCase(type))
ConfigWebAdmin.updateComponentMapping((ConfigImpl)config,virtual, null, trgFile.getAbsolutePath(), "archive", inspect);
else if("ct".equalsIgnoreCase(type))
ConfigWebAdmin.updateCustomTagMapping((ConfigImpl)config,virtual, null, trgFile.getAbsolutePath(), "archive", inspect);
}
catch (Throwable t) {
moveToFailedFolder(archive);
LogUtil.log(logger, Log.LEVEL_ERROR,"archive",t);
}
}
private static void deployExtension(Config config, Resource ext) {
ConfigImpl ci = (ConfigImpl)config;
boolean isWeb=config instanceof ConfigWeb;
String type=isWeb?"web":"server";
Log logger = ((ConfigImpl)config).getLog("deploy");
// Manifest
Manifest manifest = null;
ZipInputStream zis=null;
try {
zis = new ZipInputStream( IOUtil.toBufferedInputStream(ext.getInputStream()) ) ;
ZipEntry entry;
String name;
while ( ( entry = zis.getNextEntry()) != null ) {
name=entry.getName();
if(!entry.isDirectory() && name.equalsIgnoreCase("META-INF/MANIFEST.MF")) {
manifest = toManifest(config,zis,null);
}
zis.closeEntry() ;
}
}
catch(Throwable t){
LogUtil.log(logger, Log.LEVEL_ERROR,"extension", t);
moveToFailedFolder(ext);
return;
}
finally {
IOUtil.closeEL(zis);
}
int minCoreVersion=0;
double minLoaderVersion=0;
String strMinCoreVersion="",strMinLoaderVersion="",version=null,name=null,id=null;
if(manifest!=null) {
Attributes attr = manifest.getMainAttributes();
// version
version=unwrap(attr.getValue("version"));
id=unwrap(attr.getValue("id"));
// name
name=unwrap(attr.getValue("name"));
// core version
strMinCoreVersion=unwrap(attr.getValue("lucee-core-version"));
if(StringUtil.isEmpty(strMinCoreVersion))
strMinCoreVersion=unwrap(attr.getValue("railo-core-version"));
minCoreVersion=Info.toIntVersion(strMinCoreVersion,minCoreVersion);
// loader version
strMinLoaderVersion=unwrap(attr.getValue("lucee-loader-version"));
if(StringUtil.isEmpty(strMinLoaderVersion))
strMinLoaderVersion=unwrap(attr.getValue("railo-loader-version"));
minLoaderVersion=Caster.toDoubleValue(strMinLoaderVersion,minLoaderVersion);
}
if(StringUtil.isEmpty(name,true)) {
name=ext.getName();
int index=name.lastIndexOf('.');
name=name.substring(0,index-1);
}
name=name.trim();
// check core version
if(minCoreVersion>Info.getVersionAsInt()) {
logger.log(Log.LEVEL_ERROR,"extension", "cannot deploy Lucee Extension ["+ext+"], Lucee Version must be at least ["+strMinCoreVersion+"].");
moveToFailedFolder(ext);
return;
}
// check loader version
if(minLoaderVersion>SystemUtil.getLoaderVersion()) {
logger.log(Log.LEVEL_ERROR,"extension", "cannot deploy Lucee Extension ["+ext+"], Lucee Loader Version must be at least ["+strMinLoaderVersion+"], update the lucee.jar first.");
moveToFailedFolder(ext);
return;
}
// check id
if(!Decision.isUUId(id)) {
logger.log(Log.LEVEL_ERROR,"extension", "cannot deploy Lucee Extension ["+ext+"], this Extension has no valid id ["+id+"],id must be a valid UUID.");
moveToFailedFolder(ext);
return;
}
Resource trgFile=null;
try{
ConfigWebAdmin.removeRHExtension(ci,id);
Resource trgDir = config.getConfigDir().getRealResource("extensions").getRealResource(type).getRealResource(name);
trgFile = trgDir.getRealResource(ext.getName());
trgDir.mkdirs();
ResourceUtil.moveTo(ext, trgFile,true);
}
catch(Throwable t){
LogUtil.log(logger, Log.LEVEL_ERROR,"extension", t);
moveToFailedFolder(ext);
return;
}
try {
zis = new ZipInputStream( IOUtil.toBufferedInputStream(trgFile.getInputStream()) ) ;
ZipEntry entry;
String path;
String fileName;
List<String> jars=new ArrayList<String>(), flds=new ArrayList<String>(), tlds=new ArrayList<String>(), contexts=new ArrayList<String>(), applications=new ArrayList<String>();
while ( ( entry = zis.getNextEntry()) != null ) {
path=entry.getName();
fileName=fileName(entry);
// jars
if(!entry.isDirectory() && (startsWith(path,type,"jars") || startsWith(path,type,"jar") || startsWith(path,type,"lib") || startsWith(path,type,"libs")) && StringUtil.endsWithIgnoreCase(path, ".jar")) {
logger.log(Log.LEVEL_INFO,"extension","deploy jar "+fileName);
ConfigWebAdmin.updateJar(config,zis,fileName,false);
jars.add(fileName);
}
// flds
if(!entry.isDirectory() && startsWith(path,type,"flds") && StringUtil.endsWithIgnoreCase(path, ".fld")) {
logger.log(Log.LEVEL_INFO,"extension","deploy fld "+fileName);
ConfigWebAdmin.updateFLD(config, zis, fileName,false);
flds.add(fileName);
}
// tlds
if(!entry.isDirectory() && startsWith(path,type,"tlds") && StringUtil.endsWithIgnoreCase(path, ".tld")) {
logger.log(Log.LEVEL_INFO,"extension","deploy tld "+fileName);
ConfigWebAdmin.updateTLD(config, zis, fileName,false);
tlds.add(fileName);
}
// context
String relpath;
if(!entry.isDirectory() && startsWith(path,type,"context") && !StringUtil.startsWith(fileName(entry), '.')) {
relpath=path.substring(8);
//log.info("extension","deploy context "+relpath);
logger.log(Log.LEVEL_INFO,"extension","deploy context "+relpath);
ConfigWebAdmin.updateContext(ci, zis, relpath,false);
contexts.add(relpath);
}
// applications
if(!entry.isDirectory() && startsWith(path,type,"applications") && !StringUtil.startsWith(fileName(entry), '.')) {
relpath=path.substring(13);
//log.info("extension","deploy context "+relpath);
logger.log(Log.LEVEL_INFO,"extension","deploy application "+relpath);
ConfigWebAdmin.updateApplication(ci, zis, relpath,false);
applications.add(relpath);
}
zis.closeEntry() ;
}
//installation successfull
ConfigWebAdmin.updateRHExtension(ci,
new RHExtension(id,name,version,
jars.toArray(new String[jars.size()]),
flds.toArray(new String[flds.size()]),
tlds.toArray(new String[tlds.size()]),
contexts.toArray(new String[contexts.size()]),
applications.toArray(new String[applications.size()])));
}
catch(Throwable t){
// installation failed
LogUtil.log(logger, Log.LEVEL_ERROR,"extension",t);
moveToFailedFolder(trgFile);
return;
}
finally {
IOUtil.closeEL(zis);
}
}
private static Manifest toManifest(Config config,InputStream is, Manifest defaultValue) {
try {
String cs = config.getResourceCharset();
String str = IOUtil.toString(is,cs);
if(StringUtil.isEmpty(str,true)) return defaultValue;
str=str.trim()+"\n";
return new Manifest(new ByteArrayInputStream(str.getBytes(cs)));
}
catch (Throwable t) {
return defaultValue;
}
}
private static boolean startsWith(String path,String type, String name) {
return StringUtil.startsWithIgnoreCase(path, name+"/") || StringUtil.startsWithIgnoreCase(path, type+"/"+name+"/");
}
private static String fileName(ZipEntry entry) {
String name = entry.getName();
int index=name.lastIndexOf('/');
if(index==-1) return name;
return name.substring(index+1);
}
private static void moveToFailedFolder(Resource archive) {
Resource dir = archive.getParentResource().getRealResource("failed-to-deploy");
Resource dst = dir.getRealResource(archive.getName());
dir.mkdirs();
try {
if(dst.exists()) dst.remove(true);
ResourceUtil.moveTo(archive, dst,true);
}
catch (Throwable t) {}
// TODO Auto-generated method stub
}
private static String unwrap(String value) {
if(value==null) return "";
String res = unwrap(value,'"');
if(res!=null) return res; // was double quote
return unwrap(value,'\''); // try single quote unwrap, when there is no double quote.
}
private static String unwrap(String value, char del) {
value=value.trim();
if(StringUtil.startsWith(value, del) && StringUtil.endsWith(value, del)) {
return value.substring(1, value.length()-1);
}
return value;
}
}
|
package net.mueller_martin.turirun;
import java.io.IOException;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.math.Vector2;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Listener.ThreadedListener;
import net.mueller_martin.turirun.gameobjects.*;
import net.mueller_martin.turirun.network.TurirunNetwork;
import net.mueller_martin.turirun.network.TurirunNetwork.Register;
import net.mueller_martin.turirun.network.TurirunNetwork.AddCharacter;
import net.mueller_martin.turirun.network.TurirunNetwork.UpdateCharacter;
import net.mueller_martin.turirun.network.TurirunNetwork.MoveCharacter;
import net.mueller_martin.turirun.network.TurirunNetwork.RemoveCharacter;
import net.mueller_martin.turirun.network.TurirunNetwork.HitCharacter;
import net.mueller_martin.turirun.network.TurirunNetwork.DeadCharacter;
import net.mueller_martin.turirun.network.TurirunNetwork.AssignCharacter;
import net.mueller_martin.turirun.utils.CollusionDirections;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Collections.*;
public class WorldController {
public final static String TAG = WorldController.class.getName();
public int mapPixelWidth = 300;
public int mapPixelHeight = 300;
Client client;
public Turirun game;
public ObjectController objs;
public Level level;
public int checkpointCount = 0;
public int checkpointsNeeded = 1;
public CharacterController controller;
public static List<Object> events;
public WorldController(Turirun game) {
this.game = game;
this.objs = new ObjectController();
this.client = new Client();
// Create Character Input Controller
controller = new CharacterController(this.objs, this.client);
// Events
WorldController.events = Collections.synchronizedList(new ArrayList<Object>());
this.init();
}
// Start Game
public void init() {
//map size
level = new Level();
MapProperties prop = level.map.getProperties();
int mapWidth = prop.get("width", Integer.class);
int mapHeight = prop.get("height", Integer.class);
System.out.println("mapWidth: " + mapWidth + ", " + "mapHeight: " + mapHeight);
int tilePixelWidth = prop.get("tilewidth", Integer.class);
int tilePixelHeight = prop.get("tileheight", Integer.class);
System.out.println("tilePixelWidth: " + tilePixelWidth + ", " + "tilePixelHeight: " + tilePixelHeight);
mapPixelWidth = mapWidth * tilePixelWidth;
mapPixelHeight = mapHeight * tilePixelHeight;
System.out.println("mapPixelWidth: " + mapPixelWidth + ", " + "mapPixelHeight: " + mapPixelHeight);
// set bounding boxes for tilemap sprites
// stones
TiledMapTileLayer layer = (TiledMapTileLayer) level.map.getLayers().get("stones");
System.out.println("Layer: " + layer);
for(int x = 0; x < layer.getWidth(); x++)
{
for(int y = 0; y < layer.getHeight(); y++)
{
if(layer.getCell(x, y) != null)
{
// Spawn Walls
WallGameObject wall = new WallGameObject(x * tilePixelWidth + 16, y*tilePixelWidth + 64, 218, 97);
this.objs.addObject(wall);
}
}
}
// bushs
layer = (TiledMapTileLayer) level.map.getLayers().get("bushs");
for(int x = 0; x < layer.getWidth(); x++)
{
for(int y = 0; y < layer.getHeight(); y++)
{
if(layer.getCell(x, y) != null)
{
// Spawn Bush
BushGameObject bush = new BushGameObject(x * tilePixelWidth + 16, y*tilePixelWidth + 64, 218, 110);
this.objs.addObject(bush);
}
}
}
// checkpoints
layer = (TiledMapTileLayer) level.map.getLayers().get("checkpoint");
for(int x = 0; x < layer.getWidth(); x++)
{
for(int y = 0; y < layer.getHeight(); y++)
{
if(layer.getCell(x, y) != null)
{
// Spawn Bush
CheckpointGameObject checkpoint = new CheckpointGameObject(x * tilePixelWidth, y*tilePixelWidth, 168, 119);
this.objs.addObject(checkpoint);
}
}
}
this.client.start();
// For consistency, the classes to be sent over the network are registered by the same method for both the client and server
TurirunNetwork.register(client);
client.addListener(new ThreadedListener(new Listener() {
public void connected(Connection connection) {
}
public void received(Connection connection, Object object) {
WorldController.events.add(object);
}
public void disconnected(Connection connection) {
}
}));
try {
// Block for max. 3000ms // 172.18.12.25
client.connect(3000, this.game.host, this.game.port, TurirunNetwork.udpPort);
// Server communication after connection can go here, or in Listener#connected()
}
catch (IOException e) {
Gdx.app.error("Could not connect to server", e.getMessage());
// Create local player as fallback
TouriCharacterObject playerObj = new TouriCharacterObject(10, 10);
playerObj.setNick(game.nickname);
objs.addObject(playerObj);
controller.setPlayerObj(playerObj);
}
Register register = new Register();
register.nick = this.game.nickname;
register.type = 0;
client.sendTCP(register);
}
public void draw(SpriteBatch batch) {
level.render();
for (GameObject obj: objs.getObjects()) {
obj.draw(batch);
}
}
public void update(float deltaTime) {
// Input Update
controller.update(deltaTime);
// Netzwerk Update
this.updateEvents();
if (controller.character != null) {
// FIXME: last and current postition are always equal
//if (controller.character.currentPosition.x != controller.character.lastPosition.x || controller.character.currentPosition.y != controller.character.lastPosition.y)
{
MoveCharacter move = new MoveCharacter();
move.x = controller.character.currentPosition.x;
move.y = controller.character.currentPosition.y;
client.sendTCP(move);
}
}
Camera cam = CameraHelper.instance.camera;
// The camera dimensions, halved
float cameraHalfWidth = cam.viewportWidth * .5f;
float cameraHalfHeight = cam.viewportHeight * .5f;
if (controller.character != null) {
// Move camera after player as normal
int pos_x = (int)controller.character.currentPosition.x;
if (pos_x % 2 == 0)
pos_x++;
int pos_y = (int)controller.character.currentPosition.y;
if (pos_y % 2 == 0)
pos_y++;
CameraHelper.instance.camera.position.set(pos_x,pos_y,0);
}
float cameraLeft = cam.position.x - cameraHalfWidth;
float cameraRight = cam.position.x + cameraHalfWidth;
float cameraBottom = cam.position.y - cameraHalfHeight;
float cameraTop = cam.position.y + cameraHalfHeight;
// Horizontal axis
if(mapPixelWidth < cam.viewportWidth)
{
cam.position.x = mapPixelWidth / 2;
}
else if(cameraLeft <= 0)
{
cam.position.x = 0 + cameraHalfWidth;
}
else if(cameraRight >= mapPixelWidth)
{
cam.position.x = mapPixelWidth - cameraHalfWidth;
}
// Vertical axis
if(mapPixelHeight < cam.viewportHeight)
{
cam.position.y = mapPixelHeight / 2;
}
else if(cameraBottom <= 0)
{
cam.position.y = 0 + cameraHalfHeight;
}
else if(cameraTop >= mapPixelHeight)
{
cam.position.y = mapPixelHeight - cameraHalfHeight;
}
// update objects
checkpointCount = 0;
for (GameObject obj: objs.getObjects()) {
obj.update(deltaTime);
resetIfOutsideOfMap(obj);
checkCheckpoints(obj);
}
// check for collusion
for (GameObject obj: objs.getObjects()) {
for (GameObject collusionObj: objs.getObjects()) {
if (obj == collusionObj)
continue;
CollusionDirections.CollusionDirectionsTypes col = obj.bounds.intersection(collusionObj.bounds);
if (col != CollusionDirections.CollusionDirectionsTypes.NONE)
{
obj.isCollusion(collusionObj, col);
}
}
}
}
private void resetIfOutsideOfMap(GameObject obj)
{
if (obj.currentPosition.x < 0) {
System.out.println("x: " + obj.currentPosition.x + " " + mapPixelWidth);
obj.currentPosition.x = 1;
}
if (obj.currentPosition.x + obj.size.x > mapPixelWidth) {
System.out.println("x: " + obj.currentPosition.x + " " + mapPixelWidth);
obj.currentPosition.x = mapPixelWidth - obj.size.x + 1;
}
if (obj.currentPosition.y < 0) {
System.out.println("y: " + obj.currentPosition.y + " " + mapPixelHeight);
obj.currentPosition.y = 1;
}
if (obj.currentPosition.y + obj.size.y> mapPixelHeight) {
System.out.println("y: " + obj.currentPosition.y + " " + mapPixelHeight);
obj.currentPosition.y = mapPixelHeight - obj.size.y;
}
}
private void checkCheckpoints(GameObject obj) {
if (obj instanceof CheckpointGameObject && ((CheckpointGameObject) obj).checked) {
checkpointCount++;
if (checkpointCount == checkpointsNeeded) {
// TODO Tourist won!
System.out.println("Tourist won!");
}
}
}
private void updateEvents() {
ArrayList<Object> del = new ArrayList<Object>();
synchronized (WorldController.events) {
for (Object event : WorldController.events) {
// Add Player
if (event instanceof AddCharacter) {
AddCharacter msg = (AddCharacter)event;
CharacterObject newPlayer = new CharacterObject(msg.character.x, msg.character.y);
newPlayer.setNick(msg.character.nick);
objs.addObject(msg.character.id, newPlayer);
del.add(event);
continue;
}
if (event instanceof AssignCharacter) {
AssignCharacter msg = (AssignCharacter)event;
if(msg.type == 1)
{
KannibaleCharacterObject playerObj = new KannibaleCharacterObject(10, 10);
playerObj.setNick(game.nickname);
objs.addObject(playerObj);
controller.setPlayerObj(playerObj);
}
else
{
TouriCharacterObject playerObj = new TouriCharacterObject(10, 10);
playerObj.setNick(game.nickname);
objs.addObject(playerObj);
controller.setPlayerObj(playerObj);
}
del.add(event);
continue;
}
// Update Player
if (event instanceof UpdateCharacter) {
UpdateCharacter msg = (UpdateCharacter)event;
CharacterObject player = (CharacterObject)objs.getObject(msg.id);
if (player != null) {
player.lastPosition = new Vector2(msg.x, msg.y);
player.currentPosition = new Vector2(msg.x, msg.y);
}
del.add(event);
continue;
}
// Remove Player
if (event instanceof RemoveCharacter) {
RemoveCharacter msg = (RemoveCharacter)event;
CharacterObject player = (CharacterObject)objs.getObject(msg.id);
if (player != null) {
objs.removeObject(player);
}
del.add(event);
continue;
}
// HitCharacter
if (event instanceof HitCharacter) {
HitCharacter msg = (HitCharacter)event;
CharacterObject player = (CharacterObject)objs.getObject(msg.id);
if (player != null) {
System.out.println("Player HIT "+msg.id);
}
del.add(event);
continue;
}
// Dead Character
if (event instanceof DeadCharacter) {
DeadCharacter msg = (DeadCharacter)event;
CharacterObject player = (CharacterObject)objs.getObject(msg.id);
if (player != null && !player.isDead) {
player.isDead = true;
System.out.println("Dead "+msg.id);
}
del.add(event);
continue;
}
}
}
for (Object event : del) {
WorldController.events.remove(event);
}
}
}
|
package com.punchline.javalib.entities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Disposable;
import com.punchline.javalib.entities.systems.physical.ParticleSystem;
import com.punchline.javalib.entities.systems.render.DebugRenderSystem;
import com.punchline.javalib.entities.systems.render.RenderSystem;
public abstract class EntityWorld implements Disposable {
private final float TIME_STEP = 1.0f / 60.0f;
private final int VELOCITY_ITERATIONS = 6;
private final int POSITION_ITERATIONS = 2;
/**
* The InputMultiplexer managing this world's game.
*/
protected InputMultiplexer input;
/**
* This world's {@link EntityManager}.
*/
protected EntityManager entities;
/**
* This world's {@link SystemManager}.
*/
protected SystemManager systems;
/**
* Template map.
*/
private Map<String, EntityTemplate> templates;
/**
* Group template map.
*/
private Map<String, EntityGroupTemplate> groupTemplates;
/**
* This world's Box2D {@link com.badlogic.gdx.physics.box2d.World World}
*/
protected World physicsWorld;
/**
* This world's {@link com.badlogic.gdx.graphics.Camera Camera}.
*/
protected Camera camera;
//SYSTEMS
/**
* This world's {@link RenderSystem}.
*/
protected RenderSystem renderSystem;
/**
* This world's {@link DebugRenderSystem}.
*/
protected DebugRenderSystem debugView;
//INIT
/**
* Instantiates the EntityWorld's {@link EntityManager}, {@link SystemManager}, and template map.
* @param input The InputMultiplexer of the game containing this EntityWorld.
* @param camera The camera that will be used for rendering this world.
* @param gravity The gravity vector2.
* @param doSleeping Whether the world allows sleeping.
*/
public EntityWorld(InputMultiplexer input, Camera camera, Vector2 gravity, boolean doSleeping) {
entities = new EntityManager();
systems = new SystemManager(this);
templates = new HashMap<String, EntityTemplate>();
groupTemplates = new HashMap<String, EntityGroupTemplate>();
this.input = input;
this.camera = camera;
positionCamera();
physicsWorld = new World(gravity, doSleeping);
buildSystems();
buildTemplates();
buildEntities();
}
/**
* Adds necessary systems to the world. Called by the constructor.
*/
protected void buildSystems() {
//RENDER
renderSystem = (RenderSystem)systems.addSystem(new RenderSystem(camera));
debugView = (DebugRenderSystem)systems.addSystem(new DebugRenderSystem(input, getPhysicsWorld(), camera, systems));
input.addProcessor(debugView);
//PHYSICAL
systems.addSystem(new ParticleSystem());
}
/**
* Adds necessary templates to the world. Called by the constructor.
*/
protected void buildTemplates() { }
/**
* Adds necessary entities to the world. Called by the constructor.
*/
protected void buildEntities() { }
//FUNCTIONING LOOP
/**
* Disposes of all EntitySystems, and the physics world.
*/
@Override
public void dispose() {
systems.dispose();
physicsWorld.dispose();
}
/**
* Runs all system processing.
*/
public void process() {
systems.process(
entities.getNewEntities(),
entities.getChangedEntities(),
entities.getRemovedEntities(), Gdx.graphics.getDeltaTime());
entities.process();
physicsWorld.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
}
//GETTERS/SETTERS
/**
* @return This world's boundaries.
*/
public abstract Rectangle getBounds();
/**
* @return This world's Box2D {@link com.badlogic.gdx.physics.box2d.World World}
*/
public World getPhysicsWorld() {
return physicsWorld;
}
/**
* @return This world's {@link com.badlogic.gdx.graphics.Camera Camera}.
*/
public Camera getCamera() {
return camera;
}
/**
* Positions the camera.
*/
protected void positionCamera() { }
//ENTITY/TEMPLATE CREATION
/**
* Creates an {@link Entity} using the {@link EntityTemplate} associated with the given tag.
* @param template The tag of the template.
* @param args Arguments for creating the {@link Entity}.
* @return The created entity.
*/
public Entity createEntity(String template, Object... args) {
Entity e = templates.get(template).buildEntity(entities.obtain(), this, args); //Grab an entity from the entity pool and send it
entities.add(e);
return e;
}
/**
* Creates a group of Entities using the {@link EntityGroupTemplate} associated with the given tag.
* @param template The tag of the template to use.
* @param args Arguments for creating the entity group.
* @return The group of entities.
*/
public ArrayList<Entity> createEntityGroup(String template, Object... args) {
ArrayList<Entity> group = groupTemplates.get(template).buildEntities(this, args);
for (Entity e : group) {
entities.add(e); //Add the group to the world.
}
return group;
}
/**
* Adds an EntityTemplate to the template map.
* @param templateKey The template's key.
* @param template The template.
*/
public void addTemplate(String templateKey, EntityTemplate template) {
templates.put(templateKey, template);
}
/**
* Adds an EntityGroupTemplate to the group template map.
* @param templateKey The template's key.
* @param template The template.
*/
public void addGroupTemplate(String templateKey, EntityGroupTemplate template) {
groupTemplates.put(templateKey, template);
}
}
|
package org.joda.time.partial;
import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.DateTimeField;
import org.joda.time.DateTimeZone;
import org.joda.time.ReadableInstant;
/**
* Defines an instant that does not support every datetime field.
* <p>
* A PartialInstant supports a set of fields and cannot be compared to a
* full complete instant. Methods are provided to resolve the partial instant
* into a full instant by 'filling in the gaps'.
*
* @author Stephen Colebourne
*/
public interface PartialInstant {
/**
* Gets an array of the fields that this partial instant supports.
* <p>
* The fields are returned largest to smallest, for example Hour, Minute, Second.
*
* @return the fields supported, largest to smallest
*/
DateTimeField[] getSupportedFields();
/**
* Gets the chronology of the partial which is never null.
* <p>
* The {@link Chronology} is the calculation engine behind the partial and
* provides conversion and validation of the fields in a particular calendar system.
*
* @return the chronology
*/
Chronology getChronology();
int get(DateTimeField field);
/**
* Checks whether the field specified is supported by this partial instant.
*
* @param field the field to check, may be null which returns false
* @return true if the field is supported
*/
boolean isSupported(DateTimeField field);
/**
* Resolves this partial against another complete millisecond instant to
* create a new full instant specifying the time zone to resolve with.
* <p>
* For example, if this partial represents a time, then the result of this method
* will be the datetime from the specified base plus the time from this instant
* set using the time zone specified.
*
* @param baseMillis source of missing fields
* @return the combined instant in milliseconds
*/
long resolve(long baseMillis, DateTimeZone zone);
/**
* Resolves this partial against another complete instant to create a new
* full instant. The combination is performed using the chronology of the
* specified instant.
* <p>
* For example, if this partial represents a time, then the result of this method
* will be the date from the specified base plus the time from this instant.
*
* @param base the instant that provides the missing fields, null means now
* @return the combined datetime
*/
DateTime resolveDateTime(ReadableInstant base);
/**
* Compares this partial with the specified object for equality based
* on the implementation class, supported fields, chronology and values.
* <p>
* Instances of PartialInstant are not generally comparable to one another
* as the comparison is based on the implementation class.
*
* @param object the object to compare to
* @return true if equal
*/
boolean equals(Object object);
/**
* Gets a hash code for the instant that is compatible with the
* equals method.
*
* @return a suitable hash code
*/
int hashCode();
/**
* Get the value as a String in a recognisable ISO8601 format, only
* displaying supported fields.
* <p>
* The string output is in ISO8601 format to enable the String
* constructor to correctly parse it.
*
* @return the value as an ISO8601 string
*/
String toString();
}
|
package com.alexstyl.specialdates.util;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import com.alexstyl.specialdates.R;
import com.alexstyl.specialdates.contact.Contact;
import com.alexstyl.specialdates.date.ContactEvent;
import com.alexstyl.specialdates.date.Date;
import com.alexstyl.specialdates.datedetails.DateDetailsActivity;
import com.alexstyl.specialdates.events.ContactEvents;
import com.alexstyl.specialdates.events.bankholidays.BankHoliday;
import com.alexstyl.specialdates.images.ImageLoader;
import com.alexstyl.specialdates.settings.MainPreferenceActivity;
import com.novoda.notils.logger.simple.Log;
import java.util.List;
public class Notifier {
private static final int NOTIFICATION_ID_DAILY_REMINDER_CONTACTS = 0;
private static final int NOTIFICATION_ID_DAILY_REMINDER_NAMEDAYS = 1;
private static final int NOTIFICATION_ID_DAILY_REMINDER_BANKHOLIDAYS = 2;
private static final String TAG = "Notifier";
private final Context context;
private final Resources resources;
private final ImageLoader imageLoader;
public static Notifier newInstance(Context context) {
Resources resources = context.getResources();
ImageLoader imageLoader = ImageLoader.createSquareThumbnailLoader(resources);
return new Notifier(context, resources, imageLoader);
}
public Notifier(Context context, Resources resources, ImageLoader imageLoader) {
this.resources = resources;
this.imageLoader = imageLoader;
this.context = context.getApplicationContext();
}
/**
* Notifies the user about the special dates contained in the given daycard
*
* @param events The celebration date to display
*/
public void forDailyReminder(ContactEvents events) {
Bitmap largeIcon = null;
Date date = events.getDate();
int contactCount = events.size();
if (shouldDisplayContactImage(contactCount)) {
// Large Icons were introduced in Honeycomb
// and we are only displaying one if it is one contact
int size = resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
Contact displayingContact = events.getContacts().iterator().next();
largeIcon = loadImageAsync(displayingContact, size, size);
if (Utils.hasLollipop() && largeIcon != null) {
// in Lollipop the notifications is the default to use Rounded Images
largeIcon = getCircleBitmap(largeIcon);
}
}
Intent startIntent = DateDetailsActivity.getStartIntentFromExternal(context, date.getDayOfMonth(), date.getMonth(), date.getYear());
PendingIntent intent =
PendingIntent.getActivity(
context, NOTIFICATION_ID_DAILY_REMINDER_CONTACTS,
startIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
String title = NaturalLanguageUtils.joinContacts(context, events.getContacts(), 3);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_contact_event)
.setContentTitle(title)
.setLargeIcon(largeIcon)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setAutoCancel(true)
.setContentIntent(intent)
.setNumber(events.size())
.setColor(context.getResources().getColor(R.color.main_red));
if (events.size() == 1) {
ContactEvent event = events.getEvent(0);
String msg = event.getLabel(resources);
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle().bigText(msg);
bigTextStyle.setBigContentTitle(title);
builder.setContentText(msg);
builder.setStyle(bigTextStyle);
} else if (events.getContacts().size() > 1) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(title);
for (int i = 0; i < events.size(); ++i) {
ContactEvent event = events.getEvent(i);
Contact contact = event.getContact();
String name = contact.getDisplayName().toString();
String lineFormatted = name + "\t\t" + event.getLabel(resources);
Spannable sb = new SpannableString(lineFormatted);
sb.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
inboxStyle.addLine(sb);
}
builder.setStyle(inboxStyle);
builder.setContentText(TextUtils.join(", ", events.getContacts()));
}
if (supportsPublicNotifications()) {
String publicTitle = context.getString(R.string.contact_celebration_count, contactCount);
NotificationCompat.Builder publicNotification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_contact_event)
.setAutoCancel(true)
.setContentIntent(intent)
.setContentTitle(publicTitle)
.setColor(resources.getColor(R.color.main_red));
builder.setPublicVersion(publicNotification.build());
}
for (Contact contact : events.getContacts()) {
Uri uri = contact.getLookupUri();
if (uri != null) {
builder.addPerson(uri.toString());
}
}
String uri = MainPreferenceActivity.getDailyReminderRingtone(context);
builder.setSound(Uri.parse(uri));
if (MainPreferenceActivity.getDailyReminderVibrationSet(context)) {
builder.setDefaults(Notification.DEFAULT_VIBRATE);
}
Notification notification = builder.build();
NotificationManager mngr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mngr.notify(NOTIFICATION_ID_DAILY_REMINDER_CONTACTS, notification);
}
public static Bitmap getCircleBitmap(Bitmap bitmap) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888
);
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private Bitmap loadImageAsync(Contact displayingContact, int width, int height) {
return imageLoader.loadBitmap(displayingContact.getImagePath(), width, height);
}
private boolean supportsPublicNotifications() {
return Utils.hasLollipop();
}
private boolean shouldDisplayContactImage(int contactCount) {
return contactCount == 1;
}
public void forNamedays(List<String> names, Date date) {
if (names == null || names.isEmpty()) {
Log.w(TAG, "Tried to notify for empty name list");
return;
}
PendingIntent intent = PendingIntent.getActivity(
context, NOTIFICATION_ID_DAILY_REMINDER_NAMEDAYS,
DateDetailsActivity.getStartIntentFromExternal(context, date.getDayOfMonth(), date.getMonth(), date.getYear()),
PendingIntent.FLAG_UPDATE_CURRENT
);
String subtitle = NaturalLanguageUtils.join(context, names, 1);
String fullsubtitle = TextUtils.join(", ", names);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_namedays)
.setStyle(new NotificationCompat.BigTextStyle().bigText(fullsubtitle))
.setContentTitle(resources.getQuantityString(R.plurals.todays_nameday, names.size()))
.setContentText(subtitle)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setColor(resources.getColor(R.color.nameday_blue))
.setContentIntent(intent);
if (names.size() > 1) {
mBuilder.setNumber(names.size());
}
NotificationManager mngr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mngr.notify(NOTIFICATION_ID_DAILY_REMINDER_NAMEDAYS, mBuilder.build());
}
public void cancelAllEvents() {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(NOTIFICATION_ID_DAILY_REMINDER_CONTACTS);
manager.cancel(NOTIFICATION_ID_DAILY_REMINDER_NAMEDAYS);
manager.cancel(NOTIFICATION_ID_DAILY_REMINDER_BANKHOLIDAYS);
}
public void forBankholiday(Date date, BankHoliday bankHoliday) {
PendingIntent intent = PendingIntent.getActivity(
context, NOTIFICATION_ID_DAILY_REMINDER_BANKHOLIDAYS,
DateDetailsActivity.getStartIntentFromExternal(context, date.getDayOfMonth(), date.getMonth(), date.getYear()),
PendingIntent.FLAG_UPDATE_CURRENT
);
String subtitle = bankHoliday.getHolidayName();
CharSequence title = context.getString(R.string.dailyreminder_title_bankholiday);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_bankholidays)
.setStyle(new NotificationCompat.BigTextStyle().bigText(subtitle))
.setContentTitle(title)
.setContentText(subtitle)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setColor(resources.getColor(R.color.bankholiday_green))
.setContentIntent(intent);
NotificationManager mngr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mngr.notify(NOTIFICATION_ID_DAILY_REMINDER_BANKHOLIDAYS, builder.build());
}
}
|
package jorgealvarezlab3;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
/**
*
* @author ofici
*/
public class JorgeAlvarezLab3 {
static ArrayList<Carro> Carros = new ArrayList();
static ArrayList<Cliente> Clientes = new ArrayList();
static ArrayList<Empleado> Empleados = new ArrayList();
static ArrayList<Venta> Ventas = new ArrayList();
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String opc;
do {
opc = JOptionPane.showInputDialog(
"Menu Principal\n"
+ "1. Agregar\n"
+ "2. Modificar\n"
+ "3. Eliminar\n"
+ "4. Venta\n"
+ "5. Reporte de ventas\n"
+ "6. Salir");
switch (opc) {
case "1":
menuAgregar();
break;
case "2":
menuModificar();
break;
case "3":
menuEliminar();
break;
case "4":
venta();
break;
case "5":
listar(Ventas);
break;
default:
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
} while (!opc.equals("6"));
}
public static void venta() {
int posEmpleado = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el empleado al que asignarle un cliente\n" + listar(Empleados)));
if (Empleados.get(posEmpleado).getClient() != null) {
Clientes.add(Empleados.get(posEmpleado).getClient());
}
int posCliente = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el cliente que desea asignarle al empleado\n" + listar(Clientes)));
((Empleado) (Empleados.get(posEmpleado))).setClient(Clientes.get(posCliente));
Clientes.remove(posCliente);
int posCarro = Integer.parseInt(JOptionPane.showInputDialog("Ingrese la posición del carro\n" + listar(Carros)));
if (Empleados.get(posEmpleado).getClient().getDinero() >= Carros.get(posCarro).getPrecio()) {
Empleados.get(posEmpleado).getClient().addCarro(Carros.get(posCarro));
Ventas.add(new Venta(Carros.get(posCarro), Empleados.get(posEmpleado), Clientes.get(posCliente), Carros.get(posCarro).getPrecio(), leeFecha()));
} else {
JOptionPane.showMessageDialog(null, "No cuenta con dinero suficiente");
}
}
public static void menuAgregar() {
String opc = JOptionPane.showInputDialog(
"¿Qué desea agregar?\n"
+ "1. Carro\n"
+ "2. Cliente\n"
+ "3. Empleado\n");
switch (opc) {
case "1":
menuAgregarCarro();
break;
case "2":
addmodCliente(-1);
break;
case "3":
addmodEmpleado(-1);
break;
}
}
public static void menuAgregarCarro() {
String opc = JOptionPane.showInputDialog(
"Ingrese el tipo de carro que desea agregar\n"
+ "1. MayBach\n"
+ "2. Morgan Aero 8\n"
+ "3. Fisker Automotive\n"
+ "4. Tramontana\n");
switch (opc) {
case "1":
addmodMayBach(-1);
break;
case "2":
addmodMorganAero8(-1);
break;
case "3":
addmodFiskerAutomotive(-1);
case "4":
addmodTramontana(-1);
default:
JOptionPane.showInputDialog("No es una opción válida");
}
}
public static void menuModificar() {
String opc = JOptionPane.showInputDialog(
"¿Qué desea agregar?\n"
+ "1. Carro\n"
+ "2. Cliente\n"
+ "3. Empleado\n");
switch (opc) {
case "1":
menuModificarCarro();
break;
case "2":
int pos = Integer.parseInt(JOptionPane.showInputDialog(listar(Clientes) + "Ingrese la posicion de lo que desea modificar"));
if (pos >= 0 || pos < Clientes.size()) {
addmodCliente(pos);
} else {
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
break;
case "3":
int pos2 = Integer.parseInt(JOptionPane.showInputDialog(listar(Empleados) + "Ingrese la posicion de lo que desea modificar"));
if (pos2 >= 0 || pos2 < Empleados.size()) {
addmodEmpleado(pos2);
} else {
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
break;
default:
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
}
public static void menuModificarCarro() {
String opc = JOptionPane.showInputDialog(
"Ingrese el tipo de carro que desea agregar\n"
+ "1. MayBach\n"
+ "2. Morgan Aero 8\n"
+ "3. Fisker Automotive\n"
+ "4. Tramontana\n");
switch (opc) {
case "1":
int pos = Integer.parseInt(JOptionPane.showInputDialog(listarMayBach(Carros) + "Ingrese la posicion de lo que desea modificar"));
if (Carros.get(pos) instanceof MayBach && (pos >= 0 || pos < Carros.size())) {
addmodMayBach(pos);
} else {
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
break;
case "2":
int pos2 = Integer.parseInt(JOptionPane.showInputDialog(listarMorganAero8(Carros) + "Ingrese la posicion de lo que desea modificar"));
if (Carros.get(pos2) instanceof MorganAero8 && (pos2 >= 0 || pos2 < Carros.size())) {
addmodMayBach(pos2);
} else {
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
break;
case "3":
int pos3 = Integer.parseInt(JOptionPane.showInputDialog(listarFiskerAutomotive(Carros) + "Ingrese la posicion de lo que desea modificar"));
if (Carros.get(pos3) instanceof FiskerAutomotive && (pos3 >= 0 || pos3 < Carros.size())) {
addmodMayBach(pos3);
} else {
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
case "4":
int pos4 = Integer.parseInt(JOptionPane.showInputDialog(listarTramontana(Carros) + "Ingrese la posicion de lo que desea modificar"));
if (Carros.get(pos4) instanceof Tramontana && (pos4 >= 0 || pos4 < Carros.size())) {
addmodMayBach(pos4);
} else {
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
default:
JOptionPane.showInputDialog("No es una opción válida");
}
}
public static void menuEliminar() {
String opc = JOptionPane.showInputDialog("Ingrese lo que desea eliminar\n"
+ "1. Carro\n"
+ "2. Cliente\n"
+ "3. Carro");
switch (opc) {
case "1":
int pos = Integer.parseInt(JOptionPane.showInputDialog(listar(Carros) + "Ingrese el carro que desea eliminar"));
Carros.remove(pos);
break;
case "2":
int pos2 = Integer.parseInt(JOptionPane.showInputDialog(listar(Empleados) + "Ingrese el empleado que desea eliminar"));
Empleados.remove(pos2);
break;
case "3":
int pos3 = Integer.parseInt(JOptionPane.showInputDialog(listar(Carros) + "Ingrese el carro que desea eliminar"));
Carros.remove(pos3);
break;
default:
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
}
public static void addmodMayBach(int pos) {
String opc = "1";
boolean agregar = false;
if (pos == -1) {
Carros.add(new MayBach());
pos = Carros.size() - 1;
agregar = true;
} else {
opc = JOptionPane.showInputDialog("Ingrese lo que desea modificar\n"
+ "1. Color\n"
+ "2. Fecha\n"
+ "3. Kilometros por galón\n"
+ "4. Marca de llantas\n"
+ "5. No. de serie\n"
+ "6. Polarizado\n"
+ "7. Precio\n"
+ "8. Velocidad máxima\n"
+ "9. Cantidad de llantas de repuesto\n");
}
switch (opc) {
//Clase Carro
case "1":
Carros.get(pos).setColor(leeColor());
if (!agregar) {
break;
}
case "2":
Carros.get(pos).setFechaEnsamblado(leeFecha());
if (!agregar) {
break;
}
case "3":
Carros.get(pos).setKMxGalon(Integer.parseInt(JOptionPane.showInputDialog("Ingrese Kilómetros por galón")));
if (!agregar) {
break;
}
break;
case "4":
Carros.get(pos).setMarcaDeLlantas(JOptionPane.showInputDialog("Ingrese la marca de llantas"));
if (!agregar) {
break;
}
break;
case "5":
Carros.get(pos).setNoSerie(JOptionPane.showInputDialog("Ingrese número de serie"));
if (!agregar) {
break;
}
break;
case "6":
Carros.get(pos).setPolarizado(JOptionPane.showInputDialog("Ingrese si es polarizado o no"));
if (!agregar) {
break;
}
break;
case "7":
Carros.get(pos).setPrecio(Float.parseFloat(JOptionPane.showInputDialog("Ingrese el precio de venta")));
if (!agregar) {
break;
}
break;
case "8":
Carros.get(pos).setVelocidadMax(Float.parseFloat(JOptionPane.showInputDialog("Ingrese Kilómetros por galón")));
if (!agregar) {
break;
}
//Clase Carro
case "9":
((MayBach) (Carros.get(pos))).setLlantasRepuesto(Integer.parseInt(JOptionPane.showInputDialog("Ingrese Kilómetros por galón")));
if (!agregar) {
break;
}
break;
default:
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
}
public static void addmodMorganAero8(int pos) {
String opc = "1";
boolean agregar = false;
if (pos == -1) {
Carros.add(new MayBach());
pos = Carros.size() - 1;
agregar = true;
} else {
opc = JOptionPane.showInputDialog("Ingrese lo que desea modificar\n"
+ "1. Color\n"
+ "2. Fecha\n"
+ "3. Kilometros por galón\n"
+ "4. Marca de llantas\n"
+ "5. No. de serie\n"
+ "6. Polarizado\n"
+ "7. Precio\n"
+ "8. Velocidad máxima\n"
+ "9. Si es convertible\n"
+ "10. Cabina");
}
switch (opc) {
//Clase Carro
case "1":
Carros.get(pos).setColor(leeColor());
if (!agregar) {
break;
}
case "2":
Carros.get(pos).setFechaEnsamblado(leeFecha());
if (!agregar) {
break;
}
case "3":
Carros.get(pos).setKMxGalon(Integer.parseInt(JOptionPane.showInputDialog("Ingrese Kilómetros por galón")));
if (!agregar) {
break;
}
break;
case "4":
Carros.get(pos).setMarcaDeLlantas(JOptionPane.showInputDialog("Ingrese la marca de llantas"));
if (!agregar) {
break;
}
break;
case "5":
Carros.get(pos).setNoSerie(JOptionPane.showInputDialog("Ingrese número de serie"));
if (!agregar) {
break;
}
break;
case "6":
Carros.get(pos).setPolarizado(JOptionPane.showInputDialog("Ingrese si es polarizado o no"));
if (!agregar) {
break;
}
break;
case "7":
Carros.get(pos).setPrecio(Float.parseFloat(JOptionPane.showInputDialog("Ingrese el precio de venta")));
if (!agregar) {
break;
}
break;
case "8":
Carros.get(pos).setVelocidadMax(Float.parseFloat(JOptionPane.showInputDialog("Ingrese Kilómetros por galón")));
if (!agregar) {
break;
}
//Clase Carro
case "9":
((MorganAero8) (Carros.get(pos))).setConvertible(JOptionPane.showInputDialog("Ingrese si es CONVERTIBLE o SENCILLO"));
if (!agregar) {
break;
}
case "10":
((MorganAero8) (Carros.get(pos))).setCabina(JOptionPane.showInputDialog("Ingrese si es cabina UNICA o DOBLE"));
if (!agregar) {
break;
}
break;
default:
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
}
public static void addmodFiskerAutomotive(int pos) {
String opc = "1";
boolean agregar = false;
if (pos == -1) {
Carros.add(new MayBach());
pos = Carros.size() - 1;
agregar = true;
} else {
opc = JOptionPane.showInputDialog("Ingrese lo que desea modificar\n"
+ "1. Color\n"
+ "2. Fecha\n"
+ "3. Kilometros por galón\n"
+ "4. Marca de llantas\n"
+ "5. No. de serie\n"
+ "6. Polarizado\n"
+ "7. Precio\n"
+ "8. Velocidad máxima\n"
+ "9. Si es camioneta o turismo\n"
+ "10. Si es convertible");
}
switch (opc) {
//Clase Carro
case "1":
Carros.get(pos).setColor(leeColor());
if (!agregar) {
break;
}
case "2":
Carros.get(pos).setFechaEnsamblado(leeFecha());
if (!agregar) {
break;
}
case "3":
Carros.get(pos).setKMxGalon(Integer.parseInt(JOptionPane.showInputDialog("Ingrese Kilómetros por galón")));
if (!agregar) {
break;
}
break;
case "4":
Carros.get(pos).setMarcaDeLlantas(JOptionPane.showInputDialog("Ingrese la marca de llantas"));
if (!agregar) {
break;
}
break;
case "5":
Carros.get(pos).setNoSerie(JOptionPane.showInputDialog("Ingrese número de serie"));
if (!agregar) {
break;
}
break;
case "6":
Carros.get(pos).setPolarizado(JOptionPane.showInputDialog("Ingrese si es polarizado o no"));
if (!agregar) {
break;
}
break;
case "7":
Carros.get(pos).setPrecio(Float.parseFloat(JOptionPane.showInputDialog("Ingrese el precio de venta")));
if (!agregar) {
break;
}
break;
case "8":
Carros.get(pos).setVelocidadMax(Float.parseFloat(JOptionPane.showInputDialog("Ingrese Kilómetros por galón")));
if (!agregar) {
break;
}
//Clase Carro
case "9":
((FiskerAutomotive) (Carros.get(pos))).setCamionetaOTurismo(JOptionPane.showInputDialog("Ingrese si es CAMIONETA o TURISMO"));
if (!agregar) {
break;
}
case "10":
((FiskerAutomotive) (Carros.get(pos))).setConvertible(JOptionPane.showInputDialog("Ingrese si es CONVERTIBLE o SENCILLO"));
if (!agregar) {
break;
}
default:
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
}
public static void addmodTramontana(int pos) {
String opc = "1";
boolean agregar = false;
if (pos == -1) {
Carros.add(new MayBach());
pos = Carros.size() - 1;
agregar = true;
} else {
opc = JOptionPane.showInputDialog("Ingrese lo que desea modificar\n"
+ "1. Color\n"
+ "2. Fecha\n"
+ "3. Kilometros por galón\n"
+ "4. Marca de llantas\n"
+ "5. No. de serie\n"
+ "6. Polarizado\n"
+ "7. Precio\n"
+ "8. Velocidad máxima\n"
+ "9. Peso\n"
+ "10. Transmisión\n");
}
switch (opc) {
//Clase Carro
case "1":
Carros.get(pos).setColor(leeColor());
if (!agregar) {
break;
}
case "2":
Carros.get(pos).setFechaEnsamblado(leeFecha());
if (!agregar) {
break;
}
case "3":
Carros.get(pos).setKMxGalon(Integer.parseInt(JOptionPane.showInputDialog("Ingrese Kilómetros por galón")));
if (!agregar) {
break;
}
break;
case "4":
Carros.get(pos).setMarcaDeLlantas(JOptionPane.showInputDialog("Ingrese la marca de llantas"));
if (!agregar) {
break;
}
break;
case "5":
Carros.get(pos).setNoSerie(JOptionPane.showInputDialog("Ingrese número de serie"));
if (!agregar) {
break;
}
break;
case "6":
Carros.get(pos).setPolarizado(JOptionPane.showInputDialog("Ingrese si es polarizado o no"));
if (!agregar) {
break;
}
break;
case "7":
Carros.get(pos).setPrecio(Float.parseFloat(JOptionPane.showInputDialog("Ingrese el precio de venta")));
if (!agregar) {
break;
}
break;
case "8":
Carros.get(pos).setVelocidadMax(Float.parseFloat(JOptionPane.showInputDialog("Ingrese Kilómetros por galón")));
if (!agregar) {
break;
}
//Clase Carro
case "9":
((Tramontana) (Carros.get(pos))).setPeso(Float.parseFloat(JOptionPane.showInputDialog("Ingrese el peso")));
if (!agregar) {
break;
}
case "10":
((Tramontana) (Carros.get(pos))).setTransmision(Integer.parseInt(JOptionPane.showInputDialog("Ingrese los cambios de transmisión")));
if (!agregar) {
break;
}
break;
default:
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
}
public static void addmodEmpleado(int pos) {
String opc = "1";
boolean agregar = false;
if (pos == -1) {
Empleados.add(new Empleado());
pos = Empleados.size() - 1;
agregar = true;
} else {
opc = JOptionPane.showInputDialog("Ingrese lo que desea modificar\n"
+ "1. Altura\n"
+ "2. Edad\n"
+ "3. Ingrese ID\n"
+ "4. Ingrese el peso\n"
+ "5. Peso\n"
+ "6. Ingrese la cantidad de horas laborales\n");
}
switch (opc) {
//Clase Persona
case "1":
Empleados.get(pos).setAltura(Float.parseFloat(JOptionPane.showInputDialog("Ingrese la altura")));
if (!agregar) {
break;
}
case "2":
Empleados.get(pos).setEdad(Integer.parseInt(JOptionPane.showInputDialog("Ingrese la edad")));
if (!agregar) {
break;
}
case "3":
Empleados.get(pos).setID(JOptionPane.showInputDialog("Ingrese el ID"));
if (!agregar) {
break;
}
case "4":
Empleados.get(pos).setNombre(JOptionPane.showInputDialog("Ingrese el nombre"));
if (!agregar) {
break;
}
case "5":
Empleados.get(pos).setPeso(Float.parseFloat(JOptionPane.showInputDialog("Ingrese el peso")));
if (!agregar) {
break;
}
//Clase Persona
case "9":
((Empleado) (Empleados.get(pos))).setHorasLaborales(Float.parseFloat(JOptionPane.showInputDialog("Ingrese la cantidad de horas laborales")));
if (!agregar) {
break;
}
break;
default:
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
}
public static void addmodCliente(int pos) {
String opc = "1";
boolean agregar = false;
if (pos == -1) {
Clientes.add(new Cliente());
pos = Clientes.size() - 1;
agregar = true;
} else {
opc = JOptionPane.showInputDialog("Ingrese lo que desea modificar\n"
+ "1. Altura\n"
+ "2. Edad\n"
+ "3. Ingrese ID\n"
+ "4. Ingrese el peso\n"
+ "5. Peso\n");
}
switch (opc) {
//Clase Persona
case "1":
Clientes.get(pos).setAltura(Float.parseFloat(JOptionPane.showInputDialog("Ingrese la altura")));
if (!agregar) {
break;
}
case "2":
Clientes.get(pos).setEdad(Integer.parseInt(JOptionPane.showInputDialog("Ingrese la edad")));
if (!agregar) {
break;
}
case "3":
Clientes.get(pos).setID(JOptionPane.showInputDialog("Ingrese el ID"));
if (!agregar) {
break;
}
case "4":
Clientes.get(pos).setNombre(JOptionPane.showInputDialog("Ingrese el nombre"));
if (!agregar) {
break;
}
case "5":
Clientes.get(pos).setPeso(Float.parseFloat(JOptionPane.showInputDialog("Ingrese el peso")));
if (!agregar) {
break;
}
//Clase Persona
case "9":
((Cliente) (Clientes.get(pos))).setDinero(Float.parseFloat(JOptionPane.showInputDialog("Ingrese la cantidad de dinero")));
if (!agregar) {
break;
}
break;
default:
JOptionPane.showMessageDialog(null, "No es una opción válida");
}
}
public static Cliente escogerCliente() {
int pos = Integer.parseInt(JOptionPane.showInputDialog(listar(Clientes) + "\n Ingrese el cliente que desea agregar."));
return Clientes.get(pos);
}
public static Date leeFecha() {
Date fecha = new Date();
return fecha;
}
public static Color leeColor() {
Color color = null;
color = color.yellow;
return color;
}
public static String listar(ArrayList Array) {
String lista = "";
for (int i = 0; i < Array.size(); i++) {
lista += i + ". " + Array.get(i).toString() + "\n";
}
return lista;
}
public static String listarMayBach(ArrayList Array) {
String lista = "";
for (int i = 0; i < Array.size(); i++) {
if (Array.get(i) instanceof MayBach) {
lista += i + ". " + Array.get(i).toString() + "\n";
}
}
return lista;
}
public static String listarMorganAero8(ArrayList Array) {
String lista = "";
for (int i = 0; i < Array.size(); i++) {
if (Array.get(i) instanceof MorganAero8) {
lista += i + ". " + Array.get(i).toString() + "\n";
}
}
return lista;
}
public static String listarFiskerAutomotive(ArrayList Array) {
String lista = "";
for (int i = 0; i < Array.size(); i++) {
if (Array.get(i) instanceof FiskerAutomotive) {
lista += i + ". " + Array.get(i).toString() + "\n";
}
}
return lista;
}
public static String listarTramontana(ArrayList Array) {
String lista = "";
for (int i = 0; i < Array.size(); i++) {
if (Array.get(i) instanceof Tramontana) {
lista += i + ". " + Array.get(i).toString() + "\n";
}
}
return lista;
}
}
|
package com.alexstyl.specialdates.util;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import com.alexstyl.specialdates.R;
import com.alexstyl.specialdates.contact.Birthday;
import com.alexstyl.specialdates.contact.Contact;
import com.alexstyl.specialdates.date.ContactEvent;
import com.alexstyl.specialdates.date.Date;
import com.alexstyl.specialdates.datedetails.DateDetailsActivity;
import com.alexstyl.specialdates.events.ContactEvents;
import com.alexstyl.specialdates.events.EventType;
import com.alexstyl.specialdates.events.bankholidays.BankHoliday;
import com.alexstyl.specialdates.events.namedays.NamedayPreferences;
import com.alexstyl.specialdates.images.ImageLoader;
import com.alexstyl.specialdates.settings.MainPreferenceActivity;
import com.novoda.notils.logger.simple.Log;
import java.util.List;
public class Notifier {
private static final int NOTIFICATION_ID_DAILY_REMINDER_CONTACTS = 0;
private static final int NOTIFICATION_ID_DAILY_REMINDER_NAMEDAYS = 1;
private static final int NOTIFICATION_ID_DAILY_REMINDER_BANKHOLIDAYS = 2;
private static final String TAG = "Notifier";
private final Context context;
private final ImageLoader imageLoader;
private final NamedayPreferences namedayPreferences;
public static Notifier newInstance(Context context) {
Resources resources = context.getResources();
ImageLoader imageLoader = ImageLoader.createSquareThumbnailLoader(resources);
NamedayPreferences namedayPreferences = NamedayPreferences.newInstance(context);
return new Notifier(context, imageLoader, namedayPreferences);
}
public Notifier(Context context, ImageLoader imageLoader, NamedayPreferences namedayPreferences) {
this.imageLoader = imageLoader;
this.namedayPreferences = namedayPreferences;
this.context = context.getApplicationContext();
}
/**
* Notifies the user about the special dates contained in the given daycard
*
* @param events The celebration date to display
*/
public void forDailyReminder(ContactEvents events) {
Bitmap largeIcon = null;
Resources res = context.getResources();
Date date = events.getDate();
int contactCount = events.size();
if (shouldDisplayContactImage(contactCount)) {
// Large Icons were introduced in Honeycomb
// and we are only displaying one if it is one contact
int size = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
Contact displayingContact = events.getContacts().iterator().next();
largeIcon = loadImageAsync(displayingContact, size, size);
if (Utils.hasLollipop() && largeIcon != null) {
// in Lollipop the notifications is the default to use Rounded Images
largeIcon = getCircleBitmap(largeIcon);
}
}
Intent startIntent = DateDetailsActivity.getStartIntentFromExternal(context, date.getDayOfMonth(), date.getMonth(), date.getYear());
PendingIntent intent =
PendingIntent.getActivity(
context, NOTIFICATION_ID_DAILY_REMINDER_CONTACTS,
startIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
String title = NaturalLanguageUtils.joinContacts(context, events.getContacts(), 3);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_contact_event)
.setContentTitle(title)
.setLargeIcon(largeIcon)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setAutoCancel(true)
.setContentIntent(intent)
.setNumber(events.size())
.setColor(context.getResources().getColor(R.color.main_red));
if (events.size() == 1) {
ContactEvent event = events.getEvent(0);
String msg = "";
if (EventType.BIRTHDAY.equals(event.getType())) {
int age = event.getContact().getBirthday().getAgeOnYear(event.getYear());
msg = context.getString(R.string.turns_age, age);
} else if (EventType.NAMEDAY.equals(event.getType())) {
msg = context.getString(R.string.nameday);
}
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle().bigText(msg);
bigTextStyle.setBigContentTitle(title);
builder.setContentText(msg);
builder.setStyle(bigTextStyle);
} else if (events.getContacts().size() > 1) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(title);
for (int i = 0; i < events.size(); ++i) {
ContactEvent event = events.getEvent(i);
Contact contact = event.getContact();
String name = contact.getDisplayName().toString();
String lineFormatted = name + " " + getLabelFor(event);
Spannable sb = new SpannableString(lineFormatted);
sb.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
inboxStyle.addLine(sb);
}
builder.setStyle(inboxStyle);
builder.setContentText(TextUtils.join(", ", events.getContacts()));
}
if (supportsPublicNotifications()) {
String publicTitle = context.getString(R.string.contact_celebration_count, contactCount);
NotificationCompat.Builder publicNotification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_contact_event)
.setAutoCancel(true)
.setContentIntent(intent)
.setContentTitle(publicTitle)
.setColor(context.getResources().getColor(R.color.main_red));
builder.setPublicVersion(publicNotification.build());
}
for (Contact contact : events.getContacts()) {
Uri uri = contact.getLookupUri();
if (uri != null) {
builder.addPerson(uri.toString());
}
}
String uri = MainPreferenceActivity.getDailyReminderRingtone(context);
builder.setSound(Uri.parse(uri));
if (MainPreferenceActivity.getDailyReminderVibrationSet(context)) {
builder.setDefaults(Notification.DEFAULT_VIBRATE);
}
Notification notification = builder.build();
NotificationManager mngr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mngr.notify(NOTIFICATION_ID_DAILY_REMINDER_CONTACTS, notification);
}
/**
* TODO duplicated from {@link com.alexstyl.specialdates.upcoming.ui.ContactEventView#getLabelFor(ContactEvent)}
*
* @deprecated
*/
private String getLabelFor(ContactEvent event) {
Resources resources = context.getResources();
EventType eventType = event.getType();
if (eventType == EventType.BIRTHDAY) {
Birthday birthday = event.getContact().getBirthday();
if (birthday.includesYear()) {
int age = birthday.getAgeOnYear(event.getYear());
if (age > 0) {
return resources.getString(R.string.turns_age, age);
}
}
}
return resources.getString(eventType.nameRes());
}
public static Bitmap getCircleBitmap(Bitmap bitmap) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888
);
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private Bitmap loadImageAsync(Contact displayingContact, int width, int height) {
return imageLoader.loadBitmap(displayingContact.getImagePath(), width, height);
}
private boolean supportsPublicNotifications() {
return Utils.hasLollipop();
}
private boolean shouldDisplayContactImage(int contactCount) {
return Utils.hasHoneycomb() && contactCount == 1;
}
public void forNamedays(List<String> names, Date date) {
if (names == null || names.isEmpty()) {
Log.w(TAG, "Tried to notify for empty name list");
return;
}
PendingIntent intent = PendingIntent.getActivity(
context, NOTIFICATION_ID_DAILY_REMINDER_NAMEDAYS,
DateDetailsActivity.getStartIntentFromExternal(context, date.getDayOfMonth(), date.getMonth(), date.getYear()),
PendingIntent.FLAG_UPDATE_CURRENT
);
String subtitle = NaturalLanguageUtils.join(context, names, 1);
String fullsubtitle = TextUtils.join(", ", names);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_namedays)
.setStyle(new NotificationCompat.BigTextStyle().bigText(fullsubtitle))
.setContentTitle(context.getResources().getQuantityString(R.plurals.todays_nameday, names.size()))
.setContentText(subtitle)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setColor(context.getResources().getColor(R.color.nameday_blue))
.setContentIntent(intent);
if (names.size() > 1) {
mBuilder.setNumber(names.size());
}
NotificationManager mngr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mngr.notify(NOTIFICATION_ID_DAILY_REMINDER_NAMEDAYS, mBuilder.build());
}
public void cancelAllEvents() {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(NOTIFICATION_ID_DAILY_REMINDER_CONTACTS);
manager.cancel(NOTIFICATION_ID_DAILY_REMINDER_NAMEDAYS);
manager.cancel(NOTIFICATION_ID_DAILY_REMINDER_BANKHOLIDAYS);
}
public void forBankholiday(Date date, BankHoliday bankHoliday) {
PendingIntent intent = PendingIntent.getActivity(
context, NOTIFICATION_ID_DAILY_REMINDER_BANKHOLIDAYS,
DateDetailsActivity.getStartIntentFromExternal(context, date.getDayOfMonth(), date.getMonth(), date.getYear()),
PendingIntent.FLAG_UPDATE_CURRENT
);
String subtitle = bankHoliday.getHolidayName();
CharSequence title = context.getString(R.string.dailyreminder_title_bankholiday);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_bankholidays)
.setStyle(new NotificationCompat.BigTextStyle().bigText(subtitle))
.setContentTitle(title)
.setContentText(subtitle)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setColor(context.getResources().getColor(R.color.bankholiday_green))
.setContentIntent(intent);
NotificationManager mngr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mngr.notify(NOTIFICATION_ID_DAILY_REMINDER_BANKHOLIDAYS, builder.build());
}
}
|
package org.croudtrip.api.trips;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* A pending / accepting request from a passenger to join a trip.
*/
@Entity(name = JoinTripRequest.ENTITY_NAME)
@Table(name = "join_trip_requests")
@NamedQueries({
@NamedQuery(
name = JoinTripRequest.QUERY_NAME_FIND_ALL,
query = "SELECT r FROM " + JoinTripRequest.ENTITY_NAME + " r"
),
@NamedQuery(
name = JoinTripRequest.QUERY_FIND_BY_PASSENGER_OR_DRIVER_ID,
query = "SELECT r FROM " + JoinTripRequest.ENTITY_NAME + " r WHERE " +
"r.offer.driver.id = :" + JoinTripRequest.QUERY_PARAM_USER_ID + " OR " +
"r.query.passenger.id = :" + JoinTripRequest.QUERY_PARAM_USER_ID
),
@NamedQuery(
name = JoinTripRequest.QUERY_FIND_BY_PASSENGER_OR_DRIVER_ID_AND_PASSENGER_ACCEPTED_STATUS,
query = "SELECT r FROM " + JoinTripRequest.ENTITY_NAME + " r WHERE (" +
"r.offer.driver.id = :" + JoinTripRequest.QUERY_PARAM_USER_ID + " OR " +
"r.query.passenger.id = :" + JoinTripRequest.QUERY_PARAM_USER_ID + " ) AND " +
"r.status = 'PASSENGER_ACCEPTED'"
),
@NamedQuery(
name = JoinTripRequest.QUERY_FIND_BY_PASSENGER_OR_DRIVER_ID_AND_DRIVER_ACCEPTED_STATUS,
query = "SELECT r FROM " + JoinTripRequest.ENTITY_NAME + " r WHERE (" +
"r.offer.driver.id = :" + JoinTripRequest.QUERY_PARAM_USER_ID + " OR " +
"r.query.passenger.id = :" + JoinTripRequest.QUERY_PARAM_USER_ID + " ) AND " +
"r.status = 'DRIVER_ACCEPTED'"
),
@NamedQuery(
name = JoinTripRequest.QUERY_FIND_BY_PASSENGER_ID_AND_DECLINED_STATUS,
query = "SELECT r FROM " + JoinTripRequest.ENTITY_NAME + " r WHERE r.status = 'DRIVER_DECLINED' AND r.query.passenger.id = :" + JoinTripRequest.QUERY_PARAM_USER_ID
),
@NamedQuery(
name = JoinTripRequest.QUERY_FIND_BY_OFFER_ID,
query = "SELECT r FROM " + JoinTripRequest.ENTITY_NAME + " r WHERE r.offer.id = :" + JoinTripRequest.QUERY_PARAM_OFFER_ID
)
})
public class JoinTripRequest {
public static final String
ENTITY_NAME = "JoinTripRequest",
COLUMN_ID = "join_trip_request_id",
QUERY_NAME_FIND_ALL = "org.croudtrip.api.trips.JoinTripRequest.findAll",
QUERY_FIND_BY_PASSENGER_OR_DRIVER_ID = "org.croudtrip.api.trips.JoinTripRequest.findByPassengerOrDriverId",
QUERY_FIND_BY_PASSENGER_OR_DRIVER_ID_AND_PASSENGER_ACCEPTED_STATUS = "org.croudtrip.api.trips.JoinTripRequest.findByPassengerOrDriverIdAndPassengerAcceptStatus",
QUERY_FIND_BY_PASSENGER_ID_AND_DECLINED_STATUS = "org.croudtrip.api.trips.JoinTripRequest.findDeclinedRequests",
QUERY_FIND_BY_PASSENGER_OR_DRIVER_ID_AND_DRIVER_ACCEPTED_STATUS = "org.croudtrip.api.trips.JoinTripRequest.findAcceptedRequests",
QUERY_FIND_BY_OFFER_ID = "org.croudtrip.api.trips.JoinTripRequest.findByOfferId",
QUERY_PARAM_USER_ID = "user_id",
QUERY_PARAM_OFFER_ID = "offer_id";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = COLUMN_ID)
private long id;
@Embedded
private TripQuery query;
@Column(name = "priceInCents", nullable = false)
private int totalPriceInCents;
@Column(name = "pricePerKmInCents", nullable = false)
private int pricePerKmInCents;
@ManyToOne
@JoinColumn(name = TripOffer.COLUMN_ID, nullable = false)
private TripOffer offer;
@Column(name = "status", nullable = false)
@Enumerated(EnumType.STRING)
private JoinTripStatus status;
public JoinTripRequest() { }
@JsonCreator
public JoinTripRequest(
@JsonProperty("id") long id,
@JsonProperty("query") TripQuery query,
@JsonProperty("totalPriceInCents") int totalPriceInCents,
@JsonProperty("pricePerKmInCents") int pricePerKmInCents,
@JsonProperty("offer") TripOffer offer,
@JsonProperty("status") JoinTripStatus status) {
this.id = id;
this.query = query;
this.totalPriceInCents = totalPriceInCents;
this.pricePerKmInCents = pricePerKmInCents;
this.offer = offer;
this.status = status;
}
public JoinTripRequest(
JoinTripRequest oldRequest,
JoinTripStatus newStatus) {
this(
oldRequest.getId(),
oldRequest.getQuery(),
oldRequest.getTotalPriceInCents(),
oldRequest.getPricePerKmInCents(),
oldRequest.getOffer(),
newStatus);
}
public long getId() {
return id;
}
public TripQuery getQuery() {
return query;
}
public int getTotalPriceInCents() {
return totalPriceInCents;
}
public int getPricePerKmInCents() {
return pricePerKmInCents;
}
public TripOffer getOffer() {
return offer;
}
public JoinTripStatus getStatus() {
return status;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JoinTripRequest that = (JoinTripRequest) o;
return Objects.equal(id, that.id) &&
Objects.equal(totalPriceInCents, that.totalPriceInCents) &&
Objects.equal(pricePerKmInCents, that.pricePerKmInCents) &&
Objects.equal(query, that.query) &&
Objects.equal(offer, that.offer) &&
Objects.equal(status, that.status);
}
@Override
public int hashCode() {
return Objects.hashCode(id, query, totalPriceInCents, pricePerKmInCents, offer, status);
}
public static class Builder {
private long id;
private TripQuery query;
private int totalPriceInCents;
private int pricePerKmInCents;
private TripOffer offer;
private JoinTripStatus status;
public Builder setId(long id) {
this.id = id;
return this;
}
public Builder setQuery(TripQuery query) {
this.query = query;
return this;
}
public Builder setTotalPriceInCents(int totalPriceInCents) {
this.totalPriceInCents = totalPriceInCents;
return this;
}
public Builder setPricePerKmInCents(int pricePerKmInCents) {
this.pricePerKmInCents = pricePerKmInCents;
return this;
}
public Builder setOffer(TripOffer offer) {
this.offer = offer;
return this;
}
public Builder setStatus(JoinTripStatus status) {
this.status = status;
return this;
}
public JoinTripRequest build() {
return new JoinTripRequest(id, query, totalPriceInCents, pricePerKmInCents, offer, status);
}
}
}
|
package ch.openech.mj.db;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.joda.time.LocalDate;
import ch.openech.mj.model.Keys;
import ch.openech.mj.model.PropertyInterface;
import ch.openech.mj.util.DateUtils;
import ch.openech.mj.util.StringUtils;
public class FulltextIndex<T> implements Index<T> {
private static final Logger logger = Logger.getLogger(FulltextIndex.class.getName());
private static final Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_34);
private RAMDirectory directory;
private IndexWriter iwriter;
private final Table<T> table;
private final Object[] keys;
private final PropertyInterface[] properties;
public FulltextIndex(Table<T> table, Object[] keys) {
this.table = table;
this.keys = keys;
this.properties = Keys.getProperties(keys);
}
private static String[] getPropertyPaths(PropertyInterface[] properties) {
String[] paths = new String[properties.length];
for (int i = 0; i<properties.length; i++) {
paths[i] = properties[i].getFieldPath();
}
return paths;
}
@SuppressWarnings("deprecation")
private void initializeIndex() {
if (directory == null) {
directory = new RAMDirectory();
try {
iwriter = new IndexWriter(directory, analyzer, true, new IndexWriter.MaxFieldLength(25000));
} catch (IOException e) {
logger.log(Level.SEVERE, "Initialize index failed", e);
throw new RuntimeException("Initialize index failed");
}
}
}
public void insert(int id, T object) {
initializeIndex();
writeInIndex(id, object);
Query query = queryById(id);
try (IndexSearcher isearcher = new IndexSearcher(directory, true)) {
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
if (hits.length > 1) throw new IllegalStateException("Twice in index : " + id);
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't search after insert");
throw new RuntimeException("Couldn't search after insert");
}
}
public void update(int id, T object) {
Query query = queryById(id);
try (IndexSearcher isearcher = new IndexSearcher(directory, true)) {
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
if (hits.length != 1) throw new IllegalStateException("Id : " + id);
iwriter.deleteDocuments(query);
writeInIndex(id, object);
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't search after update");
throw new RuntimeException("Couldn't search after update");
}
}
private Query queryById(Integer id) {
QueryParser parser = new QueryParser(Version.LUCENE_34, "id", analyzer);
Query query;
try {
query = parser.parse(Integer.toString(id));
} catch (ParseException e) {
logger.log(Level.SEVERE, "Couldn't parse id " + id, e);
throw new RuntimeException("Couldn't parse id " + id);
}
return query;
}
public void clear() {
try {
if (iwriter != null) {
iwriter.deleteAll();
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Couldn't clear index of table " + table.getTableName(), e);
throw new RuntimeException("Couldn't clear index of table " + table.getTableName());
}
}
protected Field getField(PropertyInterface property, T object) {
String fieldName = property.getFieldPath();
if (property.getFieldClazz() == String.class) {
String string = (String) property.getValue(object);
if (string != null) {
Field.Index index = Field.Index.ANALYZED;
return new Field(fieldName, string, Field.Store.YES, index);
}
} else if (property.getFieldClazz() == LocalDate.class) {
LocalDate date = (LocalDate) property.getValue(object);
if (date != null) {
Field.Index index = Field.Index.NOT_ANALYZED;
String string = DateUtils.formatCH(date);
return new Field(fieldName, string, Field.Store.YES, index);
}
}
return null;
}
protected Field createIdField(int id) {
Field.Index index = Field.Index.NOT_ANALYZED;
return new Field("id", Integer.toString(id), Field.Store.YES, index);
}
private void writeInIndex(int id, T object) {
try {
Document doc = new Document();
doc.add(createIdField(id));
for (PropertyInterface property : properties) {
Field field = getField(property, object);
if (field != null) {
doc.add(field);
}
}
iwriter.addDocument(doc);
iwriter.commit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public List<T> find(String text) {
PropertyInterface[] searchProperties = Keys.getProperties(keys);
String[] searchPaths = getPropertyPaths(searchProperties);
List<T> result = new ArrayList<>();
initializeIndex();
if (directory.listAll().length == 0 || StringUtils.isBlank(text)) return Collections.emptyList();
try (IndexSearcher isearcher = new IndexSearcher(directory, true)) {
QueryParser parser;
if (searchPaths.length > 1) {
parser = new MultiFieldQueryParser(Version.LUCENE_34, searchPaths, analyzer);
} else {
parser = new QueryParser(Version.LUCENE_34, searchPaths[0], analyzer);
}
Query query = parser.parse(text);
ScoreDoc[] hits = isearcher.search(query, null, 50).scoreDocs;
for (ScoreDoc hit : hits) {
Document hitDoc = isearcher.doc(hit.doc);
Integer id = Integer.parseInt(hitDoc.get("id"));
T object = table.read(id);
result.add(object);
}
} catch (ParseException x) {
// user entered something like "*" which is not allowed
logger.info(x.getLocalizedMessage());
} catch (Exception x) {
logger.log(Level.SEVERE, x.getLocalizedMessage(), x);
x.printStackTrace();
}
return result;
}
}
|
package oasis.model.directory;
import javax.annotation.Nonnull;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.wordnik.swagger.annotations.ApiModelProperty;
import oasis.model.annotations.Id;
@JsonRootName("organization")
public class Organization {
@Id
@ApiModelProperty(required = true)
private String id;
@JsonProperty
@ApiModelProperty(required = true)
private String name;
@JsonProperty
@ApiModelProperty(required = true)
private Type type;
public Organization() {
}
/**
* Copy constructor.
* <p>
* Does not copy {@link #id} field.
*/
public Organization(@Nonnull Organization other) {
this.name = other.getName();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public enum Type {
PUBLIC_BODY,
COMPANY
}
}
|
package org.eclipse.egit.core;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.PlatformObject;
import org.eclipse.egit.core.internal.Utils;
import org.eclipse.jgit.annotations.Nullable;
/**
* Utilities for working with objects that implement {@link IAdaptable}
*/
public class AdapterUtils {
private AdapterUtils() {
// Cannot be instantiated
}
/**
* Adapt object to given target class type
*
* @param object
* @param target
* @param <V> type of target
* @return adapted
*/
@Nullable
public static <V> V adapt(Object object, Class<V> target) {
if (object == null) {
return null;
}
if (target.isInstance(object)) {
return target.cast(object);
}
if (object instanceof IAdaptable) {
V adapter = Utils.getAdapter(((IAdaptable) object), target);
if (adapter != null || object instanceof PlatformObject) {
return adapter;
}
}
Object adapted = Platform.getAdapterManager().getAdapter(object, target);
return target.cast(adapted);
}
}
|
package org.mwc.cmap.core.wizards;
import java.text.ParseException;
import java.util.Date;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Text;
import org.mwc.cmap.core.CorePlugin;
import org.osgi.service.prefs.Preferences;
import MWC.GenericData.HiResDate;
import MWC.Utilities.TextFormatting.FullFormatDateTime;
public class EnterDTGPage extends EnterStringPage implements ModifyListener
{
private static final String DATE = "DATE";
public EnterDTGPage(final ISelection selection, final HiResDate startDate,
final String pageTitle, final String pageExplanation, final String fieldExplanation, final String imagePath, final String helpContext)
{
super(selection,
FullFormatDateTime.toString(new Date().getTime()), pageTitle,
pageExplanation, fieldExplanation, imagePath, helpContext, true, null);
// tell the editor we're listening for modifications
super.addModifiedListener(this);
// if we have a date, overwrite today's date
if(startDate != null)
{
_startName = FullFormatDateTime.toString(startDate.getDate().getTime());
}
}
/**
* sort out our answer
*
* @return
*/
public HiResDate getDate()
{
HiResDate res = null;
try
{
final long time = FullFormatDateTime.fromString(super.getString());
res = new HiResDate(time);
}
catch (final ParseException e)
{
CorePlugin.logError(Status.ERROR, "Parsing this text:"
+ super.getString(), e);
}
return res;
}
@Override
public void dispose()
{
// try to store some defaults
final Preferences prefs = getPrefs();
prefs.put(DATE, _myWrapper.getName());
super.dispose();
}
public void modifyText(final ModifyEvent e)
{
// ok, check we can parse it
final Text text = (Text) e.widget;
final String val = text.getText();
try
{
// do a trial conversion, just to check it's valid
FullFormatDateTime.fromString(val);
}
catch (final ParseException e1)
{
// invalid - try to stop it!!!
super.setErrorMessage("Date not formatted correctly");
}
}
}
|
package org.microbule.osgi;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.microbule.api.JaxrsServer;
import org.microbule.api.JaxrsServerFactory;
import org.microbule.test.MockObjectTestCase;
import org.microbule.test.hello.HelloService;
import org.microbule.test.hello.HelloServiceImpl;
import org.microbule.test.osgi.OsgiRule;
import org.microbule.test.osgi.ServicePropsBuilder;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.osgi.framework.ServiceRegistration;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class JaxrsServerManagerTest extends MockObjectTestCase {
// Fields
public static final String BASE_ADDRESS = "http://localhost:8383/test";
@Rule
public final OsgiRule osgiRule = new OsgiRule();
@Mock
private JaxrsServerFactory factory;
@Mock
private JaxrsServer jaxrsServer;
@Captor
private ArgumentCaptor<Map<String, Object>> propertiesCaptor;
// Other Methods
@Test
public void testDestroyServersUponShutdown() {
final HelloServiceImpl impl = new HelloServiceImpl();
registerServer(impl);
final JaxrsServerManager manager = createManager();
manager.destroy();
verify(jaxrsServer).shutdown();
}
@Test
public void testServiceDiscovery() {
JaxrsServerManager manager = createManager();
final HelloServiceImpl impl = new HelloServiceImpl();
final ServiceRegistration<HelloServiceImpl> registration = registerServer(impl);
verify(factory).createJaxrsServer(eq(HelloService.class), same(impl), eq(BASE_ADDRESS), propertiesCaptor.capture());
Map<String, Object> properties = propertiesCaptor.getValue();
assertEquals("bar", properties.get("foo"));
assertEquals(BASE_ADDRESS, properties.get(JaxrsServerManager.ADDRESS_PROP));
registration.unregister();
verify(jaxrsServer).shutdown();
}
private JaxrsServerManager createManager() {
try {
JaxrsServerManager manager = new JaxrsServerManager(osgiRule.getBundleContext(), factory, 25);
Thread.sleep(100);
return manager;
} catch (InterruptedException e) {
throw new IllegalStateException("Unable to start server manager.");
}
}
private ServiceRegistration<HelloServiceImpl> registerServer(HelloServiceImpl impl) {
when(factory.createJaxrsServer(eq(HelloService.class), same(impl), eq(BASE_ADDRESS), anyMap())).thenReturn(jaxrsServer);
return osgiRule.registerService(HelloService.class, impl, ServicePropsBuilder.props().with(JaxrsServerManager.ADDRESS_PROP, BASE_ADDRESS).with("foo", "bar"));
}
@Test
public void testServiceDiscoveryWithExistingService() {
final HelloServiceImpl impl = new HelloServiceImpl();
final ServiceRegistration<HelloServiceImpl> registration = registerServer(impl);
JaxrsServerManager manager = createManager();
verify(factory).createJaxrsServer(eq(HelloService.class), same(impl), eq(BASE_ADDRESS), propertiesCaptor.capture());
Map<String, Object> properties = propertiesCaptor.getValue();
assertEquals("bar", properties.get("foo"));
assertEquals(BASE_ADDRESS, properties.get(JaxrsServerManager.ADDRESS_PROP));
registration.unregister();
verify(jaxrsServer).shutdown();
}
}
|
package me.shortify.sparkserver.exception;
import org.json.JSONObject;
public class Error {
public static final String URL_EXISTS = "The custom text specified already exists in the database. Try with another one.";
public static final String BAD_URL = "The URL specified refers to a not safe website. Try with another URL.";
public static final String BAD_CUSTOM_URL = "The custom text specified is not accepted.";
public static final String SHORT_URL_NOT_EXISTS = "The short URL specified does not exist.";
public static final String URL_NOT_SPECIFIED = "You need to insert a short URL.";
private final String ERROR = "error";
private String error;
public Error(String error) {
this.error = error;
}
public String toJsonString() {
JSONObject jo = new JSONObject();
jo.put(ERROR, error);
return jo.toString();
}
}
|
/**
@header@
*/
package org.pcmm;
import org.pcmm.gates.ITransactionID;
import org.pcmm.gates.impl.PCMMGateReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.umu.cops.stack.COPSError;
import java.util.Hashtable;
public class PCMMPdpDataProcess { // extends COPSPdpDataProcess
public final static Logger logger = LoggerFactory.getLogger(PCMMPdpAgent.class);
private Hashtable installPolicy;
private Hashtable removePolicy;
public PCMMPdpDataProcess() {
}
/**
* PDPAgent gets the policies to delete from PEP
*
* @param man
* @return
*/
public Hashtable getRemovePolicy(PCMMPdpReqStateMan man) {
return removePolicy;
}
/**
* PDPAgent gets the policies to be installed in PEP
*
* @param man
* @return
*/
public Hashtable getInstallPolicy(PCMMPdpReqStateMan man) {
return installPolicy;
}
/**
* PEP configuration items for sending inside the request
*
* @param man
* @param reqSIs
*/
public void setClientData(PCMMPdpReqStateMan man, Hashtable reqSIs) {
logger.info("Request Info");
/*
for (Enumeration e = reqSIs.keys() ; e.hasMoreElements() ;) {
String strprid = (String) e.nextElement();
String strepd = (String) reqSIs.get(strprid);
// Check PRID-EPD
// ....
System.out.println(getClass().getName() + ": " + "PRID: " + strprid);
System.out.println(getClass().getName() + ": " + "EPD: " + strepd);
}
// Create policies to be deleted
// ....
// Create policies to be installed
String prid = new String("<XPath>");
String epd = new String("<?xml this is an XML policy>");
installPolicy.put(prid, epd);
*/
}
/**
* Fail report received
*
* @param man
* @param gateMsg
*/
public void failReport(PCMMPdpReqStateMan man, PCMMGateReq gateMsg) {
logger.info("Fail Report notified with error - " + gateMsg.getError().toString());
/*
System.out.println(getClass().getName() + ": " + "Report Info");
for (Enumeration e = reportSIs.keys() ; e.hasMoreElements() ;) {
String strprid = (String) e.nextElement();
String strepd = (String) reportSIs.get(strprid);
// Check PRID-EPD
// ....
System.out.println(getClass().getName()+ ": " + "PRID: " + strprid);
System.out.println(getClass().getName()+ ": " + "EPD: " + strepd);
}
*/
}
/**
* Positive report received
*
* @param man
* @param gateMsg
*/
public void successReport(PCMMPdpReqStateMan man, PCMMGateReq gateMsg) {
logger.info("Success Report notified.");
if ( gateMsg.getTransactionID().getGateCommandType() == ITransactionID.GateDeleteAck ) {
logger.info("GateDeleteAck: GateID = " + gateMsg.getGateID().getGateID());
if (gateMsg.getGateID().getGateID() == PCMMGlobalConfig.getGateID1())
PCMMGlobalConfig.setGateID1(0);
if (gateMsg.getGateID().getGateID() == PCMMGlobalConfig.getGateID2())
PCMMGlobalConfig.setGateID2(0);
}
if ( gateMsg.getTransactionID().getGateCommandType() == ITransactionID.GateSetAck ) {
logger.info("GateSetAck : GateID = " + gateMsg.getGateID().getGateID());
if (0 == PCMMGlobalConfig.getGateID1())
PCMMGlobalConfig.setGateID1(gateMsg.getGateID().getGateID());
if (0 == PCMMGlobalConfig.getGateID2())
PCMMGlobalConfig.setGateID2(gateMsg.getGateID().getGateID());
}
/*
System.out.println(getClass().getName()+ ": " + "Report Info");
for (Enumeration e = reportSIs.keys() ; e.hasMoreElements() ;) {
String strprid = (String) e.nextElement();
String strepd = (String) reportSIs.get(strprid);
// Check PRID-EPD
// ....
System.out.println(getClass().getName()+ ": " + "PRID: " + strprid);
System.out.println(getClass().getName()+ ": " + "EPD: " + strepd);
}
*/
}
/**
* Accounting report received
*
* @param man
* @param gateMsg
*/
public void acctReport(PCMMPdpReqStateMan man, PCMMGateReq gateMsg) {
logger.info("Acct Report notified.");
/*
System.out.println(getClass().getName()+ ": " + "Report Info");
for (Enumeration e = reportSIs.keys() ; e.hasMoreElements() ;) {
String strprid = (String) e.nextElement();
String strepd = (String) reportSIs.get(strprid);
// Check PRID-EPD
// ....
System.out.println(getClass().getName()+ ": " + "PRID: " + strprid);
System.out.println(getClass().getName()+ ": " + "EPD: " + strepd);
}
*/
}
/**
* Notifies that an Accounting report is missing
*
* @param man
*/
public void notifyNoAcctReport(PCMMPdpReqStateMan man) {
//To change body of implemented methods use File | Settings | File Templates.
}
/**
* Notifies that a KeepAlive message is missing
*
* @param man
*/
public void notifyNoKAliveReceived(PCMMPdpReqStateMan man) {
//To change body of implemented methods use File | Settings | File Templates.
}
/**
* PEP closed the connection
*
* @param man
* @param error
*/
public void notifyClosedConnection(PCMMPdpReqStateMan man, COPSError error) {
logger.info("Connection was closed by PEP");
}
/**
* Delete request state received
*
* @param man
*/
public void notifyDeleteRequestState(PCMMPdpReqStateMan man) {
//To change body of implemented methods use File | Settings | File Templates.
}
/**
* Closes request state
*
* @param man
*/
public void closeRequestState(PCMMPdpReqStateMan man) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
|
package edu.wustl.catissuecore.domain;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import edu.wustl.catissuecore.actionForm.AbstractActionForm;
import edu.wustl.catissuecore.actionForm.DistributionForm;
import edu.wustl.common.util.MapDataParser;
import edu.wustl.common.util.logger.Logger;
/**
* An event that results in transfer of a specimen from a Repository to a Laboratory.
* @hibernate.joined-subclass table="CATISSUE_DISTRIBUTION"
* @hibernate.joined-subclass-key column="IDENTIFIER"
* @author Mandar Deshmukh
*/
public class Distribution extends SpecimenEventParameters implements java.io.Serializable
{
private static final long serialVersionUID = 1234567890L;
/**
* New location(site) of the item.
*/
protected Site toSite = new Site();
/**
* Original location(site) of the item.
*/
protected Site fromSite = new Site();
/**
* DistributionProtocol associated with this Distribution.
*/
protected DistributionProtocol distributionProtocol = new DistributionProtocol();
/**
* Collection of Items distributed in this distribution.
*/
protected Collection distributedItemCollection = new HashSet();
//Default Constructor
public Distribution()
{
}
public Distribution(AbstractActionForm form)
{
setAllValues(form);
}
/**
* Returns the destination/target Site of the Distribution.
* @hibernate.many-to-one column="TO_SITE_ID"
* class="edu.wustl.catissuecore.domain.Site" constrained="true"
* @return the destination/target Site of the Distribution.
*/
public Site getToSite()
{
return toSite;
}
/**
* @param toSite
* The toSite to set.
*/
public void setToSite(Site toSite)
{
this.toSite = toSite;
}
/**
* Returns the original/source Site of the Distribution.
* @hibernate.many-to-one column="FROM_SITE_ID"
* class="edu.wustl.catissuecore.domain.Site" constrained="true"
* @return the original/source Site of the Distribution.
*/
public Site getFromSite()
{
return fromSite;
}
/**
* @param fromSite
* The fromSite to set.
*/
public void setFromSite(Site fromSite)
{
this.fromSite = fromSite;
}
/**
* Returns the distributionProtocol of the distribution.
* @hibernate.many-to-one column="DISTRIBUTION_PROTOCOL_ID"
* class="edu.wustl.catissuecore.domain.DistributionProtocol"
* constrained="true"
* @return the distributionProtocol of the distribution.
*/
public DistributionProtocol getDistributionProtocol()
{
return distributionProtocol;
}
/**
* @param distributionProtocol
* The distributionProtocol to set.
*/
public void setDistributionProtocol(DistributionProtocol distributionProtocol)
{
this.distributionProtocol = distributionProtocol;
}
/**
* Returns the collection of DistributedItems for this Distribution.
* @hibernate.set name="distributedItemCollection"
* table="CATISSUE_DISTRIBUTED_ITEM" cascade="save-update"
* inverse="true" lazy="false"
* @hibernate.collection-key column="DISTRIBUTION_ID"
* @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.DistributedItem"
* @return Returns the collection of DistributedItems for this Distribution.
*/
public Collection getDistributedItemCollection()
{
return distributedItemCollection;
}
/**
* @param distributedItemCollection
* The distributedItemCollection to set.
*/
public void setDistributedItemCollection(Collection distributedItemCollection)
{
this.distributedItemCollection = distributedItemCollection;
}
public void setAllValues(AbstractActionForm abstractForm)
{
try
{
DistributionForm form = (DistributionForm) abstractForm;
super.setAllValues(form);
toSite.setSystemIdentifier(new Long(form.getToSite()));
fromSite.setSystemIdentifier(new Long(form.getFromSite()));
distributionProtocol.setSystemIdentifier(new Long(form.getDistributionProtocolId()));
Map map = form.getValues();
map = fixMap(map);
MapDataParser parser = new MapDataParser("edu.wustl.catissuecore.domain");
distributedItemCollection = parser.generateData(map);
}
catch(Exception excp)
{
excp.printStackTrace();
Logger.out.error(excp.getMessage());
}
}
protected Map fixMap(Map orgMap)
{
Map replaceMap = new HashMap();
Iterator it = orgMap.keySet().iterator();
while(it.hasNext())
{
String key = (String)it.next();
Logger.out.debug("Key************************"+key);
if(key.indexOf("className")!=-1)
{
String value = (String)orgMap.get(key);
Logger.out.debug("Value..........................."+value);
String replaceWith = "Specimen"+"#"+value+"Specimen";
key = key.substring(0,key.lastIndexOf("_"));
Logger.out.debug("Second Key***********************"+key);
String newKey = key.replaceFirst("Specimen",replaceWith);
Logger.out.debug("New Key................"+newKey);
replaceMap.put(key,newKey);
}
}
Map newMap = new HashMap();
it = orgMap.keySet().iterator();
while(it.hasNext())
{
String key = (String)it.next();
String value = (String)orgMap.get(key);
if(!key.endsWith("_unit"))
{
if(key.indexOf("Specimen")==-1)
{
newMap.put(key,value);
}
else
{
if(key.indexOf("className")==-1)
{
String keyPart, newKeyPart;
//Replace # and class name and FIX for abstract class
keyPart = key.substring(0,key.lastIndexOf("_"));
newKeyPart = (String)replaceMap.get(keyPart);
key = key.replaceFirst(keyPart,newKeyPart);
newMap.put(key,value);
}
}
}
}
return newMap;
}
}
|
package com.intellij.openapi.util;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A utility to prevent endless recursion and ensure the caching returns stable results if such endless recursion is prevented.
* Should be used only as a last resort, when it's impossible to detect endless recursion without using thread-local state.<p></p>
*
* Imagine a method {@code A()} calls method {@code B()}, which in turn calls {@code C()},
* which (unexpectedly) calls {@code A()} again (it's just an example; the loop could be shorter or longer).
* This would normally result in endless recursion and stack overflow. One should avoid situations like these at all cost,
* but if that's impossible (e.g. due to different plugins unaware of each other yet calling each other),
* {@code RecursionManager} is to the rescue.<p></p>
*
* It helps to track all the computations in the thread stack and return some default value when
* asked to compute {@code A()} for the second time. {@link #doPreventingRecursion} does precisely this, returning {@code null} when
* endless recursion would otherwise happen.<p></p>
*
* Additionally, imagine all these methods {@code A()}, {@code B()} and {@code C()} cache their results.
* Note that if not {@code A()} is called first, but {@code B()} or {@code C()}, the endless recursion would stay just the same,
* but it would be prevented in different places ({@code B()} or {@code C()}, respectively). That'd mean there's 3 situations possible:
* <ol>
* <li>{@code C()} calls {@code A()} and gets {@code null} as the result (if {@code A()} is first in the stack)</li>
* <li>{@code C()} calls {@code A()} which calls {@code B()} and gets {@code null} as the result (if {@code B()} is first in the stack)</li>
* <li>{@code C()} calls {@code A()} which calls {@code B()} which calls {@code C()} and gets {@code null} as the result (if {@code C()} is first in the stack)</li>
* </ol>
* Most likely, the results of {@code C()} would be different in those 3 cases, and it'd be unwise to cache just any of them randomly,
* whatever is calculated first. In a multi-threaded environment, that'd lead to unpredictability.<p></p>
*
* Of the 3 possible scenarios above, caching for {@code C()} makes sense only for the last one, because that's the result we'd get if there were no caching at all.
* Therefore, if you use any kind of caching in an endless-recursion-prone environment, please ensure you don't cache incomplete results
* that happen when you're inside the evil recursion loop.
* {@code RecursionManager} assists in distinguishing this situation and allowing caching outside that loop, but disallowing it inside.<p></p>
*
* To prevent caching incorrect values, please create a {@code private static final} field of {@link #createGuard} call, and then use
* {@link RecursionManager#markStack()} and {@link RecursionGuard.StackStamp#mayCacheNow()}
* on it.<p></p>
*
* Note that the above only helps with idempotent recursion loops, that is, the ones that stabilize after one iteration, so that
* {@code A()->B()->C()->null} returns the same value as {@code A()->B()->C()->A()->B()->C()->null} etc. If your functions lack that quality
* (e.g. if they add items to some list), you won't get stable caching results ever, and your code will produce unpredictable results
* with hard-to-catch bugs. Therefore, please strive for idempotence.
*
* @author peter
*/
@SuppressWarnings("UtilityClassWithoutPrivateConstructor")
public final class RecursionManager {
private static final Logger LOG = Logger.getInstance(RecursionManager.class);
private static final ThreadLocal<CalculationStack> ourStack = ThreadLocal.withInitial(() -> new CalculationStack());
private static final AtomicBoolean ourAssertOnPrevention = new AtomicBoolean();
private static final AtomicBoolean ourAssertOnMissedCache = new AtomicBoolean();
/**
* Run the given computation, unless it's already running in this thread.
* This is same as {@link RecursionGuard#doPreventingRecursion(Object, boolean, Computable)},
* without a need to bother to create {@link RecursionGuard}.
*/
@Nullable
public static <T> T doPreventingRecursion(@NotNull Object key, boolean memoize, Computable<T> computation) {
return createGuard(computation.getClass().getName()).doPreventingRecursion(key, memoize, computation);
}
/**
* @param id just some string to separate different recursion prevention policies from each other
* @return a helper object which allow you to perform reentrancy-safe computations and check whether caching will be safe.
* Don't use it unless you need to call it from several places in the code, inspect the computation stack and/or prohibit result caching.
*/
@NotNull
public static <Key> RecursionGuard<Key> createGuard(@NonNls final String id) {
return new RecursionGuard<Key>() {
@Override
public <T, E extends Throwable> @Nullable T computePreventingRecursion(@NotNull Key key,
boolean memoize,
@NotNull ThrowableComputable<T, E> computation) throws E{
MyKey realKey = new MyKey(id, key, true);
final CalculationStack stack = ourStack.get();
if (stack.checkReentrancy(realKey)) {
if (ourAssertOnPrevention.get()) {
throw new StackOverflowPreventedException("Endless recursion prevention occurred on " + key);
}
return null;
}
if (memoize) {
MemoizedValue memoized = stack.intermediateCache.get(realKey);
if (memoized != null) {
for (MyKey noCacheUntil : memoized.dependencies) {
stack.prohibitResultCaching(noCacheUntil);
}
//noinspection unchecked
return (T)memoized.value;
}
}
realKey = new MyKey(id, key, false);
final int sizeBefore = stack.progressMap.size();
StackFrame frame = stack.beforeComputation(realKey);
final int sizeAfter = stack.progressMap.size();
try {
T result = computation.compute();
if (memoize && frame.preventionsInside != null) {
stack.memoize(realKey, result, frame.preventionsInside);
}
return result;
}
finally {
try {
stack.afterComputation(realKey, sizeBefore, sizeAfter);
}
catch (Throwable e) {
//noinspection ThrowFromFinallyBlock
throw new RuntimeException("Throwable in afterComputation", e);
}
stack.checkDepth("4");
}
}
@NotNull
@Override
public List<Key> currentStack() {
List<Key> result = new ArrayList<>();
for (MyKey pair : ourStack.get().progressMap.keySet()) {
if (pair.guardId.equals(id)) {
//noinspection unchecked
result.add((Key)pair.userObject);
}
}
return Collections.unmodifiableList(result);
}
@Override
public void prohibitResultCaching(@NotNull Object since) {
MyKey realKey = new MyKey(id, since, false);
final CalculationStack stack = ourStack.get();
stack.prohibitResultCaching(realKey);
}
};
}
/**
* Clears the memoization cache for the current thread. This can be invoked when a side effect happens
* inside a {@link #doPreventingRecursion} call that may affect results of nested memoizing {@code doPreventingRecursion} calls,
* whose memoized results should not be reused on that point.<p></p>
*
* Please avoid this method at all cost and try to restructure your code to avoid side effects inside {@code doPreventingRecursion}.
*/
@ApiStatus.Internal
public static void dropCurrentMemoizationCache() {
ourStack.get().intermediateCache.clear();
}
/**
* Used in pair with {@link RecursionGuard.StackStamp#mayCacheNow()} to ensure that cached are only the reliable values,
* not depending on anything incomplete due to recursive prevention policies.
* A typical usage is this:
* {@code
* RecursionGuard.StackStamp stamp = RecursionManager.createGuard("id").markStack();
*
* Result result = doComputation();
*
* if (stamp.mayCacheNow()) {
* cache(result);
* }
* return result;
* }
* @return an object representing the current stack state, managed by {@link RecursionManager}
*/
@NotNull
public static RecursionGuard.StackStamp markStack() {
int stamp = ourStack.get().reentrancyCount;
return new RecursionGuard.StackStamp() {
@Override
public boolean mayCacheNow() {
CalculationStack stack = ourStack.get();
boolean result = stamp == stack.reentrancyCount;
if (!result && ourAssertOnMissedCache.get() && !stack.isCurrentNonCachingStillTolerated()) {
throw new CachingPreventedException(stack.preventions);
}
return result;
}
};
}
private static class MyKey {
final String guardId;
final Object userObject;
private final int myHashCode;
private final boolean myCallEquals;
MyKey(String guardId, @NotNull Object userObject, boolean mayCallEquals) {
this.guardId = guardId;
this.userObject = userObject;
LOG.assertTrue(!userObject.getClass().isArray(), "Arrays use the default hashCode/equals implementation");
// remember user object hashCode to ensure our internal maps consistency
myHashCode = guardId.hashCode() * 31 + userObject.hashCode();
myCallEquals = mayCallEquals;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MyKey && guardId.equals(((MyKey)obj).guardId))) return false;
if (userObject == ((MyKey)obj).userObject) {
return true;
}
if (myCallEquals || ((MyKey)obj).myCallEquals) {
return userObject.equals(((MyKey)obj).userObject);
}
return false;
}
@Override
public int hashCode() {
return myHashCode;
}
@Override
public String toString() {
return guardId + "->" + userObject;
}
}
private static final class CalculationStack {
private int reentrancyCount;
private int depth;
private int firstLoopStart = Integer.MAX_VALUE; // outermost recursion-prevented frame depth; memoized values are dropped on its change.
private final LinkedHashMap<MyKey, StackFrame> progressMap = new LinkedHashMap<>();
private final Map<MyKey, Throwable> preventions = new IdentityHashMap<>();
private final Map<MyKey, MemoizedValue> intermediateCache = ContainerUtil.createSoftKeySoftValueMap();
private int enters;
private int exits;
boolean checkReentrancy(MyKey realKey) {
if (progressMap.containsKey(realKey)) {
prohibitResultCaching(realKey);
return true;
}
return false;
}
StackFrame beforeComputation(MyKey realKey) {
enters++;
if (progressMap.isEmpty()) {
assert reentrancyCount == 0 : "Non-zero stamp with empty stack: " + reentrancyCount;
}
checkDepth("1");
int sizeBefore = progressMap.size();
StackFrame frame = new StackFrame();
frame.reentrancyStamp = reentrancyCount;
progressMap.put(realKey, frame);
depth++;
checkDepth("2");
int sizeAfter = progressMap.size();
if (sizeAfter != sizeBefore + 1) {
LOG.error("Key doesn't lead to the map size increase: " + sizeBefore + " " + sizeAfter + " " + realKey.userObject);
}
return frame;
}
void memoize(MyKey key, @Nullable Object result, @NotNull Set<MyKey> preventionsInside) {
intermediateCache.put(key, new MemoizedValue(result, preventionsInside.toArray(new MyKey[0])));
}
final void afterComputation(MyKey realKey, int sizeBefore, int sizeAfter) {
exits++;
if (sizeAfter != progressMap.size()) {
LOG.error("Map size changed: " + progressMap.size() + " " + sizeAfter + " " + realKey.userObject);
}
if (depth != progressMap.size()) {
LOG.error("Inconsistent depth after computation; depth=" + depth + "; map=" + progressMap);
}
StackFrame value = progressMap.remove(realKey);
depth
if (!preventions.isEmpty()) {
preventions.remove(realKey);
}
if (depth <= firstLoopStart) {
firstLoopStart = Integer.MAX_VALUE;
intermediateCache.clear();
}
if (sizeBefore != progressMap.size()) {
LOG.error("Map size doesn't decrease: " + progressMap.size() + " " + sizeBefore + " " + realKey.userObject);
}
reentrancyCount = value.reentrancyStamp;
}
private void prohibitResultCaching(MyKey realKey) {
reentrancyCount++;
List<Map.Entry<MyKey, StackFrame>> stack = new ArrayList<>(progressMap.entrySet());
int loopStart = ContainerUtil.indexOf(stack, entry -> entry.getKey().equals(realKey));
if (loopStart >= 0) {
MyKey loopStartKey = stack.get(loopStart).getKey();
if (!preventions.containsKey(loopStartKey)) {
preventions.put(loopStartKey, ourAssertOnMissedCache.get() ? new StackOverflowPreventedException(null) : null);
}
for (int i = loopStart + 1; i < stack.size(); i++) {
stack.get(i).getValue().addPrevention(reentrancyCount, loopStartKey);
}
if (LOG.isDebugEnabled() && loopStart < stack.size() - 1) {
LOG.debug("Recursion prevented for " + realKey +
", caching disabled for " + ContainerUtil.map(stack.subList(loopStart, stack.size()), Map.Entry::getKey));
}
if (firstLoopStart > loopStart) {
firstLoopStart = loopStart;
intermediateCache.clear();
}
}
}
private void checkDepth(String s) {
int oldDepth = depth;
if (oldDepth != progressMap.size()) {
depth = progressMap.size();
throw new AssertionError("_Inconsistent depth " + s + "; depth=" + oldDepth + "; enters=" + enters + "; exits=" + exits + "; map=" + progressMap);
}
}
/**
* Rules in this method correspond to bugs that should be fixed but for some reasons that can't be done immediately.
* The ultimate goal is to get rid of all of them.
* So, each rule should be accompanied by a reference to a tracker issue.
* Don't add rules here without discussing them with someone else.
* Don't add rules for situation where caching prevention is expected, use {@link #disableMissedCacheAssertions} instead.
*/
boolean isCurrentNonCachingStillTolerated() {
return isCurrentNonCachingStillTolerated(new Throwable()) ||
ContainerUtil.exists(preventions.values(), CalculationStack::isCurrentNonCachingStillTolerated);
}
private static boolean isCurrentNonCachingStillTolerated(Throwable t) {
String trace = ExceptionUtil.getThrowableText(t);
return ContainerUtil.exists(toleratedFrames, trace::contains);
}
}
private static final @NonNls String[] toleratedFrames = {
"com.intellij.psi.impl.source.xml.XmlAttributeImpl.getDescriptor(", // IDEA-228451
"org.jetbrains.plugins.ruby.ruby.codeInsight.symbols.structure.util.SymbolHierarchy.getAncestorsCaching(", // RUBY-25487
"com.intellij.lang.aspectj.psi.impl.PsiInterTypeReferenceImpl.", // IDEA-228779
"com.intellij.psi.impl.search.JavaDirectInheritorsSearcher.processConcurrentlyIfTooMany(", // IDEA-229003
// WEB-42912
"com.intellij.lang.javascript.psi.resolve.JSEvaluatorComplexityTracker.doRunTask(",
"com.intellij.lang.javascript.ecmascript6.types.JSTypeSignatureChooser.chooseOverload(",
"com.intellij.lang.javascript.psi.resolve.JSEvaluationCache.getElementType(",
"com.intellij.lang.ecmascript6.psi.impl.ES6ImportSpecifierImpl.multiResolve(",
"com.intellij.lang.javascript.psi.types.JSTypeBaseImpl.substitute(",
// IDEA-228814
"com.intellij.psi.ThreadLocalTypes.performWithTypes(",
// IDEA-212671
"com.intellij.xml.impl.schema.XmlNSDescriptorImpl.getRedefinedElementDescriptor(",
"com.intellij.psi.impl.source.xml.XmlTagImpl.getDescriptor(",
"com.intellij.psi.impl.source.xml.XmlTagDelegate.getNSDescriptor(",
"com.intellij.xml.impl.schema.XmlNSDescriptorImpl.findTypeDescriptor(",
"com.intellij.psi.impl.source.xml.XmlEntityRefImpl.doResolveEntity(",
"com.intellij.xml.impl.dtd.XmlNSDescriptorImpl.getElementDescriptor(",
// PY-39529
"com.jetbrains.python.psi.PyKnownDecoratorUtil.resolveDecorator(",
"com.jetbrains.python.psi.impl.references.PyReferenceImpl.multiResolve(",
};
private static class MemoizedValue {
final Object value;
final MyKey[] dependencies;
MemoizedValue(Object value, MyKey[] dependencies) {
this.value = value;
this.dependencies = dependencies;
}
}
private static class StackFrame {
int reentrancyStamp;
@Nullable Set<MyKey> preventionsInside;
void addPrevention(int stamp, MyKey prevented) {
reentrancyStamp = stamp;
if (preventionsInside == null) {
preventionsInside = new HashSet<>();
}
preventionsInside.add(prevented);
}
}
@TestOnly
public static void assertOnRecursionPrevention(@NotNull Disposable parentDisposable) {
setFlag(parentDisposable, true, ourAssertOnPrevention);
}
private static void setFlag(@NotNull Disposable parentDisposable, boolean toAssert, AtomicBoolean flag) {
boolean prev = flag.get();
if (toAssert == prev) return;
flag.set(toAssert);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
if (flag.get() != toAssert) {
throw new IllegalStateException("Non-nested assertion flag modifications");
}
flag.set(prev);
}
});
}
@TestOnly
public static void disableAssertOnRecursionPrevention(@NotNull Disposable parentDisposable) {
setFlag(parentDisposable, false, ourAssertOnPrevention);
}
/**
* Disables the effect of {@link #assertOnMissedCache}. Should be used as rarely as possible, ideally only in tests that check
* that stack isn't overflown on invalid code.
*/
@TestOnly
public static void disableMissedCacheAssertions(@NotNull Disposable parentDisposable) {
setFlag(parentDisposable, false, ourAssertOnMissedCache);
}
/**
* Enable the mode when a {@link CachingPreventedException} is thrown whenever
* {@link RecursionGuard.StackStamp#mayCacheNow()} returns false,
* either due to recursion prevention or explicit {@link RecursionGuard#prohibitResultCaching} call.
* Restore previous mode when parentDisposable is disposed.
*/
@TestOnly
public static void assertOnMissedCache(@NotNull Disposable parentDisposable) {
setFlag(parentDisposable, true, ourAssertOnMissedCache);
}
/**
* If this exception happened to you, this means that your caching might be suboptimal due to endless recursion, and you'd better fix that.
* The exception's cause might help, as it contains a full stack trace of the endless recursion prevention that has led to this caching prohibition.
* <p></p>
* Try to get rid of the cyclic dependency. Often it's easy: look carefully at the stack trace, put breakpoints, look at the values passed,
* and find something that shouldn't be called there. There's almost always such something. Remove it and voila, you've got rid of the cycle,
* improved caching and also avoided calling unnecessary code which can speed up the execution even in unrelated circumstances.
* <p></p>
* What not to do: don't replace {@code RecursionManager} with your own thread-local,
* don't just remove {@code mayCacheNow} checks and cache despite them.
* Both approaches will likely result in test & production flakiness and {@code IdempotenceChecker} assertions.
* <p></p>
* There are rare cases when recursion prevention is acceptable. They might involve analyzing very incorrect code or
* independent plugins calling into each other. This should be an exotic situation, not a normal workflow.
* In this case, you may call {@link #disableMissedCacheAssertions} in the tests
* which check such exotic situations.
*/
static class CachingPreventedException extends RuntimeException {
CachingPreventedException(Map<MyKey, Throwable> preventions) {
super("Caching disabled due to recursion prevention, please get rid of cyclic dependencies. Preventions: " + new ArrayList<>(preventions.keySet()),
ContainerUtil.getFirstItem(preventions.values()));
}
}
}
|
package git4idea.commands;
import com.intellij.openapi.util.Key;
/**
* @deprecated Use the {@link GitLineHandlerListener}.
*/
@Deprecated
public class GitLineHandlerAdapter implements GitLineHandlerListener {
@Override
public void onLineAvailable(final String line, final Key outputType) {
}
}
|
package org.pm4j.core.pm.impl;
import java.util.Set;
import org.pm4j.core.pm.PmCommand;
import org.pm4j.core.pm.PmObject;
import org.pm4j.core.pm.annotation.PmCommandCfg;
import org.pm4j.core.pm.annotation.PmCommandCfg.BEFORE_DO;
/**
* Proxy commands are designed as stand-in's for optionally existing real application commands.
* <p>
* Command proxies do not directly trigger validations. That is the task of the {@link #delegateCmd} to delegate the
* call to.
*
* @author olaf boede
*/
@PmCommandCfg(beforeDo=BEFORE_DO.DO_NOTHING)
public class PmCommandProxy extends PmCommandImpl {
/**
* Defines, what to do in case of a missing delegate command.
*/
public static enum OnMissingDelegate {
/** Shows the disabled command. */
DISABLE,
/** Makes the command invisible. */
HIDE
}
/** The command to delegate the calls to. */
private PmCommand delegateCmd;
/** Defines what to do in case of a missing forward command. */
private OnMissingDelegate onMissingDelegate;
/** The clone of the delegate that has executed the last <code>doIt</code> call. */
private PmCommand executedDelegateCmdClone;
/**
* @param pmParent The PM tree parent.
* @param onMissingDelegate Defines what to do in case of a missing forward command.
*/
public PmCommandProxy(PmObject pmParent, OnMissingDelegate onMissingDelegate) {
super(pmParent);
this.onMissingDelegate = onMissingDelegate;
}
/**
* Defines a proxy that gets disabled if there is no forward command defined.
*
* @param pmParent The PM tree parent.
*/
public PmCommandProxy(PmObject pmParent) {
super(pmParent);
this.onMissingDelegate = OnMissingDelegate.DISABLE;
}
/**
* Defines the command that really executes the tool bar command functionality.
*
* @param delegateCmd
* The command that defines the logic.
*/
public void setDelegateCmd(PmCommand delegateCmd) {
this.delegateCmd = delegateCmd;
}
/**
* @return The command that defines the logic. May be <code>null</code> if there is no delegate configured.
*/
public PmCommand getDelegateCmd() {
return delegateCmd;
}
@Override
protected boolean isPmEnabledImpl() {
return delegateCmd != null
? delegateCmd.isPmEnabled()
: false;
}
@Override
protected boolean isPmVisibleImpl() {
return delegateCmd != null
? delegateCmd.isPmVisible()
: onMissingDelegate != OnMissingDelegate.HIDE;
}
@Override
protected void doItImpl() throws Exception {
executedDelegateCmdClone = delegateCmd.doIt();
}
/**
* Returns the clone of the delegate that has been executed.<br>
* If the command proxy itself was stopped by a before-do veto, the
* executeded proxy instance will be returned.
*/
@Override
public PmCommand doIt(boolean changeCommandHistory) {
PmCommandProxy proxyCmdClone = (PmCommandProxy) super.doIt(changeCommandHistory);
return proxyCmdClone.executedDelegateCmdClone != null
? proxyCmdClone.executedDelegateCmdClone
: proxyCmdClone;
}
/**
* Provides the state of the executed delegate command (if it already exists).
*/
@Override
public CommandState getCommandState() {
return executedDelegateCmdClone != null
? executedDelegateCmdClone.getCommandState()
: super.getCommandState();
}
@Override
protected String getPmTitleImpl() {
return delegateCmd != null
? delegateCmd.getPmTitle()
: super.getPmTitleImpl();
}
@Override
protected String getPmTooltipImpl() {
return delegateCmd != null
? delegateCmd.getPmTooltip()
: super.getPmTitleImpl();
}
@Override
protected void getPmStyleClassesImpl(Set<String> styleClassSet) {
if (delegateCmd != null) {
styleClassSet.addAll(delegateCmd.getPmStyleClasses());
}
else {
super.getPmStyleClassesImpl(styleClassSet);
}
}
}
|
package org.jetel.lookup;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.jetel.connection.jdbc.AbstractCopySQLData;
import org.jetel.connection.jdbc.SQLCloverStatement;
import org.jetel.connection.jdbc.SQLUtil;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.Defaults;
import org.jetel.data.HashKey;
import org.jetel.data.RecordKey;
import org.jetel.data.lookup.Lookup;
import org.jetel.data.lookup.LookupTable;
import org.jetel.database.sql.CopySQLData;
import org.jetel.database.sql.DBConnection;
import org.jetel.database.sql.JdbcSpecific;
import org.jetel.database.sql.JdbcSpecific.OperationType;
import org.jetel.database.sql.SqlConnection;
import org.jetel.exception.AttributeNotFoundException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.GraphConfigurationException;
import org.jetel.exception.JetelException;
import org.jetel.exception.NotInitializedException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.GraphElement;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.metadata.DataRecordParsingType;
import org.jetel.util.primitive.TypedProperties;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
/**
* Database table/SQLquery based lookup table which gets data by performing SQL
* query. Caching of found values can be provided - if the constructor with
* <code>numCached</code> parameter is used.
*
* The XML DTD describing the internal structure is as follows:
*
* * <!ATTLIST LookupTable
* id ID #REQUIRED
* type NMTOKEN (DBLookup) #REQUIRED
* metadata CDATA #REQUIRED
* sqlQuery CDATA #REQUIRED
* dbConnection CDATA #REQUIRED
* maxCached CDATA #IMPLIED>
* storeNulls CDATA #IMPLIED>
*
*
*@author dpavlis
*@since May 22, 2003
*/
public class DBLookupTable extends GraphElement implements LookupTable {
private static final String XML_LOOKUP_TYPE_DB_LOOKUP = "DBLookup";
private static final String XML_SQL_QUERY = "sqlQuery";
private static final String XML_LOOKUP_MAX_CACHE_SIZE = "maxCached";
private static final String XML_STORE_NULL_RESPOND = "storeNulls";
private final static String[] REQUESTED_ATTRIBUTE = {XML_ID_ATTRIBUTE, XML_TYPE_ATTRIBUTE, XML_DBCONNECTION,
XML_SQL_QUERY
};
protected String metadataId;
protected String connectionId;
protected DataRecordMetadata dbMetadata;
protected DBConnection connection;
protected SqlConnection sqlConnection;
protected String sqlQuery;//this query can contain $field
protected int maxCached = 0;
protected boolean storeNulls = false;
private List<DBLookup> activeLookups = Collections.synchronizedList(new ArrayList<DBLookup>());
public DBLookupTable(String id, String connectionId, String metadataId, String sqlQuery){
super(id);
this.connectionId = connectionId;
this.metadataId = metadataId;
this.sqlQuery = sqlQuery;
}
/**
* Constructor for the DBLookupTable object
*
*@param dbConnection Description of the Parameter
*@param dbRecordMetadata Description of the Parameter
*@param sqlQuery Description of the Parameter
*/
public DBLookupTable(String id, DBConnection connection,
DataRecordMetadata dbRecordMetadata, String sqlQuery) {
super(id);
this.connection = connection;
this.dbMetadata = dbRecordMetadata;
this.sqlQuery = sqlQuery;
}
public DBLookupTable(String id, DBConnection connection,
DataRecordMetadata dbRecordMetadata, String sqlQuery, int numCached) {
super(id);
this.connection = connection;
this.dbMetadata = dbRecordMetadata;
this.sqlQuery = sqlQuery;
this.maxCached = numCached;
}
/**
* Gets the dbMetadata attribute of the DBLookupTable object.<br>
* <i>init() should be called prior to calling this method (unless dbMetadata
* was passed in using appropriate constructor.</i>
*
*@return The dbMetadata value
*/
@Override
public DataRecordMetadata getMetadata() {
if (dbMetadata == null) {
synchronized (activeLookups) {
for (DBLookup activeLookup : activeLookups) {
if (activeLookup.getMetadata() != null) {
dbMetadata = activeLookup.getMetadata();
break;
}
}
}
}
return dbMetadata;
}
/**
* Initialization of lookup table - loading all data into it.
*
*@exception JetelException Description of the Exception
*@since May 2, 2002
*/
@Override
synchronized public void init() throws ComponentNotReadyException {
if (isInitialized()) {
return;
}
super.init();
if (metadataId != null) {
dbMetadata = getGraph().getDataRecordMetadata(metadataId, true);
}
if (connection == null) {
connection = (DBConnection) getGraph().getConnection(connectionId);
if (connection == null) {
throw new ComponentNotReadyException("Connection " + StringUtils.quote(connectionId) + " does not exist!!!");
}
connection.init();
}
}
@Override
public synchronized void preExecute() throws ComponentNotReadyException {
super.preExecute();
try {
sqlConnection = connection.getConnection(getId(), OperationType.READ);
} catch (JetelException e) {
throw new ComponentNotReadyException("Can't connect to database", e);
}
}
@Override
public void postExecute() throws ComponentNotReadyException {
super.postExecute();
try {
synchronized (activeLookups) {
for (DBLookup activeLookup : activeLookups) {
activeLookup.close();
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
activeLookups.clear();
}
connection.closeConnection(getId(), OperationType.READ);
}
public static DBLookupTable fromProperties(TypedProperties properties)
throws AttributeNotFoundException, GraphConfigurationException{
for (String property : REQUESTED_ATTRIBUTE) {
if (!properties.containsKey(property)) {
throw new AttributeNotFoundException(property);
}
}
String type = properties.getStringProperty(XML_TYPE_ATTRIBUTE);
if (!type.equalsIgnoreCase(XML_LOOKUP_TYPE_DB_LOOKUP)){
throw new GraphConfigurationException("Can't create db lookup table from type " + type);
}
DBLookupTable lookupTable = new DBLookupTable(properties.getProperty(XML_ID_ATTRIBUTE),
properties.getStringProperty(XML_DBCONNECTION), properties.getStringProperty(XML_METADATA_ID),
properties.getStringProperty(XML_SQL_QUERY));
if (properties.containsKey(XML_NAME_ATTRIBUTE)){
lookupTable.setName(properties.getStringProperty(XML_NAME_ATTRIBUTE));
}
if(properties.containsKey(XML_LOOKUP_MAX_CACHE_SIZE)) {
lookupTable.setNumCached(properties.getIntProperty(XML_LOOKUP_MAX_CACHE_SIZE));
}
if (properties.containsKey(XML_STORE_NULL_RESPOND)){
lookupTable.setStoreNulls(properties.getBooleanProperty(XML_STORE_NULL_RESPOND));
}
return lookupTable;
}
public static DBLookupTable fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException, AttributeNotFoundException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
DBLookupTable lookupTable = null;
String id;
String type;
//reading obligatory attributes
id = xattribs.getString(XML_ID_ATTRIBUTE);
type = xattribs.getString(XML_TYPE_ATTRIBUTE);
//check type
if (!type.equalsIgnoreCase(XML_LOOKUP_TYPE_DB_LOOKUP)) {
throw new XMLConfigurationException("Can't create db lookup table from type " + type);
}
//create db lookup table
//String[] keys = xattribs.getString(XML_LOOKUP_KEY).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX);
lookupTable = new DBLookupTable(id, xattribs.getString(XML_DBCONNECTION),
xattribs.exists(XML_METADATA_ID) ? xattribs.getString(XML_METADATA_ID) : null, xattribs.getString(XML_SQL_QUERY));
if (xattribs.exists(XML_NAME_ATTRIBUTE)){
lookupTable.setName(xattribs.getString(XML_NAME_ATTRIBUTE));
}
if(xattribs.exists(XML_LOOKUP_MAX_CACHE_SIZE)) {
lookupTable.setNumCached(xattribs.getInteger(XML_LOOKUP_MAX_CACHE_SIZE));
}
if (xattribs.exists(XML_STORE_NULL_RESPOND)) {
lookupTable.setStoreNulls(xattribs.getBoolean(XML_STORE_NULL_RESPOND));
}
return lookupTable;
}
@Override
public synchronized void clear() {
synchronized (activeLookups) {
for (DBLookup activeLookup : activeLookups) {
activeLookup.clear();
}
}
}
@Override
public synchronized void free() {
if (isInitialized()) {
super.free();
try {
synchronized (activeLookups) {
for (DBLookup activeLookup : activeLookups) {
activeLookup.close();
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
activeLookups.clear();
}
}
}
/**
* Set max number of records stored in cache
*
* @param numCached
*/
public void setNumCached(int numCached){
this.maxCached=numCached;
}
/**
* Set max number of records stored in cache
*
* @param numCached max number of stored records
* @param storeNulls inicates if store key for which there aren't records in db
*/
public void setStoreNulls(boolean storeNulls){
this.storeNulls = storeNulls;
}
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if (connection == null) {
DBConnection tmp = (DBConnection)getGraph().getConnection(connectionId);
if (tmp == null) {
status.addError(this, XML_DBCONNECTION, "Connection " + StringUtils.quote(connectionId) + " does not exist!!!");
}
}
if (metadataId != null) {
dbMetadata = getGraph().getDataRecordMetadata(metadataId, false);
if (dbMetadata == null) {
status.addWarning(this, XML_METADATA_ID, "Metadata " + StringUtils.quote(metadataId) +
" does not exist. DB metadata will be created from sql query.");
}
}
return status;
}
@Override
public Iterator<DataRecord> iterator() {
if (!isInitialized()) {
throw new NotInitializedException(this);
} else if (sqlConnection == null) {
throw new NotInitializedException("No DB connection! (pre-execute initialization not performed?)", this);
}
//remove WHERE condidion from sql query
StringBuilder query = new StringBuilder(sqlQuery);
int whereIndex = query.toString().toLowerCase().indexOf("where");
int groupIndex = query.toString().toLowerCase().indexOf("group");
int orderIndex = query.toString().toLowerCase().indexOf("order");
if (whereIndex > -1){
if (groupIndex > -1 || orderIndex > -1){
query.delete(whereIndex, groupIndex);
}else{
query.setLength(whereIndex);
}
}
synchronized (sqlConnection) {
return iteratorImpl(query.toString());
}
}
private Iterator<DataRecord> iteratorImpl(String query) {
ResultSet resultSet = null;
try {
SQLCloverStatement st = new SQLCloverStatement(sqlConnection, query, null);
st.init();
resultSet = st.executeQuery();
sqlConnection.getJdbcSpecific().optimizeResultSet(resultSet, OperationType.READ);
if (dbMetadata == null) {
if (st.getCloverOutputFields() == null) {
dbMetadata = SQLUtil.dbMetadata2jetel(resultSet .getMetaData(), sqlConnection.getJdbcSpecific());
}else{
ResultSetMetaData dbMeta = resultSet.getMetaData();
JdbcSpecific jdbcSpecific = sqlConnection.getJdbcSpecific();
String[] fieldName = st.getCloverOutputFields();
DataFieldMetadata fieldMetadata;
String tableName = dbMeta.getTableName(1);
dbMetadata = new DataRecordMetadata(DataRecordMetadata.EMPTY_NAME, DataRecordParsingType.DELIMITED);
dbMetadata.setLabel(tableName);
dbMetadata.setFieldDelimiter(Defaults.Component.KEY_FIELDS_DELIMITER);
dbMetadata.setRecordDelimiter("\n");
for (int i = 1; i <= dbMeta.getColumnCount(); i++) {
fieldMetadata = SQLUtil.dbMetadata2jetel(fieldName[i], dbMeta, i, jdbcSpecific);
dbMetadata.addField(fieldMetadata);
}
dbMetadata.normalize();
}
}
DataRecord record = DataRecordFactory.newRecord(dbMetadata);
CopySQLData[] transMap = AbstractCopySQLData.sql2JetelTransMap(SQLUtil.getFieldTypes(dbMetadata, sqlConnection.getJdbcSpecific()),
dbMetadata, record, sqlConnection.getJdbcSpecific());
ArrayList<DataRecord> records = new ArrayList<DataRecord>();
while (resultSet.next()){
for (int i = 0; i < transMap.length; i++) {
transMap[i].sql2jetel(resultSet);
}
records.add(record.duplicate());
}
return records.iterator();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (resultSet != null)
resultSet.close();
} catch (SQLException e) {
// we ignore this, as we are only trying to close the stream after exception was thrown before
// - the orignal exception is the one the user is interested in, not this unsuccessful attempt
// to clean up
}
}
}
@Override
public Lookup createLookup(RecordKey key) throws ComponentNotReadyException {
return createLookup(key, null);
}
@Override
public Lookup createLookup(RecordKey key, DataRecord keyRecord) throws ComponentNotReadyException {
if (!isInitialized()) {
throw new NotInitializedException(this);
} else if ((sqlConnection == null) && (connection == null)) {
throw new NotInitializedException("No DB connection! (pre-execute initialization not performed?)", this);
} else if ((sqlConnection == null) && (connection != null)) {
try {
sqlConnection = connection.getConnection(getId(), OperationType.READ);
} catch (JetelException e) {
throw new ComponentNotReadyException("Can't connect to database", e);
}
}
DBLookup lookup;
key.setEqualNULLs(true); //see CLO-5786
try {
lookup = new DBLookup(new SQLCloverStatement(sqlConnection, sqlQuery, keyRecord, key.getKeyFieldNames()),
key, keyRecord);
} catch (SQLException e) {
throw new ComponentNotReadyException(this, e);
}
lookup.setLookupTable(this);
activeLookups.add(lookup);
return lookup;
}
@Override
public DataRecordMetadata getKeyMetadata() throws ComponentNotReadyException {
throw new UnsupportedOperationException("DBLookupTable does not provide key metadata.");
}
@Override
public boolean isPutSupported() {
return false;
}
@Override
public boolean isRemoveSupported() {
return false;
}
@Override
public boolean put(DataRecord dataRecord) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(DataRecord dataRecord) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(HashKey key) {
throw new UnsupportedOperationException();
}
@Override
public void setCurrentPhase(int phase) {
//isn't required by the lookup table
}
}
|
package edu.utah.sci.cyclist.ui.views;
import org.controlsfx.control.RangeSlider;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.MapProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleMapProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import edu.utah.sci.cyclist.Resources;
import edu.utah.sci.cyclist.event.dnd.DnD;
import edu.utah.sci.cyclist.model.Field;
import edu.utah.sci.cyclist.model.FieldProperties;
import edu.utah.sci.cyclist.model.Filter;
import edu.utah.sci.cyclist.model.Table;
import edu.utah.sci.cyclist.model.DataType.Role;
import edu.utah.sci.cyclist.model.Table.NumericRangeValues;
import edu.utah.sci.cyclist.ui.components.Spring;
import edu.utah.sci.cyclist.ui.panels.TitledPanel;
import edu.utah.sci.cyclist.util.SQL;
public class FilterPanel extends TitledPanel {
private Filter _filter;
private ListProperty<Object> _valuesProperty = new SimpleListProperty<>();
private VBox _cbBox;
private ProgressIndicator _indicator;
private Button _closeButton;
private Task<?> _task;
private boolean _reportChange = true;
private BooleanProperty _highlight = new SimpleBooleanProperty(false);
MapProperty<Object, Object> _map = new SimpleMapProperty<>();
private ObjectProperty<EventHandler<ActionEvent>> _closeAction = new SimpleObjectProperty<>();
public BooleanProperty highlight() {
return _highlight;
}
public void setHighlight(boolean value) {
_highlight.set(value);
}
public boolean getHighlight() {
return _highlight.get();
}
public FilterPanel(Filter filter) {
//super(filter.getName());
super(getTitle(filter));
_filter = filter;
build();
}
public Filter getFilter() {
return _filter;
}
public void setTask(Task<?> task) {
if (_task != null && _task.isRunning()) {
_task.cancel();
}
_task = task;
if (_task == null) {
_indicator.visibleProperty().unbind();
_indicator.setVisible(false);
} else {
_indicator.visibleProperty().bind(_task.runningProperty());
_indicator.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
System.out.println("Canceling task: "+_task.cancel());
}
});
}
}
/*
* Close
*/
public ObjectProperty<EventHandler<ActionEvent>> onCloseProperty() {
return _closeAction;
}
public EventHandler<ActionEvent> getOnClose() {
return _closeAction.get();
}
public void setOnClose(EventHandler<ActionEvent> handler) {
_closeAction.set(handler);
}
private void build() {
setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE);
final HBox header = getHeader();
_indicator = new ProgressIndicator();
_indicator.setProgress(-1);
_indicator.setMaxWidth(20);
_indicator.setMaxHeight(20);
_indicator.setVisible(false);
_closeButton = new Button();
_closeButton.getStyleClass().add("flat-button");
_closeButton.setGraphic(new ImageView(Resources.getIcon("close_view")));
_closeButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
setTask(null);
if(getOnClose() != null){
getOnClose().handle(e);
}
}
});
header.getChildren().addAll(_indicator, new Spring(), _closeButton);
header.setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Dragboard db = header.startDragAndDrop(TransferMode.MOVE);
DnD.LocalClipboard clipboard = DnD.getInstance().createLocalClipboard();
clipboard.put(DnD.FILTER_FORMAT, Filter.class, _filter);
ClipboardContent content = new ClipboardContent();
content.putString(_filter.getName());
SnapshotParameters snapParams = new SnapshotParameters();
snapParams.setFill(Color.TRANSPARENT);
content.putImage(header.getChildren().get(0).snapshot(snapParams, null));
db.setContent(content);
}
});
header.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
_highlight.set(!_highlight.get());
}
});
_highlight.addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean oldValue, Boolean newValue) {
System.out.println("highlight: "+newValue);
if (newValue)
getHeader().setStyle("-fx-background-color: #beffbf");
else
getHeader().setStyle("-fx-background-color: #e0e0ef");
}
});
configure();
}
private void configure() {
switch (_filter.getClassification()) {
case C:
createList();
break;
case Cdate:
break;
case Qd:
createRange();
break;
case Qi:
createList();
}
}
private void createList() {
_cbBox = new VBox();
_cbBox.setSpacing(4);
_cbBox.setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE);
setContent(_cbBox);
_valuesProperty.addListener(new InvalidationListener() {
@Override
public void invalidated(Observable arg0) {
populateValues();
}
});
_valuesProperty.bind(_filter.valuesProperty());
if (!_filter.isValid()) {
Field field = _filter.getField();
Table table = field.getTable();
Task<ObservableList<Object>> task = table.getFieldValues(field);
setTask(task);
field.valuesProperty().bind(task.valueProperty());
} else {
populateValues();
}
}
private void populateValues() {
_cbBox.getChildren().clear();
if (_valuesProperty.get() != null) {
_cbBox.getChildren().add(createAllEntry());
for (Object item: _valuesProperty.get()) {
_cbBox.getChildren().add(createEntry(item));
}
}
}
private Node createAllEntry() {
CheckBox cb = new CheckBox("All");
cb.setSelected(true);
cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean oldValue, Boolean newValue) {
_reportChange = false;
for (Node node : _cbBox.getChildren()) {
((CheckBox) node).setSelected(newValue);
}
_reportChange = true;
_filter.selectAll(newValue);
}
});
return cb;
}
private Node createEntry(final Object item) {
CheckBox cb = new CheckBox(item.toString());
cb.setSelected(_filter.isSelected(item));
cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean oldValue, Boolean newValue) {
if (_reportChange)
_filter.selectValue(item, newValue);
}
});
return cb;
}
/* Name: createRange
* For numerical Fields - get the possible minimum and maximum values of the field
* and creates a filter within that range */
private void createRange() {
_cbBox = new VBox();
_cbBox.setSpacing(4);
_cbBox.setPrefSize(USE_COMPUTED_SIZE,USE_COMPUTED_SIZE);
setContent(_cbBox);
_cbBox.setPadding(new Insets(0,8,0,8));
_map.addListener(new InvalidationListener() {
@Override
public void invalidated(Observable arg0) {
populateRangeValues();
}
});
_map.bind(_filter.rangeValuesProperty());
if (!_filter.isRangeValid()) {
Field field = _filter.getField();
Table table = field.getTable();
Task<ObservableMap<Object,Object>> task = table.getFieldRange(field);
setTask(task);
field.rangeValuesProperty().bind(task.valueProperty());
}
else{
populateRangeValues();
}
}
/* Name: populateRangeValues
* Populates a filter panel for a "measure" type filter.
* In this case there would be a range slider which displays the possible values in the range
* and the user can change the minimum and maximum values which are displayed */
private void populateRangeValues() {
_cbBox.getChildren().clear();
if (_map.get() != null) {
Double min = (Double) (_map.get(NumericRangeValues.MIN) != null ? _map.get(NumericRangeValues.MIN):0.0);
Double max = (Double) (_map.get(NumericRangeValues.MAX) != null ? _map.get(NumericRangeValues.MAX):0.0);
final RangeSlider rangeSlider = new RangeSlider(min,max,min,max);
rangeSlider.setShowTickLabels(true);
rangeSlider.setShowTickMarks(true);
//rangeSlider.setOrientation(Orientation.VERTICAL);
double currentWidth = this.widthProperty().doubleValue();
_cbBox.setPrefWidth(0.95*currentWidth);
double majorTicks = (rangeSlider.getMax()-rangeSlider.getMin())/4;
rangeSlider.setMajorTickUnit(majorTicks);
final HBox hbox = new HBox();
hbox.setSpacing(20);
final TextField minTxt = new TextField();
final TextField maxTxt = new TextField();
hbox.getChildren().addAll(minTxt, maxTxt);
hbox.setPrefWidth(currentWidth);
hbox.setSpacing(currentWidth-120);
minTxt.setPrefSize(80, 18);
maxTxt.setPrefSize(80, 18);
minTxt.setEditable(false);
maxTxt.setEditable(false);
minTxt.setAlignment(Pos.CENTER_LEFT);
maxTxt.setAlignment(Pos.CENTER_LEFT);
minTxt.setText(Double.toString(min));
maxTxt.setText(Double.toString(max));
_cbBox.getChildren().addAll(rangeSlider,hbox);
//Listen to the width property of the parent - so the slider width can be changed accordingly.
this.widthProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
double width = newValue.doubleValue();
_cbBox.setPrefWidth(0.95*width);
}
});
_cbBox.widthProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
double width = newValue.doubleValue();
hbox.setPrefWidth(width);
hbox.setSpacing(width-160);
}
});
// Change the filter's values according to the user new choice.
rangeSlider.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent e) {
_filter.selectMinMaxValues(rangeSlider.getLowValue(),rangeSlider.getHighValue());
}
});
// Update the text field to show the current value on the slider.
rangeSlider.setOnMouseDragged(new EventHandler<Event>() {
public void handle(Event e) {
minTxt.setText(Double.toString(rangeSlider.getLowValue()));
maxTxt.setText(Double.toString(rangeSlider.getHighValue()));
}
});
}
}
/* Name: getTitle
* Gets the filter name and function (if exists).
* If the filter is connected to a field, and the field has an aggregation function
* sets the filter panel header to display both the filter name and the function*/
private static String getTitle(Filter filter) {
String title = null;
if (filter.getRole() == Role.DIMENSION) {
title = filter.getName();
} else {
String funcName = filter.getField().get(FieldProperties.AGGREGATION_FUNC, String.class);
if (funcName == null){
funcName = filter.getField().get(FieldProperties.AGGREGATION_DEFAULT_FUNC, String.class);
filter.getField().set(FieldProperties.AGGREGATION_FUNC, funcName);
}
SQL.Function func = SQL.getFunction(funcName);
title = func.getLabel(filter.getName());
}
return title;
}
}
|
package components;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.swing.JEditorPane;
import javax.swing.JTree;
/**
*
* @author Fernanda Floriano Silva
*/
public class EditorDropTarget implements DropTargetListener, PropertyChangeListener {
/**
* Constructor
* @param pane
* @param tree
*/
EditorDropTarget(JEditorPane pane, JTree tree) {
this.pane = pane;
this.tree = tree;
pane.addPropertyChangeListener(this);
dropTarget = new DropTarget(pane, DnDConstants.ACTION_COPY_OR_MOVE, this, pane.isEnabled(), null);
}
/**
* Drag Enter
* @param dtde
*/
@Override
public void dragEnter(DropTargetDragEvent dtde) {
DnDUtils.debugPrintln("dragEnter, drop action = "
+ DnDUtils.showActions(dtde.getDropAction()));
checkTransferType(dtde);
boolean acceptedDrag = acceptOrRejectDrag(dtde);
dragUnderFeedback(dtde, acceptedDrag);
}
/**
* drag Exit
* @param dte
*/
@Override
public void dragExit(DropTargetEvent dte) {
DnDUtils.debugPrintln("DropTarget dragExit");
dragUnderFeedback(null, false);
}
/**
* drag Over
* @param dtde
*/
@Override
public void dragOver(DropTargetDragEvent dtde) {
DnDUtils.debugPrintln("DropTarget dragOver, drop action = "
+ DnDUtils.showActions(dtde.getDropAction()));
boolean acceptedDrag = acceptOrRejectDrag(dtde);
dragUnderFeedback(dtde, acceptedDrag);
}
/**
* Drop Action Changed
* @param dtde
*/
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
DnDUtils.debugPrintln("DropTarget dropActionChanged, drop action = "
+ DnDUtils.showActions(dtde.getDropAction()));
boolean acceptedDrag = acceptOrRejectDrag(dtde);
dragUnderFeedback(dtde, acceptedDrag);
}
/**
* Drop
* @param dtde
*/
@Override
public void drop(DropTargetDropEvent dtde) {
DnDUtils.debugPrintln("DropTarget drop, drop action = "
+ DnDUtils.showActions(dtde.getDropAction()));
if ((dtde.getDropAction() & DnDConstants.ACTION_COPY_OR_MOVE) != 0) {
dtde.acceptDrop(dtde.getDropAction());
Transferable transferable = dtde.getTransferable();
try {
boolean result = false;
if (draggingFile) {
result = dropFile(transferable);
} else {
result = dropContent(transferable, dtde);
}
dtde.dropComplete(result);
DnDUtils.debugPrintln("Drop completed, success: " + result);
} catch (Exception e) {
DnDUtils.debugPrintln("Exception while handling drop " + e);
dtde.rejectDrop();
}
} else {
DnDUtils.debugPrintln("Drop target rejected drop");
dtde.dropComplete(false);
}
}
/**
* Property Change
* @param evt
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (propertyName.equals("enabled")) {
dropTarget.setActive(pane.isEnabled());
}
}
/**
* Accept Or Reject Drag
* @param dtde
* @return boolean
*/
protected boolean acceptOrRejectDrag(DropTargetDragEvent dtde) {
int dropAction = dtde.getDropAction();
int sourceActions = dtde.getSourceActions();
boolean acceptedDrag = false;
DnDUtils.debugPrintln("\tSource actions are "
+ DnDUtils.showActions(sourceActions) + ", drop action is "
+ DnDUtils.showActions(dropAction));
if (!acceptableType
|| (sourceActions & DnDConstants.ACTION_COPY_OR_MOVE) == 0) {
DnDUtils.debugPrintln("Drop target rejecting drag");
dtde.rejectDrag();
} else if (!draggingFile && !pane.isEditable()) {
DnDUtils.debugPrintln("Drop target rejecting drag");
dtde.rejectDrag();
} else if ((dropAction & DnDConstants.ACTION_COPY_OR_MOVE) == 0) {
DnDUtils.debugPrintln("Drop target offering COPY");
dtde.acceptDrag(DnDConstants.ACTION_COPY);
acceptedDrag = true;
} else {
DnDUtils.debugPrintln("Drop target accepting drag");
dtde.acceptDrag(dropAction);
acceptedDrag = true;
}
return acceptedDrag;
}
/**
* Drag Under Feedback
* @param dtde
* @param acceptedDrag
*/
protected void dragUnderFeedback(DropTargetDragEvent dtde,
boolean acceptedDrag) {
if (dtde != null && acceptedDrag) {
Point location = dtde.getLocation();
pane.getCaret().setVisible(true);
pane.setCaretPosition(pane.viewToModel(location));
} else {
pane.getCaret().setVisible(false);
}
}
/**
* Check Transfer Type
* @param dtde
*/
protected void checkTransferType(DropTargetDragEvent dtde) {
acceptableType = false;
draggingFile = false;
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
acceptableType = true;
draggingFile = true;
}
acceptableType = true;
DnDUtils.debugPrintln("File type acceptable - " + acceptableType);
DnDUtils.debugPrintln("Dragging a file - " + draggingFile);
}
/**
* Drop File
* @param transferable
* @return boolean
* @throws IOException
* @throws UnsupportedFlavorException
* @throws MalformedURLException
*/
protected boolean dropFile(Transferable transferable) throws IOException,
UnsupportedFlavorException, MalformedURLException {
List fileList = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
File transferFile = (File) fileList.get(0);
final URL transferURL = transferFile.toURI().toURL();
DnDUtils.debugPrintln("File URL is " + transferURL);
pane.setPage(transferURL);
return true;
}
/**
* Drop Content
* @param transferable
* @param dtde
* @return boolean
*/
protected boolean dropContent(Transferable transferable,
DropTargetDropEvent dtde) {
if (!pane.isEditable()) {
return false;
}
try {
DataFlavor[] flavors = dtde.getCurrentDataFlavors();
DataFlavor selectedFlavor = null;
for (int i = 0; i < flavors.length; i++) {
DataFlavor flavor = flavors[i];
DnDUtils.debugPrintln("Drop MIME type " + flavor.getMimeType()
+ " is available");
if (flavor.equals(DataFlavor.stringFlavor)) {
selectedFlavor = flavor;
break;
}
}
if (selectedFlavor == null) {
return false;
}
DnDUtils.debugPrintln("Selected flavor is "
+ selectedFlavor.getHumanPresentableName());
// Get the transferable and then obtain the data
Object data = transferable.getTransferData(selectedFlavor);
DnDUtils.debugPrintln("Transfer data type is "
+ data.getClass().getName());
String insertData = null;
if (data instanceof InputStream) {
String charSet = selectedFlavor.getParameter("charset");
InputStream is = (InputStream) data;
byte[] bytes = new byte[is.available()];
is.read(bytes);
try {
insertData = new String(bytes, charSet);
} catch (UnsupportedEncodingException e) {
insertData = new String(bytes);
}
} else if (data instanceof String) {
insertData = (String) data;
}
if (insertData != null) {
int selectionStart = pane.getCaretPosition();
pane.replaceSelection(insertData);
pane.select(selectionStart, selectionStart
+ insertData.length());
return true;
}
return false;
} catch (Exception e) {
return false;
}
}
protected JEditorPane pane;
protected JTree tree;
protected DropTarget dropTarget;
protected boolean acceptableType;
protected boolean draggingFile;
}
|
package edu.mum.waa.group9.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ConnectionManager {
public static Connection getConnection() throws NamingException, SQLException {
Context ctx = new InitialContext();
return ((DataSource) ctx.lookup("jdbc/letsgodb")).getConnection();
}
public static void closeConnection(Connection con) throws SQLException {
if (con != null) {
con.close();
}
}
}
|
package eu.project.rapid.ac.rm;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import eu.project.rapid.common.Clone;
import eu.project.rapid.common.RapidConstants;
import eu.project.rapid.common.RapidConstants.REGIME;
import eu.project.rapid.common.RapidMessages;
import eu.project.rapid.utils.Configuration;
import eu.project.rapid.utils.Constants;
/**
* This class is the common component of the AC project. It takes care of registering with the DS.
* Is started by the first application that runs on the machine. When this class is started the
* first time it launches a server on the given port so the next application that tries to start the
* AC_RM again will fail. The AC_RM will register the client with the DS according to user
* preferences (build a GUI or through preference files). In particular, the AC_RM will choose to
* connect to the previous VM or to ask a new VM.
*
* @author sokol
*
*/
public class AC_RM {
private static final Logger log = LogManager.getLogger(AC_RM.class.getSimpleName());
private static Configuration config;
private Properties sharedPrefs;
private Clone vm;
// private String slamIp;
private long myId = -1;
private final String prevVmFileName = "prevVm.ser"; // The file where the VM will be stored for
// future use.
private String prevVmFilePath; // The full path of the file where the VM will
// be stored for future use.
private static boolean registerAsPrev;
public AC_RM() {
// Read the configuration file to know the DS IP, the DS Port, and the port where the AC_RM
// server should listen.
config = new Configuration(AC_RM.class.getSimpleName(), REGIME.AC);
registerAsPrev = config.isConnectToPrevVm();
prevVmFilePath = config.getRapidFolder() + File.separator + prevVmFileName;
sharedPrefs = new Properties();
// Read previously saved information, like userID, etc.
try {
FileInputStream sharedPrefIs = new FileInputStream(new File(config.getSharedPrefsFile()));
sharedPrefs.load(sharedPrefIs);
myId =
Long.parseLong(sharedPrefs.getProperty(Constants.USER_ID_KEY, Constants.USER_ID_DEFAULT));
} catch (IOException e) {
log.error("Could not open shared prefs file: " + e);
log.error("Will not be possible to ask for the prev vm, asking for a new one.");
registerAsPrev = false;
}
if (config.isConnectToPrevVm()) {
// Read the previously saved VM. If there is no previously saved VM, then the VM object
// still remains null, so we'll ask for a new one when registering with the DS.
readPrevVm();
}
}
private void handleNewClient(Socket clientSocket) {
new Thread(new ClientHandler(clientSocket)).start();
}
private boolean registerWithDsAndSlam() {
if (registerWithDs()) {
// register with SLAM
if (registerWithSlam(config.getSlamIp())) {
// Save the userID, etc.
savePrevParameters();
// Save the VM for future references.
saveVm();
return true;
} else {
log.info("Could not register with SLAM");
}
} else {
log.info("Could not register with DS");
}
return false;
}
/**
* Register to the DS.<br>
*
* If the VM is null then ask for a list of SLAMs that can provide a VM. Otherwise notify the DS
* that we want to connect to the previous VM.
*
* @throws IOException
* @throws UnknownHostException
* @throws ClassNotFoundException
*/
private boolean registerWithDs() {
log.info("Registering with DS " + config.getDsIp() + ":" + config.getDsPort());
try (Socket dsSocket = new Socket(config.getDsIp(), config.getDsPort());
ObjectOutputStream dsOut = new ObjectOutputStream(dsSocket.getOutputStream());
ObjectInputStream dsIn = new ObjectInputStream(dsSocket.getInputStream())) {
if (!registerAsPrev) { // Get a new VM
log.info("Registering as NEW with ID:" + myId + " with the DS...");
dsOut.writeByte(RapidMessages.AC_REGISTER_NEW_DS);
} else { // Register and ask for the previous VM
log.info("Registering as PREV with ID: " + myId + " with the DS...");
dsOut.writeByte(RapidMessages.AC_REGISTER_PREV_DS);
}
dsOut.writeLong(myId);
dsOut.writeInt(RapidConstants.OS.LINUX.ordinal());
dsOut.writeInt(RapidConstants.REGISTER_WITHOUT_QOS_PARAMS); // TODO QoS support to come in
// the future.
dsOut.flush();
// Receive message format: status (java byte), userId (java long), ipList (java object)
byte status = dsIn.readByte();
log.info("Return Status from DS: " + (status == RapidMessages.OK ? "OK" : "ERROR"));
if (status == RapidMessages.OK) {
myId = dsIn.readLong();
log.info("New userId is: " + myId);
// Receiving the SLAM IP
String slamIp = dsIn.readUTF();
log.info("slamIp: " + slamIp);
config.setSlamIp(slamIp);
return true;
}
} catch (IOException e) {
log.error("Could not connect with the DS: " + e);
}
return false;
}
private void savePrevParameters() {
sharedPrefs.setProperty(Constants.USER_ID_KEY, Long.toString(myId));
// The file containing preferences shared by all applications, like userID, etc.
try {
log.info("Saving properties in file: " + config.getSharedPrefsFile());
FileOutputStream sharedPrefsOs = new FileOutputStream(config.getSharedPrefsFile());
sharedPrefs.store(sharedPrefsOs, "Previous userID");
// sharedPrefsOs.close();
log.info("Finished saving properties in file");
} catch (FileNotFoundException e) {
log.error("Could not create or open the sharedPrefs file: " + e);
} catch (IOException e) {
log.error("Could not save the user parameters: " + e);
}
}
private void readPrevVm() {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(prevVmFilePath));) {
vm = (Clone) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
log.error("Could not read the VM: " + e);
}
}
private void saveVm() {
try (ObjectOutputStream oos =
new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(prevVmFilePath)));) {
oos.writeObject(vm);
} catch (IOException e) {
log.error("Could not store the VM: " + e);
}
}
// private void chooseBestSlam(List<String> slamIPs) {
// // FIXME Currently just choose the first one.
// log.info("Choosing the best SLAM from the list...");
// if (slamIPs == null || slamIPs.size() == 0) {
// throw new NoSuchElementException("Exptected at least one SLAM, don't know how to proceed!");
// } else {
// Iterator<String> ipListIterator = slamIPs.iterator();
// log.info("Received SLAM IP List: ");
// while (ipListIterator.hasNext()) {
// log.info(ipListIterator.next());
// config.setSlamIp(slamIPs.get(0));
/**
* FIXME Implement this after talking to Omer.
*
* @param slamIp
* @throws IOException
* @throws UnknownHostException
*/
private boolean registerWithSlam(String slamIp) {
log.info("Registering with SLAM " + config.getSlamIp() + ":" + config.getSlamPort());
try (Socket socket = new Socket(config.getSlamIp(), config.getSlamPort());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
oos.writeByte(RapidMessages.AC_REGISTER_SLAM);
oos.writeInt(RapidConstants.OS.LINUX.ordinal());
oos.writeLong(myId);
oos.flush();
int response = ois.readByte();
if (response == RapidMessages.OK) {
log.info("SLAM OK, getting the VM details");
String vmIp = ois.readUTF();
vm = new Clone("", vmIp);
vm.setId((int) myId);
return true;
} else if (response == RapidMessages.ERROR) {
log.error("SLAM registration replied with ERROR, VM will be null");
} else {
log.error(
"SLAM registration replied with uknown message " + response + ", VM will be null");
}
} catch (IOException e) {
log.error("Could not connect with the SLAM: " + e);
}
return false;
}
/**
* Handles the client requests, which are actually applications running on the same machine as the
* AC_RM is running.
*
* @author sokol
*
*/
private class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
// TODO Implement communication with the client, which is actually an application running on
// the same machine. The application will ask for info about the VM to connect to.
try (InputStream is = clientSocket.getInputStream();
OutputStream os = clientSocket.getOutputStream();
ObjectInputStream ois = new ObjectInputStream(is);
ObjectOutputStream oos = new ObjectOutputStream(os)) {
int command = -1;
do {
command = is.read();
log.info("Received command from app: " + command);
switch (command) {
case RapidMessages.AC_HELLO_AC_RM:
log.info("An app is asking for VM info
oos.writeLong(myId);
oos.writeObject(vm);
oos.flush();
break;
}
} while (command != -1);
} catch (IOException e) {
log.error("Error talking to the client (which is an app runnig on the same machine): " + e);
} finally {
try {
clientSocket.close();
log.info("Communication closed with client");
} catch (IOException e) {
log.error("Error while closing the socket: " + e);
}
}
}
}
public static void main(String[] args) {
log.info("Starting the AC_RM server");
AC_RM acRm = new AC_RM();
try (ServerSocket serverSocket = new ServerSocket(config.getAcRmPort())) {
log.info("Started server on port " + config.getAcRmPort());
// If it didn't throw an exception it means that this is the first instance of the AC_RM.
// This is responsible for registering with the DS.
boolean registered = false;
long waitToRegister = 2000;
int timesTriedRegistering = 0;
do {
registered = acRm.registerWithDsAndSlam();
timesTriedRegistering++;
if (!registered) {
log.info("Could not register with DS and SLAM, trying after " + waitToRegister + " ms");
try {
Thread.sleep(waitToRegister);
} catch (InterruptedException e) {
}
if (timesTriedRegistering >= 3) {
if (registerAsPrev) {
registerAsPrev = false;
timesTriedRegistering = 0;
} else {
waitToRegister *= 2;
}
}
}
} while (!registered);
while (true) {
Socket clientSocket = serverSocket.accept();
log.info("New client connected");
acRm.handleNewClient(clientSocket);
}
// else VM is null, so when we register with the DS we'll get a new one.
} catch (IOException e) {
if (e instanceof java.net.BindException) {
// If this exception is thrown, it means that the port is already in use by a previous
// instance of the AC_RM.
// The client should just connect to the listening server in that case.
log.warn("AC_RM is already running: " + e);
} else {
e.printStackTrace();
}
}
}
}
|
package com.ezardlabs.lostsector.objects.warframes;
import com.ezardlabs.dethsquare.Animation;
import com.ezardlabs.dethsquare.Animation.AnimationListener;
import com.ezardlabs.dethsquare.AnimationType;
import com.ezardlabs.dethsquare.Animator;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.TextureAtlas;
import com.ezardlabs.dethsquare.TextureAtlas.Sprite;
import com.ezardlabs.lostsector.Game;
import com.ezardlabs.lostsector.objects.Avatar;
import com.ezardlabs.lostsector.objects.Player;
import com.ezardlabs.lostsector.objects.hud.StatusIndicator;
import com.ezardlabs.lostsector.objects.weapons.MeleeWeapon;
import com.ezardlabs.lostsector.objects.weapons.RangedWeapon;
import java.util.Timer;
import java.util.TimerTask;
public abstract class Warframe extends Avatar {
protected final TextureAtlas ta;
protected final int maxShields;
protected int shields;
protected final int maxEnergy;
protected int energy;
public RangedWeapon rangedWeapon;
public MeleeWeapon meleeWeapon;
private StatusIndicator statusIndicator;
public Warframe(String name, int maxHealth, int maxShields, int maxEnergy) {
super(maxHealth);
this.maxShields = maxShields;
shields = maxShields;
this.maxEnergy = maxEnergy;
energy = maxEnergy;
ta = new TextureAtlas("images/warframes/" + name + "/atlas.png", "images/warframes/" + name + "/atlas.txt");
}
@Override
public void start() {
gameObject.renderer.setTextureAtlas(ta, 200, 200);
gameObject.animator.setAnimations(getIdleAnimation(), getRunAnimation(), getJumpAnimation(), getDoubleJumpAnimation(), getFallAnimation(), getLandAnimation(), getDieAnimation());
gameObject.animator.play("idle");
}
protected Animation getIdleAnimation() {
return new Animation("idle", new Sprite[]{ta.getSprite("idle0")}, AnimationType.ONE_SHOT, 0);
}
protected Animation getRunAnimation() {
return new Animation("run", new Sprite[]{ta.getSprite("run0"), ta.getSprite("run1"), ta.getSprite("run2"), ta.getSprite("run3"), ta.getSprite("run4"), ta.getSprite("run5")},
AnimationType.LOOP, 100);
}
protected Animation getJumpAnimation() {
return new Animation("jump", new Sprite[]{ta.getSprite("jump0")}, AnimationType.ONE_SHOT, 0);
}
protected Animation getDoubleJumpAnimation() {
return new Animation("doublejump",
new Sprite[]{ta.getSprite("jump1"), ta.getSprite("jump2"), ta.getSprite("jump3"), ta.getSprite("jump4"), ta.getSprite("jump5"), ta.getSprite("jump6"), ta.getSprite("jump7")},
AnimationType.ONE_SHOT, 50, new AnimationListener() {
@Override
public void onAnimatedStarted(Animator animator) {
}
@Override
public void onFrame(Animator animator, int frameNum) {
}
@Override
public void onAnimationFinished(Animator animator) {
animator.play("fall");
}
});
}
protected Animation getFallAnimation() {
return new Animation("fall", new Sprite[]{ta.getSprite("fall0"), ta.getSprite("fall1"), ta.getSprite("fall2")}, AnimationType.LOOP, 90);
}
protected Animation getLandAnimation() {
return new Animation("land", new Sprite[]{ta.getSprite("land0"), ta.getSprite("land1"), ta.getSprite("land2")}, AnimationType.ONE_SHOT, 100);
}
protected Animation getDieAnimation() {
return new Animation("die", new Sprite[]{ta.getSprite("die0"), ta.getSprite("die1"), ta.getSprite("die2"), ta.getSprite("die3"), ta.getSprite("die4")}, AnimationType.ONE_SHOT, 100, new
AnimationListener() {
@Override
public void onAnimatedStarted(Animator animator) {
gameObject.renderer.setOffsets(-200, -100);
gameObject.renderer.setSize(400, 300);
}
@Override
public void onFrame(Animator animator, int frameNum) {
}
@Override
public void onAnimationFinished(Animator animator) {
statusIndicator.spawnGravestone(transform.position);
GameObject.destroy(gameObject, 2000);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Game.createPlayer();
}
}, 2000);
}
});
}
public abstract void ability1();
public abstract void ability2();
public abstract void ability3();
public abstract void ability4();
public final void setPrimaryWeapon(RangedWeapon rangedWeapon) {
this.rangedWeapon = rangedWeapon;
gameObject.animator.addAnimations(rangedWeapon.getAnimation(ta));
}
public final void setMeleeWeapon(MeleeWeapon meleeWeapon) {
this.meleeWeapon = meleeWeapon;
gameObject.animator.addAnimations(meleeWeapon.getAnimations(ta));
}
public void setStatusIndicator(StatusIndicator statusIndicator) {
this.statusIndicator = statusIndicator;
statusIndicator.init();
}
public void addHealth(int health) {
this.health += health;
if (this.health > maxHealth) this.health = maxHealth;
if (statusIndicator != null) statusIndicator.setHealth(this.health);
}
public void removeHealth(int health) {
this.health -= health;
if (this.health < 0) {
this.health = 0;
gameObject.animator.play("die");
if (gameObject.getComponent(Player.class) != null) {
gameObject.getComponent(Player.class).dead = true;
}
gameObject.setTag(null);
Game.players = new GameObject[0];
}
if (statusIndicator != null) statusIndicator.setHealth(this.health);
}
public void addEnergy(int energy) {
this.energy += energy;
if (this.energy > maxEnergy) this.energy = maxEnergy;
if (statusIndicator != null) statusIndicator.setEnergy(this.energy);
}
public void removeEnergy(int energy) {
this.energy -= energy;
if (this.energy < 0) throw new Error("Energy cannot be reduced to below 0");
if (statusIndicator != null) statusIndicator.setEnergy(this.energy);
}
public boolean hasEnergy(int energy) {
return this.energy >= energy;
}
}
|
package com.googlecode.objectify.test;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Load;
import com.googlecode.objectify.annotation.Mapify;
import com.googlecode.objectify.mapper.Mapper;
import com.googlecode.objectify.test.entity.Trivial;
import com.googlecode.objectify.test.util.TestBase;
import com.googlecode.objectify.test.util.TestObjectify;
/**
* Test persisting of Map with @Mapify annotations
*/
public class MapifyTests extends TestBase
{
@Embed
public static class Thing {
String name;
Long weight;
public Thing() {}
public Thing(String name, Long weight) {
this.name = name;
this.weight = weight;
}
/** Simplistic implementation */
@Override
public boolean equals(Object other) {
return name.equals(((Thing)other).name) && weight.equals(((Thing)other).weight);
}
@Override
public String toString() {
return "Thing(name=" + name + ", weight=" + weight + ")";
}
}
public static class ThingMapper implements Mapper<Long, Thing> {
@Override
public Long getKey(Thing value) {
return value.weight;
}
}
@com.googlecode.objectify.annotation.Entity
public static class HasMapify {
@Id Long id;
@Mapify(ThingMapper.class)
Map<Long, Thing> things = new HashMap<Long, Thing>();
}
@Test
public void testMapify() throws Exception {
this.fact.register(HasMapify.class);
HasMapify hasMap = new HasMapify();
Thing thing0 = new Thing("foo", 123L);
hasMap.things.put(thing0.weight, thing0);
Thing thing1 = new Thing("bar", 456L);
hasMap.things.put(thing1.weight, thing1);
HasMapify fetched = this.putClearGet(hasMap);
assert hasMap.things.equals(fetched.things);
}
@Entity
public static class Top {
public @Id long id;
@Mapify(BottomMapper.class)
public Map<String, Bottom> bottoms = new HashMap<String, Bottom>();
public Top() {}
public Top(long id) { this.id = id; }
}
@Embed
public static class Bottom {
public @Load Top top;
public String name;
public Bottom() {}
}
public static class BottomMapper implements Mapper<String, Bottom> {
@Override
public String getKey(Bottom value) {
assert value.top != null; // this is the problem place
return value.name;
}
}
/**
* This is a perverse case that gives nasty trouble.
*/
@Test
public void testBidirectionalMapify() throws Exception
{
fact.register(Top.class);
TestObjectify ofy = fact.begin();
Top top = new Top(123);
Bottom bot = new Bottom();
bot.name = "foo";
bot.top = top;
top.bottoms.put(bot.name, bot);
ofy.put(top);
ofy.clear();
Top topFetched = ofy.load().entity(top).get();
assert topFetched.bottoms.size() == 1;
Bottom bottomFetched = topFetched.bottoms.get(bot.name);
assert bottomFetched.top.id == top.id;
assert bottomFetched.name.equals(bot.name);
}
public static class TrivialMapper implements Mapper<Key<Trivial>, Trivial> {
@Override
public Key<Trivial> getKey(Trivial value) {
return Key.create(Trivial.class, value.getId());
}
}
@com.googlecode.objectify.annotation.Entity
public static class HasMapifyTrivial {
@Id Long id;
@Mapify(TrivialMapper.class)
@Load
Map<Key<Trivial>, Trivial> trivials = new HashMap<Key<Trivial>, Trivial>();
}
/** Tests using mapify on entities */
@Test
public void testMapifyTrivials() throws Exception {
this.fact.register(Trivial.class);
this.fact.register(HasMapifyTrivial.class);
TestObjectify ofy = this.fact.begin();
Trivial triv = new Trivial("foo", 123L);
Key<Trivial> trivKey = ofy.save().entity(triv).now();
HasMapifyTrivial hasMap = new HasMapifyTrivial();
hasMap.trivials.put(trivKey, triv);
HasMapifyTrivial fetched = this.putClearGet(hasMap);
assert hasMap.trivials.get(trivKey).getSomeString().equals(fetched.trivials.get(trivKey).getSomeString());
}
}
|
package com.mobilesolutionworks.codex;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.SparseArray;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Codex
{
private static final int START_ACTION = 1;
private static final int UPDATE_PROPERTY = 2;
SparseArray<List<ActionHookHandler>> allHooks = new SparseArray<>();
SparseArray<List<PropertySubscriberHandler>> allSubscribers = new SparseArray<>();
SparseArray<PropertyHandler> allProperties = new SparseArray<>();
WeakReference<ArrayList<PropertySubscriberHandler>> _subscriberHandlers;
WeakReference<ArrayList<ActionHookHandler>> _actionHandlers;
final Handler mHandler;
final List<Object> mObjects;
boolean mUseWeakReference;
public Codex()
{
this(Looper.getMainLooper());
}
public Codex(Handler handler)
{
this(handler.getLooper());
}
public Codex(Looper looper)
{
mHandler = new Handler(looper, new CallbackImpl());
mObjects = new ArrayList<>();
}
public void weakenReference()
{
mUseWeakReference = true;
}
public void register(Object object)
{
if (!mUseWeakReference) mObjects.add(object);
SparseArray<List<ActionHookHandler>> hooks = ReflectionAnnotationProcessor.findActionHooks(object);
// register all hooks
int length = hooks.size();
for (int i = 0; i < length; i++)
{
int key = hooks.keyAt(i);
List<ActionHookHandler> registeredHooks = allHooks.get(key, new ArrayList<ActionHookHandler>());
List<ActionHookHandler> handlers = hooks.valueAt(i);
registeredHooks.addAll(handlers);
Collections.sort(registeredHooks);
allHooks.put(key, registeredHooks);
}
// check if the new object has property, and dispatch to existing property subscriber
SparseArray<PropertyHandler> properties = ReflectionAnnotationProcessor.findDefaultProperties(object);
if (properties != null && properties.size() != 0)
{
length = properties.size();
for (int i = 0; i < length; i++)
{
int key = properties.keyAt(i);
PropertyHandler handler = properties.valueAt(i);
allProperties.put(key, handler);
Object value;
try
{
value = handler.getProperty();
dispatchPropertyToSubscribers(value, allSubscribers.get(key));
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Property " + handler + "throws an exception", e);
}
}
}
// now get all property subscriber of the object
SparseArray<List<PropertySubscriberHandler>> subscribers = ReflectionAnnotationProcessor.findPropertySubscribers(object);
if (subscribers != null && subscribers.size() != 0)
{
length = subscribers.size();
for (int i = 0; i < length; i++)
{
int key = subscribers.keyAt(i);
List<PropertySubscriberHandler> handlers = subscribers.valueAt(i);
List<PropertySubscriberHandler> registeredHandlers = allSubscribers.get(key, new ArrayList<PropertySubscriberHandler>());
registeredHandlers.addAll(handlers);
allSubscribers.put(key, registeredHandlers);
}
}
// dispatch the properties to newly registered subscribers
if (subscribers != null && subscribers.size() != 0)
{
for (int i = 0; i < length; i++)
{
int key = subscribers.keyAt(i);
List<PropertySubscriberHandler> handlers = subscribers.valueAt(i);
PropertyHandler propertyHandler = allProperties.get(key);
if (propertyHandler != null)
{
try
{
Object value = propertyHandler.getProperty();
dispatchPropertyToSubscribers(value, handlers);
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Property " + propertyHandler + "throws an exception", e);
}
}
}
}
}
public void unregister(Object object)
{
if (!mUseWeakReference) mObjects.remove(object);
SparseArray<List<ActionHookHandler>> hooks = ReflectionAnnotationProcessor.findActionHooks(object);
int length = hooks.size();
if (length != 0)
{
for (int i = 0; i < length; i++)
{
int key = hooks.keyAt(i);
List<ActionHookHandler> handlers = hooks.valueAt(i);
List<ActionHookHandler> registeredHooks = allHooks.get(key);
registeredHooks.removeAll(handlers);
}
}
SparseArray<PropertyHandler> properties = ReflectionAnnotationProcessor.findDefaultProperties(object);
length = properties.size();
if (length != 0)
{
for (int i = 0; i < length; i++)
{
int key = properties.keyAt(i);
PropertyHandler handler = properties.valueAt(i);
PropertyHandler registeredHandler = allProperties.get(key);
if (handler.equals(registeredHandler))
{
allProperties.remove(key);
}
}
}
SparseArray<List<PropertySubscriberHandler>> subscribers = ReflectionAnnotationProcessor.findPropertySubscribers(object);
length = subscribers.size();
if (length != 0)
{
for (int i = 0; i < length; i++)
{
int key = subscribers.keyAt(i);
List<PropertySubscriberHandler> handlers = subscribers.valueAt(i);
List<PropertySubscriberHandler> registeredSubscribers = allSubscribers.get(key);
if (registeredSubscribers != null)
{
registeredSubscribers.removeAll(handlers);
}
}
}
}
/**
* Publish an action to the system and allow the hook to pick it up.
*/
public void startActionEnforced(Object object, String name, Object... args)
{
int key = (name + args.length).hashCode();
mHandler.obtainMessage(START_ACTION, key, 0, args).sendToTarget();
// if (Looper.myLooper() != mHandler.getLooper()) {
// } else {
// dispatchStartAction(key, args);
}
/**
* Publish an action to the system and allow the hook to pick it up.
*/
public void startAction(String name, Object... args)
{
int key = (name + args.length).hashCode();
mHandler.obtainMessage(START_ACTION, key, 0, args).sendToTarget();
// if (Looper.myLooper() != mHandler.getLooper()) {
// } else {
// dispatchStartAction(key, args);
}
/**
* Update specified property for this owner
*/
public void updateProperty(Object owner, String name)
{
int key = name.hashCode();
mHandler.obtainMessage(UPDATE_PROPERTY, key, 0, owner).sendToTarget();
// if (Looper.myLooper() != mHandler.getLooper()) {
// } else {
// dispatchUpdateProperty(owner, key);
}
private void dispatchPropertyToSubscribers(Object value, List<PropertySubscriberHandler> handlers)
{
if (handlers == null || handlers.isEmpty()) return;
if (_subscriberHandlers == null || _subscriberHandlers.get() == null)
{
_subscriberHandlers = new WeakReference<>(new ArrayList<PropertySubscriberHandler>());
}
ArrayList<PropertySubscriberHandler> list = _subscriberHandlers.get();
list.clear();
for (PropertySubscriberHandler h : handlers)
{
if (h.isReachable()) list.add(h);
}
handlers.retainAll(list);
for (PropertySubscriberHandler handler : new ArrayList<>(list))
{
try
{
handler.receiveProperty(value);
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Could not dispatch property " + value + " to " + handler, e);
}
}
}
private void dispatchStartAction(int key, Object[] args)
{
List<ActionHookHandler> handlers = allHooks.get(key);
if (handlers == null) return;
if (_actionHandlers == null || _actionHandlers.get() == null)
{
_actionHandlers = new WeakReference<>(new ArrayList<ActionHookHandler>());
}
ArrayList<ActionHookHandler> list = _actionHandlers.get();
list.clear();
for (ActionHookHandler h : handlers)
{
if (h.isReachable()) list.add(h);
}
handlers.retainAll(list);
for (ActionHookHandler handler : new ArrayList<>(list))
{
try
{
handler.actionHook(args);
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
}
private class CallbackImpl implements Handler.Callback
{
@Override
public boolean handleMessage(Message msg)
{
switch (msg.what)
{
case START_ACTION:
{
dispatchStartAction(msg.arg1, (Object[]) msg.obj);
break;
}
case UPDATE_PROPERTY:
{
dispatchUpdateProperty(msg.obj, msg.arg1);
break;
}
}
return true;
}
}
private void dispatchUpdateProperty(Object owner, int key)
{
PropertyHandler propertyHandler = allProperties.get(key);
if (propertyHandler != null)
{
if (!propertyHandler.isReachable())
{
allProperties.remove(key);
return;
}
if (propertyHandler.target.get() != owner)
{
throw new IllegalStateException("only owner can dispatch this property change");
}
List<PropertySubscriberHandler> handlers = allSubscribers.get(key);
try
{
Object value = propertyHandler.getProperty();
dispatchPropertyToSubscribers(value, handlers);
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Property " + propertyHandler + "throws an exception", e);
}
}
}
}
|
package com.qiniu.android.http;
import java.util.Locale;
/**
* HTTP
*/
public final class ResponseInfo {
public static final int InvalidArgument = -4;
public static final int InvalidFile = -3;
public static final int Cancelled = -2;
public static final int NetworkError = -1;
// <-- error code copy from ios
public static final int TimedOut = -1001;
public static final int UnknownHost = -1003;
public static final int CannotConnectToHost = -1004;
public static final int NetworkConnectionLost = -1005;
public final int statusCode;
public final String reqId;
public final String xlog;
/**
* cdn
*/
public final String xvia;
public final String error;
public final double duration;
public final String host;
public final String ip;
public final int port;
public ResponseInfo(int statusCode, String reqId, String xlog, String xvia, String host, String ip, int port, double duration, String error) {
this.statusCode = statusCode;
this.reqId = reqId;
this.xlog = xlog;
this.xvia = xvia;
this.host = host;
this.duration = duration;
this.error = error;
this.ip = ip;
this.port = port;
}
public static ResponseInfo cancelled() {
return new ResponseInfo(Cancelled, "", "", "", "", "", -1, 0, "cancelled by user");
}
public static ResponseInfo invalidArgument(String message) {
return new ResponseInfo(InvalidArgument, "", "", "", "", "", -1, 0,
message);
}
public static ResponseInfo fileError(Exception e) {
return new ResponseInfo(InvalidFile, "", "", "", "", "", -1,
0, e.getMessage());
}
public boolean isCancelled() {
return statusCode == Cancelled;
}
public boolean isOK() {
return statusCode == 200 && error == null && reqId != null;
}
public boolean isNetworkBroken() {
return statusCode == NetworkError || statusCode == UnknownHost
|| statusCode == CannotConnectToHost || statusCode == TimedOut
|| statusCode == NetworkConnectionLost;
}
public boolean isServerError() {
return (statusCode >= 500 && statusCode < 600 && statusCode != 579)
|| statusCode == 996;
}
public boolean needSwitchServer() {
return isNetworkBroken() || isServerError();
}
public boolean needRetry() {
return !isCancelled() && (needSwitchServer() || statusCode == 406
|| (statusCode == 200 && error != null));
}
public String toString() {
return String.format(Locale.ENGLISH, "{ResponseInfo:%s,status:%d, reqId:%s, xlog:%s, xvia:%s, host:%s, ip:%s, port:%d, duration:%f s, error:%s}",
super.toString(), statusCode, reqId, xlog, xvia, host, ip, port, duration, error);
}
}
|
package play.mvc;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import play.api.mvc.MultipartFormData;
import play.core.formatters.Multipart;
import scala.Option;
import java.nio.charset.Charset;
import java.util.concurrent.ThreadLocalRandom;
public class MultipartFormatter {
public static String randomBoundary() {
return Multipart.randomBoundary(18, ThreadLocalRandom.current());
}
public static String boundaryToContentType(String boundary) {
return "multipart/form-data; boundary=" + boundary;
}
public static Source<ByteString, ?> transform(
Source<? super Http.MultipartFormData.Part<Source<ByteString, ?>>, ?> parts,
String boundary) {
@SuppressWarnings("unchecked")
Source<MultipartFormData.Part<akka.stream.scaladsl.Source<ByteString, ?>>, ?> source =
parts.map(
part -> {
if (part instanceof Http.MultipartFormData.DataPart) {
Http.MultipartFormData.DataPart dp = (Http.MultipartFormData.DataPart) part;
return (MultipartFormData.Part)
new MultipartFormData.DataPart(dp.getKey(), dp.getValue());
} else if (part instanceof Http.MultipartFormData.FilePart) {
Http.MultipartFormData.FilePart<?> fp = (Http.MultipartFormData.FilePart<?>) part;
if (fp.ref instanceof Source) {
Source<ByteString, ?> ref = (Source<ByteString, ?>) fp.ref;
Option<String> ct = Option.apply(fp.getContentType());
return new MultipartFormData.FilePart<akka.stream.scaladsl.Source<ByteString, ?>>(
fp.getKey(),
fp.getFilename(),
ct,
ref.asScala(),
fp.getFileSize(),
fp.getDispositionType());
}
}
throw new UnsupportedOperationException("Unsupported Part Class");
});
return source.via(Multipart.format(boundary, Charset.defaultCharset(), 4096));
}
}
|
package com.facebook.litho;
import android.support.v4.util.Pools;
import android.support.v4.util.Pools.Pool;
import android.support.v4.util.SimpleArrayMap;
import javax.annotation.Nullable;
/**
* Keeps the {@link Component} and its information that will allow the framework
* to understand how to render it.
*
* SpanSize will be defaulted to 1. It is the information that is required to calculate
* how much of the SpanCount the component should occupy in a Grid layout.
*
* IsSticky will be defaulted to false. It determines if the component should be
* a sticky header or not
*/
public class ComponentInfo {
public static final String CLIP_CHILDREN = "clip_children";
private static final Pool<Builder> sBuilderPool = new Pools.SynchronizedPool<>(2);
private static final String IS_STICKY = "is_sticky";
private static final String SPAN_SIZE = "span_size";
private final @Nullable Component mComponent;
private final @Nullable SimpleArrayMap<String, Object> mCustomAttributes;
public static Builder create() {
Builder builder = sBuilderPool.acquire();
if (builder == null) {
builder = new Builder();
}
return builder;
}
public static ComponentInfo createEmpty() {
return new ComponentInfo();
}
private ComponentInfo(Builder builder) {
mComponent = builder.mComponent;
mCustomAttributes = builder.mCustomAttributes;
}
private ComponentInfo() {
mComponent = null;
mCustomAttributes = null;
}
public @Nullable Component getComponent() {
return mComponent;
}
public boolean isSticky() {
if (mCustomAttributes == null || !mCustomAttributes.containsKey(IS_STICKY)) {
return false;
}
return (boolean) mCustomAttributes.get(IS_STICKY);
}
public int getSpanSize() {
if (mCustomAttributes == null || !mCustomAttributes.containsKey(SPAN_SIZE)) {
return 1;
}
return (int) mCustomAttributes.get(SPAN_SIZE);
}
public @Nullable Object getCustomAttribute(String key) {
return mCustomAttributes == null ? null : mCustomAttributes.get(key);
}
public static class Builder {
private @Nullable Component mComponent;
private @Nullable SimpleArrayMap<String, Object> mCustomAttributes;
private Builder() {
mComponent = null;
}
public Builder component(Component component) {
mComponent = component;
return this;
}
public Builder isSticky(boolean isSticky) {
return customAttribute(IS_STICKY, isSticky);
}
public Builder spanSize(int spanSize) {
return customAttribute(SPAN_SIZE, spanSize);
}
public Builder customAttribute(String key, Object value) {
if (mCustomAttributes == null) {
mCustomAttributes = new SimpleArrayMap<>();
}
mCustomAttributes.put(key, value);
return this;
}
public ComponentInfo build() {
ComponentInfo componentInfo = new ComponentInfo(this);
release();
return componentInfo;
}
private void release() {
mComponent = null;
mCustomAttributes = null;
sBuilderPool.release(this);
}
}
}
|
package org.epnoi.harvester;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.processor.idempotent.FileIdempotentRepository;
import org.apache.camel.spring.SpringCamelContext;
import org.epnoi.harvester.routes.converter.FileTypeConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import java.io.File;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
@Configuration("harvester")
@ComponentScan({"org.epnoi.harvester","org.epnoi.storage","org.epnoi.eventbus"})
@PropertySource({"classpath:harvester.properties","classpath:eventbus.properties","classpath:storage.properties"})
public class Config {
@Autowired
List<RouteBuilder> builders;
@Autowired
private Environment env;
@Value("${epnoi.harvester.folder.input}")
String inputFolder;
@Value("${epnoi.eventbus.host}")
private String host;
@Value("${epnoi.eventbus.port}")
private String port;
@Value("${epnoi.eventbus.user}")
private String user;
@Value("${epnoi.eventbus.password}")
private String pwd;
@Value("${epnoi.eventbus.keyspace}")
private String keyspace;
@Value("${epnoi.eventbus.protocol}")
private String protocol;
@Bean
public SpringCamelContext camelContext(ApplicationContext applicationContext) throws Exception {
SpringCamelContext camelContext = new SpringCamelContext(applicationContext);
for(RouteBuilder builder : builders){
camelContext.addRoutes(builder);
}
return camelContext;
}
//To resolve ${} in @Value
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean(name = "fileStore")
public FileIdempotentRepository getFileStore(){
FileIdempotentRepository repository = new FileIdempotentRepository();
repository.setFileStore(new File(inputFolder+File.separator+".fileStore.dat"));
repository.setMaxFileStoreSize(512000);
repository.setCacheSize(1000);
return repository;
}
@Bean(name="customConnectionFactory")
public ConnectionFactory getCustomConnectionFactory() throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setAutomaticRecoveryEnabled(true);
String uri = new StringBuilder().
append(protocol).append("://").append(user).append(":").append(pwd).
append("@").append(host).append(":").append(port).
append("/").append(keyspace).toString();
connectionFactory.setUri(uri);
return connectionFactory;
}
}
|
package bisq.core.dao.node.lite;
import bisq.core.btc.wallet.BsqWalletService;
import bisq.core.dao.node.BsqNode;
import bisq.core.dao.node.explorer.ExportJsonFilesService;
import bisq.core.dao.node.full.RawBlock;
import bisq.core.dao.node.lite.network.LiteNodeNetworkService;
import bisq.core.dao.node.messages.GetBlocksResponse;
import bisq.core.dao.node.messages.NewBlockBroadcastMessage;
import bisq.core.dao.node.parser.BlockParser;
import bisq.core.dao.node.parser.exceptions.RequiredReorgFromSnapshotException;
import bisq.core.dao.state.DaoStateService;
import bisq.core.dao.state.DaoStateSnapshotService;
import bisq.network.p2p.P2PService;
import bisq.network.p2p.network.Connection;
import bisq.common.Timer;
import bisq.common.UserThread;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
/**
* Main class for lite nodes which receive the BSQ transactions from a full node (e.g. seed nodes).
* Verification of BSQ transactions is done also by the lite node.
*/
@Slf4j
public class LiteNode extends BsqNode {
private static final int CHECK_FOR_BLOCK_RECEIVED_DELAY_SEC = 10;
private final LiteNodeNetworkService liteNodeNetworkService;
private final BsqWalletService bsqWalletService;
private Timer checkForBlockReceivedTimer;
// Constructor
@SuppressWarnings("WeakerAccess")
@Inject
public LiteNode(BlockParser blockParser,
DaoStateService daoStateService,
DaoStateSnapshotService daoStateSnapshotService,
P2PService p2PService,
LiteNodeNetworkService liteNodeNetworkService,
BsqWalletService bsqWalletService,
ExportJsonFilesService exportJsonFilesService) {
super(blockParser, daoStateService, daoStateSnapshotService, p2PService, exportJsonFilesService);
this.liteNodeNetworkService = liteNodeNetworkService;
this.bsqWalletService = bsqWalletService;
}
// Public methods
@Override
public void start() {
super.onInitialized();
liteNodeNetworkService.start();
bsqWalletService.addNewBestBlockListener(block -> {
int height = block.getHeight();
log.info("New block at height {} from bsqWalletService", height);
// Check if we are done with parsing
if (!daoStateService.isParseBlockChainComplete())
return;
if (checkForBlockReceivedTimer != null) {
// In case we received a new block before out timer gets called we stop the old timer
checkForBlockReceivedTimer.stop();
}
// We expect to receive the new BSQ block from the network shortly after BitcoinJ has been aware of it.
// If we don't receive it we request it manually from seed nodes
checkForBlockReceivedTimer = UserThread.runAfter(() -> {
int chainHeight = daoStateService.getChainHeight();
if (chainHeight < height) {
log.warn("We did not receive a block from the network {} seconds after we saw the new block in BicoinJ. " +
"We request from our seed nodes missing blocks from block height {}.",
CHECK_FOR_BLOCK_RECEIVED_DELAY_SEC, chainHeight + 1);
liteNodeNetworkService.requestBlocks(chainHeight + 1);
}
}, CHECK_FOR_BLOCK_RECEIVED_DELAY_SEC);
});
}
@Override
public void shutDown() {
super.shutDown();
liteNodeNetworkService.shutDown();
}
// Protected
@Override
protected void onP2PNetworkReady() {
super.onP2PNetworkReady();
liteNodeNetworkService.addListener(new LiteNodeNetworkService.Listener() {
@Override
public void onRequestedBlocksReceived(GetBlocksResponse getBlocksResponse, Runnable onParsingComplete) {
LiteNode.this.onRequestedBlocksReceived(new ArrayList<>(getBlocksResponse.getBlocks()),
onParsingComplete);
}
@Override
public void onNewBlockReceived(NewBlockBroadcastMessage newBlockBroadcastMessage) {
LiteNode.this.onNewBlockReceived(newBlockBroadcastMessage.getBlock());
}
@Override
public void onNoSeedNodeAvailable() {
}
@Override
public void onFault(String errorMessage, @Nullable Connection connection) {
}
});
if (!parseBlockchainComplete)
startParseBlocks();
}
// First we request the blocks from a full node
@Override
protected void startParseBlocks() {
log.info("startParseBlocks");
liteNodeNetworkService.requestBlocks(getStartBlockHeight());
}
@Override
protected void startReOrgFromLastSnapshot() {
super.startReOrgFromLastSnapshot();
int startBlockHeight = getStartBlockHeight();
liteNodeNetworkService.reset();
liteNodeNetworkService.requestBlocks(startBlockHeight);
}
// Private
// We received the missing blocks
private void onRequestedBlocksReceived(List<RawBlock> blockList, Runnable onParsingComplete) {
if (!blockList.isEmpty()) {
chainTipHeight = blockList.get(blockList.size() - 1).getHeight();
log.info("We received blocks from height {} to {}", blockList.get(0).getHeight(), chainTipHeight);
}
// We delay the parsing to next render frame to avoid that the UI get blocked in case we parse a lot of blocks.
// Parsing itself is very fast (3 sec. for 7000 blocks) but creating the hash chain slows down batch processing a lot
// (30 sec for 7000 blocks).
// The updates at block height change are not much optimized yet, so that can be for sure improved
// 144 blocks a day would result in about 4000 in a month, so if a user downloads the app after 1 months latest
// release it will be a bit of a performance hit. It is a one time event as the snapshots gets created and be
// used at next startup. New users will get the shipped snapshot. Users who have not used Bisq for longer might
// experience longer durations for batch processing.
long ts = System.currentTimeMillis();
if (blockList.isEmpty()) {
onParseBlockChainComplete();
return;
}
runDelayedBatchProcessing(new ArrayList<>(blockList),
() -> {
log.info("Parsing {} blocks took {} seconds.", blockList.size(), (System.currentTimeMillis() - ts) / 1000d);
if (daoStateService.getChainHeight() < bsqWalletService.getBestChainHeight()) {
liteNodeNetworkService.requestBlocks(getStartBlockHeight());
} else {
onParsingComplete.run();
onParseBlockChainComplete();
}
});
}
private void runDelayedBatchProcessing(List<RawBlock> blocks, Runnable resultHandler) {
UserThread.execute(() -> {
if (blocks.isEmpty()) {
resultHandler.run();
return;
}
RawBlock block = blocks.remove(0);
try {
doParseBlock(block);
runDelayedBatchProcessing(blocks, resultHandler);
} catch (RequiredReorgFromSnapshotException e) {
resultHandler.run();
}
});
}
// We received a new block
private void onNewBlockReceived(RawBlock block) {
int blockHeight = block.getHeight();
log.info("onNewBlockReceived: block at height {}, hash={}", blockHeight, block.getHash());
// We only update chainTipHeight if we get a newer block
if (blockHeight > chainTipHeight)
chainTipHeight = blockHeight;
try {
doParseBlock(block);
} catch (RequiredReorgFromSnapshotException ignore) {
}
maybeExportToJson();
}
}
|
package cgeo.geocaching.activity;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.ShareUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;
public abstract class TabbedViewPagerFragment<ViewBindingClass extends ViewBinding> extends Fragment {
protected ViewBindingClass binding;
protected ViewGroup container;
private boolean contentIsUpToDate = false;
private final Integer mutextContentIsUpToDate = 0;
public TabbedViewPagerFragment() {
Log.d("new fragment for " + getClass().toString());
}
public void setClickListener(final View view, final String url) {
final Activity activity = getActivity();
if (activity != null) {
view.setOnClickListener(v -> ShareUtils.openUrl(activity, url));
}
}
@Override
public void onAttach(@NonNull final Activity activity) {
super.onAttach(activity);
// notify TabbedViewPagerActivity to help it rebuild the fragment cache
((TabbedViewPagerActivity) activity).registerFragment(getPageId(), this);
}
public abstract ViewBindingClass createView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
public abstract void setContent();
public abstract long getPageId();
@Override
public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
binding = createView(inflater, container, savedInstanceState);
binding.getRoot().setVisibility(View.GONE);
this.container = container;
synchronized (mutextContentIsUpToDate) {
contentIsUpToDate = false;
setContent();
contentIsUpToDate = true;
}
return binding.getRoot();
}
public void notifyDataSetChanged() {
synchronized (mutextContentIsUpToDate) {
contentIsUpToDate = false;
// do an update anyway to catch situations where currently active view gets updated (and thus no onResume gets called)
setContent();
}
}
@Override
public void onResume() {
super.onResume();
synchronized (mutextContentIsUpToDate) {
Log.d("onResume: update=" + (!contentIsUpToDate) + " " + getClass().getName());
if (!contentIsUpToDate) {
setContent();
contentIsUpToDate = true;
}
}
}
// Fragment lifecycle methods - for testing purposes
/*
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("onCreate " + getClass().toString());
}
// onCreateView(), see above
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.e("onViewCreated " + getClass().toString());
}
@Override
public void onStart() {
super.onStart();
Log.e("onStart " + getClass().toString());
}
// onResume(), see above
@Override
public void onPause() {
Log.e("onPause " + getClass().toString());
super.onPause();
}
@Override
public void onStop() {
Log.e("onStop " + getClass().toString());
super.onStop();
}
@Override
public void onDestroyView() {
Log.e("onDestroyView " + getClass().toString());
super.onDestroyView();
}
@Override
public void onDestroy() {
Log.e("onDestroy " + getClass().toString());
super.onDestroy();
}
*/
}
|
package com.example.flink;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.graph.Edge;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.GraphAlgorithm;
import org.apache.flink.graph.Vertex;
import org.apache.flink.graph.pregel.ComputeFunction;
import org.apache.flink.graph.pregel.MessageCombiner;
import org.apache.flink.graph.pregel.MessageIterator;
import java.util.Arrays;
import java.util.List;
public class PregelShortestPath {
public static void main(String... args) throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
List<Vertex<Integer, String>> vertices = Arrays.asList(
new Vertex<>(1, "1"),
new Vertex<>(2, "2"),
new Vertex<>(3, "3"),
new Vertex<>(4, "4"),
new Vertex<>(5, "5")
);
List<Edge<Integer, Double>> edges = Arrays.asList(
new Edge<>(1, 2, 2.0),
new Edge<>(1, 3, 7.0),
new Edge<>(2, 3, 2.0),
new Edge<>(3, 2, 5.0),
new Edge<>(2, 4, 4.0),
new Edge<>(3, 4, 6.0),
new Edge<>(3, 5, 3.0),
new Edge<>(4, 5, 4.0),
new Edge<>(5, 4, 1.0),
new Edge<>(5, 1, 8.0)
);
Graph<Integer, String, Double> graph = Graph.fromCollection(vertices, edges, env);
graph.run(new ShortestPath<>(1, 10)).print();
}
}
class ShortestPath<K, VV> implements GraphAlgorithm<K, VV, Double, DataSet<Vertex<K, Double>>> {
private final K sourceVertex;
private final int maxIterations;
public ShortestPath(K sourceVertex, int maxIterations) {
this.sourceVertex = sourceVertex;
this.maxIterations = maxIterations;
}
@Override
public DataSet<Vertex<K, Double>> run(Graph<K, VV, Double> graph) throws Exception {
Graph<K, Double, Double> resultGraph = graph.mapVertices(new ShortestPathInit<>(sourceVertex))
.runVertexCentricIteration(new ShortestPathComputeFunction(sourceVertex),
new ShortestPathCombiner(),
maxIterations);
return resultGraph.getVertices();
}
private static class ShortestPathInit<K, VV> implements MapFunction<Vertex<K,VV>, Double> {
private final K sourceVertex;
public ShortestPathInit(K sourceVertex) {
this.sourceVertex = sourceVertex;
}
@Override
public Double map(Vertex<K, VV> vertex) throws Exception {
if (vertex.getId().equals(sourceVertex)) {
return 0d;
}
return Double.MAX_VALUE;
}
}
}
class ShortestPathComputeFunction<K> extends ComputeFunction<K, Double, Double, NewMinDistance> {
private final K sourceVertex;
public ShortestPathComputeFunction(K sourceVertex) {
this.sourceVertex = sourceVertex;
}
@Override
public void compute(Vertex<K, Double> vertex, MessageIterator<NewMinDistance> messageIterator) throws Exception {
// Send initial group of messages from the source vertex
if (vertex.getId().equals(sourceVertex) && getSuperstepNumber() == 1) {
sendNewDistanceToAll(0);
}
// Calculate new min distance from source node
double minDistance = minDistance(messageIterator);
// Send new min distance to neighbour vertices if new min distance is less
if (minDistance < vertex.getValue()) {
setNewVertexValue(minDistance);
sendNewDistanceToAll(minDistance);
}
}
private double minDistance(MessageIterator<NewMinDistance> messageIterator) {
double minDistance = Double.MAX_VALUE;
for (NewMinDistance message : messageIterator) {
minDistance = Math.min(message.getDistance(), minDistance);
}
return minDistance;
}
private void sendNewDistanceToAll(double newDistance) {
for (Edge<K, Double> edge : getEdges()) {
sendMessageTo(edge.getTarget(), new NewMinDistance(edge.getValue() + newDistance));
}
}
}
/**
* Message that contains new value of minimal distances for a particular path.
*/
class NewMinDistance {
private final double distance;
public NewMinDistance(double distance) {
this.distance = distance;
}
public double getDistance() {
return distance;
}
}
/**
* Combine multiple outgoing messages directed to the same vertex.
* @param <K>
*/
class ShortestPathCombiner<K> extends MessageCombiner<K, NewMinDistance> {
@Override
public void combineMessages(MessageIterator<NewMinDistance> messageIterator) throws Exception {
double minDistance = Double.MAX_VALUE;
for (NewMinDistance message : messageIterator) {
minDistance = Math.min(message.getDistance(), minDistance);
}
sendCombinedMessage(new NewMinDistance(minDistance));
}
}
|
package edu.brandeis.cs.steele.wn;
import java.util.*;
import java.util.logging.*;
/** A <code>Synset</code>, or <b>syn</b>onym <b>set</b>, represents a line of a WordNet <var>pos</var><code>.data</code> file.
* A <code>Synset</code> represents a concept, and contains a set of {@link WordSense}s, each of which has a sense
* that names that concept (and each of which is therefore synonymous with the other <code>WordSense</code>s in the
* <code>Synset</code>).
*
* <p><code>Synset</code>'s are linked by {@link Pointer}s into a network of related concepts; this is the <i>Net</i>
* in WordNet. {@link Synset#getTargets Synset.getTargets()} retrieves the targets of these links, and
* {@link Synset#getPointers Synset.getPointers()} retrieves the pointers themselves.
*
* @see WordSense
* @see Pointer
* @author Oliver Steele, steele@cs.brandeis.edu
* @version 1.0
*/
public class Synset implements PointerTarget, Comparable<Synset>, Iterable<WordSense> {
private static final Logger log = Logger.getLogger(Synset.class.getName());
// Instance implementation
/** offset in <code>data.</code><var>pos</var> file */
private final int offset;
private final WordSense[] wordSenses;
private final Pointer[] pointers;
//TODO make this a byte[]
private final char[] gloss;
private final byte posOrdinal;
private final byte lexfilenum;
private final boolean isAdjectiveCluster;
// Constructor
@SuppressWarnings("deprecation") // using Character.isSpace() for file compat
Synset(final String line) {
final CharSequenceTokenizer tokenizer = new CharSequenceTokenizer(line, " ");
this.offset = tokenizer.nextInt();
final int lexfilenumInt = tokenizer.nextInt();
// there are currently only 45 lexfiles
// disable assert to be lenient generated WordNets
//assert lexfilenumInt < 45 : "lexfilenumInt: "+lexfilenumInt;
this.lexfilenum = (byte)lexfilenumInt;
CharSequence ss_type = tokenizer.nextToken();
if ("s".contentEquals(ss_type)) {
ss_type = "a";
this.isAdjectiveCluster = true;
} else {
this.isAdjectiveCluster = false;
}
this.posOrdinal = (byte) POS.lookup(ss_type).ordinal();
final int wordCount = tokenizer.nextHexInt();
this.wordSenses = new WordSense[wordCount];
for (int i = 0; i < wordCount; i++) {
String lemma = tokenizer.nextToken().toString();
final int lexid = tokenizer.nextHexInt();
int flags = 0;
// strip the syntactic marker, e.g. "(a)" || "(ip)" || ...
final int lparenIdx;
if (lemma.charAt(lemma.length() - 1) == ')' &&
(lparenIdx = lemma.lastIndexOf('(')) > 0) {
final int rparenIdx = lemma.length() - 1;
assert ')' == lemma.charAt(rparenIdx);
//TODO use String.regionMatches() instead of creating 'marker'
final String marker = lemma.substring(lparenIdx + 1, rparenIdx);
lemma = lemma.substring(0, lparenIdx);
if (marker.equals("p")) {
flags |= WordSense.AdjPosition.PREDICATIVE.flag;
} else if (marker.equals("a")) {
flags |= WordSense.AdjPosition.ATTRIBUTIVE.flag;
} else if (marker.equals("ip")) {
flags |= WordSense.AdjPosition.IMMEDIATE_POSTNOMINAL.flag;
} else {
throw new RuntimeException("unknown syntactic marker " + marker);
}
}
wordSenses[i] = new WordSense(this, lemma.replace('_', ' '), lexid, flags);
}
final int pointerCount = tokenizer.nextInt();
this.pointers = new Pointer[pointerCount];
for (int i = 0; i < pointerCount; i++) {
pointers[i] = new Pointer(this, i, tokenizer);
}
if (posOrdinal == POS.VERB.ordinal()) {
final int f_cnt = tokenizer.nextInt();
for (int i = 0; i < f_cnt; i++) {
final CharSequence skip = tokenizer.nextToken();
assert "+".contentEquals(skip) : "skip: "+skip;
final int f_num = tokenizer.nextInt();
final int w_num = tokenizer.nextHexInt();
if (w_num > 0) {
wordSenses[w_num - 1].setVerbFrameFlag(f_num);
} else {
for (int j = 0; j < wordSenses.length; j++) {
wordSenses[j].setVerbFrameFlag(f_num);
}
}
}
}
// parse gloss
final int index = line.indexOf('|');
if (index > 0) {
// jump '|' and immediately following ' '
assert line.charAt(index + 1) == ' ';
int incEnd = line.length() - 1;
for (int i = incEnd; i >= 0; i
if (Character.isSpace(line.charAt(i)) == false) {
incEnd = i;
break;
}
}
final int finalLen = (incEnd + 1) - (index + 2);
if (finalLen > 0) {
this.gloss = new char[finalLen];
assert gloss.length == finalLen: "gloss.length: "+gloss.length+" finalLen: "+finalLen;
line.getChars(index + 2, incEnd + 1, gloss, 0);
} else {
// synset with no gloss (support generated WordNets)
this.gloss = new char[0];
}
} else {
log.log(Level.SEVERE, "Synset has no gloss?:\n" + line);
this.gloss = null;
}
}
// Accessors
public POS getPOS() {
return POS.fromOrdinal(posOrdinal);
}
boolean isAdjectiveCluster() {
return isAdjectiveCluster;
}
int lexfilenum() {
return lexfilenum;
}
public String getLexCategory() {
final FileBackedDictionary dictionary = FileBackedDictionary.getInstance();
return dictionary.lookupLexCategory(lexfilenum());
}
public String getGloss() {
return new String(gloss);
}
public WordSense[] getWordSenses() {
return wordSenses;
}
/**
* If <var>word</var> is a member of this <code>Synset</code>, return the
* <code>WordSense</code> it implies, else return <code>null</code>.
*/
public WordSense getWordSense(final Word word) {
for (final WordSense wordSense : wordSenses) {
if (wordSense.getLemma().equalsIgnoreCase(word.getLemma())) {
return wordSense;
}
}
return null;
}
/** {@inheritDoc} */
public Iterator<WordSense> iterator() {
return Arrays.asList(wordSenses).iterator();
}
int getOffset() {
return offset;
}
WordSense getWordSense(final int index) {
return wordSenses[index];
}
// Description
public String getDescription() {
return getDescription(false);
}
public String getDescription(final boolean verbose) {
final StringBuilder buffer = new StringBuilder();
buffer.append("{");
for (int i = 0; i < wordSenses.length; i++) {
if (i > 0) {
buffer.append(", ");
}
if (verbose) {
buffer.append(wordSenses[i].getDescription());
} else {
buffer.append(wordSenses[i].getLemma());
}
}
buffer.append("}");
return buffer.toString();
}
public String getLongDescription() {
return getLongDescription(false);
}
public String getLongDescription(final boolean verbose) {
final StringBuilder description = new StringBuilder(this.getDescription(verbose));
final String gloss = this.getGloss();
if (gloss != null) {
description.
append("
append(gloss).
append(")");
}
return description.toString();
}
// Pointers
static PointerTarget[] collectTargets(final Pointer[] pointers) {
final PointerTarget[] targets = new PointerTarget[pointers.length];
for (int i = 0; i < pointers.length; i++) {
targets[i] = pointers[i].getTarget();
}
return targets;
}
public Pointer[] getPointers() {
return pointers;
}
private static final Pointer[] NO_POINTERS = new Pointer[0];
public Pointer[] getPointers(final PointerType type) {
List<Pointer> vector = null;
//TODO
// if superTypes exist, search them, then current type
// if current type exists, search it, then if subTypes exist, search them
for (final Pointer pointer : pointers) {
if (pointer.getType() == type) {
if (vector == null) {
vector = new ArrayList<Pointer>();
}
vector.add(pointer);
}
}
if (vector == null) {
return NO_POINTERS;
}
return vector.toArray(new Pointer[vector.size()]);
}
public PointerTarget[] getTargets() {
return collectTargets(getPointers());
}
public PointerTarget[] getTargets(final PointerType type) {
return collectTargets(getPointers(type));
}
/** @see PointerTarget */
public Synset getSynset() {
return this;
}
// Object methods
@Override public boolean equals(Object that) {
return (that instanceof Synset)
&& ((Synset) that).posOrdinal == posOrdinal
&& ((Synset) that).offset == offset;
}
@Override public int hashCode() {
// times 10 shifts right by 1 decimal place
return (offset * 10) + getPOS().hashCode();
}
@Override public String toString() {
return new StringBuilder("[Synset ").
append(offset).
append("@").
append(getPOS()).
append("<").
append("
append(lexfilenum()).
append("::").
append(getLexCategory()).
append(">").
append(": \"").
append(getDescription()).
append("\"]").toString();
}
/**
* {@inheritDoc}
*/
public int compareTo(final Synset that) {
int result;
result = this.getPOS().compareTo(that.getPOS());
if(result == 0) {
result = this.offset - that.offset;
}
return result;
}
}
|
package com.bloatit.web.linkable.team;
import static com.bloatit.framework.webprocessor.context.Context.tr;
import java.util.EnumSet;
import java.util.Iterator;
import com.bloatit.common.Log;
import com.bloatit.data.DaoTeamRight.UserTeamRight;
import com.bloatit.framework.exceptions.highlevel.ShallNotPassException;
import com.bloatit.framework.exceptions.lowlevel.RedirectException;
import com.bloatit.framework.exceptions.lowlevel.UnauthorizedOperationException;
import com.bloatit.framework.utils.PageIterable;
import com.bloatit.framework.utils.i18n.DateLocale.FormatStyle;
import com.bloatit.framework.webprocessor.annotations.ParamConstraint;
import com.bloatit.framework.webprocessor.annotations.ParamContainer;
import com.bloatit.framework.webprocessor.annotations.RequestParam;
import com.bloatit.framework.webprocessor.annotations.tr;
import com.bloatit.framework.webprocessor.components.HtmlDiv;
import com.bloatit.framework.webprocessor.components.HtmlLink;
import com.bloatit.framework.webprocessor.components.HtmlList;
import com.bloatit.framework.webprocessor.components.HtmlListItem;
import com.bloatit.framework.webprocessor.components.HtmlParagraph;
import com.bloatit.framework.webprocessor.components.HtmlTitleBlock;
import com.bloatit.framework.webprocessor.components.PlaceHolderElement;
import com.bloatit.framework.webprocessor.components.advanced.HtmlTable;
import com.bloatit.framework.webprocessor.components.advanced.HtmlTable.HtmlTableModel;
import com.bloatit.framework.webprocessor.components.meta.HtmlElement;
import com.bloatit.framework.webprocessor.components.meta.HtmlMixedText;
import com.bloatit.framework.webprocessor.components.meta.HtmlText;
import com.bloatit.framework.webprocessor.components.meta.XmlNode;
import com.bloatit.framework.webprocessor.components.renderer.HtmlCachedMarkdownRenderer;
import com.bloatit.framework.webprocessor.context.Context;
import com.bloatit.framework.webprocessor.url.PageNotFoundUrl;
import com.bloatit.model.Member;
import com.bloatit.model.Team;
import com.bloatit.model.right.Action;
import com.bloatit.model.visitor.Visitor;
import com.bloatit.web.WebConfiguration;
import com.bloatit.web.components.MoneyDisplayComponent;
import com.bloatit.web.components.SideBarButton;
import com.bloatit.web.linkable.documentation.SideBarDocumentationBlock;
import com.bloatit.web.pages.master.Breadcrumb;
import com.bloatit.web.pages.master.HtmlDefineParagraph;
import com.bloatit.web.pages.master.MasterPage;
import com.bloatit.web.pages.master.sidebar.SideBarElementLayout;
import com.bloatit.web.pages.master.sidebar.TitleSideBarElementLayout;
import com.bloatit.web.pages.master.sidebar.TwoColumnLayout;
import com.bloatit.web.url.AccountPageUrl;
import com.bloatit.web.url.GiveRightActionUrl;
import com.bloatit.web.url.JoinTeamActionUrl;
import com.bloatit.web.url.MemberPageUrl;
import com.bloatit.web.url.ModifyMemberPageUrl;
import com.bloatit.web.url.SendTeamInvitationPageUrl;
import com.bloatit.web.url.TeamPageUrl;
/**
* <p>
* Home page for handling teams
* </p>
*/
@ParamContainer("team")
public final class TeamPage extends MasterPage {
private final TeamPageUrl url;
@RequestParam(name = "id", conversionErrorMsg = @tr("I cannot find the team number: ''%value%''."))
@ParamConstraint(optionalErrorMsg = @tr("You have to specify a team number."))
private final Team targetTeam;
public TeamPage(final TeamPageUrl url) {
super(url);
this.url = url;
this.targetTeam = url.getTargetTeam();
}
@Override
protected HtmlElement createBodyContent() throws RedirectException {
final TwoColumnLayout layout = new TwoColumnLayout(true, url);
layout.addLeft(generateMain());
layout.addRight(generateContactBox());
layout.addRight(new SideBarDocumentationBlock("team_role"));
layout.addRight(new SideBarTeamWithdrawMoneyBlock());
return layout;
}
@Override
protected String createPageTitle() {
return Context.tr("Consult team information");
}
@Override
public boolean isStable() {
return true;
}
private SideBarElementLayout generateContactBox() {
final TitleSideBarElementLayout contacts = new TitleSideBarElementLayout();
try {
contacts.setTitle(Context.tr("How to contact {0}?", targetTeam.getLogin()));
} catch (final UnauthorizedOperationException e) {
session.notifyBad(Context.tr("Oops, an error prevented us from showing you team name, please notify us."));
throw new ShallNotPassException("Couldn't display team name", e);
}
if (targetTeam.canAccessEmail(Action.READ)) {
try {
contacts.add(new HtmlParagraph().addText(targetTeam.getEmail()));
} catch (final UnauthorizedOperationException e) {
session.notifyBad("An error prevented us from showing you team contact information. Please notify us.");
throw new ShallNotPassException("User can't see team contact information while he should", e);
}
} else {
contacts.add(new HtmlParagraph().addText("No public contact information available"));
}
return contacts;
}
private HtmlElement generateMain() {
final HtmlDiv master = new HtmlDiv();
targetTeam.authenticate(session.getAuthToken());
Visitor me = session.getAuthToken().getVisitor();
if (me.hasModifyTeamRight(targetTeam)) {
// Link to change account settings
final HtmlDiv modify = new HtmlDiv("float_right");
master.add(modify);
modify.add(new ModifyMemberPageUrl().getHtmlLink(Context.tr("Change team settings")));
}
// Title and team type
HtmlTitleBlock titleBlock;
try {
titleBlock = new HtmlTitleBlock(targetTeam.getLogin(), 1);
} catch (final UnauthorizedOperationException e) {
throw new ShallNotPassException("Not allowed to see team name in team page, should not happen", e);
}
master.add(titleBlock);
// Avatar
titleBlock.add(new HtmlDiv("float_left").add(TeamTools.getTeamAvatar(targetTeam)));
// Group informations
HtmlList informationsList = new HtmlList();
// Visibility
informationsList.add(new HtmlDefineParagraph(Context.tr("Visibility: "), (targetTeam.isPublic() ? Context.tr("Public")
: Context.tr("Private"))));
// Creation date
try {
informationsList.add(new HtmlDefineParagraph(Context.tr("Creation date: "),
Context.getLocalizator()
.getDate(targetTeam.getDateCreation())
.toString(FormatStyle.LONG)));
} catch (final UnauthorizedOperationException e) {
// Should never happen
Log.web().error("Not allowed to see team creation date in team page, should not happen", e);
}
// Member count
informationsList.add(new HtmlDefineParagraph(Context.tr("Number of members: "),
String.valueOf(targetTeam.getMembers().size())));
// Features count
int featuresCount = getFeatureCount();
informationsList.add(new HtmlDefineParagraph(Context.tr("Involved in features: "),
new HtmlMixedText(Context.tr("{0} (<0::see details>)",
featuresCount),
new PageNotFoundUrl().getHtmlLink())));
titleBlock.add(informationsList);
// Description
final HtmlTitleBlock description = new HtmlTitleBlock(Context.tr("Description"), 2);
titleBlock.add(description);
final HtmlCachedMarkdownRenderer hcmr = new HtmlCachedMarkdownRenderer(targetTeam.getDescription());
description.add(hcmr);
// Bank informations
if (targetTeam.canGetInternalAccount() && targetTeam.canGetExternalAccount()) {
try {
final HtmlTitleBlock bankInformations = new HtmlTitleBlock(Context.tr("Bank informations"), 2);
titleBlock.add(bankInformations);
{
HtmlList bankInformationsList = new HtmlList();
bankInformations.add(bankInformationsList);
// Account balance
MoneyDisplayComponent amount = new MoneyDisplayComponent(targetTeam.getInternalAccount().getAmount(), true, targetTeam);
AccountPageUrl accountPageUrl = new AccountPageUrl();
accountPageUrl.setTeam(targetTeam);
HtmlListItem accountBalanceItem = new HtmlListItem(new HtmlDefineParagraph(Context.tr("Account balance: "),
new HtmlMixedText(Context.tr("<0:amount (1000€):> (<1::view details>)"),
amount,
accountPageUrl.getHtmlLink())));
bankInformationsList.add(accountBalanceItem);
}
} catch (final UnauthorizedOperationException e) {
// Should never happen
Log.web().error("Cannot access to bank informations, should not happen", e);
}
}
// Members
final HtmlTitleBlock memberTitle = new HtmlTitleBlock(Context.tr("Members ({0})", targetTeam.getMembers().size()), 2);
titleBlock.add(memberTitle);
if(me.hasInviteTeamRight(targetTeam)) {
final SendTeamInvitationPageUrl sendInvitePage = new SendTeamInvitationPageUrl(targetTeam);
final HtmlLink inviteMember = new HtmlLink(sendInvitePage.urlString(), Context.tr("Invite a member to this team"));
memberTitle.add(new HtmlParagraph().add(inviteMember));
}
if (targetTeam.isPublic() && !me.isInTeam(targetTeam)) {
final HtmlLink joinLink = new HtmlLink(new JoinTeamActionUrl(targetTeam).urlString(), Context.tr("Join this team"));
memberTitle.add(joinLink);
}
final PageIterable<Member> members = targetTeam.getMembers();
final HtmlTable membersTable = new HtmlTable(new MyTableModel(members));
membersTable.setCssClass("members_table");
memberTitle.add(membersTable);
return master;
}
@Override
protected Breadcrumb createBreadcrumb() {
return TeamPage.generateBreadcrumb(targetTeam);
}
public static Breadcrumb generateBreadcrumb(final Team team) {
final Breadcrumb breadcrumb = TeamsPage.generateBreadcrumb();
try {
breadcrumb.pushLink(new TeamPageUrl(team).getHtmlLink(team.getLogin()));
} catch (final UnauthorizedOperationException e) {
breadcrumb.pushLink(new TeamPageUrl(team).getHtmlLink(tr("Unknown team")));
}
return breadcrumb;
}
private int getFeatureCount() {
// TODO: real work
return 3;
}
/**
* Model used to display information about each team members.
*/
private class MyTableModel extends HtmlTableModel {
private final PageIterable<Member> members;
private Member member;
private Iterator<Member> iterator;
private Visitor visitor;
private static final int CONSULT = 1;
private static final int TALK = 2;
private static final int MODIFY = 4;
private static final int INVITE = 3;
private static final int BANK = 5;
private static final int PROMOTE = 6;
public MyTableModel(final PageIterable<Member> members) {
this.members = members;
if (session.getAuthToken() != null) {
this.visitor = session.getAuthToken().getVisitor();
}
iterator = members.iterator();
}
@Override
public int getColumnCount() {
return UserTeamRight.values().length + 1;
}
@Override
public XmlNode getHeader(final int column) {
if (column == 0) {
return new HtmlText(Context.tr("Member name"));
}
final EnumSet<UserTeamRight> e = EnumSet.allOf(UserTeamRight.class);
final UserTeamRight ugr = (UserTeamRight) e.toArray()[column - 1];
switch (ugr) {
case CONSULT:
return new HtmlText(Context.tr("Consult"));
case TALK:
return new HtmlText(Context.tr("Talk"));
case MODIFY:
return new HtmlText(Context.tr("Modify"));
case INVITE:
return new HtmlText(Context.tr("Invite"));
case BANK:
return new HtmlText(Context.tr("Bank"));
case PROMOTE:
return new HtmlText(Context.tr("Promote"));
default:
return new HtmlText("");
}
}
@Override
public XmlNode getBody(final int column) {
switch (column) {
case 0: // Name
try {
return new HtmlLink(new MemberPageUrl(member).urlString(), member.getDisplayName());
} catch (final UnauthorizedOperationException e) {
session.notifyError("An error prevented us from showing you team name. Please notify us.");
throw new ShallNotPassException("Cannot display a team name", e);
}
case CONSULT:
return getUserRightStatus(UserTeamRight.CONSULT);
case TALK:
return getUserRightStatus(UserTeamRight.TALK);
case MODIFY:
return getUserRightStatus(UserTeamRight.MODIFY);
case INVITE:
return getUserRightStatus(UserTeamRight.INVITE);
case PROMOTE:
return getUserRightStatus(UserTeamRight.PROMOTE);
case BANK:
return getUserRightStatus(UserTeamRight.BANK);
default:
return new HtmlText("");
}
}
private XmlNode getUserRightStatus(final UserTeamRight right) {
final PlaceHolderElement ph = new PlaceHolderElement();
if(right == UserTeamRight.CONSULT) {
if(member.canBeKickFromTeam(targetTeam, visitor.getMember())) {
if (member.equals(visitor)) {
ph.add(new GiveRightActionUrl(targetTeam, member, right, false).getHtmlLink(Context.tr("Leave")));
} else {
ph.add(new GiveRightActionUrl(targetTeam, member, right, false).getHtmlLink(Context.tr("Kick")));
}
}
} else {
if(targetTeam.canChangeRight(visitor.getMember(), member, right, true)) {
ph.add(new GiveRightActionUrl(targetTeam, member, right, true).getHtmlLink(Context.tr("Grant")));
} else if(targetTeam.canChangeRight(visitor.getMember(), member, right, false)) {
ph.add(new GiveRightActionUrl(targetTeam, member, right, false).getHtmlLink(Context.tr("Remove")));
}
}
return ph;
}
@Override
public String getColumnCss(int column) {
switch (column) {
case 0: // Name
return "name";
case CONSULT:
return getUserRightStyle(UserTeamRight.CONSULT);
case TALK:
return getUserRightStyle(UserTeamRight.TALK);
case MODIFY:
return getUserRightStyle(UserTeamRight.MODIFY);
case INVITE:
return getUserRightStyle(UserTeamRight.INVITE);
case PROMOTE:
return getUserRightStyle(UserTeamRight.PROMOTE);
case BANK:
return getUserRightStyle(UserTeamRight.BANK);
default:
return "";
}
}
private String getUserRightStyle(final UserTeamRight right) {
if (member.hasTeamRight(targetTeam, right)) {
return "can";
}
return "";
}
@Override
public boolean next() {
if (iterator == null) {
iterator = members.iterator();
}
if (iterator.hasNext()) {
member = iterator.next();
return true;
}
return false;
}
}
public static class SideBarTeamWithdrawMoneyBlock extends TitleSideBarElementLayout {
SideBarTeamWithdrawMoneyBlock() {
setTitle(tr("Team account"));
add(new HtmlParagraph(tr("Like users, teams have an elveos account where they can store money.")));
add(new HtmlParagraph(tr("People with the talk right can decide to make developments under the name of the team to let it earn money.")));
add(new HtmlParagraph(tr("People with the bank right can withdraw money from the elveos account back to the team bank account.")));
// TODO good URL
add(new SideBarButton(tr("Withdraw money"), new PageNotFoundUrl(), WebConfiguration.getImgAccountWithdraw()).asElement());
}
}
}
|
package com.laytonsmith.core.functions;
import com.laytonsmith.PureUtilities.Common.StringUtils;
import com.laytonsmith.PureUtilities.Version;
import com.laytonsmith.abstraction.MCChunk;
import com.laytonsmith.abstraction.MCCommandSender;
import com.laytonsmith.abstraction.MCItemStack;
import com.laytonsmith.abstraction.MCLocation;
import com.laytonsmith.abstraction.MCPlayer;
import com.laytonsmith.abstraction.MCWorld;
import com.laytonsmith.abstraction.MCWorldCreator;
import com.laytonsmith.abstraction.StaticLayer;
import com.laytonsmith.abstraction.MVector3D;
import com.laytonsmith.abstraction.blocks.MCFallingBlock;
import com.laytonsmith.abstraction.enums.MCDifficulty;
import com.laytonsmith.abstraction.enums.MCGameRule;
import com.laytonsmith.abstraction.enums.MCWorldEnvironment;
import com.laytonsmith.abstraction.enums.MCWorldType;
import com.laytonsmith.annotations.api;
import com.laytonsmith.core.CHVersion;
import com.laytonsmith.core.ObjectGenerator;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.constructs.CArray;
import com.laytonsmith.core.constructs.CBoolean;
import com.laytonsmith.core.constructs.CDouble;
import com.laytonsmith.core.constructs.CInt;
import com.laytonsmith.core.constructs.CNull;
import com.laytonsmith.core.constructs.CString;
import com.laytonsmith.core.constructs.CVoid;
import com.laytonsmith.core.constructs.Construct;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.environments.CommandHelperEnvironment;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.exceptions.CancelCommandException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.functions.Exceptions.ExceptionType;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class World {
public static String docs() {
return "Provides functions for manipulating a world";
}
@api(environments=CommandHelperEnvironment.class)
public static class get_spawn extends AbstractFunction {
@Override
public String getName() {
return "get_spawn";
}
@Override
public Integer[] numArgs() {
return new Integer[]{0, 1};
}
@Override
public String docs() {
return "array {[world]} Returns a location array for the specified world, or the current player's world, if not specified.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
String world;
if (args.length == 1) {
world = args[0].val();
} else {
if(environment.getEnv(CommandHelperEnvironment.class).GetPlayer() == null){
throw new ConfigRuntimeException("A world must be specified in a context with no player.", ExceptionType.InvalidWorldException, t);
}
world = environment.getEnv(CommandHelperEnvironment.class).GetPlayer().getWorld().getName();
}
MCWorld w = Static.getServer().getWorld(world);
if (w == null) {
throw new ConfigRuntimeException("The specified world \"" + world + "\" is not a valid world.", ExceptionType.InvalidWorldException, t);
}
return ObjectGenerator.GetGenerator().location(w.getSpawnLocation(), false);
}
}
@api(environments=CommandHelperEnvironment.class)
public static class set_spawn extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException,
ExceptionType.CastException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCWorld w = (environment.getEnv(CommandHelperEnvironment.class).GetPlayer() != null ? environment.getEnv(CommandHelperEnvironment.class).GetPlayer().getWorld() : null);
int x = 0;
int y = 0;
int z = 0;
if (args.length == 1) {
MCLocation l = ObjectGenerator.GetGenerator().location(args[0], w, t);
w = l.getWorld();
x = l.getBlockX();
y = l.getBlockY();
z = l.getBlockZ();
} else if (args.length == 3) {
x = Static.getInt32(args[0], t);
y = Static.getInt32(args[1], t);
z = Static.getInt32(args[2], t);
} else if (args.length == 4) {
w = Static.getServer().getWorld(args[0].val());
x = Static.getInt32(args[1], t);
y = Static.getInt32(args[2], t);
z = Static.getInt32(args[3], t);
}
if (w == null) {
throw new ConfigRuntimeException("Invalid world given.", ExceptionType.InvalidWorldException, t);
}
w.setSpawnLocation(x, y, z);
return CVoid.VOID;
}
@Override
public String getName() {
return "set_spawn";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 3, 4};
}
@Override
public String docs() {
return "void {locationArray | [world], x, y, z} Sets the spawn of the world. Note that in some cases, a plugin"
+ " may set the spawn differently, and this method will do nothing. In that case, you should use"
+ " the plugin's commands to set the spawn.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api(environments=CommandHelperEnvironment.class)
public static class refresh_chunk extends AbstractFunction {
@Override
public String getName() {
return "refresh_chunk";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2, 3};
}
@Override
public String docs() {
return "void {[world], x, z | [world], locationArray} Resends the chunk data to all clients, using the specified world, or the current"
+ " players world if not provided.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer m = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCWorld world;
int x;
int z;
if (args.length == 1) {
//Location array provided
MCLocation l = ObjectGenerator.GetGenerator().location(args[0], m != null ? m.getWorld() : null, t);
world = l.getWorld();
x = l.getBlockX();
z = l.getBlockZ();
} else if (args.length == 2) {
//Either location array and world provided, or x and z. Test for array at pos 2
if (args[1] instanceof CArray) {
world = Static.getServer().getWorld(args[0].val());
MCLocation l = ObjectGenerator.GetGenerator().location(args[1], null, t);
x = l.getBlockX();
z = l.getBlockZ();
} else {
if (m == null) {
throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t);
}
world = m.getWorld();
x = Static.getInt32(args[0], t);
z = Static.getInt32(args[1], t);
}
} else {
//world, x and z provided
world = Static.getServer().getWorld(args[0].val());
x = Static.getInt32(args[1], t);
z = Static.getInt32(args[2], t);
}
world.refreshChunk(x, z);
return CVoid.VOID;
}
}
@api
public static class load_chunk extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer m = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCWorld world;
int x;
int z;
if (args.length == 1) {
//Location array provided
MCLocation l = ObjectGenerator.GetGenerator().location(args[0], m != null ? m.getWorld() : null, t);
world = l.getWorld();
x = l.getBlockX();
z = l.getBlockZ();
} else if (args.length == 2) {
//Either location array and world provided, or x and z. Test for array at pos 2
if (args[1] instanceof CArray) {
world = Static.getServer().getWorld(args[0].val());
MCLocation l = ObjectGenerator.GetGenerator().location(args[1], null, t);
x = l.getBlockX();
z = l.getBlockZ();
} else {
if (m == null) {
throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t);
}
world = m.getWorld();
x = Static.getInt32(args[0], t);
z = Static.getInt32(args[1], t);
}
} else {
//world, x and z provided
world = Static.getServer().getWorld(args[0].val());
x = Static.getInt32(args[1], t);
z = Static.getInt32(args[2], t);
}
world.loadChunk(x, z);
return CVoid.VOID;
}
@Override
public String getName() {
return "load_chunk";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2, 3};
}
@Override
public String docs() {
return "void {[world], x, z | [world], locationArray} Loads the chunk, using the specified world, or the current"
+ " players world if not provided.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
}
@api(environments=CommandHelperEnvironment.class)
public static class unload_chunk extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer m = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCWorld world;
int x;
int z;
if (args.length == 1) {
//Location array provided
MCLocation l = ObjectGenerator.GetGenerator().location(args[0], m != null ? m.getWorld() : null, t);
world = l.getWorld();
x = l.getBlockX();
z = l.getBlockZ();
} else if (args.length == 2) {
//Either location array and world provided, or x and z. Test for array at pos 2
if (args[1] instanceof CArray) {
world = Static.getServer().getWorld(args[0].val());
MCLocation l = ObjectGenerator.GetGenerator().location(args[1], null, t);
x = l.getBlockX();
z = l.getBlockZ();
} else {
if (m == null) {
throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t);
}
world = m.getWorld();
x = Static.getInt32(args[0], t);
z = Static.getInt32(args[1], t);
}
} else {
//world, x and z provided
world = Static.getServer().getWorld(args[0].val());
x = Static.getInt32(args[1], t);
z = Static.getInt32(args[2], t);
}
world.unloadChunk(x, z);
return CVoid.VOID;
}
@Override
public String getName() {
return "unload_chunk";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2, 3};
}
@Override
public String docs() {
return "void {[world], x, z | [world], locationArray} Unloads the chunk, using the specified world, or the current"
+ " players world if not provided.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
}
@api
public static class get_loaded_chunks extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer m = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCWorld world;
if (args.length == 1) {
// World Provided
world = Static.getServer().getWorld(args[0].val());
} else {
if (m == null) {
throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t);
}
world = m.getWorld();
}
MCChunk[] chunks = world.getLoadedChunks();
CArray ret = new CArray(t);
for (int i = 0; i < chunks.length; i++) {
CArray chunk = new CArray(t);
chunk.set("x", new CInt(chunks[i].getX(), t), t);
chunk.set("z", new CInt(chunks[i].getZ(), t), t);
chunk.set("world", chunks[i].getWorld().getName(), t);
ret.set(i, chunk, t);
}
return ret;
}
@Override
public String getName() {
return "get_loaded_chunks";
}
@Override
public Integer[] numArgs() {
return new Integer[] {0, 1};
}
@Override
public String docs() {
return "array {[world]} Gets all currently loaded chunks, in the specified world, or the current"
+ " players world if not provided.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
}
@api(environments=CommandHelperEnvironment.class)
public static class regen_chunk extends AbstractFunction {
@Override
public String getName() {
return "regen_chunk";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2, 3};
}
@Override
public String docs() {
return "void {x, z, [world]| locationArray, [world]} Regenerate the chunk, using the specified world, or the current"
+ " players world if not provided. Beware that this is destructive! Any data in this chunk will be lost!";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer m = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCWorld world;
int x;
int z;
if (args.length == 1) {
//Location array provided
MCLocation l = ObjectGenerator.GetGenerator().location(args[0], m != null ? m.getWorld() : null, t);
world = l.getWorld();
x = l.getChunk().getX();
z = l.getChunk().getZ();
} else if (args.length == 2) {
//Either location array and world provided, or x and z. Test for array at pos 1
if (args[0] instanceof CArray) {
world = Static.getServer().getWorld(args[1].val());
MCLocation l = ObjectGenerator.GetGenerator().location(args[0], null, t);
x = l.getChunk().getX();
z = l.getChunk().getZ();
} else {
if (m == null) {
throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t);
}
world = m.getWorld();
x = Static.getInt32(args[0], t);
z = Static.getInt32(args[1], t);
}
} else {
//world, x and z provided
x = Static.getInt32(args[0], t);
z = Static.getInt32(args[1], t);
world = Static.getServer().getWorld(args[2].val());
}
return CBoolean.get(world.regenerateChunk(x, z));
}
}
@api(environments=CommandHelperEnvironment.class)
public static class is_slime_chunk extends AbstractFunction {
@Override
public String getName() {
return "is_slime_chunk";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2, 3};
}
@Override
public String docs() {
return "boolean {x, z, [world]| locationArray, [world]} Returns if the chunk is a slime spawning chunk, using the specified world, or the current"
+ " players world if not provided.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public Boolean runAsync() {
return false;
}
Random rnd = new Random();
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer m = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCWorld world;
int x;
int z;
long seed;
if (args.length == 1) {
//Location array provided
MCLocation l = ObjectGenerator.GetGenerator().location(args[0], m != null ? m.getWorld() : null, t);
world = l.getWorld();
seed = world.getSeed();
x = l.getChunk().getX();
z = l.getChunk().getZ();
} else if (args.length == 2) {
//Either location array and world provided, or x and z. Test for array at pos 1
if (args[0] instanceof CArray) {
world = Static.getServer().getWorld(args[1].val());
seed = world.getSeed();
MCLocation l = ObjectGenerator.GetGenerator().location(args[0], null, t);
x = l.getChunk().getX();
z = l.getChunk().getZ();
} else {
if (m == null) {
throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t);
}
world = m.getWorld();
seed = world.getSeed();
x = Static.getInt32(args[0], t);
z = Static.getInt32(args[1], t);
}
} else {
//world, x and z provided
x = Static.getInt32(args[0], t);
z = Static.getInt32(args[1], t);
world = Static.getServer().getWorld(args[2].val());
seed = world.getSeed();
}
rnd.setSeed(seed
+ x * x * 0x4c1906
+ x * 0x5ac0db
+ z * z * 0x4307a7L
+ z * 0x5f24f
^ 0x3ad8025f);
return CBoolean.get(rnd.nextInt(10) == 0);
}
}
private static final SortedMap<String, Construct> TimeLookup = new TreeMap<String, Construct>();
static {
synchronized (World.class) {
Properties p = new Properties();
try {
p.load(Minecraft.class.getResourceAsStream("/time_names.txt"));
Enumeration e = p.propertyNames();
while (e.hasMoreElements()) {
String name = e.nextElement().toString();
TimeLookup.put(name, new CString(p.getProperty(name).toString(), Target.UNKNOWN));
}
} catch (IOException ex) {
Logger.getLogger(World.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@api(environments=CommandHelperEnvironment.class)
public static class set_world_time extends AbstractFunction {
@Override
public String getName() {
return "set_world_time";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
@Override
public String docs() {
StringBuilder doc = new StringBuilder();
synchronized (World.class) {
doc.append("void {[world], time} Sets the time of a given world. Should be a number from 0 to"
+ " 24000, if not, it is modulo scaled. ---- Alternatively, common time notation (9:30pm, 4:00 am)"
+ " is acceptable, and convenient english mappings also exist:");
doc.append("<ul>");
for (String key : TimeLookup.keySet()) {
doc.append("<li>").append(key).append(" = ").append(TimeLookup.get(key)).append("</li>");
}
doc.append("</ul>");
}
return doc.toString();
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCWorld w = null;
if (environment.getEnv(CommandHelperEnvironment.class).GetPlayer() != null) {
w = environment.getEnv(CommandHelperEnvironment.class).GetPlayer().getWorld();
}
if (args.length == 2) {
w = Static.getServer().getWorld(args[0].val());
}
if (w == null) {
throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t);
}
long time = 0;
String stime = (args.length == 1 ? args[0] : args[1]).val().toLowerCase();
if (TimeLookup.containsKey(stime.replaceAll("[^a-z]", ""))) {
stime = TimeLookup.get(stime.replaceAll("[^a-z]", "")).val();
}
if (stime.matches("^([\\d]+)[:.]([\\d]+)[ ]*?(?:([pa])\\.*m\\.*){0,1}$")) {
Pattern p = Pattern.compile("^([\\d]+)[:.]([\\d]+)[ ]*?(?:([pa])\\.*m\\.*){0,1}$");
Matcher m = p.matcher(stime);
m.find();
int hour = Integer.parseInt(m.group(1));
int minute = Integer.parseInt(m.group(2));
String offset = "a";
if (m.group(3) != null) {
offset = m.group(3);
}
if (offset.equals("p")) {
hour += 12;
}
if (hour == 24) {
hour = 0;
}
if (hour > 24) {
throw new ConfigRuntimeException("Invalid time provided", ExceptionType.FormatException, t);
}
if (minute > 59) {
throw new ConfigRuntimeException("Invalid time provided", ExceptionType.FormatException, t);
}
hour -= 6;
hour = hour % 24;
long ttime = hour * 1000;
ttime += ((minute / 60.0) * 1000);
stime = Long.toString(ttime);
}
try {
Long.valueOf(stime);
} catch (NumberFormatException e) {
throw new ConfigRuntimeException("Invalid time provided", ExceptionType.FormatException, t);
}
time = Long.parseLong(stime);
w.setTime(time);
return CVoid.VOID;
}
}
@api(environments=CommandHelperEnvironment.class)
public static class get_world_time extends AbstractFunction {
@Override
public String getName() {
return "get_world_time";
}
@Override
public Integer[] numArgs() {
return new Integer[]{0, 1};
}
@Override
public String docs() {
return "int {[world]} Returns the time of the specified world, as an integer from"
+ " 0 to 24000-1";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCWorld w = null;
if (environment.getEnv(CommandHelperEnvironment.class).GetPlayer() != null) {
w = environment.getEnv(CommandHelperEnvironment.class).GetPlayer().getWorld();
}
if (args.length == 1) {
w = Static.getServer().getWorld(args[0].val());
}
if (w == null) {
throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t);
}
return new CInt(w.getTime(), t);
}
}
@api(environments={CommandHelperEnvironment.class})
public static class create_world extends AbstractFunction{
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException, ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
MCWorldCreator creator = StaticLayer.GetConvertor().getWorldCreator(args[0].val());
if (args.length >= 3) {
MCWorldType type;
try {
type = MCWorldType.valueOf(args[1].val().toUpperCase());
} catch (IllegalArgumentException e) {
throw new ConfigRuntimeException(args[1].val() + " is not a valid world type. Must be one of: " + StringUtils.Join(MCWorldType.values(), ", "), ExceptionType.FormatException, t);
}
MCWorldEnvironment environment;
try {
environment = MCWorldEnvironment.valueOf(args[2].val().toUpperCase());
} catch (IllegalArgumentException e) {
throw new ConfigRuntimeException(args[2].val() + " is not a valid environment type. Must be one of: " + StringUtils.Join(MCWorldEnvironment.values(), ", "), ExceptionType.FormatException, t);
}
creator.type(type).environment(environment);
}
if ((args.length >= 4) && !(args[3] instanceof CNull)) {
if (args[3] instanceof CInt) {
creator.seed(Static.getInt(args[3], t));
} else {
creator.seed(args[3].val().hashCode());
}
}
if (args.length == 5) {
creator.generator(args[4].val());
}
creator.createWorld();
return CVoid.VOID;
}
@Override
public String getName() {
return "create_world";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 3, 4, 5};
}
@Override
public String docs() {
return "void {name, [type, environment, [seed, [generator]]]} Creates a new world with the specified options."
+ " If the world already exists, it will be loaded from disk, and the last 3 arguments may be"
+ " ignored. name is the name of the world, type is one of "
+ StringUtils.Join(MCWorldType.values(), ", ") + " and environment is one of "
+ StringUtils.Join(MCWorldEnvironment.values(), ", ") + ". The seed can be an integer, a string (will be the hashcode), or null (will be random int)."
+ " Generator is the name of a world generator loaded on the server.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api(environments={CommandHelperEnvironment.class})
public static class get_worlds extends AbstractFunction{
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
CArray worlds = new CArray(t);
for(MCWorld w : Static.getServer().getWorlds()){
worlds.push(new CString(w.getName(), t));
}
return worlds;
}
@Override
public String getName() {
return "get_worlds";
}
@Override
public Integer[] numArgs() {
return new Integer[]{0};
}
@Override
public String docs() {
return "array {} Returns a list of all currently loaded worlds.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api(environments={CommandHelperEnvironment.class})
public static class get_chunk_loc extends AbstractFunction {
@Override
public String getName() {
return "get_chunk_loc";
}
@Override
public Integer[] numArgs() {
return new Integer[]{0, 1};
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
MCCommandSender cs = env.getEnv(CommandHelperEnvironment.class).GetCommandSender();
MCPlayer p = null;
MCWorld w = null;
MCLocation l = null;
if (cs instanceof MCPlayer) {
p = (MCPlayer)cs;
Static.AssertPlayerNonNull(p, t);
l = p.getLocation();
w = l.getWorld();
}
if (args.length == 1) {
if (args[0] instanceof CArray) {
l = ObjectGenerator.GetGenerator().location(args[0], w, t);
} else {
throw new ConfigRuntimeException("expecting argument 1 of get_chunk_loc to be a location array"
, ExceptionType.FormatException, t);
}
} else {
if (p == null) {
throw new ConfigRuntimeException("expecting a player context for get_chunk_loc when used without arguments"
, ExceptionType.InsufficientArgumentsException, t);
}
}
CArray chunk = new CArray(t,
new CInt(l.getChunk().getX(), t),
new CInt(l.getChunk().getZ(), t),
new CString(l.getChunk().getWorld().getName(), t));
chunk.set("x", new CInt(l.getChunk().getX(), t), t);
chunk.set("z", new CInt(l.getChunk().getZ(), t), t);
chunk.set("world", l.getChunk().getWorld().getName(), t);
return chunk;
}
@Override
public String docs() {
return "array {[location array]} Returns an array of x, z, world "
+ "coords of the chunk of either the location specified or the location of "
+ "the player running the command.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException, ExceptionType.InsufficientArgumentsException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public Boolean runAsync() {
return false;
}
}
@api(environments={CommandHelperEnvironment.class})
public static class spawn_falling_block extends AbstractFunction{
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
MCPlayer p = env.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], p != null ? p.getWorld() : null , t);
MCItemStack item = Static.ParseItemNotation(this.getName(), args[1].val(), 1, t);
CArray vect = null;
if (args.length == 3) {
if (args[2] instanceof CArray) {
vect = (CArray)args[2];
if (vect.size() < 3) {
throw new ConfigRuntimeException("Argument 3 of spawn_falling_block must have 3 items", ExceptionType.FormatException, t);
}
} else {
throw new ConfigRuntimeException("Expected array for argument 3 of spawn_falling_block", ExceptionType.FormatException, t);
}
}
MCFallingBlock block = loc.getWorld().spawnFallingBlock(loc, item.getType().getType(), (byte)item.getData().getData());
if (args.length == 3 && vect != null) {
double x = Double.valueOf(vect.get(0, t).val());
double y = Double.valueOf(vect.get(1, t).val());
double z = Double.valueOf(vect.get(2, t).val());
MVector3D v = new MVector3D(x, y, z);
block.setVelocity(v);
}
return new CInt(block.getEntityId(), t);
}
@Override
public String getName() {
return "spawn_falling_block";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2, 3};
}
@Override
public String docs() {
return "integer {location array, id[:type], [vector array ie. array(x, y, z)]} Spawns a"
+ " falling block of the specified id and type at the specified location, applying"
+ " vector array as a velocity if given. Values for the vector array are doubles, and 1.0"
+ " seems to imply about 3 times walking speed. Gravity applies for y.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api
public static class world_info extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment,
Construct... args) throws ConfigRuntimeException {
MCWorld w = Static.getServer().getWorld(args[0].val());
if (w == null) {
throw new ConfigRuntimeException("Unknown world: " + args[0],
ExceptionType.InvalidWorldException, t);
}
CArray ret = new CArray(t);
ret.set("name", new CString(w.getName(), t), t);
ret.set("seed", new CInt(w.getSeed(), t), t);
ret.set("environment", new CString(w.getEnvironment().name(), t), t);
ret.set("generator", new CString(w.getGenerator(), t), t);
ret.set("worldtype", new CString(w.getWorldType().name(), t), t);
return ret;
}
@Override
public String getName() {
return "world_info";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "array {world} Returns an associative array of all the info needed to duplicate the world."
+ " The keys are name, seed, environment, generator, and worldtype.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api
public static class unload_world extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
boolean save = true;
if (args.length == 2) {
save = Static.getBoolean(args[1]);
}
MCWorld world = Static.getServer().getWorld(args[0].val());
if (world == null) {
throw new ConfigRuntimeException("Unknown world: " + args[0].val(), ExceptionType.InvalidWorldException, t);
}
return CBoolean.get(Static.getServer().unloadWorld(world, save));
}
@Override
public String getName() {
return "unload_world";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
@Override
public String docs() {
return "boolean {world, [save]} Unloads a world, and saves it if save is true (defaults true),"
+ " and returns whether or not the operation was successful.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
}
@api
public static class get_difficulty extends AbstractFunction {
@Override
public String getName() {
return "get_difficulty";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public String docs() {
return "string {world} Returns the difficulty of the world, It will be one of " + StringUtils.Join(MCDifficulty.values(), ", ", ", or ", " or ") + ".";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCWorld world = Static.getServer().getWorld(args[0].val());
if (world == null) {
throw new ConfigRuntimeException("Unknown world: " + args[0].val(), ExceptionType.InvalidWorldException, t);
}
return new CString(world.getDifficulty().toString(), t);
}
}
@api
public static class set_difficulty extends AbstractFunction {
@Override
public String getName() {
return "set_difficulty";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public String docs() {
return "void {[world], difficulty} Sets the difficulty of the world with the given name, or all worlds if the name is not given."
+ " difficulty can be " + StringUtils.Join(MCDifficulty.values(), ", ", ", or ", " or ") + ".";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCDifficulty difficulty;
if (args.length == 1) {
try {
difficulty = MCDifficulty.valueOf(args[0].val().toUpperCase());
} catch (IllegalArgumentException exception) {
throw new ConfigRuntimeException("The difficulty \"" + args[0].val() + "\" does not exist.", ExceptionType.FormatException, t);
}
for (MCWorld world : Static.getServer().getWorlds()) {
world.setDifficulty(difficulty);
}
} else {
MCWorld world = Static.getServer().getWorld(args[0].val());
if (world == null) {
throw new ConfigRuntimeException("Unknown world: " + args[0].val(), ExceptionType.InvalidWorldException, t);
}
try {
difficulty = MCDifficulty.valueOf(args[1].val().toUpperCase());
} catch (IllegalArgumentException exception) {
throw new ConfigRuntimeException("The difficulty \"" + args[1].val() + "\" does not exist.", ExceptionType.FormatException, t);
}
world.setDifficulty(difficulty);
}
return CVoid.VOID;
}
}
@api
public static class get_pvp extends AbstractFunction {
@Override
public String getName() {
return "get_pvp";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public String docs() {
return "boolean {world} Returns if PVP is allowed in the world.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCWorld world = Static.getServer().getWorld(args[0].val());
if (world == null) {
throw new ConfigRuntimeException("Unknown world: " + args[0].val(), ExceptionType.InvalidWorldException, t);
}
return CBoolean.get(world.getPVP());
}
}
@api
public static class set_pvp extends AbstractFunction {
@Override
public String getName() {
return "set_pvp";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public String docs() {
return "void {[world], boolean} Sets if PVP is allowed in the world with the given name, or all worlds if the name is not given.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
if (args.length == 1) {
boolean pvp = Static.getBoolean(args[0]);
for (MCWorld world : Static.getServer().getWorlds()) {
world.setPVP(pvp);
}
} else {
MCWorld world = Static.getServer().getWorld(args[0].val());
if (world == null) {
throw new ConfigRuntimeException("Unknown world: " + args[0].val(), ExceptionType.InvalidWorldException, t);
}
world.setPVP(Static.getBoolean(args[1]));
}
return CVoid.VOID;
}
}
@api
public static class get_gamerule extends AbstractFunction {
@Override
public String getName() {
return "get_gamerule";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public String docs() {
return "mixed {world, [gameRule]} Returns an associative array containing the values of all existing gamerules for the given world."
+ " If gameRule is set, the function only returns the value of the specified gamerule, a boolean."
+ "gameRule can be " + StringUtils.Join(MCGameRule.values(), ", ", ", or ", " or ") + ".";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCWorld world = Static.getServer().getWorld(args[0].val());
if (world == null) {
throw new ConfigRuntimeException("Unknown world: " + args[0].val(), ExceptionType.InvalidWorldException, t);
}
if (args.length == 1) {
CArray gameRules = new CArray(t);
for (MCGameRule gameRule : MCGameRule.values()) {
gameRules.set(new CString(gameRule.getGameRule(), t), CBoolean.get(world.getGameRuleValue(gameRule)), t);
}
return gameRules;
} else {
MCGameRule gameRule;
try {
gameRule = MCGameRule.valueOf(args[1].val().toUpperCase());
} catch (IllegalArgumentException exception) {
throw new ConfigRuntimeException("The gamerule \"" + args[1].val() + "\" does not exist.", ExceptionType.FormatException, t);
}
return CBoolean.get(world.getGameRuleValue(gameRule));
}
}
}
@api
public static class set_gamerule extends AbstractFunction {
@Override
public String getName() {
return "set_gamerule";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2, 3};
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public String docs() {
return "void {[world], gameRule, value} Sets the value of the gamerule for the specified world, value is a boolean. If world is not given the value is set for all worlds."
+ " gameRule can be " + StringUtils.Join(MCGameRule.values(), ", ", ", or ", " or ") + ".";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCGameRule gameRule;
if (args.length == 2) {
try {
gameRule = MCGameRule.valueOf(args[0].val().toUpperCase());
} catch (IllegalArgumentException exception) {
throw new ConfigRuntimeException("The gamerule \"" + args[0].val() + "\" does not exist.", ExceptionType.FormatException, t);
}
boolean value = Static.getBoolean(args[1]);
for (MCWorld world : Static.getServer().getWorlds()) {
world.setGameRuleValue(gameRule, value);
}
} else {
try {
gameRule = MCGameRule.valueOf(args[1].val().toUpperCase());
} catch (IllegalArgumentException exception) {
throw new ConfigRuntimeException("The gamerule \"" + args[1].val() + "\" does not exist.", ExceptionType.FormatException, t);
}
MCWorld world = Static.getServer().getWorld(args[0].val());
if (world == null) {
throw new ConfigRuntimeException("Unknown world: " + args[0].val(), ExceptionType.InvalidWorldException, t);
}
world.setGameRuleValue(gameRule, Static.getBoolean(args[2]));
}
return CVoid.VOID;
}
}
@api
public static class location_shift extends AbstractFunction {
@Override
public String getName() {
return "location_shift";
}
@Override
public Integer[] numArgs() {
return new Integer[]{3};
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.FormatException,
ExceptionType.RangeException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public String docs() {
return "void {location_from, location_to, distance} Shift from one location to another, by defined distance.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
MCPlayer p = env.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCLocation from = ObjectGenerator.GetGenerator().location(args[0], p != null ? p.getWorld() : null, t);
MCLocation to = ObjectGenerator.GetGenerator().location(args[1], p != null ? p.getWorld() : null, t);
int distance = Static.getInt32(args[2], t);
if (distance <= 0) {
throw new ConfigRuntimeException("Distance must be greater than 0.", ExceptionType.RangeException, t);
}
MCLocation shifted_from = from;
MVector3D velocity = to.toVector().subtract(from.toVector()).normalize();
for (int i = 0; i < distance; i++) {
shifted_from = shifted_from.add(velocity);
}
return ObjectGenerator.GetGenerator().location(shifted_from);
}
}
@api
public static class get_yaw extends AbstractFunction {
@Override
public String getName() {
return "get_yaw";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2};
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public String docs() {
return "void {location_from, location_to} Calculate yaw from one location to another.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
MCPlayer p = env.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCLocation from = ObjectGenerator.GetGenerator().location(args[0], p != null ? p.getWorld() : null, t);
MCLocation to = ObjectGenerator.GetGenerator().location(args[1], p != null ? p.getWorld() : null, t);
MCLocation subtract = to.subtract(from);
double dX = subtract.getX();
double dY = subtract.getY();
double dZ = subtract.getZ();
double distanceXZ = java.lang.Math.sqrt(dX * dX + dZ * dZ);
double yaw = java.lang.Math.toDegrees(java.lang.Math.acos(dX / distanceXZ));
if (dZ < 0.0) {
yaw += java.lang.Math.abs(180 - yaw) * 2;
}
return new CDouble(yaw - 90, t);
}
}
@api
public static class get_pitch extends AbstractFunction {
@Override
public String getName() {
return "get_pitch";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2};
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public String docs() {
return "void {location_from, location_to} Calculate pitch from one location to another.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
MCPlayer p = env.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCLocation from = ObjectGenerator.GetGenerator().location(args[0], p != null ? p.getWorld() : null, t);
MCLocation to = ObjectGenerator.GetGenerator().location(args[1], p != null ? p.getWorld() : null, t);
MCLocation subtract = to.subtract(from);
double dX = subtract.getX();
double dY = subtract.getY();
double dZ = subtract.getZ();
double distanceXZ = java.lang.Math.sqrt(dX * dX + dZ * dZ);
double distanceY = java.lang.Math.sqrt(distanceXZ * distanceXZ + dY * dY);
double pitch = java.lang.Math.toDegrees(java.lang.Math.acos(dY / distanceY)) - 90;
return new CDouble(pitch, t);
}
}
@api
public static class save_world extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidWorldException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCWorld world = Static.getWorld(args[0], t);
world.save();
return CVoid.VOID;
}
@Override
public String getName() {
return "save_world";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "void {world_name} Saves the specified world.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
}
@api
public static class get_temperature extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new Exceptions.ExceptionType[]{Exceptions.ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target target, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer player = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCWorld world = null;
if(player != null) {
world = player.getWorld();
}
MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], world, target);
return new CDouble(loc.getBlock().getTemperature(), target);
}
@Override
public String getName() {
return "get_temperature";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "double {locationArray} Returns the current temperature of the location given.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
}
}
|
package jenkins.model.lazy;
import java.util.AbstractList;
import java.util.Arrays;
/**
* {@code ArrayList<Integer>} that uses {@code int} for storage.
*
* Plus a number of binary-search related methods that assume the array is sorted in the ascending order.
*
* @author Kohsuke Kawaguchi
*/
class SortedIntList extends AbstractList<Integer> {
private int[] data;
private int size;
public SortedIntList(int capacity) {
this.data = new int[capacity];
this.size = 0;
}
/**
* Internal copy constructor.
*/
public SortedIntList(SortedIntList that) {
this.data = new int[that.size+8];
System.arraycopy(that.data, 0, this.data, 0,
that.size);
this.size = that.size;
}
/**
* Binary search to find the position of the given string.
*
* @return
* -(insertionPoint+1) if the exact string isn't found.
* That is, -1 means the probe would be inserted at the very beginning.
*/
public int find(int probe) {
return Arrays.binarySearch(data, 0, size, probe);
}
@Override
public boolean contains(Object o) {
return o instanceof Integer && contains(((Integer)o).intValue());
}
public boolean contains(int i) {
return find(i)>=0;
}
@Override
public Integer get(int index) {
if (size<=index) throw new IndexOutOfBoundsException();
return data[index];
}
@Override
public int size() {
return size;
}
public int max() {
return size > 0 ? data[size - 1] : 0;
}
@Override
public boolean add(Integer i) {
return add(i.intValue());
}
public boolean add(int i) {
ensureCapacity(size+1);
data[size++] = i;
return true;
}
private void ensureCapacity(int i) {
if (data.length<i) {
int[] r = new int[Math.max(data.length*2,i)];
System.arraycopy(data,0,r,0,size);
data = r;
}
}
/**
* Finds the index of the entry lower than v.
*/
public int lower(int v) {
return Boundary.LOWER.apply(find(v));
}
/**
* Finds the index of the entry greater than v.
*/
public int higher(int v) {
return Boundary.HIGHER.apply(find(v));
}
/**
* Finds the index of the entry lower or equal to v.
*/
public int floor(int v) {
return Boundary.FLOOR.apply(find(v));
}
/**
* Finds the index of the entry greater or equal to v.
*/
public int ceil(int v) {
return Boundary.CEIL.apply(find(v));
}
public boolean isInRange(int idx) {
return 0<=idx && idx<size;
}
public void sort() {
Arrays.sort(data,0,size);
}
public void copyInto(int[] dest) {
System.arraycopy(data,0,dest,0,size);
}
public void removeValue(int n) {
int idx = find(n);
if (idx<0) return;
System.arraycopy(data,idx+1,data,idx,size-(idx+1));
size
}
}
|
package example.callbacks;
import java.util.function.Supplier;
import org.junit.jupiter.api.extension.Extension;
class Logger {
static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(Logger.class.getName());
static void beforeAllMethod(String text) {
log(() -> "@BeforeAll " + text);
}
static void beforeEachCallback(Extension extension) {
log(() -> " " + extension.getClass().getSimpleName() + ".beforeEach()");
}
static void beforeEachMethod(String text) {
log(() -> " @BeforeEach " + text);
}
static void testMethod(String text) {
log(() -> " @Test " + text);
}
static void afterEachMethod(String text) {
log(() -> " @AfterEach " + text);
}
static void afterEachCallback(Extension extension) {
log(() -> " " + extension.getClass().getSimpleName() + ".afterEach()");
}
static void afterAllMethod(String text) {
log(() -> "@AfterAll " + text);
}
private static void log(Supplier<String> supplier) {
// System.err.println(supplier.get());
logger.info(supplier);
}
}
|
package acs.benchmark.util;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.omg.CORBA.ORB;
import si.ijs.maci.Administrator;
import si.ijs.maci.AdministratorPOATie;
import si.ijs.maci.ComponentInfo;
import si.ijs.maci.ContainerInfo;
import si.ijs.maci.LoggingConfigurableHelper;
import si.ijs.maci.LoggingConfigurableOperations;
import si.ijs.maci.LoggingConfigurablePackage.LogLevels;
import alma.ACSErrTypeCommon.BadParameterEx;
import alma.ACSErrTypeCommon.IllegalArgumentEx;
import alma.ACSErrTypeCommon.wrappers.AcsJBadParameterEx;
import alma.JavaContainerError.wrappers.AcsJContainerEx;
import alma.acs.container.AcsManagerProxy;
import alma.acs.container.ContainerServices;
import alma.acs.logging.AcsLogger;
import alma.acs.logging.level.AcsLogLevelDefinition;
import alma.acs.util.ACSPorts;
import alma.acs.util.AcsLocations;
import alma.acsdaemon.ContainerDaemonHelper;
import alma.acsdaemon.ContainerDaemonOperations;
import alma.acsdaemonErrType.FailedToStartContainerEx;
import alma.acsdaemonErrType.FailedToStopContainerEx;
import alma.acsdaemonErrType.wrappers.AcsJFailedToStartContainerEx;
import alma.maci.containerconfig.types.ContainerImplLangType;
import alma.maciErrType.LoggerDoesNotExistEx;
import alma.maciErrType.NoPermissionEx;
/**
* Provides direct container access to test code.
* <p>
* The constructors only store parameters. You must call {@link #loginToManager()} explicitly
* before using the other methods. * Make sure to call {@link #logoutFromManager()} when done.
* <p>
* Some methods use JUnit asserts from {@link Assert} which means that runtime exceptions such as
* {@link AssertionFailedError} may be thrown.
* <p>
* TODO: Merge with similar class in ACS/LGPL/CommonSoftware/containerTests/contLogTest
* (which builds before this, but does not get installed).
*
* @author hsommer
*/
public class ContainerUtil
{
protected ContainerServices containerServices;
protected AcsLogger logger;
protected AcsManagerProxy adminProxy;
protected boolean loggedInToManager;
protected ORB orb;
protected ManagerAdminClient managerAdminClient;
// c'tor stuff
/**
* Constructor for use as stand-alone application.
*
* @param cs
* @param managerLoc
*/
public ContainerUtil(ContainerServices cs) {
String managerLoc = AcsLocations.figureOutManagerLocation();
cs.getLogger().fine("Will use managerLoc='" + managerLoc + "'.");
init(cs, new AcsManagerProxy(managerLoc, cs.getAdvancedContainerServices().getORB(), cs.getLogger()));
}
/**
* Constructor for use in a ComponentClientTestCase.
* <p>
* Allows access to the manager as an administrator client, on top of the existing manager connection
* from <code>managerProxy</code>;
* @param cs
* @param managerProxy As inherited from ComponentClientTestCase
* @see ManagerAdminClient
*/
public ContainerUtil(ContainerServices cs, AcsManagerProxy managerProxy) {
Assert.assertNotNull(managerProxy);
init(cs, managerProxy.createInstance());
}
/**
* Common to both constructors.
* @param cs
* @param adminProxy
*/
protected void init(ContainerServices cs, AcsManagerProxy adminProxy) {
Assert.assertNotNull(cs);
Assert.assertNotNull(adminProxy);
this.containerServices = cs;
this.logger = cs.getLogger();
this.adminProxy = adminProxy;
loggedInToManager = false;
orb = cs.getAdvancedContainerServices().getORB();
}
// Manager login
public void loginToManager() throws AcsJContainerEx {
if (!loggedInToManager) {
managerAdminClient = new ManagerAdminClient(containerServices.getName(), logger);
AdministratorPOATie adminpoa = new AdministratorPOATie(managerAdminClient);
Administrator adminCorbaObj = adminpoa._this(orb);
adminProxy.loginToManager(adminCorbaObj, false);
int adminManagerHandle = adminProxy.getManagerHandle();
Assert.assertTrue(adminManagerHandle > 0);
loggedInToManager = true;
}
}
public void logoutFromManager() {
if (loggedInToManager) {
adminProxy.logoutFromManager();
loggedInToManager = false;
}
}
// Container access
public List<ContainerInfo> getAllContainerInfos() throws NoPermissionEx, AcsJContainerEx {
if (!loggedInToManager) {
throw new IllegalStateException("must be logged in to the manager.");
}
ContainerInfo[] containerInfos = adminProxy.getManager().get_container_info(adminProxy.getManagerHandle(), new int[0], "*");
return Arrays.asList(containerInfos);
}
public boolean isContainerLoggedIn(String containerName) throws AcsJContainerEx, NoPermissionEx {
if (!loggedInToManager) {
throw new IllegalStateException("must be logged in to the manager.");
}
ContainerInfo[] containerInfos =
adminProxy.getManager().get_container_info(adminProxy.getManagerHandle(), new int[0], containerName);
Assert.assertTrue("Expected 0 or 1 container of name " + containerName + " but found " + containerInfos.length,
containerInfos.length <= 1);
return (containerInfos.length == 1);
}
/**
* Gets a reference to the LoggingConfigurableOperations interface of a container with a given name.
* <p>
* Note that only in test code like here we are allowed to talk directly with the manager.
* For operational code, the ContainerServices methods must be used and extended if necessary.
*
* @param containerName
*/
public LoggingConfigurableOperations getContainerLoggingIF(String containerName) throws AcsJContainerEx, NoPermissionEx {
for (ContainerInfo containerInfo : getAllContainerInfos()) {
if (containerInfo.name.equals(containerName)) {
return LoggingConfigurableHelper.narrow(containerInfo.reference);
}
}
Assert.fail("No container '" + containerName + "' found.");
return null; // to appease the compile which does not see the terminal nature of Assert.fail
}
/**
* Complete logging spec for a container.
*/
public static class ContainerLogLevelSpec {
private AcsLogLevelDefinition defaultMin;
private AcsLogLevelDefinition defaultMinLocal;
private Map<String, AcsLogLevelDefinition[]> namedLoggerMap = new HashMap<String, AcsLogLevelDefinition[]>();
public ContainerLogLevelSpec(AcsLogLevelDefinition defaultMin, AcsLogLevelDefinition defaultMinLocal) {
this.defaultMin = defaultMin;
this.defaultMinLocal = defaultMinLocal;
}
public void addNamedLoggerSpec(String name, AcsLogLevelDefinition levelMin, AcsLogLevelDefinition levelMinLocal) {
AcsLogLevelDefinition[] levels = new AcsLogLevelDefinition[] {levelMin, levelMinLocal};
namedLoggerMap.put(name, levels);
}
public void configure(LoggingConfigurableOperations target) {
LogLevels defaultLogLevels = new LogLevels(false, (short)defaultMin.value, (short)defaultMinLocal.value);
try {
target.set_default_logLevels(defaultLogLevels);
} catch (IllegalArgumentEx ex) {
ex.printStackTrace();
}
for (String loggerName : namedLoggerMap.keySet()) {
AcsLogLevelDefinition[] levels = namedLoggerMap.get(loggerName);
LogLevels namedLogLevels = new LogLevels(false, (short)levels[0].value, (short)levels[1].value);
try {
target.set_logLevels(loggerName, namedLogLevels);
} catch (LoggerDoesNotExistEx ex) {
ex.printStackTrace();
} catch (IllegalArgumentEx ex) {
ex.printStackTrace();
}
}
}
}
/**
* Dynamically configures container log levels, using {@link #getContainerLoggingIF(String)}.
* @param containerName
* @param defaultConfig
* @param namedLoggerConfigs
*/
public void setContainerLogLevels(String containerName, ContainerLogLevelSpec spec) throws AcsJContainerEx, NoPermissionEx {
LoggingConfigurableOperations loggingConfigurable = getContainerLoggingIF(containerName);
spec.configure(loggingConfigurable);
}
/**
* Gets the name of the container running (or configured to run) the component of the given name.
*/
public String resolveContainerName(String componentName) throws AcsJContainerEx, NoPermissionEx {
if (!loggedInToManager) {
throw new IllegalStateException("must be logged in to the manager.");
}
ComponentInfo[] componentInfos = adminProxy.getManager().get_component_info(adminProxy.getManagerHandle(), new int[0], componentName, "*", false);
Assert.assertNotNull(componentInfos);
Assert.assertEquals("Exactly one match for component name '" + componentName + "' expected.", 1, componentInfos.length);
String containerName = componentInfos[0].container_name;
Assert.assertNotNull(containerName);
return containerName;
}
// Container daemon access
/**
* @TODO possibly cache the daemon references for the various host machines.
* @param host
* @return
*/
public ContainerDaemonOperations getContainerDaemon(String host) {
String daemonCORBALOC = AcsLocations.convertToContainerDaemonLocation(host);
ContainerDaemonOperations daemon = null;
try {
org.omg.CORBA.Object obj = orb.string_to_object(daemonCORBALOC);
daemon = ContainerDaemonHelper.narrow(obj);
if (daemon == null) {
throw new NullPointerException("Daemon object was null");
}
} catch (Throwable thr) {
throw new RuntimeException("Failed to resolve daemon reference for " + daemonCORBALOC, thr);
}
return daemon;
}
/**
* Starts (possibly remote) containers using container daemons.
* <p>
* Note that outside of performance tests it is required to start containers either through the OMC
* or by the manager in case of CDB-configured autostart containers.
* Here we do it from application code in order to run flexible tests that don't require a CDB setup.
* <p>
* Similar code from module acscommandcenter (Executor#remoteDaemonForContainers) does not seem to implement
* synchronization on the container becoming available.
*
* @param host Name of container host. Can be <code>null</code> for localhost.
* @param containerType
* @param containerName
* @param flags
* @param waitContainerReady If true, waits for the container to be ready, as indicated by a callback from the manager (requires prior login to the manager).
* @throws FailedToStartContainerEx
* @throws BadParameterEx
*/
public void startContainer(String host, ContainerImplLangType containerType, String containerName, String flags, boolean waitContainerReady)
throws AcsJBadParameterEx, AcsJFailedToStartContainerEx {
if (!loggedInToManager && waitContainerReady ) {
throw new IllegalStateException("must be logged in to the manager if waitContainerReady==true");
}
if (host == null || host.isEmpty()) {
host = ACSPorts.getIP();
}
if (flags == null) {
flags = "";
}
ContainerDaemonOperations daemon = getContainerDaemon(host);
String containerTypeName = containerType.toString(); // TODO check that string is as expected by daemon, e.g. "py" vs. "python"
short instanceNumber = (short) ACSPorts.getBasePort();
try {
daemon.start_container(containerTypeName, containerName, instanceNumber, new String[0], flags);
} catch (BadParameterEx ex) {
throw new AcsJBadParameterEx();
}
catch (FailedToStartContainerEx ex) {
throw new AcsJFailedToStartContainerEx();
}
if (waitContainerReady) {
boolean containerOK = false;
try {
containerOK = managerAdminClient.awaitContainerLogin(containerName, 30, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
// just leave containerOK = false
}
if (!containerOK) {
throw new AcsJFailedToStartContainerEx("Did not receive manager notification about container '" +
containerName + "' having logged in.");
}
}
}
/**
* @param host Name of container host. Can be <code>null</code> for localhost.
* @param containerName
*/
public void stopContainer(String host, String containerName) throws BadParameterEx, FailedToStopContainerEx {
if (host == null || host.isEmpty()) {
host = ACSPorts.getIP();
}
ContainerDaemonOperations daemon = getContainerDaemon(host);
short instanceNumber = (short) ACSPorts.getBasePort();
daemon.stop_container(containerName, instanceNumber, "");
}
}
|
package org.intermine.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.poi.hssf.usermodel.*;
import org.intermine.web.results.PagedTable;
/**
* Implemented by objects that can export PagedTables.
*
* @author Kim Rutherford
*/
public interface TableExporter
{
/**
* Method called to export a PagedTable object
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward export(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception;
/**
* Check if this TableExporter can export the given PagedTable.
* @param pt the PagedTable
* @return true if and only if this TableExporter can export the argument PagedTable
*/
public boolean canExport(PagedTable pt);
}
|
package com.smartnsoft.droid4me.app;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import com.smartnsoft.droid4me.LifeCycle;
import com.smartnsoft.droid4me.app.AppPublics.BroadcastListener;
import com.smartnsoft.droid4me.framework.ActivityResultHandler.CompositeHandler;
import com.smartnsoft.droid4me.log.Logger;
import com.smartnsoft.droid4me.log.LoggerFactory;
import com.smartnsoft.droid4me.menu.MenuCommand;
import com.smartnsoft.droid4me.menu.MenuHandler;
import com.smartnsoft.droid4me.menu.MenuHandler.Composite;
import com.smartnsoft.droid4me.menu.StaticMenuCommand;
public final class Droid4mizer<AggregateClass, ComponentClass>
implements Smartable<AggregateClass>
{
private static final Logger log = LoggerFactory.getInstance("Smartable");
private final Activity activity;
private final ComponentClass component;
private final ComponentClass interceptorComponent;
private final Smartable<AggregateClass> smartable;
private final AppInternals.StateContainer<AggregateClass, ComponentClass> stateContainer;
/**
* The only way to create an instance.
*
* @param activity
* the activity this instance relies on
* @param smartable
* the component to be droid4mized
* @param component
* the declared component used to determine whether {@linkplain #onRetrieveBusinessObjects() the business object should be retrieved
* asynchronously}, and to {@linkplain #registerBroadcastListeners(BroadcastListener[]) register broadcast listeners}
* @param interceptorComponent
* the declared component used to send life-cycle events to the {@link ActivityController.Interceptor}
*/
public Droid4mizer(Activity activity, Smartable<AggregateClass> smartable, ComponentClass component, ComponentClass interceptorComponent)
{
this.activity = activity;
this.smartable = smartable;
this.component = component;
this.interceptorComponent = interceptorComponent;
stateContainer = new AppInternals.StateContainer<AggregateClass, ComponentClass>(activity, component);
}
/*
* The {@link Smarted} methods.
*/
public AggregateClass getAggregate()
{
return stateContainer.getAggregate();
}
public void setAggregate(AggregateClass aggregate)
{
stateContainer.setAggregate(aggregate);
}
public Handler getHandler()
{
return stateContainer.getHandler();
}
public List<StaticMenuCommand> getMenuCommands()
{
return smartable.getMenuCommands();
}
public void onException(Throwable throwable, boolean fromGuiThread)
{
ActivityController.getInstance().handleException(activity, interceptorComponent, throwable);
}
public void registerBroadcastListeners(BroadcastListener[] broadcastListeners)
{
stateContainer.registerBroadcastListeners(broadcastListeners);
}
public void onBusinessObjectsRetrieved()
{
}
/**
* Same as invoking {@link #refreshBusinessObjectsAndDisplay(true, null, false)}.
*
* @see #refreshBusinessObjectsAndDisplay(boolean, Runnable, boolean)
*/
public void refreshBusinessObjectsAndDisplay()
{
refreshBusinessObjectsAndDisplay(true, null, false);
}
/**
* Same as invoking {@link #refreshBusinessObjectsAndDisplay(boolean, null, false)}.
*
* @see #refreshBusinessObjectsAndDisplay(boolean, Runnable, boolean)
*/
public final void refreshBusinessObjectsAndDisplay(boolean retrieveBusinessObjects)
{
refreshBusinessObjectsAndDisplay(retrieveBusinessObjects, null, false);
}
public void refreshBusinessObjectsAndDisplay(final boolean retrieveBusinessObjects, final Runnable onOver, boolean immediately)
{
if (stateContainer.shouldDelayRefreshBusinessObjectsAndDisplay(retrieveBusinessObjects, onOver, immediately) == true)
{
return;
}
stateContainer.onRefreshingBusinessObjectsAndDisplayStart();
// We can safely retrieve the business objects
if (!(component instanceof LifeCycle.BusinessObjectsRetrievalAsynchronousPolicy))
{
if (onRetrieveBusinessObjectsInternal(retrieveBusinessObjects) == false)
{
return;
}
onFulfillAndSynchronizeDisplayObjectsInternal(onOver);
}
else
{
// We call that routine asynchronously in a background thread
stateContainer.execute(activity, component, new Runnable()
{
public void run()
{
if (onRetrieveBusinessObjectsInternal(retrieveBusinessObjects) == false)
{
return;
}
// If the activity has been finished in the meantime, no need to update the UI
if (activity.isFinishing() == true)
{
return;
}
// We are handling the UI, and we need to make sure that this is done through the GUI thread
activity.runOnUiThread(new Runnable()
{
public void run()
{
onFulfillAndSynchronizeDisplayObjectsInternal(onOver);
}
});
}
});
}
}
/*
* The {@link AppPublics.LifeCyclePublic} methods.
*/
public boolean isRefreshingBusinessObjectsAndDisplay()
{
return stateContainer.isRefreshingBusinessObjectsAndDisplay();
}
public final int getOnSynchronizeDisplayObjectsCount()
{
return stateContainer.getOnSynchronizeDisplayObjectsCount();
}
public final boolean isFirstLifeCycle()
{
return stateContainer.isFirstLifeCycle();
}
public final boolean isInteracting()
{
return stateContainer.isInteracting();
}
/*
* The {@link AppInternals.LifeCycleInternals} methods.
*/
public boolean shouldKeepOn()
{
return stateContainer.shouldKeepOn();
}
public Composite getCompositeActionHandler()
{
return stateContainer.compositeActionHandler;
}
public CompositeHandler getCompositeActivityResultHandler()
{
return stateContainer.compositeActivityResultHandler;
}
/*
* The {@link Activity}/{@link Fragment} methods.
*/
public void onCreate(Runnable superMethod, Bundle savedInstanceState)
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onCreate");
}
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onSuperCreateBefore);
superMethod.run();
if (ActivityController.getInstance().needsRedirection(activity) == true)
{
// We stop here if a redirection is needed
stateContainer.beingRedirected();
return;
}
else
{
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onCreate);
}
if (savedInstanceState != null && savedInstanceState.containsKey(AppInternals.ALREADY_STARTED) == true)
{
stateContainer.setFirstLifeCycle(false);
}
else
{
stateContainer.setFirstLifeCycle(true);
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onActuallyCreatedDone);
}
stateContainer.registerBroadcastListeners();
stateContainer.initialize();
try
{
onRetrieveDisplayObjects();
}
catch (Throwable throwable)
{
stateContainer.stopHandling();
onException(throwable, true);
return;
}
// We add the static menu commands
smartable.getCompositeActionHandler().add(new MenuHandler.Static()
{
@Override
protected List<MenuCommand<Void>> retrieveCommands()
{
final List<StaticMenuCommand> staticMenuCommands = getMenuCommands();
if (staticMenuCommands == null)
{
return null;
}
final List<MenuCommand<Void>> menuCommands = new ArrayList<MenuCommand<Void>>(staticMenuCommands.size());
for (StaticMenuCommand staticMenuCommand : staticMenuCommands)
{
menuCommands.add(staticMenuCommand);
}
return menuCommands;
}
});
}
public void onNewIntent(Intent intent)
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onNewIntent");
}
if (ActivityController.getInstance().needsRedirection(activity) == true)
{
// We stop here if a redirection is needed
stateContainer.beingRedirected();
}
}
public void onContentChanged()
{
if (shouldKeepOn() == false)
{
return;
}
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onContentChanged);
}
public void onResume()
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onResume");
}
if (shouldKeepOn() == false)
{
return;
}
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onResume);
stateContainer.onResume();
businessObjectRetrievalAndResultHandlers();
}
public void onSaveInstanceState(Bundle outState)
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onSaveInstanceState");
}
stateContainer.onSaveInstanceState(outState);
}
public void onRestoreInstanceState(Bundle savedInstanceState)
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onRestoreInstanceState");
}
businessObjectRetrievalAndResultHandlers();
}
public void onStart()
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onStart");
}
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onStart);
stateContainer.onStart();
}
public void onPause()
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onPause");
}
if (shouldKeepOn() == false)
{
// We stop here if a redirection is needed or is something went wrong
return;
}
else
{
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onPause);
stateContainer.onPause();
}
}
public void onStop()
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onStop");
}
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onStop);
stateContainer.onStop();
}
public void onDestroy()
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onDestroy");
}
stateContainer.onDestroy();
if (shouldKeepOn() == false)
{
// We stop here if a redirection is needed or is something went wrong
return;
}
if (stateContainer.isDoNotCallOnActivityDestroyed() == false)
{
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onActuallyDestroyedDone);
}
else
{
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent, ActivityController.Interceptor.InterceptorEvent.onDestroy);
}
}
public boolean onCreateOptionsMenu(boolean superResult, Menu menu)
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onCreateOptionsMenu");
}
if (stateContainer.compositeActionHandler != null)
{
stateContainer.compositeActionHandler.onCreateOptionsMenu(activity, menu);
}
else
{
if (log.isErrorEnabled())
{
log.error("onCreateOptionsMenu() being called whereas the 'stateContainer.compositeActionHandler' has not yet been initialized!");
}
}
return superResult;
}
public boolean onPrepareOptionsMenu(boolean superResult, Menu menu)
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onPrepareOptionsMenu");
}
if (stateContainer.compositeActionHandler != null)
{
stateContainer.compositeActionHandler.onPrepareOptionsMenu(menu);
}
else
{
if (log.isErrorEnabled())
{
log.error("onPrepareOptionsMenu() being called whereas the 'stateContainer.compositeActionHandler' has not yet been initialized!");
}
}
return superResult;
}
public boolean onOptionsItemSelected(boolean superResult, MenuItem item)
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onOptionsItemSelected");
}
if (stateContainer.compositeActionHandler != null)
{
if (stateContainer.compositeActionHandler.onOptionsItemSelected(item) == true)
{
return true;
}
}
else
{
if (log.isErrorEnabled())
{
log.error("onOptionsItemSelected() being called whereas the 'stateContainer.compositeActionHandler' has not yet been initialized!");
}
}
return superResult;
}
public boolean onContextItemSelected(boolean superResult, MenuItem item)
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onContextItemSelected");
}
if (stateContainer.compositeActionHandler.onContextItemSelected(item) == true)
{
return true;
}
return superResult;
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (log.isDebugEnabled())
{
log.debug("Droid4mizer::onActivityResult");
}
// // BUG: this seems to be a bug in Android, because this method is invoked before the "onResume()"
// try
// businessObjectRetrievalAndResultHandlers();
// catch (Throwable throwable)
// handleUnhandledException(throwable);
// return;
smartable.getCompositeActivityResultHandler().handle(requestCode, resultCode, data);
}
/*
* The LifeCycle interface implementation.
*/
public void onFulfillDisplayObjects()
{
smartable.onFulfillDisplayObjects();
}
public void onRetrieveBusinessObjects()
throws BusinessObjectUnavailableException
{
smartable.onRetrieveBusinessObjects();
}
public void onRetrieveDisplayObjects()
{
smartable.onRetrieveDisplayObjects();
}
public void onSynchronizeDisplayObjects()
{
smartable.onSynchronizeDisplayObjects();
}
public SharedPreferences getPreferences()
{
return stateContainer.getPreferences(activity);
}
/*
* The specific methods.
*/
/**
* This method should not trigger any exception!
*/
private boolean onRetrieveBusinessObjectsInternal(boolean retrieveBusinessObjects)
{
onBeforeRefreshBusinessObjectsAndDisplay();
if (retrieveBusinessObjects == true)
{
try
{
onRetrieveBusinessObjects();
}
catch (Throwable throwable)
{
stateContainer.onRefreshingBusinessObjectsAndDisplayStop(this);
onInternalBusinessObjectAvailableException(throwable);
return false;
}
}
stateContainer.setBusinessObjectsRetrieved();
return true;
}
private void onBeforeRefreshBusinessObjectsAndDisplay()
{
stateContainer.onStartLoading();
}
private void onFulfillAndSynchronizeDisplayObjectsInternal(Runnable onOver)
{
if (stateContainer.isResumedForTheFirstTime() == true)
{
try
{
onFulfillDisplayObjects();
}
catch (Throwable throwable)
{
stateContainer.onRefreshingBusinessObjectsAndDisplayStop(this);
onException(throwable, true);
stateContainer.onStopLoading();
return;
}
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent,
ActivityController.Interceptor.InterceptorEvent.onFulfillDisplayObjectsDone);
}
try
{
stateContainer.onSynchronizeDisplayObjects();
onSynchronizeDisplayObjects();
}
catch (Throwable throwable)
{
stateContainer.onRefreshingBusinessObjectsAndDisplayStop(this);
onException(throwable, true);
return;
}
finally
{
stateContainer.onStopLoading();
}
ActivityController.getInstance().onLifeCycleEvent(activity, interceptorComponent,
ActivityController.Interceptor.InterceptorEvent.onSynchronizeDisplayObjectsDone);
stateContainer.markNotResumedForTheFirstTime();
if (onOver != null)
{
try
{
onOver.run();
}
catch (Throwable throwable)
{
if (log.isErrorEnabled())
{
log.error("An exception occurred while executing the 'refreshBusinessObjectsAndDisplay()' runnable!", throwable);
}
}
}
stateContainer.onRefreshingBusinessObjectsAndDisplayStop(this);
}
private void businessObjectRetrievalAndResultHandlers()
{
smartable.refreshBusinessObjectsAndDisplay(stateContainer.isRetrieveBusinessObjects(), stateContainer.getRetrieveBusinessObjectsOver(), true);
if (stateContainer.actionResultsRetrieved == false)
{
onRegisterResultHandlers(stateContainer.compositeActivityResultHandler);
stateContainer.actionResultsRetrieved = true;
}
}
private final void onInternalBusinessObjectAvailableException(Throwable throwable)
{
if (log.isErrorEnabled())
{
log.error("Cannot retrieve the business objects", throwable);
}
stateContainer.onStopLoading();
if (stateContainer.onInternalBusinessObjectAvailableExceptionWorkAround(throwable) == true)
{
return;
}
// We need to invoke that method on the GUI thread, because that method may have been triggered from another thread
onException(throwable, false);
}
private void onRegisterResultHandlers(CompositeHandler compositeActivityResultHandler)
{
// THINK: should we plug the feature?
}
}
|
package com.malhartech.dag;
import com.malhartech.util.CircularBuffer;
import java.io.IOException;
import java.nio.BufferOverflowException;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The for context for all of the operators<p>
* <br>
*
* @author Chetan Narsude <chetan@malhar-inc.com>
*/
public class ModuleContext implements Context
{
private static final Logger LOG = LoggerFactory.getLogger(ModuleContext.class);
public interface ModuleRequest
{
/**
* Command to be executed at subsequent end of window.
* Current used for module state saving, but applicable more widely.
*/
public void execute(Module module, String id, long windowId) throws IOException;
}
private long lastProcessedWindowId;
private final String id;
// the size of the circular queue should be configurable. hardcoded to 1024 for now.
private final CircularBuffer<HeartbeatCounters> heartbeatCounters = new CircularBuffer<HeartbeatCounters>(1024);
private final CircularBuffer<ModuleRequest> requests = new CircularBuffer<ModuleRequest>(4);
/**
* The AbstractModule to which this context is passed, will timeout after the following milliseconds if no new tuple has been received by it.
*/
// we should make it configurable somehow.
private long idleTimeout = 1000L;
public CircularBuffer<ModuleRequest> getRequests()
{
return requests;
}
/**
* @return the idleTimeout
*/
public long getIdleTimeout()
{
return idleTimeout;
}
/**
* @param idleTimeout the idleTimeout to set
*/
public void setIdleTimeout(long idleTimeout)
{
this.idleTimeout = idleTimeout;
}
public ModuleContext(String id, Thread t)
{
this.id = id;
}
public String getId()
{
return id;
}
/**
* Reset counts for next heartbeateinterval and return current counts. This is called as part of the heartbeat processing.
*
* @return int
*/
public final synchronized int drainHeartbeatCounters(Collection<? super HeartbeatCounters> counters)
{
return heartbeatCounters.drainTo(counters);
}
public final synchronized long getLastProcessedWindowId()
{
return lastProcessedWindowId;
}
synchronized void report(int consumedTupleCount, long processedBytes, long windowId)
{
lastProcessedWindowId = windowId;
HeartbeatCounters newWindow = new HeartbeatCounters();
newWindow.windowId = windowId;
newWindow.tuplesProcessed = consumedTupleCount;
newWindow.bytesProcessed = processedBytes;
try {
heartbeatCounters.add(newWindow);
}
catch (BufferOverflowException boe) {
heartbeatCounters.get();
heartbeatCounters.add(newWindow);
}
}
public void request(ModuleRequest request)
{
LOG.debug("Received request {} for (node={})", request, id);
requests.add(request);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.malhartech.dag;
import com.malhartech.bufferserver.Buffer.Data;
import com.malhartech.stram.StreamContext;
import com.malhartech.stram.StreamingNodeContext;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author chetan
*/
public abstract class AbstractNode implements Runnable, Node
{
class Blah {}
final StreamingNodeContext ctx;
final PriorityQueue<Tuple> inputQueue;
final HashMap<StreamContext, Sink> outputStreams = new HashMap<StreamContext, Sink>();
final HashMap<StreamContext, Blah> inputStreams = new HashMap<StreamContext, Blah>();
public AbstractNode(StreamingNodeContext ctx)
{
// initial capacity should be some function of the window length
this.ctx = ctx;
this.inputQueue = new PriorityQueue<Tuple>(1024 * 1024, new DataComparator());
}
// i feel that we may just want to push the data out from here and depending upon
// whether the data needs to flow on the stream (as per partitions), the streams
// create tuples or drop the data on the floor.
private Data currentData = null;
public void emit(Object o)
{
for (Entry<StreamContext, Sink> entry : outputStreams.entrySet()) {
Tuple t = new Tuple(o, entry.getKey());
t.data = currentData;
entry.getValue().doSomething(t);
}
}
public void emitStream(Object o, StreamContext ctx)
{
Tuple t = new Tuple(o, ctx);
t.data = currentData;
outputStreams.get(ctx).doSomething(t);
}
public void connectOutputStreams(Collection<Sink> streams)
{
for (Sink stream : streams) {
outputStreams.put(stream.getStreamContext(), stream);
}
}
public void connectInputStreams(Collection<StreamContext> streams)
{
for (StreamContext stream : streams) {
inputStreams.put(stream, new Blah());
}
}
public long getWindowId(Data d)
{
long windowId;
switch (d.getType()) {
case BEGIN_WINDOW:
windowId = d.getWindowId();
break;
case END_WINDOW:
windowId = d.getWindowId();
break;
case SIMPLE_DATA:
windowId = d.getWindowId();
break;
case PARTITIONED_DATA:
windowId = d.getWindowId();
break;
default:
windowId = 0;
break;
}
return windowId;
}
final class DataComparator implements Comparator<Tuple>
{
public int compare(Tuple t, Tuple t1)
{
Data d = t.data;
Data d1 = t1.data;
if (d != d1) {
long tid = getWindowId(d);
long t1id = getWindowId(d1);
if (tid < t1id) {
return -1;
}
else if (tid > t1id) {
return 1;
}
else if (d.getType() == Data.DataType.BEGIN_WINDOW) {
return -1;
}
else if (d1.getType() == Data.DataType.BEGIN_WINDOW) {
return 1;
}
else if (d.getType() == Data.DataType.END_WINDOW) {
return 1;
}
else if (d1.getType() == Data.DataType.END_WINDOW) {
return -1;
}
}
return 0;
}
}
private boolean alive;
public void stopSafely() {
alive = false;
}
public void run()
{
alive = true;
setup(ctx);
int canStartNewWindow = 0;
boolean shouldWait = false;
long currentWindow = 0;
int tupleCount = 0;
while (alive) {
Tuple t;
synchronized (inputQueue) {
if ((t = inputQueue.peek()) == null) {
shouldWait = true;
}
else {
Data d = t.getData();
switch (d.getType()) {
case BEGIN_WINDOW:
if (canStartNewWindow == 0) {
tupleCount = 0;
canStartNewWindow = inputStreams.size();
inputQueue.poll();
currentWindow = d.getWindowId();
shouldWait = false;
}
else if (d.getWindowId() == currentWindow) {
shouldWait = false;
}
else {
shouldWait = true;
}
break;
case END_WINDOW:
if (d.getWindowId() == currentWindow
&& d.getEndwindow().getTupleCount() <= tupleCount) {
tupleCount -= d.getEndwindow().getTupleCount();
if (tupleCount == 0) {
canStartNewWindow
inputQueue.poll();
shouldWait = false;
}
}
else {
shouldWait = true;
}
break;
default:
if (d.getType() == Data.DataType.SIMPLE_DATA
&& d.getWindowId() == currentWindow) {
tupleCount++;
inputQueue.poll();
shouldWait = false;
}
else if (d.getType() == Data.DataType.PARTITIONED_DATA
&& d.getWindowId() == currentWindow) {
tupleCount++;
inputQueue.poll();
shouldWait = false;
}
else {
shouldWait = true;
}
break;
}
}
if (shouldWait) {
try {
inputQueue.wait();
}
catch (InterruptedException ex) {
Logger.getLogger(AbstractNode.class.getName()).log(Level.SEVERE, null, ex);
}
}
else {
currentData = t.data;
/*
* we process this outside to keep the critical region free.
*/
switch (currentData.getType()) {
case BEGIN_WINDOW:
beginWindow(currentWindow);
break;
case END_WINDOW:
endWidndow(currentWindow);
break;
default:
process(t);
break;
}
}
}
}
teardown(ctx);
}
}
|
package com.malhartech.stram;
import com.malhartech.api.Context.PortContext;
import com.malhartech.api.Operator.InputPort;
import com.malhartech.api.Operator.OutputPort;
import com.malhartech.api.Operator.Unifier;
import com.malhartech.api.*;
import com.malhartech.bufferserver.Server;
import com.malhartech.bufferserver.storage.DiskStorage;
import com.malhartech.bufferserver.util.Codec;
import com.malhartech.engine.Operators.PortMappingDescriptor;
import com.malhartech.engine.*;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeat;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat.DNodeState;
import com.malhartech.stream.*;
import com.malhartech.util.AttributeMap;
import com.malhartech.util.ScheduledThreadPoolExecutor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URISyntaxException;
import java.security.PrivilegedExceptionAction;
import java.util.Map.Entry;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.log4j.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* The main() for streaming container processes launched by {@link com.malhartech.stram.StramAppMaster}.<p>
* <br>
*
*/
public class StramChild
{
private static final Logger logger = LoggerFactory.getLogger(StramChild.class);
private static final String NODE_PORT_SPLIT_SEPARATOR = "\\.";
public static final String NODE_PORT_CONCAT_SEPARATOR = ".";
private static final int SPIN_MILLIS = 20;
private final String containerId;
private final Configuration conf;
private final StreamingContainerUmbilicalProtocol umbilical;
protected final Map<Integer, Node<?>> nodes = new ConcurrentHashMap<Integer, Node<?>>();
private final Map<String, ComponentContextPair<Stream<Object>, StreamContext>> streams = new ConcurrentHashMap<String, ComponentContextPair<Stream<Object>, StreamContext>>();
protected final Map<Integer, WindowGenerator> generators = new ConcurrentHashMap<Integer, WindowGenerator>();
protected final Map<Integer, OperatorContext> activeNodes = new ConcurrentHashMap<Integer, OperatorContext>();
private final Map<Stream<?>, StreamContext> activeStreams = new ConcurrentHashMap<Stream<?>, StreamContext>();
private final Map<WindowGenerator, Object> activeGenerators = new ConcurrentHashMap<WindowGenerator, Object>();
private int heartbeatIntervalMillis = 1000;
private volatile boolean exitHeartbeatLoop = false;
private final Object heartbeatTrigger = new Object();
private String checkpointFsPath;
private String appPath;
/**
* Map of last backup window id that is used to communicate checkpoint state back to Stram. TODO: Consider adding this to the node context instead.
*/
private final Map<Integer, Long> backupInfo = new ConcurrentHashMap<Integer, Long>();
private long firstWindowMillis;
private int windowWidthMillis;
private InetSocketAddress bufferServerAddress;
private com.malhartech.bufferserver.Server bufferServer;
private AttributeMap<DAGContext> applicationAttributes;
protected HashMap<String, TupleRecorder> tupleRecorders = new HashMap<String, TupleRecorder>();
private int tupleRecordingPartFileSize;
private String daemonAddress;
private long tupleRecordingPartFileTimeMillis;
protected StramChild(String containerId, Configuration conf, StreamingContainerUmbilicalProtocol umbilical)
{
logger.debug("instantiated StramChild {}", containerId);
this.umbilical = umbilical;
this.containerId = containerId;
this.conf = conf;
}
public void setup(StreamingContainerContext ctx)
{
this.applicationAttributes = ctx.applicationAttributes;
heartbeatIntervalMillis = ctx.applicationAttributes.attrValue(DAG.STRAM_HEARTBEAT_INTERVAL_MILLIS, 1000);
firstWindowMillis = ctx.startWindowMillis;
windowWidthMillis = ctx.applicationAttributes.attrValue(DAG.STRAM_WINDOW_SIZE_MILLIS, 500);
this.appPath = ctx.applicationAttributes.attrValue(DAG.STRAM_APP_PATH, "app-dfs-path-not-configured");
this.checkpointFsPath = this.appPath + "/" + DAG.SUBDIR_CHECKPOINTS;
this.tupleRecordingPartFileSize = ctx.applicationAttributes.attrValue(DAG.STRAM_TUPLE_RECORDING_PART_FILE_SIZE, 100 * 1024);
this.tupleRecordingPartFileTimeMillis = ctx.applicationAttributes.attrValue(DAG.STRAM_TUPLE_RECORDING_PART_FILE_TIME_MILLIS, 30 * 60 * 60 * 1000);
this.daemonAddress = ctx.applicationAttributes.attrValue(DAG.STRAM_DAEMON_ADDRESS, null);
try {
if (ctx.deployBufferServer) {
// start buffer server, if it was not set externally
bufferServer = new Server(0, 64 * 1024 * 1024, 8);
bufferServer.setSpoolStorage(new DiskStorage());
SocketAddress bindAddr = bufferServer.run();
logger.info("Buffer server started: {}", bindAddr);
this.bufferServerAddress = NetUtils.getConnectAddress(((InetSocketAddress)bindAddr));
}
}
catch (Exception ex) {
logger.warn("deploy request failed due to {}", ex);
throw new IllegalStateException("Failed to deploy buffer server", ex);
}
}
public String getContainerId()
{
return this.containerId;
}
public TupleRecorder getTupleRecorder(int operId, String portName)
{
return tupleRecorders.get(getRecorderKey(operId, portName));
}
/**
* Initialize container. Establishes heartbeat connection to the master
* process through the callback address provided on the command line. Deploys
* initial modules, then enters the heartbeat loop, which will only terminate
* once container receives shutdown request from the master. On shutdown,
* after exiting heartbeat loop, deactivate all modules and terminate
* processing threads.
*
* @param args
* @throws Throwable
*/
public static void main(String[] args) throws Throwable
{
logger.info("Child starting with classpath: {}", System.getProperty("java.class.path"));
final Configuration defaultConf = new Configuration();
//defaultConf.addResource(MRJobConfig.JOB_CONF_FILE);
UserGroupInformation.setConfiguration(defaultConf);
String host = args[0];
int port = Integer.parseInt(args[1]);
final InetSocketAddress address =
NetUtils.createSocketAddrForHost(host, port);
final String childId = System.getProperty("stram.cid");
//Token<JobTokenIdentifier> jt = loadCredentials(defaultConf, address);
// Communicate with parent as actual task owner.
UserGroupInformation taskOwner =
UserGroupInformation.createRemoteUser(StramChild.class.getName());
//taskOwner.addToken(jt);
final StreamingContainerUmbilicalProtocol umbilical =
taskOwner.doAs(new PrivilegedExceptionAction<StreamingContainerUmbilicalProtocol>()
{
@Override
public StreamingContainerUmbilicalProtocol run() throws Exception
{
return RPC.getProxy(StreamingContainerUmbilicalProtocol.class,
StreamingContainerUmbilicalProtocol.versionID, address, defaultConf);
}
});
logger.debug("PID: " + System.getenv().get("JVM_PID"));
UserGroupInformation childUGI;
int exitStatus = 1;
try {
childUGI = UserGroupInformation.createRemoteUser(System.getenv(ApplicationConstants.Environment.USER.toString()));
// Add tokens to new user so that it may execute its task correctly.
for (Token<?> token: UserGroupInformation.getCurrentUser().getTokens()) {
childUGI.addToken(token);
}
childUGI.doAs(new PrivilegedExceptionAction<Object>()
{
@Override
public Object run() throws Exception
{
StreamingContainerContext ctx = umbilical.getInitContext(childId);
StramChild stramChild = new StramChild(childId, defaultConf, umbilical);
logger.debug("Got context: " + ctx);
stramChild.setup(ctx);
try {
// main thread enters heartbeat loop
stramChild.monitorHeartbeat();
}
finally {
// teardown
stramChild.teardown();
}
return null;
}
});
exitStatus = 0;
}
catch (Exception exception) {
logger.warn("Exception running child : "
+ StringUtils.stringifyException(exception));
// Report back any failures, for diagnostic purposes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
exception.printStackTrace(new PrintStream(baos));
umbilical.log(childId, "FATAL: " + baos.toString());
}
catch (Throwable throwable) {
logger.error("Error running child : "
+ StringUtils.stringifyException(throwable));
Throwable tCause = throwable.getCause();
String cause = tCause == null
? throwable.getMessage()
: StringUtils.stringifyException(tCause);
umbilical.log(childId, cause);
}
finally {
RPC.stopProxy(umbilical);
DefaultMetricsSystem.shutdown();
// Shutting down log4j of the child-vm...
// This assumes that on return from Task.activate()
// there is no more logging done.
LogManager.shutdown();
}
if (exitStatus != 0) {
System.exit(exitStatus);
}
}
public synchronized void deactivate()
{
ArrayList<Thread> activeThreads = new ArrayList<Thread>();
ArrayList<Integer> activeOperators = new ArrayList<Integer>();
for (Entry<Integer, Node<?>> e: nodes.entrySet()) {
OperatorContext oc = activeNodes.get(e.getKey());
if (oc == null) {
disconnectNode(e.getKey());
}
else {
activeThreads.add(oc.getThread());
activeOperators.add(e.getKey());
e.getValue().deactivate();
}
}
try {
Iterator<Integer> iterator = activeOperators.iterator();
for (Thread t: activeThreads) {
t.join();
disconnectNode(iterator.next());
}
assert (activeNodes.isEmpty());
}
catch (InterruptedException ex) {
logger.info("Aborting wait for for operators to get deactivated as got interrupted with {}", ex);
}
for (WindowGenerator wg: activeGenerators.keySet()) {
wg.deactivate();
}
activeGenerators.clear();
for (Stream<?> stream: activeStreams.keySet()) {
stream.deactivate();
}
activeStreams.clear();
}
private void disconnectNode(int nodeid)
{
Node<?> node = nodes.get(nodeid);
disconnectWindowGenerator(nodeid, node);
Set<String> removableStreams = new HashSet<String>(); // temporary fix - find out why List does not work.
// with the logic i have in here, the list should not contain repeated streams. but it does and that causes problem.
for (Entry<String, ComponentContextPair<Stream<Object>, StreamContext>> entry: streams.entrySet()) {
String indexingKey = entry.getKey();
Stream<?> stream = entry.getValue().component;
StreamContext context = entry.getValue().context;
String sourceIdentifier = context.getSourceId();
String sinkIdentifier = context.getSinkId();
logger.debug("considering stream {} against id {}", stream, indexingKey);
if (nodeid == Integer.parseInt(sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR)[0])) {
/*
* the stream originates at the output port of one of the operators that are going to vanish.
*/
if (activeStreams.containsKey(stream)) {
logger.debug("deactivating {}", stream);
stream.deactivate();
activeStreams.remove(stream);
}
removableStreams.add(sourceIdentifier);
String[] sinkIds = sinkIdentifier.split(", ");
for (String sinkId: sinkIds) {
if (!sinkId.startsWith("tcp:
String[] nodeport = sinkId.split(NODE_PORT_SPLIT_SEPARATOR);
Node<?> n = nodes.get(Integer.parseInt(nodeport[0]));
if (n instanceof UnifierNode) {
n.connectInputPort(nodeport[1] + "(" + sourceIdentifier + ")", null, null);
}
else if (n != null) {
// check why null pointer exception gets thrown here during shutdown! - chetan
n.connectInputPort(nodeport[1], null, null);
}
}
else if (stream.isMultiSinkCapable()) {
ComponentContextPair<Stream<Object>, StreamContext> spair = streams.get(sinkId);
logger.debug("found stream {} against {}", spair == null ? null : spair.component, sinkId);
if (spair == null) {
assert (!sinkId.startsWith("tcp:
}
else {
assert (sinkId.startsWith("tcp:
if (activeStreams.containsKey(spair.component)) {
logger.debug("deactivating {} for sink {}", spair.component, sinkId);
spair.component.deactivate();
activeStreams.remove(spair.component);
}
removableStreams.add(sinkId);
}
}
}
}
else {
/**
* the stream may or may not feed into one of the operators which are being undeployed.
*/
String[] sinkIds = sinkIdentifier.split(", ");
for (int i = sinkIds.length; i
String[] nodeport = sinkIds[i].split(NODE_PORT_SPLIT_SEPARATOR);
if (Integer.toString(nodeid).equals(nodeport[0])) {
stream.setSink(sinkIds[i], null);
if (node instanceof UnifierNode) {
node.connectInputPort(nodeport[1] + "(" + sourceIdentifier + ")", null, null);
}
else {
node.connectInputPort(nodeport[1], null, null);
}
sinkIds[i] = null;
}
}
String sinkId = null;
for (int i = sinkIds.length; i
if (sinkIds[i] != null) {
if (sinkId == null) {
sinkId = sinkIds[i];
}
else {
sinkId = sinkId.concat(", ").concat(sinkIds[i]);
}
}
}
if (sinkId == null) {
if (activeStreams.containsKey(stream)) {
logger.debug("deactivating {}", stream);
stream.deactivate();
activeStreams.remove(stream);
}
removableStreams.add(indexingKey);
}
else {
// may be we should also check if the count has changed from something to 1
// and replace mux with 1:1 sink. it's not necessary though.
context.setSinkId(sinkId);
}
}
}
for (String streamId: removableStreams) {
logger.debug("removing stream {}", streamId);
// need to check why control comes here twice to remove the stream which was deleted before.
// is it because of multiSinkCapableStream ?
ComponentContextPair<Stream<Object>, StreamContext> pair = streams.remove(streamId);
pair.component.teardown();
}
}
private void disconnectWindowGenerator(int nodeid, Node<?> node)
{
WindowGenerator chosen1 = generators.remove(nodeid);
if (chosen1 != null) {
chosen1.setSink(Integer.toString(nodeid).concat(NODE_PORT_CONCAT_SEPARATOR).concat(Node.INPUT), null);
node.connectInputPort(Node.INPUT, null, null);
int count = 0;
for (WindowGenerator wg: generators.values()) {
if (chosen1 == wg) {
count++;
}
}
if (count == 0) {
activeGenerators.remove(chosen1);
chosen1.deactivate();
chosen1.teardown();
}
}
}
private synchronized void undeploy(List<OperatorDeployInfo> nodeList)
{
logger.info("got undeploy request {}", nodeList);
/**
* make sure that all the operators which we are asked to undeploy are in this container.
*/
HashMap<Integer, Node<?>> toUndeploy = new HashMap<Integer, Node<?>>();
for (OperatorDeployInfo ndi: nodeList) {
Node<?> node = nodes.get(ndi.id);
if (node == null) {
throw new IllegalArgumentException("Node " + ndi.id + " is not hosted in this container!");
}
else if (toUndeploy.containsKey(ndi.id)) {
throw new IllegalArgumentException("Node " + ndi.id + " is requested to be undeployed more than once");
}
else {
toUndeploy.put(ndi.id, node);
}
}
// track all the ids to undeploy
// track the ones which are active
ArrayList<Thread> joinList = new ArrayList<Thread>();
ArrayList<Integer> discoList = new ArrayList<Integer>();
for (OperatorDeployInfo ndi: nodeList) {
OperatorContext oc = activeNodes.get(ndi.id);
if (oc == null) {
disconnectNode(ndi.id);
}
else {
joinList.add(oc.getThread());
discoList.add(ndi.id);
nodes.get(ndi.id).deactivate();
}
}
try {
Iterator<Integer> iterator = discoList.iterator();
for (Thread t: joinList) {
t.join();
disconnectNode(iterator.next());
}
logger.info("undeploy complete");
}
catch (InterruptedException ex) {
logger.warn("Aborted waiting for the deactivate to finish!");
}
for (OperatorDeployInfo ndi: nodeList) {
nodes.remove(ndi.id);
}
}
public void teardown()
{
deactivate();
assert (streams.isEmpty());
nodes.clear();
for (TupleRecorder entry: tupleRecorders.values()) {
entry.teardown();
}
tupleRecorders.clear();
HashSet<WindowGenerator> gens = new HashSet<WindowGenerator>();
gens.addAll(generators.values());
generators.clear();
for (WindowGenerator wg: gens) {
wg.teardown();
}
if (bufferServer != null) {
bufferServer.shutdown();
}
gens.clear();
}
protected void triggerHeartbeat()
{
synchronized (heartbeatTrigger) {
heartbeatTrigger.notifyAll();
}
}
protected void monitorHeartbeat() throws IOException
{
umbilical.log(containerId, "[" + containerId + "] Entering heartbeat loop..");
logger.debug("Entering heartbeat loop (interval is {} ms)", this.heartbeatIntervalMillis);
while (!exitHeartbeatLoop) {
synchronized (this.heartbeatTrigger) {
try {
this.heartbeatTrigger.wait(heartbeatIntervalMillis);
}
catch (InterruptedException e1) {
logger.warn("Interrupted in heartbeat loop, exiting..");
break;
}
}
long currentTime = System.currentTimeMillis();
ContainerHeartbeat msg = new ContainerHeartbeat();
msg.setContainerId(this.containerId);
if (this.bufferServerAddress != null) {
msg.bufferServerHost = this.bufferServerAddress.getHostName();
msg.bufferServerPort = this.bufferServerAddress.getPort();
}
List<StreamingNodeHeartbeat> heartbeats = new ArrayList<StreamingNodeHeartbeat>(nodes.size());
// gather heartbeat info for all operators
for (Map.Entry<Integer, Node<?>> e: nodes.entrySet()) {
StreamingNodeHeartbeat hb = new StreamingNodeHeartbeat();
hb.setNodeId(e.getKey());
hb.setGeneratedTms(currentTime);
hb.setIntervalMs(heartbeatIntervalMillis);
if (activeNodes.containsKey(e.getKey())) {
activeNodes.get(e.getKey()).drainHeartbeatCounters(hb.getWindowStats());
hb.setState(DNodeState.ACTIVE.toString());
}
else {
hb.setState(e.getValue().isAlive() ? DNodeState.FAILED.toString() : DNodeState.IDLE.toString());
}
// propagate the backup window, if any
Long backupWindowId = backupInfo.get(e.getKey());
if (backupWindowId != null) {
hb.setLastBackupWindowId(backupWindowId);
}
TupleRecorder tupleRecorder = tupleRecorders.get(String.valueOf(e.getKey()));
if (tupleRecorder != null) {
hb.addRecordingName(tupleRecorder.getRecordingName());
}
PortMappingDescriptor portMappingDescriptor = e.getValue().getPortMappingDescriptor();
for (String portName: portMappingDescriptor.inputPorts.keySet()) {
tupleRecorder = tupleRecorders.get(this.getRecorderKey(e.getKey(), portName));
if (tupleRecorder != null) {
hb.addRecordingName(tupleRecorder.getRecordingName());
}
}
for (String portName: portMappingDescriptor.outputPorts.keySet()) {
tupleRecorder = tupleRecorders.get(this.getRecorderKey(e.getKey(), portName));
if (tupleRecorder != null) {
hb.addRecordingName(tupleRecorder.getRecordingName());
}
}
heartbeats.add(hb);
}
msg.setDnodeEntries(heartbeats);
// heartbeat call and follow-up processing
//logger.debug("Sending heartbeat for {} operators.", msg.getDnodeEntries().size());
try {
ContainerHeartbeatResponse rsp = umbilical.processHeartbeat(msg);
if (rsp != null) {
processHeartbeatResponse(rsp);
// keep polling at smaller interval if work is pending
while (rsp != null && rsp.hasPendingRequests) {
logger.info("Waiting for pending request.");
synchronized (this.heartbeatTrigger) {
try {
this.heartbeatTrigger.wait(500);
}
catch (InterruptedException e1) {
logger.warn("Interrupted in heartbeat loop, exiting..");
break;
}
}
rsp = umbilical.pollRequest(this.containerId);
if (rsp != null) {
processHeartbeatResponse(rsp);
}
}
}
}
catch (Exception e) {
logger.warn("Exception received (may be during shutdown?)", e);
}
}
logger.debug("Exiting hearbeat loop");
umbilical.log(containerId, "[" + containerId + "] Exiting heartbeat loop..");
}
protected void processHeartbeatResponse(ContainerHeartbeatResponse rsp)
{
if (rsp.shutdown) {
logger.info("Received shutdown request");
this.exitHeartbeatLoop = true;
return;
}
if (rsp.undeployRequest != null) {
logger.info("Undeploy request: {}", rsp.undeployRequest);
undeploy(rsp.undeployRequest);
}
if (rsp.deployRequest != null) {
logger.info("Deploy request: {}", rsp.deployRequest);
try {
deploy(rsp.deployRequest);
}
catch (Exception e) {
logger.error("deploy request failed due to {}", e);
// TODO: report it to stram?
try {
umbilical.log(this.containerId, "deploy request failed: " + rsp.deployRequest + " " + ExceptionUtils.getStackTrace(e));
}
catch (IOException ioe) {
// ignore
}
this.exitHeartbeatLoop = true;
throw new IllegalStateException("Deploy request failed: " + rsp.deployRequest, e);
}
}
if (rsp.nodeRequests != null) {
// processing of per operator requests
for (StramToNodeRequest req: rsp.nodeRequests) {
OperatorContext nc = activeNodes.get(req.getOperatorId());
if (nc == null) {
logger.warn("Received request with invalid operator id {} ({})", req.getOperatorId(), req);
}
else {
logger.debug("Stram request: {}", req);
processStramRequest(nc, req);
}
}
}
}
abstract private class AbstractNodeRequest implements OperatorContext.NodeRequest
{
final Node<?> node;
final StramToNodeRequest snr;
AbstractNodeRequest(OperatorContext context, final StramToNodeRequest snr)
{
this.node = nodes.get(context.getId());
this.snr = snr;
}
};
/**
* Process request from stram for further communication through the protocol. Extended reporting is on a per node basis (won't occur under regular operation)
*
* @param n
* @param snr
*/
private void processStramRequest(OperatorContext context, final StramToNodeRequest snr)
{
int operatorId = snr.getOperatorId();
final Node<?> node = nodes.get(operatorId);
switch (snr.getRequestType()) {
case CHECKPOINT:
// avoid filling queue with checkpoint requests that would write same state multiple times
OperatorContext.NodeRequest nr = context.getRequests().peek();
if (nr != null && nr instanceof AbstractNodeRequest) {
AbstractNodeRequest aor = (AbstractNodeRequest)nr;
if (aor.snr.getRequestType() == StramToNodeRequest.RequestType.CHECKPOINT) {
aor.snr.setRecoveryCheckpoint(snr.getRecoveryCheckpoint());
logger.debug("Duplicates queued request, skipping {}", snr);
return;
}
}
context.request(new AbstractNodeRequest(context, snr)
{
@Override
public void execute(Operator operator, int id, long windowId) throws IOException
{
new HdfsBackupAgent(StramChild.this.conf, StramChild.this.checkpointFsPath).backup(id, windowId, operator, StramUtils.getNodeSerDe(null));
// record last backup window id for heartbeat
StramChild.this.backupInfo.put(id, windowId);
node.emitCheckpoint(windowId);
if (operator instanceof CheckpointListener) {
((CheckpointListener)operator).checkpointed(windowId);
((CheckpointListener)operator).committed(snr.getRecoveryCheckpoint());
}
}
});
break;
case START_RECORDING: {
final String portName = snr.getPortName();
logger.debug("Received start recording request for {}", getRecorderKey(operatorId, portName));
context.request(new OperatorContext.NodeRequest()
{
@Override
public void execute(Operator operator, int operatorId, long windowId) throws IOException
{
startRecording(node, operatorId, portName, false);
}
});
}
break;
case STOP_RECORDING: {
final String portName = snr.getPortName();
logger.debug("Received stop recording request for {}", getRecorderKey(operatorId, portName));
context.request(new OperatorContext.NodeRequest()
{
@Override
public void execute(Operator operator, int operatorId, long windowId) throws IOException
{
stopRecording(node, operatorId, portName);
}
});
}
break;
case SYNC_RECORDING: {
final String portName = snr.getPortName();
logger.debug("Received sync recording request for {}", getRecorderKey(operatorId, portName));
context.request(new OperatorContext.NodeRequest()
{
@Override
public void execute(Operator operator, int operatorId, long windowId) throws IOException
{
syncRecording(node, operatorId, portName);
}
});
}
break;
case SET_PROPERTY:
context.request(new OperatorContext.NodeRequest()
{
@Override
public void execute(Operator operator, int id, long windowId) throws IOException
{
final Map<String, String> properties = Collections.singletonMap(snr.setPropertyKey, snr.setPropertyValue);
logger.info("Setting property {} on operator {}", properties, operator);
DAGPropertiesBuilder.setOperatorProperties(operator, properties);
}
});
break;
default:
logger.error("Unknown request {}", snr);
}
}
private synchronized void deploy(List<OperatorDeployInfo> nodeList) throws Exception
{
/*
* A little bit of up front sanity check would reduce the percentage of deploy failures later.
*/
for (OperatorDeployInfo ndi: nodeList) {
if (nodes.containsKey(ndi.id)) {
throw new IllegalStateException("Node with id: " + ndi.id + " already present in the container");
}
}
deployNodes(nodeList);
HashMap<String, ArrayList<String>> groupedInputStreams = new HashMap<String, ArrayList<String>>();
for (OperatorDeployInfo ndi: nodeList) {
groupInputStreams(groupedInputStreams, ndi);
}
deployOutputStreams(nodeList, groupedInputStreams);
deployInputStreams(nodeList);
activate(nodeList);
}
private void massageUnifierDeployInfo(OperatorDeployInfo odi)
{
for (OperatorDeployInfo.InputDeployInfo idi: odi.inputs) {
idi.portName += "(" + idi.sourceNodeId + NODE_PORT_CONCAT_SEPARATOR + idi.sourcePortName + ")";
}
}
@SuppressWarnings("unchecked")
private void deployNodes(List<OperatorDeployInfo> nodeList) throws Exception
{
OperatorCodec operatorSerDe = StramUtils.getNodeSerDe(null);
BackupAgent backupAgent = new HdfsBackupAgent(this.conf, this.checkpointFsPath);
for (OperatorDeployInfo ndi: nodeList) {
try {
final Object foreignObject;
if (ndi.checkpointWindowId > 0) {
logger.debug("Restoring node {} to checkpoint {}", ndi.id, Codec.getStringWindowId(ndi.checkpointWindowId));
foreignObject = backupAgent.restore(ndi.id, ndi.checkpointWindowId, operatorSerDe);
}
else {
foreignObject = operatorSerDe.read(new ByteArrayInputStream(ndi.serializedNode));
}
String nodeid = Integer.toString(ndi.id).concat("/").concat(ndi.declaredId).concat(":").concat(foreignObject.getClass().getSimpleName());
if (foreignObject instanceof InputOperator && ndi.type == OperatorDeployInfo.OperatorType.INPUT) {
nodes.put(ndi.id, new InputNode(nodeid, (InputOperator)foreignObject));
}
else if (foreignObject instanceof Unifier && ndi.type == OperatorDeployInfo.OperatorType.UNIFIER) {
nodes.put(ndi.id, new UnifierNode(nodeid, (Unifier<Object>)foreignObject));
massageUnifierDeployInfo(ndi);
}
else {
nodes.put(ndi.id, new GenericNode(nodeid, (Operator)foreignObject));
}
}
catch (Exception e) {
logger.error(e.getLocalizedMessage());
throw e;
}
}
}
private void deployOutputStreams(List<OperatorDeployInfo> nodeList, HashMap<String, ArrayList<String>> groupedInputStreams) throws Exception
{
/*
* We proceed to deploy all the output streams. At the end of this block, our streams collection
* will contain all the streams which originate at the output port of the operators. The streams
* are generally mapped against the "nodename.portname" string. But the BufferOutputStreams which
* share the output port with other inline streams are mapped against the Buffer Server port to
* avoid collision and at the same time keep track of these buffer streams.
*/
for (OperatorDeployInfo ndi: nodeList) {
Node<?> node = nodes.get(ndi.id);
for (OperatorDeployInfo.OutputDeployInfo nodi: ndi.outputs) {
String sourceIdentifier = Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nodi.portName);
String sinkIdentifier;
StreamContext context = new StreamContext(nodi.declaredStreamId);
Stream<Object> stream;
ArrayList<String> collection = groupedInputStreams.get(sourceIdentifier);
if (collection == null) {
/*
* Let's create a stream to carry the data to the Buffer Server.
* Nobody in this container is interested in the output placed on this stream, but
* this stream exists. That means someone outside of this container must be interested.
*/
assert (nodi.isInline() == false): "output should not be inline: " + nodi;
context.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
if (NetUtils.isLocalAddress(context.getBufferServerAddress().getAddress())) {
context.setBufferServerAddress(new InetSocketAddress(InetAddress.getByName(null), nodi.bufferServerPort));
}
stream = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName));
stream.setup(context);
logger.debug("deployed a buffer stream {}", stream);
sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
}
else if (collection.size() == 1) {
if (nodi.isInline()) {
/**
* Let's create an inline stream to carry data from output port to input port of some other node.
* There is only one node interested in output placed on this stream, and that node is in this container.
*/
stream = new InlineStream();
stream.setup(context);
sinkIdentifier = null;
}
else {
/**
* Let's create 2 streams: 1 inline and 1 going to the Buffer Server.
* Although there is a node in this container interested in output placed on this stream, there
* seems to at least one more party interested but placed in a container other than this one.
*/
sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
StreamContext bssc = new StreamContext(nodi.declaredStreamId);
bssc.setSourceId(sourceIdentifier);
bssc.setSinkId(sinkIdentifier);
bssc.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint
bssc.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
if (NetUtils.isLocalAddress(bssc.getBufferServerAddress().getAddress())) {
bssc.setBufferServerAddress(new InetSocketAddress(InetAddress.getByName(null), nodi.bufferServerPort));
}
BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName));
bsos.setup(bssc);
logger.debug("deployed a buffer stream {}", bsos);
streams.put(sinkIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(bsos, bssc));
// should we create inline stream here or wait for the input deployments to create the inline streams?
stream = new MuxStream();
stream.setup(context);
stream.setSink(sinkIdentifier, bsos);
logger.debug("stored stream {} against key {}", bsos, sinkIdentifier);
}
}
else {
/**
* Since there are multiple parties interested in this node itself, we are going to come
* to this block multiple times. The actions we take subsequent times are going to be different
* than the first time. We create the MuxStream only the first time.
*/
ComponentContextPair<Stream<Object>, StreamContext> pair = streams.get(sourceIdentifier);
if (pair == null) {
/**
* Let's multiplex the output placed on this stream.
* This container itself contains more than one parties interested.
*/
stream = new MuxStream();
stream.setup(context);
}
else {
stream = pair.component;
}
if (nodi.isInline()) {
sinkIdentifier = null;
}
else {
sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
StreamContext bssc = new StreamContext(nodi.declaredStreamId);
bssc.setSourceId(sourceIdentifier);
bssc.setSinkId(sinkIdentifier);
bssc.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint
bssc.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName));
bsos.setup(bssc);
logger.debug("deployed a buffer stream {}", bsos);
streams.put(sinkIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(bsos, bssc));
logger.debug("stored stream {} against key {}", bsos, sinkIdentifier);
stream.setup(context);
stream.setSink(sinkIdentifier, bsos);
}
}
if (!streams.containsKey(sourceIdentifier)) {
node.connectOutputPort(nodi.portName, nodi.contextAttributes, stream);
context.setSourceId(sourceIdentifier);
context.setSinkId(sinkIdentifier);
context.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint
streams.put(sourceIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(stream, context));
logger.debug("stored stream {} against key {}", stream, sourceIdentifier);
}
}
}
}
/**
* If the port is connected, find return the declared stream Id.
*
* @param operatorId id of the operator to which the port belongs.
* @param portname name of port to which the stream is connected.
* @return Stream Id if connected, null otherwise.
*/
public final String getDeclaredStreamId(int operatorId, String portname)
{
String identifier = String.valueOf(operatorId).concat(NODE_PORT_CONCAT_SEPARATOR).concat(portname);
ComponentContextPair<Stream<Object>, StreamContext> spair = streams.get(identifier);
if (spair == null) {
return null;
}
return spair.context.getId();
}
private void deployInputStreams(List<OperatorDeployInfo> nodeList) throws Exception
{
// collect any input operators along with their smallest window id,
// those are subsequently used to setup the window generator
ArrayList<OperatorDeployInfo> inputNodes = new ArrayList<OperatorDeployInfo>();
long smallestCheckpointedWindowId = Long.MAX_VALUE;
/*
* Hook up all the downstream ports. There are 2 places where we deal with more than 1
* downstream ports. The first one follows immediately for WindowGenerator. The second
* case is when source for the input port of some node in this container is in another
* container. So we need to create the stream. We need to track this stream along with
* other streams,and many such streams may exist, we hash them against buffer server
* info as we did for outputs but throw in the sinkid in the mix as well.
*/
for (OperatorDeployInfo ndi: nodeList) {
if (ndi.inputs == null || ndi.inputs.isEmpty()) {
/**
* This has to be InputNode, so let's hook the WindowGenerator to it.
* A node which does not take any input cannot exist in the DAG since it would be completely
* unaware of the windows. So for that reason, AbstractInputNode allows Component.INPUT port.
*/
inputNodes.add(ndi);
/*
* When we activate the window Generator, we plan to activate it only from required windowId.
*/
if (ndi.checkpointWindowId < smallestCheckpointedWindowId) {
smallestCheckpointedWindowId = ndi.checkpointWindowId;
}
}
else {
Node<?> node = nodes.get(ndi.id);
for (OperatorDeployInfo.InputDeployInfo nidi: ndi.inputs) {
String sourceIdentifier = Integer.toString(nidi.sourceNodeId).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName);
String sinkIdentifier = Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName);
ComponentContextPair<Stream<Object>, StreamContext> pair = streams.get(sourceIdentifier);
if (pair == null) {
/*
* We connect to the buffer server for the input on this port.
* We have already placed all the output streams for all the operators in this container.
* Yet, there is no stream which can source this port so it has to come from the buffer
* server, so let's make a connection to it.
*/
assert (nidi.isInline() == false);
StreamContext context = new StreamContext(nidi.declaredStreamId);
context.setPartitions(nidi.partitionMask, nidi.partitionKeys);
context.setSourceId(sourceIdentifier);
context.setSinkId(sinkIdentifier);
context.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint
context.setBufferServerAddress(InetSocketAddress.createUnresolved(nidi.bufferServerHost, nidi.bufferServerPort));
if (NetUtils.isLocalAddress(context.getBufferServerAddress().getAddress())) {
context.setBufferServerAddress(new InetSocketAddress(InetAddress.getByName(null), nidi.bufferServerPort));
}
@SuppressWarnings("unchecked")
Stream<Object> stream = (Stream)new BufferServerInputStream(StramUtils.getSerdeInstance(nidi.serDeClassName));
stream.setup(context);
logger.debug("deployed buffer input stream {}", stream);
Sink<Object> s = node.connectInputPort(nidi.portName, nidi.contextAttributes, stream);
stream.setSink(sinkIdentifier,
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(stream, sinkIdentifier, s, ndi.checkpointWindowId) : s);
streams.put(sinkIdentifier,
new ComponentContextPair<Stream<Object>, StreamContext>(stream, context));
logger.debug("put input stream {} against key {}", stream, sinkIdentifier);
}
else {
String streamSinkId = pair.context.getSinkId();
Sink<Object> s;
if (streamSinkId == null) {
s = node.connectInputPort(nidi.portName, nidi.contextAttributes, pair.component);
pair.context.setSinkId(sinkIdentifier);
}
else if (pair.component.isMultiSinkCapable()) {
s = node.connectInputPort(nidi.portName, nidi.contextAttributes, pair.component);
pair.context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier));
}
else {
/**
* we are trying to tap into existing InlineStream or BufferServerOutputStream.
* Since none of those streams are MultiSinkCapable, we need to replace them with Mux.
*/
StreamContext context = new StreamContext(nidi.declaredStreamId);
context.setSourceId(sourceIdentifier);
context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier));
context.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint
Stream<Object> stream = new MuxStream();
stream.setup(context);
logger.debug("deployed input mux stream {}", stream);
s = node.connectInputPort(nidi.portName, nidi.contextAttributes, stream);
streams.put(sourceIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(stream, context));
logger.debug("stored input stream {} against key {}", stream, sourceIdentifier);
/**
* Lets wire the MuxStream to upstream node.
*/
String[] nodeport = sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR);
Node<?> upstreamNode = nodes.get(Integer.parseInt(nodeport[0]));
upstreamNode.connectOutputPort(nodeport[1], nidi.contextAttributes, stream);
Sink<Object> existingSink;
if (pair.component instanceof InlineStream) {
String[] np = streamSinkId.split(NODE_PORT_SPLIT_SEPARATOR);
Node<?> anotherNode = nodes.get(Integer.parseInt(np[0]));
existingSink = anotherNode.connectInputPort(np[1], nidi.contextAttributes, stream); // the context object here is probably wrong
/*
* we do not need to do this but looks bad if leave it in limbo.
*/
pair.component.deactivate();
pair.component.teardown();
}
else {
existingSink = pair.component;
/*
* we got this stream since it was mapped against sourceId, but since
* we took that place for MuxStream, we give this a new place of its own.
*/
streams.put(pair.context.getSinkId(), pair);
logger.debug("relocated stream {} against key {}", pair.context.getSinkId());
}
stream.setSink(streamSinkId, existingSink);
}
if (nidi.partitionKeys == null || nidi.partitionKeys.isEmpty()) {
logger.debug("got simple inline stream from {} to {} - {}", new Object[] {sourceIdentifier, sinkIdentifier, nidi});
pair.component.setSink(sinkIdentifier,
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(pair.component, sinkIdentifier, s, ndi.checkpointWindowId) : s);
}
else {
/*
* generally speaking we do not have partitions on the inline streams so the control should not
* come here but if it comes, then we are ready to handle it using the partition aware streams.
*/
logger.debug("got partitions on the inline stream from {} to {} - {}", new Object[] {sourceIdentifier, sinkIdentifier, nidi});
PartitionAwareSink<Object> pas = new PartitionAwareSink<Object>(StramUtils.getSerdeInstance(nidi.serDeClassName), nidi.partitionKeys, nidi.partitionMask, s);
pair.component.setSink(sinkIdentifier,
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(pair.component, sinkIdentifier, pas, ndi.checkpointWindowId) : pas);
}
}
}
}
}
if (!inputNodes.isEmpty()) {
WindowGenerator windowGenerator = setupWindowGenerator(smallestCheckpointedWindowId);
for (OperatorDeployInfo ndi: inputNodes) {
generators.put(ndi.id, windowGenerator);
Node<?> node = nodes.get(ndi.id);
Sink<Object> s = node.connectInputPort(Node.INPUT, null, windowGenerator);
windowGenerator.setSink(Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(Node.INPUT),
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(windowGenerator, Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(Node.INPUT), s, ndi.checkpointWindowId) : s);
}
}
}
/**
* Create the window generator for the given start window id.
* This is a hook for tests to control the window generation.
*
* @param smallestWindowId
* @return WindowGenerator
*/
protected WindowGenerator setupWindowGenerator(long smallestWindowId)
{
WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1, "WindowGenerator"));
/**
* let's make sure that we send the same window Ids with the same reset windows.
*/
windowGenerator.setResetWindow(firstWindowMillis);
long millisAtFirstWindow = (smallestWindowId >> 32) * 1000 + windowWidthMillis * (smallestWindowId & WindowGenerator.MAX_WINDOW_ID);
windowGenerator.setFirstWindow(millisAtFirstWindow > firstWindowMillis ? millisAtFirstWindow : firstWindowMillis);
windowGenerator.setWindowWidth(windowWidthMillis);
return windowGenerator;
}
@SuppressWarnings({"SleepWhileInLoop", "SleepWhileHoldingLock"})
public synchronized void activate(List<OperatorDeployInfo> nodeList)
{
for (ComponentContextPair<Stream<Object>, StreamContext> pair: streams.values()) {
if (!(pair.component instanceof SocketInputStream || activeStreams.containsKey(pair.component))) {
activeStreams.put(pair.component, pair.context);
pair.component.activate(pair.context);
}
}
final AtomicInteger activatedNodeCount = new AtomicInteger(activeNodes.size());
for (final OperatorDeployInfo ndi: nodeList) {
final Node<?> node = nodes.get(ndi.id);
final Map<String, AttributeMap<PortContext>> inputPortAttributes = new HashMap<String, AttributeMap<PortContext>>();
final Map<String, AttributeMap<PortContext>> outputPortAttributes = new HashMap<String, AttributeMap<PortContext>>();
assert (!activeNodes.containsKey(ndi.id));
for (OperatorDeployInfo.InputDeployInfo idi: ndi.inputs) {
inputPortAttributes.put(idi.portName, idi.contextAttributes);
}
for (OperatorDeployInfo.OutputDeployInfo odi: ndi.outputs) {
outputPortAttributes.put(odi.portName, odi.contextAttributes);
}
new Thread(node.id)
{
@Override
public void run()
{
try {
OperatorContext context = new OperatorContext(new Integer(ndi.id), this, ndi.contextAttributes, applicationAttributes, inputPortAttributes, outputPortAttributes);
node.getOperator().setup(context);
for (Map.Entry<String, AttributeMap<PortContext>> entry: inputPortAttributes.entrySet()) {
AttributeMap<PortContext> attrMap = entry.getValue();
if (attrMap != null && attrMap.attrValue(PortContext.AUTO_RECORD, false)) {
startRecording(node, ndi.id, entry.getKey(), true);
}
}
for (Map.Entry<String, AttributeMap<PortContext>> entry: outputPortAttributes.entrySet()) {
AttributeMap<PortContext> attrMap = entry.getValue();
if (attrMap != null && attrMap.attrValue(PortContext.AUTO_RECORD, false)) {
startRecording(node, ndi.id, entry.getKey(), true);
}
}
activeNodes.put(ndi.id, context);
activatedNodeCount.incrementAndGet();
logger.info("activating {} in container {}", node, containerId);
node.activate(context);
}
catch (Throwable ex) {
logger.error("Node stopped abnormally because of exception", ex);
}
finally {
activeNodes.remove(ndi.id);
node.getOperator().teardown();
logger.info("deactivated {}", node.id);
}
}
}.start();
}
/**
* we need to make sure that before any of the operators gets the first message, it's activate.
*/
try {
do {
Thread.sleep(SPIN_MILLIS);
}
while (activatedNodeCount.get() < nodes.size());
}
catch (InterruptedException ex) {
logger.debug(ex.getLocalizedMessage());
}
for (ComponentContextPair<Stream<Object>, StreamContext> pair: streams.values()) {
if (pair.component instanceof SocketInputStream && !activeStreams.containsKey(pair.component)) {
activeStreams.put(pair.component, pair.context);
pair.component.activate(pair.context);
}
}
for (WindowGenerator wg: generators.values()) {
if (!activeGenerators.containsKey(wg)) {
activeGenerators.put(wg, generators);
wg.activate(null);
}
}
}
private void groupInputStreams(HashMap<String, ArrayList<String>> groupedInputStreams, OperatorDeployInfo ndi)
{
for (OperatorDeployInfo.InputDeployInfo nidi: ndi.inputs) {
String source = Integer.toString(nidi.sourceNodeId).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName);
/*
* if we do not want to combine multiple streams with different partitions from the
* same upstream node, we could also use the partition to group the streams together.
* This logic comes with the danger that the performance of the group which shares
* the same stream is bounded on the higher side by the performance of the lowest
* performer upstream port. May be combining the streams is not such a good thing
* but let's see if we allow this as an option to the user, what they end up choosing
* the most.
*/
ArrayList<String> collection = groupedInputStreams.get(source);
if (collection == null) {
collection = new ArrayList<String>();
groupedInputStreams.put(source, collection);
}
collection.add(Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName));
}
}
private String getRecorderKey(int operatorId, String portName)
{
return String.valueOf(operatorId) + (portName != null ? ("$" + portName) : "");
}
private void startRecording(Node<?> node, int operatorId, String portName, boolean recordEvenIfNotConnected)
{
PortMappingDescriptor descriptor = node.getPortMappingDescriptor();
String operatorPortName = getRecorderKey(operatorId, portName);
// check any recording conflict
boolean conflict = false;
if (tupleRecorders.containsKey(String.valueOf(operatorId))) {
conflict = true;
}
else if (portName == null) {
for (Map.Entry<String, InputPort<?>> entry: descriptor.inputPorts.entrySet()) {
if (tupleRecorders.containsKey(getRecorderKey(operatorId, entry.getKey()))) {
conflict = true;
break;
}
}
for (Map.Entry<String, OutputPort<?>> entry: descriptor.outputPorts.entrySet()) {
if (tupleRecorders.containsKey(getRecorderKey(operatorId, entry.getKey()))) {
conflict = true;
break;
}
}
}
else {
if (tupleRecorders.containsKey(operatorPortName)) {
conflict = true;
}
}
if (!conflict) {
logger.debug("Executing start recording request for " + operatorPortName);
TupleRecorder tupleRecorder = new TupleRecorder();
String basePath = StramChild.this.appPath + "/recordings/" + operatorId + "/" + tupleRecorder.getStartTime();
String defaultName = StramChild.this.containerId + "_" + operatorPortName + "_" + tupleRecorder.getStartTime();
tupleRecorder.setRecordingName(defaultName);
tupleRecorder.setBasePath(basePath);
tupleRecorder.setBytesPerPartFile(StramChild.this.tupleRecordingPartFileSize);
tupleRecorder.setMillisPerPartFile(StramChild.this.tupleRecordingPartFileTimeMillis);
if (StramChild.this.daemonAddress != null) {
String url = "ws://" + StramChild.this.daemonAddress + "/pubsub";
try {
tupleRecorder.setPubSubUrl(url);
}
catch (URISyntaxException ex) {
logger.warn("URL {} is not valid. NOT posting live tuples to daemon.", url, ex);
}
}
HashMap<String, Sink<Object>> sinkMap = new HashMap<String, Sink<Object>>();
for (Map.Entry<String, InputPort<?>> entry: descriptor.inputPorts.entrySet()) {
String streamId = getDeclaredStreamId(operatorId, entry.getKey());
if (recordEvenIfNotConnected && streamId == null) {
streamId = portName + "_implicit_stream";
}
if (streamId != null && (portName == null || entry.getKey().equals(portName))) {
logger.info("Adding recorder sink to input port {}, stream {}", entry.getKey(), streamId);
tupleRecorder.addInputPortInfo(entry.getKey(), streamId);
sinkMap.put(entry.getKey(), tupleRecorder.newSink(entry.getKey()));
}
}
for (Map.Entry<String, OutputPort<?>> entry: descriptor.outputPorts.entrySet()) {
String streamId = getDeclaredStreamId(operatorId, entry.getKey());
if (recordEvenIfNotConnected && streamId == null) {
streamId = portName + "_implicit_stream";
}
if (streamId != null && (portName == null || entry.getKey().equals(portName))) {
logger.info("Adding recorder sink to output port {}, stream {}", entry.getKey(), streamId);
tupleRecorder.addOutputPortInfo(entry.getKey(), streamId);
sinkMap.put(entry.getKey(), tupleRecorder.newSink(entry.getKey()));
}
}
if (!sinkMap.isEmpty()) {
logger.debug("Started recording (name: {}) to base path {}", operatorPortName, basePath);
node.addSinks(sinkMap);
tupleRecorder.setup(null);
tupleRecorders.put(operatorPortName, tupleRecorder);
}
else {
logger.warn("Tuple recording request ignored because operator is not connected on the specified port.");
}
}
else {
logger.error("Operator id {} is already being recorded.", operatorPortName);
}
}
private void stopRecording(Node<?> node, int operatorId, String portName)
{
String operatorPortName = getRecorderKey(operatorId, portName);
if (tupleRecorders.containsKey(operatorPortName)) {
logger.debug("Executing stop recording request for {}", operatorPortName);
TupleRecorder tupleRecorder = tupleRecorders.get(operatorPortName);
if (tupleRecorder != null) {
node.removeSinks(tupleRecorder.getSinkMap());
tupleRecorder.teardown();
logger.debug("Stopped recording for operator/port {}", operatorPortName);
tupleRecorders.remove(operatorPortName);
}
}
else {
logger.error("Operator/port {} is not being recorded.", operatorPortName);
}
}
private void syncRecording(Node<?> node, int operatorId, String portName)
{
String operatorPortName = getRecorderKey(operatorId, portName);
if (tupleRecorders.containsKey(operatorPortName)) {
logger.debug("Executing sync recording request for {}" + operatorPortName);
TupleRecorder tupleRecorder = tupleRecorders.get(operatorPortName);
if (tupleRecorder != null) {
tupleRecorder.requestSync();
logger.debug("Requested sync recording for operator/port {}" + operatorPortName);
}
}
else {
logger.error("(SYNC_RECORDING) Operator/port " + operatorPortName + " is not being recorded.");
}
}
}
|
package com.malhartech.stram;
import com.malhartech.dag.Component;
import com.malhartech.dag.Module;
import com.malhartech.dag.ModuleConfiguration;
import com.malhartech.dag.ModuleContext;
import com.malhartech.dag.ModuleSerDe;
import com.malhartech.dag.Sink;
import com.malhartech.dag.Stream;
import com.malhartech.dag.StreamConfiguration;
import com.malhartech.dag.StreamContext;
import com.malhartech.dag.WindowIdActivatedSink;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeat;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat.DNodeState;
import com.malhartech.stream.BufferServerInputStream;
import com.malhartech.stream.BufferServerOutputStream;
import com.malhartech.stream.InlineStream;
import com.malhartech.stream.MuxStream;
import com.malhartech.stream.PartitionAwareSink;
import com.malhartech.stream.SocketInputStream;
import com.malhartech.util.ScheduledThreadPoolExecutor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSError;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.log4j.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// make sure that setup and teardown is called through the same thread which calls process
/**
*
* The main() for streaming container processes launched by {@link com.malhartech.stram.StramAppMaster}.<p>
* <br>
*
*/
public class StramChild
{
private static final Logger logger = LoggerFactory.getLogger(StramChild.class);
private static final String NODE_PORT_SPLIT_SEPARATOR = "\\.";
private static final String NODE_PORT_CONCAT_SEPARATOR = ".";
private static final int SPIN_MILLIS = 20;
private final String containerId;
private final Configuration conf;
private final StreamingContainerUmbilicalProtocol umbilical;
protected final Map<String, Module> nodes = new ConcurrentHashMap<String, Module>();
private final Map<String, ComponentContextPair<Stream, StreamContext>> streams = new ConcurrentHashMap<String, ComponentContextPair<Stream, StreamContext>>();
protected final Map<String, WindowGenerator> generators = new ConcurrentHashMap<String, WindowGenerator>();
/**
* for the following 3 fields, my preferred type is HashSet but synchronizing access to HashSet object was resulting in very verbose code.
*/
protected final Map<String, ModuleContext> activeNodes = new ConcurrentHashMap<String, ModuleContext>();
private final Map<Stream, StreamContext> activeStreams = new ConcurrentHashMap<Stream, StreamContext>();
private final Map<WindowGenerator, Object> activeGenerators = new ConcurrentHashMap<WindowGenerator, Object>();
private long heartbeatIntervalMillis = 1000;
private volatile boolean exitHeartbeatLoop = false;
private final Object heartbeatTrigger = new Object();
private String checkpointFsPath;
/**
* Map of last backup window id that is used to communicate checkpoint state back to Stram. TODO: Consider adding this to the node context instead.
*/
private final Map<String, Long> backupInfo = new ConcurrentHashMap<String, Long>();
private long firstWindowMillis;
private int windowWidthMillis;
protected StramChild(String containerId, Configuration conf, StreamingContainerUmbilicalProtocol umbilical)
{
logger.debug("instantiated StramChild {}", containerId);
this.umbilical = umbilical;
this.containerId = containerId;
this.conf = conf;
}
public void setup(StreamingContainerContext ctx)
{
heartbeatIntervalMillis = ctx.getHeartbeatIntervalMillis();
if (heartbeatIntervalMillis == 0) {
heartbeatIntervalMillis = 1000;
}
firstWindowMillis = ctx.getStartWindowMillis();
windowWidthMillis = ctx.getWindowSizeMillis();
if (windowWidthMillis == 0) {
windowWidthMillis = 500;
}
if ((this.checkpointFsPath = ctx.getCheckpointDfsPath()) == null) {
this.checkpointFsPath = "checkpoint-dfs-path-not-configured";
}
try {
deploy(ctx.nodeList);
}
catch (Exception ex) {
logger.debug("deploy request failed due to {}", ex);
}
}
public String getContainerId()
{
return this.containerId;
}
/**
* Initialize container. Establishes heartbeat connection to the master
* process through the callback address provided on the command line. Deploys
* initial modules, then enters the heartbeat loop, which will only terminate
* once container receives shutdown request from the master. On shutdown,
* after exiting heartbeat loop, deactivate all modules and terminate
* processing threads.
*
*/
public static void main(String[] args) throws Throwable
{
logger.info("Child starting with classpath: {}", System.getProperty("java.class.path"));
final Configuration defaultConf = new Configuration();
//defaultConf.addResource(MRJobConfig.JOB_CONF_FILE);
UserGroupInformation.setConfiguration(defaultConf);
String host = args[0];
int port = Integer.parseInt(args[1]);
final InetSocketAddress address =
NetUtils.createSocketAddrForHost(host, port);
final String childId = args[2];
//Token<JobTokenIdentifier> jt = loadCredentials(defaultConf, address);
// Communicate with parent as actual task owner.
UserGroupInformation taskOwner =
UserGroupInformation.createRemoteUser(StramChild.class.getName());
//taskOwner.addToken(jt);
final StreamingContainerUmbilicalProtocol umbilical =
taskOwner.doAs(new PrivilegedExceptionAction<StreamingContainerUmbilicalProtocol>()
{
@Override
public StreamingContainerUmbilicalProtocol run() throws Exception
{
return RPC.getProxy(StreamingContainerUmbilicalProtocol.class,
StreamingContainerUmbilicalProtocol.versionID, address, defaultConf);
}
});
logger.debug("PID: " + System.getenv().get("JVM_PID"));
UserGroupInformation childUGI;
try {
childUGI = UserGroupInformation.createRemoteUser(System.getenv(ApplicationConstants.Environment.USER.toString()));
// Add tokens to new user so that it may execute its task correctly.
for (Token<?> token: UserGroupInformation.getCurrentUser().getTokens()) {
childUGI.addToken(token);
}
childUGI.doAs(new PrivilegedExceptionAction<Object>()
{
@Override
public Object run() throws Exception
{
StramChild stramChild = new StramChild(childId, defaultConf, umbilical);
StreamingContainerContext ctx = umbilical.getInitContext(childId);
logger.debug("Got context: " + ctx);
stramChild.setup(ctx);
// main thread enters heartbeat loop
stramChild.monitorHeartbeat();
// teardown
stramChild.teardown();
return null;
}
});
}
catch (FSError e) {
logger.error("FSError from child", e);
umbilical.log(childId, e.getMessage());
}
catch (Exception exception) {
logger.warn("Exception running child : "
+ StringUtils.stringifyException(exception));
// Report back any failures, for diagnostic purposes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
exception.printStackTrace(new PrintStream(baos));
umbilical.log(childId, "FATAL: " + baos.toString());
}
catch (Throwable throwable) {
logger.error("Error running child : "
+ StringUtils.stringifyException(throwable));
Throwable tCause = throwable.getCause();
String cause = tCause == null
? throwable.getMessage()
: StringUtils.stringifyException(tCause);
umbilical.log(childId, cause);
}
finally {
RPC.stopProxy(umbilical);
DefaultMetricsSystem.shutdown();
// Shutting down log4j of the child-vm...
// This assumes that on return from Task.activate()
// there is no more logging done.
LogManager.shutdown();
}
}
@SuppressWarnings( {"SleepWhileInLoop", "SleepWhileHoldingLock"})
public synchronized void deactivate()
{
for (String nodeid: activeNodes.keySet()) {
nodes.get(nodeid).deactivate();
}
try {
while (!activeNodes.isEmpty()) {
Thread.sleep(SPIN_MILLIS);
}
}
catch (InterruptedException ex) {
logger.info("Aborting wait for for operators to get deactivated as got interrupted with {}", ex);
}
for (WindowGenerator wg: activeGenerators.keySet()) {
wg.deactivate();
}
activeGenerators.clear();
for (Stream stream: activeStreams.keySet()) {
stream.deactivate();
}
activeStreams.clear();
}
private synchronized void disconnectNode(String nodeid)
{
Module node = nodes.get(nodeid);
disconnectWindowGenerator(nodeid, node);
Set<String> removableSocketOutputStreams = new HashSet<String>(); // temporary fix - find out why List does not work.
// with the logic i have in here, the list should not contain repeated streams. but it does and that causes problem.
for (Entry<String, ComponentContextPair<Stream, StreamContext>> entry: streams.entrySet()) {
String indexingKey = entry.getKey();
Stream stream = entry.getValue().component;
StreamContext context = entry.getValue().context;
String sourceIdentifier = context.getSourceId();
String sinkIdentifier = context.getSinkId();
logger.debug("considering stream {} against id {}", stream, indexingKey);
if (nodeid.equals(sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR)[0])) {
/**
* the stream originates at the output port of one of the operators that are going to vanish.
*/
if (activeStreams.containsKey(stream)) {
logger.debug("deactivating {}", stream);
stream.deactivate();
activeStreams.remove(stream);
}
removableSocketOutputStreams.add(sourceIdentifier);
String[] sinkIds = sinkIdentifier.split(", ");
for (String sinkId: sinkIds) {
if (!sinkId.startsWith("tcp:
String[] nodeport = sinkId.split(NODE_PORT_SPLIT_SEPARATOR);
Module n = nodes.get(nodeport[0]);
n.connect(nodeport[1], null);
}
else if (stream.isMultiSinkCapable()) {
ComponentContextPair<Stream, StreamContext> spair = streams.get(sinkId);
logger.debug("found stream {} against {}", spair == null ? null : spair.component, sinkId);
if (spair == null) {
assert (!sinkId.startsWith("tcp:
}
else {
assert (sinkId.startsWith("tcp:
if (activeStreams.containsKey(spair.component)) {
logger.debug("deactivating {} for sink {}", spair.component, sinkId);
spair.component.deactivate();
activeStreams.remove(spair.component);
}
spair.component.connect(Component.INPUT, null);
removableSocketOutputStreams.add(sinkId);
}
}
}
stream.connect(Component.INPUT, null);
}
else {
/**
* the stream may or may not feed into one of the operators which are being undeployed.
*/
String[] sinkIds = sinkIdentifier.split(", ");
for (int i = sinkIds.length; i
String[] nodeport = sinkIds[i].split(NODE_PORT_SPLIT_SEPARATOR);
if (nodeid.equals(nodeport[0])) {
stream.connect(sinkIds[i], null);
node.connect(nodeport[1], null);
sinkIds[i] = null;
}
}
String sinkId = null;
for (int i = sinkIds.length; i
if (sinkIds[i] != null) {
if (sinkId == null) {
sinkId = sinkIds[i];
}
else {
sinkId = sinkId.concat(", ").concat(sinkIds[i]);
}
}
}
if (sinkId == null) {
if (activeStreams.containsKey(stream)) {
logger.debug("deactivating {}", stream);
stream.deactivate();
activeStreams.remove(stream);
}
removableSocketOutputStreams.add(indexingKey);
}
else {
// may be we should also check if the count has changed from something to 1
// and replace mux with 1:1 sink. it's not necessary though.
context.setSinkId(sinkId);
}
}
}
for (String streamId: removableSocketOutputStreams) {
logger.debug("removing stream {}", streamId);
// need to check why control comes here twice to remove the stream which was deleted before.
// is it because of multiSinkCapableStream ?
ComponentContextPair<Stream, StreamContext> pair = streams.remove(streamId);
pair.component.teardown();
}
}
private void disconnectWindowGenerator(String nodeid, Module node)
{
WindowGenerator chosen1 = generators.remove(nodeid);
if (chosen1 != null) {
chosen1.connect(nodeid.concat(NODE_PORT_CONCAT_SEPARATOR).concat(Component.INPUT), null);
node.connect(Component.INPUT, null);
int count = 0;
for (WindowGenerator wg: generators.values()) {
if (chosen1 == wg) {
count++;
}
}
if (count == 0) {
activeGenerators.remove(chosen1);
chosen1.deactivate();
chosen1.teardown();
}
}
}
private synchronized void undeploy(List<ModuleDeployInfo> nodeList)
{
/**
* make sure that all the operators which we are asked to undeploy are in this container.
*/
HashMap<String, Module> toUndeploy = new HashMap<String, Module>();
for (ModuleDeployInfo ndi: nodeList) {
Module pair = nodes.get(ndi.id);
if (pair == null) {
throw new IllegalArgumentException("Node " + ndi.id + " is not hosted in this container!");
}
else if (toUndeploy.containsKey(ndi.id)) {
throw new IllegalArgumentException("Node " + ndi.id + " is requested to be undeployed more than once");
}
else {
toUndeploy.put(ndi.id, pair);
}
}
for (ModuleDeployInfo ndi: nodeList) {
if (activeNodes.containsKey(ndi.id)) {
nodes.get(ndi.id).deactivate();
// must remove from node list to reach defined state before next heartbeat,
// subsequent response may request deploy, which would fail if deactivate node is still tracked
activeNodes.remove(ndi.id);
nodes.remove(ndi.id);
}
}
}
public void teardown()
{
deactivate();
HashSet<WindowGenerator> gens = new HashSet<WindowGenerator>();
gens.addAll(generators.values());
generators.clear();
for (WindowGenerator wg: gens) {
wg.teardown();
}
gens.clear();
}
protected void triggerHeartbeat()
{
synchronized (heartbeatTrigger) {
heartbeatTrigger.notifyAll();
}
}
protected void monitorHeartbeat() throws IOException
{
umbilical.log(containerId, "[" + containerId + "] Entering heartbeat loop..");
logger.debug("Entering hearbeat loop (interval is {} ms)", this.heartbeatIntervalMillis);
while (!exitHeartbeatLoop) {
synchronized (this.heartbeatTrigger) {
try {
this.heartbeatTrigger.wait(heartbeatIntervalMillis);
}
catch (InterruptedException e1) {
logger.warn("Interrupted in heartbeat loop, exiting..");
break;
}
}
long currentTime = System.currentTimeMillis();
ContainerHeartbeat msg = new ContainerHeartbeat();
msg.setContainerId(this.containerId);
List<StreamingNodeHeartbeat> heartbeats = new ArrayList<StreamingNodeHeartbeat>(nodes.size());
// gather heartbeat info for all operators
for (Map.Entry<String, Module> e: nodes.entrySet()) {
StreamingNodeHeartbeat hb = new StreamingNodeHeartbeat();
hb.setNodeId(e.getKey());
hb.setGeneratedTms(currentTime);
hb.setIntervalMs(heartbeatIntervalMillis);
if (activeNodes.containsKey(e.getKey())) {
activeNodes.get(e.getKey()).drainHeartbeatCounters(hb.getHeartbeatsContainer());
hb.setState(DNodeState.PROCESSING.toString());
}
else {
hb.setState(DNodeState.IDLE.toString());
}
// propagate the backup window, if any
Long backupWindowId = backupInfo.get(e.getKey());
if (backupWindowId != null) {
hb.setLastBackupWindowId(backupWindowId);
}
heartbeats.add(hb);
}
msg.setDnodeEntries(heartbeats);
// heartbeat call and follow-up processing
//logger.debug("Sending heartbeat for {} operators.", msg.getDnodeEntries().size());
try {
ContainerHeartbeatResponse rsp = umbilical.processHeartbeat(msg);
if (rsp != null) {
processHeartbeatResponse(rsp);
// keep polling at smaller interval if work is pending
while (rsp != null && rsp.hasPendingRequests) {
logger.info("Waiting for pending request.");
synchronized (this.heartbeatTrigger) {
try {
this.heartbeatTrigger.wait(500);
}
catch (InterruptedException e1) {
logger.warn("Interrupted in heartbeat loop, exiting..");
break;
}
}
rsp = umbilical.pollRequest(this.containerId);
if (rsp != null) {
processHeartbeatResponse(rsp);
}
}
}
}
catch (Exception e) {
logger.warn("Exception received (may be during shutdown?)", e);
}
}
logger.debug("Exiting hearbeat loop");
umbilical.log(containerId, "[" + containerId + "] Exiting heartbeat loop..");
}
protected void processHeartbeatResponse(ContainerHeartbeatResponse rsp)
{
if (rsp.shutdown) {
logger.info("Received shutdown request");
this.exitHeartbeatLoop = true;
return;
}
if (rsp.undeployRequest != null) {
logger.info("Undeploy request: {}", rsp.undeployRequest);
undeploy(rsp.undeployRequest);
}
if (rsp.deployRequest != null) {
logger.info("Deploy request: {}", rsp.deployRequest);
try {
deploy(rsp.deployRequest);
}
catch (Exception e) {
logger.error("deploy request failed due to {}", e);
// report it to stram
}
}
if (rsp.nodeRequests != null) {
// extended processing per node
for (StramToNodeRequest req: rsp.nodeRequests) {
ModuleContext nc = activeNodes.get(req.getNodeId());
if (nc == null) {
logger.warn("Received request with invalid node id {} ({})", req.getNodeId(), req);
}
else {
logger.debug("Stram request: {}", req);
processStramRequest(nc, req);
}
}
}
}
/**
* Process request from stram for further communication through the protocol. Extended reporting is on a per node basis (won't occur under regular operation)
*
* @param n
* @param snr
*/
private void processStramRequest(ModuleContext context, StramToNodeRequest snr)
{
switch (snr.getRequestType()) {
case REPORT_PARTION_STATS:
logger.warn("Ignoring stram request {}", snr);
break;
case CHECKPOINT:
context.request(new ModuleContext.ModuleRequest() {
@Override
public void execute(Module module, String id, long windowId) throws IOException {
new HdfsBackupAgent(StramChild.this.conf, StramChild.this.checkpointFsPath).backup(id, windowId, module, StramUtils.getNodeSerDe(null));
// record last backup window id for heartbeat
StramChild.this.backupInfo.put(id, windowId);
}
});
break;
default:
logger.error("Unknown request from stram {}", snr);
}
}
private synchronized void deploy(List<ModuleDeployInfo> nodeList) throws Exception
{
/**
* A little bit of up front sanity check would reduce the percentage of deploy failures later.
*/
HashMap<String, ArrayList<String>> groupedInputStreams = new HashMap<String, ArrayList<String>>();
for (ModuleDeployInfo ndi: nodeList) {
if (nodes.containsKey(ndi.id)) {
throw new IllegalStateException("Node with id: " + ndi.id + " already present in the container");
}
groupInputStreams(groupedInputStreams, ndi);
}
deployNodes(nodeList);
deployOutputStreams(nodeList, groupedInputStreams);
deployInputStreams(nodeList);
activate(nodeList);
}
private void deployNodes(List<ModuleDeployInfo> nodeList) throws Exception
{
ModuleSerDe moduleSerDe = StramUtils.getNodeSerDe(null);
HdfsBackupAgent backupAgent = new HdfsBackupAgent(this.conf, this.checkpointFsPath);
for (ModuleDeployInfo ndi: nodeList) {
try {
final Object foreignObject;
if (ndi.checkpointWindowId > 0) {
logger.debug("Restoring node {} to checkpoint {}", ndi.id, ndi.checkpointWindowId);
foreignObject = backupAgent.restore(ndi.id, ndi.checkpointWindowId, moduleSerDe);
}
else {
foreignObject = moduleSerDe.read(new ByteArrayInputStream(ndi.serializedNode));
}
nodes.put(ndi.id, (Module)foreignObject);
}
catch (Exception e) {
logger.error(e.getLocalizedMessage());
throw e;
}
}
}
private void deployOutputStreams(List<ModuleDeployInfo> nodeList, HashMap<String, ArrayList<String>> groupedInputStreams) throws Exception
{
/**
* We proceed to deploy all the output streams.
* At the end of this block, our streams collection will contain all the streams which originate at the
* output port of the operators. The streams are generally mapped against the "nodename.portname" string.
* But the BufferOutputStreams which share the output port with other inline streams are mapped against
* the Buffer Server port to avoid collision and at the same time keep track of these buffer streams.
*/
for (ModuleDeployInfo ndi: nodeList) {
Module node = nodes.get(ndi.id);
for (ModuleDeployInfo.NodeOutputDeployInfo nodi: ndi.outputs) {
String sourceIdentifier = ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nodi.portName);
String sinkIdentifier;
Stream stream;
ArrayList<String> collection = groupedInputStreams.get(sourceIdentifier);
if (collection == null) {
/**
* Let's create a stream to carry the data to the Buffer Server.
* Nobody in this container is interested in the output placed on this stream, but
* this stream exists. That means someone outside of this container must be interested.
*/
assert (nodi.isInline() == false);
StreamConfiguration config = new StreamConfiguration();
config.setSocketAddr(StreamConfiguration.SERVER_ADDRESS, InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
stream = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName));
stream.setup(config);
logger.debug("deployed a buffer stream {}", stream);
sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
}
else if (collection.size() == 1) {
if (nodi.isInline()) {
/**
* Let's create an inline stream to carry data from output port to input port of some other node.
* There is only one node interested in output placed on this stream, and that node is in this container.
*/
stream = new InlineStream();
stream.setup(new StreamConfiguration());
sinkIdentifier = null;
}
else {
/**
* Let's create 2 streams: 1 inline and 1 going to the Buffer Server.
* Although there is a node in this container interested in output placed on this stream, there
* seems to at least one more party interested but placed in a container other than this one.
*/
StreamConfiguration config = new StreamConfiguration();
config.setSocketAddr(StreamConfiguration.SERVER_ADDRESS, InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName));
bsos.setup(config);
logger.debug("deployed a buffer stream {}", bsos);
// the following sinkIdentifier may not gel well with the rest of the logic
sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
StreamContext bssc = new StreamContext(nodi.declaredStreamId);
bssc.setSourceId(sourceIdentifier);
bssc.setSinkId(sinkIdentifier);
streams.put(sinkIdentifier, new ComponentContextPair<Stream, StreamContext>(bsos, bssc));
// should we create inline stream here or wait for the input deployments to create the inline streams?
stream = new MuxStream();
stream.setup(new StreamConfiguration());
Sink s = bsos.connect(Component.INPUT, stream);
stream.connect(sinkIdentifier, s);
logger.debug("stored stream {} against key {}", bsos, sinkIdentifier);
}
}
else {
/**
* Since there are multiple parties interested in this node itself, we are going to come
* to this block multiple times. The actions we take subsequent times are going to be different
* than the first time. We create the MuxStream only the first time.
*/
ComponentContextPair<Stream, StreamContext> pair = streams.get(sourceIdentifier);
if (pair == null) {
/**
* Let's multiplex the output placed on this stream.
* This container itself contains more than one parties interested.
*/
stream = new MuxStream();
stream.setup(new StreamConfiguration());
}
else {
stream = pair.component;
}
if (nodi.isInline()) {
sinkIdentifier = null;
}
else {
StreamConfiguration config = new StreamConfiguration();
config.setSocketAddr(StreamConfiguration.SERVER_ADDRESS, InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName));
bsos.setup(config);
logger.debug("deployed a buffer stream {}", bsos);
sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
StreamContext bssc = new StreamContext(nodi.declaredStreamId);
bssc.setSourceId(sourceIdentifier);
bssc.setSinkId(sinkIdentifier);
Sink s = bsos.connect(Component.INPUT, stream);
stream.connect(sinkIdentifier, s);
streams.put(sinkIdentifier, new ComponentContextPair<Stream, StreamContext>(bsos, bssc));
logger.debug("stored stream {} against key {}", bsos, sinkIdentifier);
}
}
if (!streams.containsKey(sourceIdentifier)) {
Sink s = stream.connect(Component.INPUT, node);
node.connect(nodi.portName, s);
StreamContext context = new StreamContext(nodi.declaredStreamId);
context.setSourceId(sourceIdentifier);
context.setSinkId(sinkIdentifier);
streams.put(sourceIdentifier, new ComponentContextPair<Stream, StreamContext>(stream, context));
logger.debug("stored stream {} against key {}", stream, sourceIdentifier);
}
}
}
}
private void deployInputStreams(List<ModuleDeployInfo> nodeList) throws Exception
{
// collect any input operators along with their smallest window id,
// those are subsequently used to setup the window generator
ArrayList<ModuleDeployInfo> inputNodes = new ArrayList<ModuleDeployInfo>();
long smallestWindowId = Long.MAX_VALUE;
/**
* Hook up all the downstream sinks.
* There are 2 places where we deal with more than sinks. The first one follows immediately for WindowGenerator.
* The second case is when source for the input of some node in this container is another container. So we need
* to create the stream. We need to track this stream along with other streams, and many such streams may exist,
* we hash them against buffer server info as we did for outputs but throw in the sinkid in the mix as well.
*/
for (ModuleDeployInfo ndi: nodeList) {
if (ndi.inputs == null || ndi.inputs.isEmpty()) {
/**
* This has to be AbstractInputNode, so let's hook the WindowGenerator to it.
* A node which does not take any input cannot exist in the DAG since it would be completely
* unaware of the windows. So for that reason, AbstractInputNode allows Component.INPUT port.
*/
inputNodes.add(ndi);
/**
* When we activate the window Generator, we plan to activate it only from required windowId.
*/
if (ndi.checkpointWindowId < smallestWindowId) {
smallestWindowId = ndi.checkpointWindowId;
}
}
else {
Module node = nodes.get(ndi.id);
for (ModuleDeployInfo.NodeInputDeployInfo nidi: ndi.inputs) {
String sourceIdentifier = nidi.sourceNodeId.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName);
String sinkIdentifier = ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName);
ComponentContextPair<Stream, StreamContext> pair = streams.get(sourceIdentifier);
if (pair == null) {
/**
* We connect to the buffer server for the input on this port.
* We have already placed all the output streams for all the operators in this container yet, there is no stream
* which can source this port so it has to come from the buffer server, so let's make a connection to it.
*/
assert (nidi.isInline() == false);
StreamConfiguration config = new StreamConfiguration();
config.setSocketAddr(StreamConfiguration.SERVER_ADDRESS, InetSocketAddress.createUnresolved(nidi.bufferServerHost, nidi.bufferServerPort));
Stream stream = new BufferServerInputStream(StramUtils.getSerdeInstance(nidi.serDeClassName));
stream.setup(config);
logger.debug("deployed buffer input stream {}", stream);
StreamContext context = new StreamContext(nidi.declaredStreamId);
context.setPartitions(nidi.partitionKeys);
context.setSourceId(sourceIdentifier);
context.setSinkId(sinkIdentifier);
Sink s = node.connect(nidi.portName, stream);
stream.connect(sinkIdentifier, ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink(stream, sinkIdentifier, s, ndi.checkpointWindowId) : s);
streams.put(sinkIdentifier,
new ComponentContextPair<Stream, StreamContext>(stream, context));
logger.debug("put input stream {} against key {}", stream, sinkIdentifier);
}
else {
String streamSinkId = pair.context.getSinkId();
Sink s;
if (streamSinkId == null) {
s = node.connect(nidi.portName, pair.component);
pair.context.setSinkId(sinkIdentifier);
}
else if (pair.component.isMultiSinkCapable()) {
s = node.connect(nidi.portName, pair.component);
pair.context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier));
}
else {
/**
* we are trying to tap into existing InlineStream or BufferServerOutputStream.
* Since none of those streams are MultiSinkCapable, we need to replace them with Mux.
*/
StreamContext context = new StreamContext(nidi.declaredStreamId);
context.setSourceId(sourceIdentifier);
context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier));
Stream stream = new MuxStream();
stream.setup(new StreamConfiguration());
logger.debug("deployed input mux stream {}", stream);
s = node.connect(nidi.portName, stream);
streams.put(sourceIdentifier, new ComponentContextPair<Stream, StreamContext>(stream, context));
logger.debug("stored input stream {} against key {}", stream, sourceIdentifier);
/**
* Lets wire the MuxStream to upstream node.
*/
String[] nodeport = sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR);
Module upstreamNode = nodes.get(nodeport[0]);
Sink muxSink = stream.connect(Component.INPUT, upstreamNode);
upstreamNode.connect(nodeport[1], muxSink);
Sink existingSink;
if (pair.component instanceof InlineStream) {
String[] np = streamSinkId.split(NODE_PORT_SPLIT_SEPARATOR);
Module anotherNode = nodes.get(np[0]);
existingSink = anotherNode.connect(np[1], stream);
/*
* we do not need to do this but looks bad if leave it in limbo.
*/
pair.component.deactivate();
pair.component.teardown();
}
else {
existingSink = pair.component.connect(Component.INPUT, stream);
/*
* we got this stream since it was mapped against sourceId, but since
* we took that place for MuxStream, we give this a new place of its own.
*/
streams.put(pair.context.getSinkId(), pair);
logger.debug("relocated stream {} against key {}", pair.context.getSinkId());
}
stream.connect(streamSinkId, existingSink);
}
if (nidi.partitionKeys == null || nidi.partitionKeys.isEmpty()) {
pair.component.connect(sinkIdentifier,
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink(pair.component, sinkIdentifier, s, ndi.checkpointWindowId) : s);
}
else {
/*
* generally speaking we do not have partitions on the inline streams so the control should not
* come here but if it comes, then we are ready to handle it using the partition aware streams.
*/
PartitionAwareSink pas = new PartitionAwareSink(StramUtils.getSerdeInstance(nidi.serDeClassName), nidi.partitionKeys, s);
pair.component.connect(sinkIdentifier,
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink(pair.component, sinkIdentifier, pas, ndi.checkpointWindowId) : pas);
}
}
}
}
}
if (!inputNodes.isEmpty()) {
WindowGenerator windowGenerator = setupWindowGenerator(smallestWindowId);
for (ModuleDeployInfo ndi: inputNodes) {
generators.put(ndi.id, windowGenerator);
Module node = nodes.get(ndi.id);
Sink s = node.connect(Component.INPUT, windowGenerator);
windowGenerator.connect(ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(Component.INPUT),
ndi.checkpointWindowId > 0
? new WindowIdActivatedSink(windowGenerator, ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(Component.INPUT), s, ndi.checkpointWindowId)
: s);
}
}
}
/**
* Create the window generator for the given start window id.
* This is a hook for tests to control the window generation.
*
* @param smallestWindowId
* @return
*/
protected WindowGenerator setupWindowGenerator(long smallestWindowId)
{
WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1, "WindowGenerator"));
/**
* let's make sure that we send the same window Ids with the same reset windows.
*/
// let's see if we want to send the exact same window id even the second time.
ModuleConfiguration config = new ModuleConfiguration("doesn't matter", null);
config.setLong(WindowGenerator.RESET_WINDOW_MILLIS, firstWindowMillis);
if (smallestWindowId > firstWindowMillis) {
config.setLong(WindowGenerator.FIRST_WINDOW_MILLIS, (smallestWindowId >> 32) * 1000 + windowWidthMillis * (smallestWindowId & WindowGenerator.MAX_WINDOW_ID));
}
else {
config.setLong(WindowGenerator.FIRST_WINDOW_MILLIS, firstWindowMillis);
}
config.setInt(WindowGenerator.WINDOW_WIDTH_MILLIS, windowWidthMillis);
windowGenerator.setup(config);
return windowGenerator;
}
@SuppressWarnings({"SleepWhileInLoop", "SleepWhileHoldingLock"})
public synchronized void activate(List<ModuleDeployInfo> nodeList)
{
for (ComponentContextPair<Stream, StreamContext> pair: streams.values()) {
if (!(pair.component instanceof SocketInputStream || activeStreams.containsKey(pair.component))) {
activeStreams.put(pair.component, pair.context);
pair.component.activate(pair.context);
}
}
final AtomicInteger activatedNodeCount = new AtomicInteger(activeNodes.size());
for (final ModuleDeployInfo ndi: nodeList) {
final Module node = nodes.get(ndi.id);
final String nodeInternalId = ndi.id.concat(":").concat(ndi.declaredId);
assert (!activeNodes.containsKey(ndi.id));
new Thread(nodeInternalId)
{
@Override
public void run()
{
try {
ModuleConfiguration config = new ModuleConfiguration(ndi.id, ndi.properties);
StramUtils.internalSetupNode(node, nodeInternalId);
node.setup(config);
ModuleContext nc = new ModuleContext(ndi.id, this);
activeNodes.put(ndi.id, nc);
activatedNodeCount.incrementAndGet();
logger.debug("activating {} in container {}", node.toString(), containerId);
node.activate(nc);
}
catch (Exception ex) {
logger.error("Node stopped abnormally because of exception", ex);
}
activeNodes.remove(ndi.id);
node.teardown();
disconnectNode(ndi.id);
}
}.start();
}
/**
* we need to make sure that before any of the operators gets the first message, it's activated.
*/
try {
do {
Thread.sleep(SPIN_MILLIS);
}
while (activatedNodeCount.get() < nodes.size());
}
catch (InterruptedException ex) {
logger.debug(ex.getLocalizedMessage());
}
for (ComponentContextPair<Stream, StreamContext> pair: streams.values()) {
if (pair.component instanceof SocketInputStream && !activeStreams.containsKey(pair.component)) {
activeStreams.put(pair.component, pair.context);
pair.component.activate(pair.context);
}
}
for (WindowGenerator wg: generators.values()) {
if (!activeGenerators.containsKey(wg)) {
activeGenerators.put(wg, generators);
wg.activate(null);
}
}
}
private void groupInputStreams(HashMap<String, ArrayList<String>> groupedInputStreams, ModuleDeployInfo ndi)
{
for (ModuleDeployInfo.NodeInputDeployInfo nidi: ndi.inputs) {
String source = nidi.sourceNodeId.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName);
/**
* if we do not want to combine multiple streams with different partitions from the
* same upstream node, we could also use the partition to group the streams together.
* This logic comes with the danger that the performance of the group which shares the same
* stream is bounded on the higher side by the performance of the lowest performer. May be
* combining the streams is not such a good thing but let's see if we allow this as an option
* to the user, what they end up choosing the most.
*/
ArrayList<String> collection = groupedInputStreams.get(source);
if (collection == null) {
collection = new ArrayList<String>();
groupedInputStreams.put(source, collection);
}
collection.add(ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName));
}
}
}
|
package net.mingsoft.cms.action;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import net.mingsoft.basic.action.BaseAction;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.biz.ICategoryBiz;
import net.mingsoft.basic.biz.IColumnBiz;
import net.mingsoft.basic.biz.IModelBiz;
import net.mingsoft.basic.constant.Const;
import net.mingsoft.basic.constant.ModelCode;
import net.mingsoft.basic.constant.e.SessionConstEnum;
import net.mingsoft.basic.entity.ColumnEntity;
import net.mingsoft.basic.entity.ManagerEntity;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.FileUtil;
import net.mingsoft.basic.util.StringUtil;
import net.mingsoft.mdiy.util.ParserUtil;
/**
* MS,basic
* @author
* @version
* 100-000-000<br/>
* 201789<br/>
* <br/>
*/
@Controller("articleColumnAction")
@RequestMapping("/${ms.manager.path}/cms/column")
public class ColumnAction extends BaseAction{
@Autowired
private IColumnBiz columnBiz;
@Autowired
private ICategoryBiz categoryBiz;
@Autowired
private IModelBiz modelBiz;
/**
* index
*/
@RequestMapping("/index")
@RequiresPermissions("cms:column:view")
public String index(HttpServletResponse response,HttpServletRequest request,ModelMap model){
model.addAttribute("model", "cms");
return view ("/column/index");
}
/**
*
*
* @return
*/
@RequestMapping("/add")
public String add(HttpServletRequest request,ModelMap model) {
int appId =BasicUtil.getAppId();
List<ColumnEntity> list = columnBiz.queryAll(appId, BasicUtil.getModelCodeId(net.mingsoft.cms.constant.ModelCode.CMS_COLUMN.toString()));
ColumnEntity columnSuper = new ColumnEntity();
model.addAttribute("appId",appId);
model.addAttribute("columnSuper", columnSuper);
model.addAttribute("column",new ColumnEntity());
model.addAttribute("listColumn", JSONArray.toJSONString(list));
model.addAttribute("model", "cms");
return "/column/form";
}
/**
*
* @param column
* @param response
* @return false: true:
*/
private boolean checkForm(ColumnEntity column, HttpServletResponse response){
if(StringUtils.isBlank(column.getCategoryTitle())){
this.outJson( response, ModelCode.COLUMN, false, getResString("err.empty", this.getResString("categoryTitle")));
return false;
}
if(!StringUtil.checkLength(column.getCategoryTitle(), 1, 31)){
this.outJson( response, ModelCode.COLUMN, false, getResString("err.length", this.getResString("categoryTitle"), "1", "30"));
return false;
}
if(StringUtils.isBlank(column.getColumnType()+"")){
this.outJson( response, ModelCode.COLUMN, false, getResString("err.empty", this.getResString("columnType")));
return false;
}
return true;
}
/**
*
* @param request
* @param column
*/
private void columnPath(HttpServletRequest request,ColumnEntity column){
StringBuffer columnPath = new StringBuffer();
String file = BasicUtil.getRealPath("")+ParserUtil.HTML+File.separator+ column.getAppId();
String delFile = "";
column = (ColumnEntity) columnBiz.getEntity(column.getCategoryId());
delFile = file + column.getColumnPath();
if(!StringUtils.isBlank(delFile)){
File delFileName = new File(delFile);
delFileName.delete();
}
if(column.getCategoryCategoryId() == 0){
column.setColumnPath(File.separator+column.getCategoryId());
file = file + File.separator + column.getCategoryId();
} else {
List<ColumnEntity> list = columnBiz.queryParentColumnByColumnId(column.getCategoryId());
if(list != null){
StringBuffer temp = new StringBuffer();
for(int i = list.size()-1; i>=0; i
ColumnEntity entity = list.get(i);
columnPath.append(File.separator).append(entity.getCategoryId());
temp.append(File.separator).append(entity.getCategoryId());
}
column.setColumnPath(columnPath.append(File.separator).append(column.getCategoryId()).toString());
file = file + temp.toString() + File.separator + column.getCategoryId();
}
}
columnBiz.updateEntity(column);
File fileName = new File(file);
fileName.mkdir();
}
/**
* @param column
* <i>column</i><br/>
* columnCategoryid:columnCategoryid,columnCategoryid=1,2,3,4
*
* <dt><span class="strong"></span></dt><br/>
* <dd>{code:"",<br/>
* result:"truefalse",<br/>
* resultMsg:""<br/>
* }</dd>
*/
@RequestMapping("/delete")
@ResponseBody
public void delete(HttpServletResponse response, HttpServletRequest request) {
int[] ids = BasicUtil.getInts("ids", ",");
ColumnEntity column =new ColumnEntity();
for(int i=0;i<ids.length;i++){
column = (ColumnEntity) columnBiz.getEntity(ids[i]);
columnBiz.deleteCategory(ids[i]);
FileUtil.del(column);
};
this.outJson(response, true);
}
/**
*
* @param columnId ID
* @param request
* @param model
* @return
*/
@RequestMapping("/{columnId}/edit")
public String edit(@PathVariable int columnId, HttpServletRequest request,ModelMap model) {
ManagerEntity managerSession = (ManagerEntity) BasicUtil.getSession( SessionConstEnum.MANAGER_SESSION);
int appId = BasicUtil.getAppId();
List<ColumnEntity> list = new ArrayList<ColumnEntity>();
list = columnBiz.queryAll(appId, BasicUtil.getModelCodeId(net.mingsoft.cms.constant.ModelCode.CMS_COLUMN.toString()));
ColumnEntity column = (ColumnEntity) columnBiz.getEntity(columnId);
model.addAttribute("appId",appId);
model.addAttribute("column", column);
model.addAttribute("columnc", column.getCategoryId());
ColumnEntity columnSuper = new ColumnEntity();
if (column.getCategoryCategoryId() != Const.COLUMN_TOP_CATEGORY_ID) {
columnSuper = (ColumnEntity) columnBiz.getEntity(column.getCategoryCategoryId());
}
model.addAttribute("columnSuper", columnSuper);
model.addAttribute("listColumn", JSONArray.toJSONString(list));
model.addAttribute("model", "cms");
return "/column/form";
}
@SuppressWarnings("deprecation")
@RequestMapping("/list")
public void list(@ModelAttribute ColumnEntity column,HttpServletResponse response, HttpServletRequest request,ModelMap model) {
// IDsession
int websiteId = BasicUtil.getAppId();
List list = columnBiz.queryAll(websiteId, BasicUtil.getModelCodeId(net.mingsoft.cms.constant.ModelCode.CMS_COLUMN.toString()));
EUListBean _list = new EUListBean(list, list.size());
this.outJson(response, net.mingsoft.base.util.JSONArray.toJSONString(_list));
}
/**
*
*
* @param column
*
* @return
*/
@RequestMapping("/save")
public void save(@ModelAttribute ColumnEntity column,HttpServletRequest request,HttpServletResponse response) {
if(!checkForm(column,response)){
return;
}
column.setCategoryAppId( BasicUtil.getAppId());
column.setAppId(BasicUtil.getAppId());
column.setCategoryManagerId(getManagerBySession(request).getManagerId());
column.setCategoryDateTime(new Timestamp(System.currentTimeMillis()));
column.setCategoryModelId(BasicUtil.getModelCodeId(net.mingsoft.cms.constant.ModelCode.CMS_COLUMN.toString()));
if(column.getColumnType()==ColumnEntity.ColumnTypeEnum.COLUMN_TYPE_COVER.toInt()){
column.setColumnListUrl(null);
}
columnBiz.saveCategory(column);
this.columnPath(request,column);
this.outJson(response, ModelCode.COLUMN, true,null,JSONArray.toJSONString(column.getCategoryId()));
}
/**
*
* @param column
* @param request
* @param response
*/
@RequestMapping("/update")
@ResponseBody
public void update(@ModelAttribute ColumnEntity column,HttpServletRequest request,HttpServletResponse response) {
int websiteId = BasicUtil.getAppId();
if(!checkForm(column,response)){
return;
}
//Null
if(column.getColumnType()==ColumnEntity.ColumnTypeEnum.COLUMN_TYPE_COVER.toInt()){
column.setColumnListUrl(null);
}
column.setCategoryManagerId(getManagerBySession(request).getManagerId());
column.setAppId(websiteId);
columnBiz.updateCategory(column);
this.columnPath(request,column);
List<ColumnEntity> childList = columnBiz.queryChild(column.getCategoryId(), websiteId,BasicUtil.getModelCodeId(net.mingsoft.cms.constant.ModelCode.CMS_COLUMN.toString()),null);
if(childList != null && childList.size()>0){
//IDID
for(int i=0;i<childList.size();i++){
childList.get(i).setCategoryCategoryId(column.getCategoryId());
childList.get(i).setCategoryManagerId(getManagerBySession(request).getManagerId());
childList.get(i).setAppId(websiteId);
columnBiz.updateCategory(childList.get(i));
this.columnPath(request, childList.get(i));
}
}
this.outJson(response, ModelCode.COLUMN, true,null,JSONArray.toJSONString(column.getCategoryId()));
}
}
|
package com.malhartech.stram;
import com.malhartech.api.Operator.Unifier;
import com.malhartech.api.*;
import com.malhartech.bufferserver.Server;
import com.malhartech.bufferserver.storage.DiskStorage;
import com.malhartech.bufferserver.util.Codec;
import com.malhartech.engine.*;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeat;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat.DNodeState;
import com.malhartech.stream.*;
import com.malhartech.util.AttributeMap;
import com.malhartech.util.ScheduledThreadPoolExecutor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.PrivilegedExceptionAction;
import java.util.Map.Entry;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSError;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.log4j.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* The main() for streaming container processes launched by {@link com.malhartech.stram.StramAppMaster}.<p>
* <br>
*
*/
public class StramChild
{
private static final Logger logger = LoggerFactory.getLogger(StramChild.class);
private static final String NODE_PORT_SPLIT_SEPARATOR = "\\.";
public static final String NODE_PORT_CONCAT_SEPARATOR = ".";
private static final int SPIN_MILLIS = 20;
private final String containerId;
private final Configuration conf;
private final StreamingContainerUmbilicalProtocol umbilical;
protected final Map<Integer, Node<?>> nodes = new ConcurrentHashMap<Integer, Node<?>>();
private final Map<String, ComponentContextPair<Stream<Object>, StreamContext>> streams = new ConcurrentHashMap<String, ComponentContextPair<Stream<Object>, StreamContext>>();
protected final Map<Integer, WindowGenerator> generators = new ConcurrentHashMap<Integer, WindowGenerator>();
protected final Map<Integer, OperatorContext> activeNodes = new ConcurrentHashMap<Integer, OperatorContext>();
private final Map<Stream<?>, StreamContext> activeStreams = new ConcurrentHashMap<Stream<?>, StreamContext>();
private final Map<WindowGenerator, Object> activeGenerators = new ConcurrentHashMap<WindowGenerator, Object>();
private int heartbeatIntervalMillis = 1000;
private volatile boolean exitHeartbeatLoop = false;
private final Object heartbeatTrigger = new Object();
private String checkpointFsPath;
/**
* Map of last backup window id that is used to communicate checkpoint state back to Stram. TODO: Consider adding this to the node context instead.
*/
private final Map<Integer, Long> backupInfo = new ConcurrentHashMap<Integer, Long>();
private long firstWindowMillis;
private int windowWidthMillis;
private InetSocketAddress bufferServerAddress;
private com.malhartech.bufferserver.Server bufferServer;
private AttributeMap<DAGConstants> applicationAttributes;
protected StramChild(String containerId, Configuration conf, StreamingContainerUmbilicalProtocol umbilical)
{
logger.debug("instantiated StramChild {}", containerId);
this.umbilical = umbilical;
this.containerId = containerId;
this.conf = conf;
}
public void setup(StreamingContainerContext ctx)
{
this.applicationAttributes = ctx.applicationAttributes;
heartbeatIntervalMillis = ctx.applicationAttributes.attrValue(DAG.STRAM_HEARTBEAT_INTERVAL_MILLIS, 1000);
firstWindowMillis = ctx.startWindowMillis;
windowWidthMillis = ctx.applicationAttributes.attrValue(DAG.STRAM_WINDOW_SIZE_MILLIS, 500);
this.checkpointFsPath = ctx.applicationAttributes.attrValue(DAG.STRAM_CHECKPOINT_DIR, "checkpoint-dfs-path-not-configured");
try {
if (ctx.deployBufferServer) {
// start buffer server, if it was not set externally
bufferServer = new Server(0, 64 * 1024 * 1024, 8);
bufferServer.setSpoolStorage(new DiskStorage());
SocketAddress bindAddr = bufferServer.run();
logger.info("Buffer server started: {}", bindAddr);
this.bufferServerAddress = NetUtils.getConnectAddress(((InetSocketAddress)bindAddr));
}
}
catch (Exception ex) {
logger.warn("deploy request failed due to {}", ex);
}
}
public String getContainerId()
{
return this.containerId;
}
/**
* Initialize container. Establishes heartbeat connection to the master
* process through the callback address provided on the command line. Deploys
* initial modules, then enters the heartbeat loop, which will only terminate
* once container receives shutdown request from the master. On shutdown,
* after exiting heartbeat loop, deactivate all modules and terminate
* processing threads.
*
*/
public static void main(String[] args) throws Throwable
{
logger.info("Child starting with classpath: {}", System.getProperty("java.class.path"));
final Configuration defaultConf = new Configuration();
//defaultConf.addResource(MRJobConfig.JOB_CONF_FILE);
UserGroupInformation.setConfiguration(defaultConf);
String host = args[0];
int port = Integer.parseInt(args[1]);
final InetSocketAddress address =
NetUtils.createSocketAddrForHost(host, port);
final String childId = System.getProperty("stram.cid");
//Token<JobTokenIdentifier> jt = loadCredentials(defaultConf, address);
// Communicate with parent as actual task owner.
UserGroupInformation taskOwner =
UserGroupInformation.createRemoteUser(StramChild.class.getName());
//taskOwner.addToken(jt);
final StreamingContainerUmbilicalProtocol umbilical =
taskOwner.doAs(new PrivilegedExceptionAction<StreamingContainerUmbilicalProtocol>()
{
@Override
public StreamingContainerUmbilicalProtocol run() throws Exception
{
return RPC.getProxy(StreamingContainerUmbilicalProtocol.class,
StreamingContainerUmbilicalProtocol.versionID, address, defaultConf);
}
});
logger.debug("PID: " + System.getenv().get("JVM_PID"));
UserGroupInformation childUGI;
try {
childUGI = UserGroupInformation.createRemoteUser(System.getenv(ApplicationConstants.Environment.USER.toString()));
// Add tokens to new user so that it may execute its task correctly.
for (Token<?> token: UserGroupInformation.getCurrentUser().getTokens()) {
childUGI.addToken(token);
}
childUGI.doAs(new PrivilegedExceptionAction<Object>()
{
@Override
public Object run() throws Exception
{
StreamingContainerContext ctx = umbilical.getInitContext(childId);
StramChild stramChild = new StramChild(childId, defaultConf, umbilical);
logger.debug("Got context: " + ctx);
stramChild.setup(ctx);
try {
// main thread enters heartbeat loop
stramChild.monitorHeartbeat();
}
finally {
// teardown
stramChild.teardown();
}
return null;
}
});
}
catch (FSError e) {
logger.error("FSError from child", e);
umbilical.log(childId, e.getMessage());
}
catch (Exception exception) {
logger.warn("Exception running child : "
+ StringUtils.stringifyException(exception));
// Report back any failures, for diagnostic purposes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
exception.printStackTrace(new PrintStream(baos));
umbilical.log(childId, "FATAL: " + baos.toString());
}
catch (Throwable throwable) {
logger.error("Error running child : "
+ StringUtils.stringifyException(throwable));
Throwable tCause = throwable.getCause();
String cause = tCause == null
? throwable.getMessage()
: StringUtils.stringifyException(tCause);
umbilical.log(childId, cause);
}
finally {
RPC.stopProxy(umbilical);
DefaultMetricsSystem.shutdown();
// Shutting down log4j of the child-vm...
// This assumes that on return from Task.activate()
// there is no more logging done.
LogManager.shutdown();
}
}
public synchronized void deactivate()
{
ArrayList<Thread> activeThreads = new ArrayList<Thread>();
ArrayList<Integer> activeOperators = new ArrayList<Integer>();
for (Entry<Integer, Node<?>> e: nodes.entrySet()) {
OperatorContext oc = activeNodes.get(e.getKey());
if (oc == null) {
disconnectNode(e.getKey());
}
else {
activeThreads.add(oc.getThread());
activeOperators.add(e.getKey());
e.getValue().deactivate();
}
}
try {
Iterator<Integer> iterator = activeOperators.iterator();
for (Thread t: activeThreads) {
t.join();
disconnectNode(iterator.next());
}
assert (activeNodes.isEmpty());
}
catch (InterruptedException ex) {
logger.info("Aborting wait for for operators to get deactivated as got interrupted with {}", ex);
}
for (WindowGenerator wg: activeGenerators.keySet()) {
wg.deactivate();
}
activeGenerators.clear();
for (Stream<?> stream: activeStreams.keySet()) {
stream.deactivate();
}
activeStreams.clear();
}
private void disconnectNode(int nodeid)
{
Node<?> node = nodes.get(nodeid);
disconnectWindowGenerator(nodeid, node);
Set<String> removableStreams = new HashSet<String>(); // temporary fix - find out why List does not work.
// with the logic i have in here, the list should not contain repeated streams. but it does and that causes problem.
for (Entry<String, ComponentContextPair<Stream<Object>, StreamContext>> entry: streams.entrySet()) {
String indexingKey = entry.getKey();
Stream<?> stream = entry.getValue().component;
StreamContext context = entry.getValue().context;
String sourceIdentifier = context.getSourceId();
String sinkIdentifier = context.getSinkId();
logger.debug("considering stream {} against id {}", stream, indexingKey);
if (nodeid == Integer.parseInt(sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR)[0])) {
/*
* the stream originates at the output port of one of the operators that are going to vanish.
*/
if (activeStreams.containsKey(stream)) {
logger.debug("deactivating {}", stream);
stream.deactivate();
activeStreams.remove(stream);
}
removableStreams.add(sourceIdentifier);
String[] sinkIds = sinkIdentifier.split(", ");
for (String sinkId: sinkIds) {
if (!sinkId.startsWith("tcp:
String[] nodeport = sinkId.split(NODE_PORT_SPLIT_SEPARATOR);
Node<?> n = nodes.get(nodeport[0]);
if (n instanceof UnifierNode) {
n.connectInputPort(nodeport[1] + "(" + sourceIdentifier + ")", null);
}
else if (n != null) {
// check why null pointer exception gets thrown here during shutdown! - chetan
n.connectInputPort(nodeport[1], null);
}
}
else if (stream.isMultiSinkCapable()) {
ComponentContextPair<Stream<Object>, StreamContext> spair = streams.get(sinkId);
logger.debug("found stream {} against {}", spair == null ? null : spair.component, sinkId);
if (spair == null) {
assert (!sinkId.startsWith("tcp:
}
else {
assert (sinkId.startsWith("tcp:
if (activeStreams.containsKey(spair.component)) {
logger.debug("deactivating {} for sink {}", spair.component, sinkId);
spair.component.deactivate();
activeStreams.remove(spair.component);
}
removableStreams.add(sinkId);
}
}
}
}
else {
/**
* the stream may or may not feed into one of the operators which are being undeployed.
*/
String[] sinkIds = sinkIdentifier.split(", ");
for (int i = sinkIds.length; i
String[] nodeport = sinkIds[i].split(NODE_PORT_SPLIT_SEPARATOR);
if (Integer.toString(nodeid).equals(nodeport[0])) {
stream.setSink(sinkIds[i], null);
if (node instanceof UnifierNode) {
node.connectInputPort(nodeport[1] + "(" + sourceIdentifier + ")", null);
}
else {
node.connectInputPort(nodeport[1], null);
}
sinkIds[i] = null;
}
}
String sinkId = null;
for (int i = sinkIds.length; i
if (sinkIds[i] != null) {
if (sinkId == null) {
sinkId = sinkIds[i];
}
else {
sinkId = sinkId.concat(", ").concat(sinkIds[i]);
}
}
}
if (sinkId == null) {
if (activeStreams.containsKey(stream)) {
logger.debug("deactivating {}", stream);
stream.deactivate();
activeStreams.remove(stream);
}
removableStreams.add(indexingKey);
}
else {
// may be we should also check if the count has changed from something to 1
// and replace mux with 1:1 sink. it's not necessary though.
context.setSinkId(sinkId);
}
}
}
for (String streamId: removableStreams) {
logger.debug("removing stream {}", streamId);
// need to check why control comes here twice to remove the stream which was deleted before.
// is it because of multiSinkCapableStream ?
ComponentContextPair<Stream<Object>, StreamContext> pair = streams.remove(streamId);
pair.component.teardown();
}
}
private void disconnectWindowGenerator(int nodeid, Node<?> node)
{
WindowGenerator chosen1 = generators.remove(nodeid);
if (chosen1 != null) {
chosen1.setSink(Integer.toString(nodeid).concat(NODE_PORT_CONCAT_SEPARATOR).concat(Node.INPUT), null);
node.connectInputPort(Node.INPUT, null);
int count = 0;
for (WindowGenerator wg: generators.values()) {
if (chosen1 == wg) {
count++;
}
}
if (count == 0) {
activeGenerators.remove(chosen1);
chosen1.deactivate();
chosen1.teardown();
}
}
}
private synchronized void undeploy(List<OperatorDeployInfo> nodeList)
{
logger.info("got undeploy request {}", nodeList);
/**
* make sure that all the operators which we are asked to undeploy are in this container.
*/
HashMap<Integer, Node<?>> toUndeploy = new HashMap<Integer, Node<?>>();
for (OperatorDeployInfo ndi: nodeList) {
Node<?> node = nodes.get(ndi.id);
if (node == null) {
throw new IllegalArgumentException("Node " + ndi.id + " is not hosted in this container!");
}
else if (toUndeploy.containsKey(ndi.id)) {
throw new IllegalArgumentException("Node " + ndi.id + " is requested to be undeployed more than once");
}
else {
toUndeploy.put(ndi.id, node);
}
}
// track all the ids to undeploy
// track the ones which are active
ArrayList<Thread> joinList = new ArrayList<Thread>();
ArrayList<Integer> discoList = new ArrayList<Integer>();
for (OperatorDeployInfo ndi: nodeList) {
OperatorContext oc = activeNodes.get(ndi.id);
if (oc == null) {
disconnectNode(ndi.id);
}
else {
joinList.add(oc.getThread());
discoList.add(ndi.id);
nodes.get(ndi.id).deactivate();
}
}
try {
Iterator<Integer> iterator = discoList.iterator();
for (Thread t: joinList) {
t.join();
disconnectNode(iterator.next());
}
logger.info("undeploy complete");
}
catch (InterruptedException ex) {
logger.warn("Aborted waiting for the deactivate to finish!");
}
for (OperatorDeployInfo ndi: nodeList) {
nodes.remove(ndi.id);
}
}
public void teardown()
{
deactivate();
assert (streams.isEmpty());
nodes.clear();
HashSet<WindowGenerator> gens = new HashSet<WindowGenerator>();
gens.addAll(generators.values());
generators.clear();
for (WindowGenerator wg: gens) {
wg.teardown();
}
if (bufferServer != null) {
bufferServer.shutdown();
}
gens.clear();
}
protected void triggerHeartbeat()
{
synchronized (heartbeatTrigger) {
heartbeatTrigger.notifyAll();
}
}
protected void monitorHeartbeat() throws IOException
{
umbilical.log(containerId, "[" + containerId + "] Entering heartbeat loop..");
logger.debug("Entering heartbeat loop (interval is {} ms)", this.heartbeatIntervalMillis);
while (!exitHeartbeatLoop) {
synchronized (this.heartbeatTrigger) {
try {
this.heartbeatTrigger.wait(heartbeatIntervalMillis);
}
catch (InterruptedException e1) {
logger.warn("Interrupted in heartbeat loop, exiting..");
break;
}
}
long currentTime = System.currentTimeMillis();
ContainerHeartbeat msg = new ContainerHeartbeat();
msg.setContainerId(this.containerId);
if (this.bufferServerAddress != null) {
msg.bufferServerHost = this.bufferServerAddress.getHostName();
msg.bufferServerPort = this.bufferServerAddress.getPort();
}
List<StreamingNodeHeartbeat> heartbeats = new ArrayList<StreamingNodeHeartbeat>(nodes.size());
// gather heartbeat info for all operators
for (Map.Entry<Integer, Node<?>> e: nodes.entrySet()) {
StreamingNodeHeartbeat hb = new StreamingNodeHeartbeat();
hb.setNodeId(e.getKey());
hb.setGeneratedTms(currentTime);
hb.setIntervalMs(heartbeatIntervalMillis);
if (activeNodes.containsKey(e.getKey())) {
activeNodes.get(e.getKey()).drainHeartbeatCounters(hb.getWindowStats());
hb.setState(DNodeState.ACTIVE.toString());
}
else {
hb.setState(e.getValue().isAlive() ? DNodeState.FAILED.toString() : DNodeState.IDLE.toString());
}
// propagate the backup window, if any
Long backupWindowId = backupInfo.get(e.getKey());
if (backupWindowId != null) {
hb.setLastBackupWindowId(backupWindowId);
}
heartbeats.add(hb);
}
msg.setDnodeEntries(heartbeats);
// heartbeat call and follow-up processing
//logger.debug("Sending heartbeat for {} operators.", msg.getDnodeEntries().size());
try {
ContainerHeartbeatResponse rsp = umbilical.processHeartbeat(msg);
if (rsp != null) {
processHeartbeatResponse(rsp);
// keep polling at smaller interval if work is pending
while (rsp != null && rsp.hasPendingRequests) {
logger.info("Waiting for pending request.");
synchronized (this.heartbeatTrigger) {
try {
this.heartbeatTrigger.wait(500);
}
catch (InterruptedException e1) {
logger.warn("Interrupted in heartbeat loop, exiting..");
break;
}
}
rsp = umbilical.pollRequest(this.containerId);
if (rsp != null) {
processHeartbeatResponse(rsp);
}
}
}
}
catch (Exception e) {
logger.warn("Exception received (may be during shutdown?)", e);
}
}
logger.debug("Exiting hearbeat loop");
umbilical.log(containerId, "[" + containerId + "] Exiting heartbeat loop..");
}
protected void processHeartbeatResponse(ContainerHeartbeatResponse rsp)
{
if (rsp.shutdown) {
logger.info("Received shutdown request");
this.exitHeartbeatLoop = true;
return;
}
if (rsp.undeployRequest != null) {
logger.info("Undeploy request: {}", rsp.undeployRequest);
undeploy(rsp.undeployRequest);
}
if (rsp.deployRequest != null) {
logger.info("Deploy request: {}", rsp.deployRequest);
try {
deploy(rsp.deployRequest);
}
catch (Exception e) {
logger.error("deploy request failed due to {}", e);
// report it to stram
}
}
if (rsp.nodeRequests != null) {
// extended processing per node
for (StramToNodeRequest req: rsp.nodeRequests) {
OperatorContext nc = activeNodes.get(req.getNodeId());
if (nc == null) {
logger.warn("Received request with invalid node id {} ({})", req.getNodeId(), req);
}
else {
logger.debug("Stram request: {}", req);
processStramRequest(nc, req);
}
}
}
}
/**
* Process request from stram for further communication through the protocol. Extended reporting is on a per node basis (won't occur under regular operation)
*
* @param n
* @param snr
*/
private void processStramRequest(OperatorContext context, final StramToNodeRequest snr)
{
switch (snr.getRequestType()) {
case REPORT_PARTION_STATS:
logger.warn("Ignoring stram request {}", snr);
break;
case CHECKPOINT:
final Node<?> node = nodes.get(snr.getNodeId());
context.request(new OperatorContext.NodeRequest()
{
@Override
public void execute(Operator operator, int id, long windowId) throws IOException
{
new HdfsBackupAgent(StramChild.this.conf, StramChild.this.checkpointFsPath).backup(id, windowId, operator, StramUtils.getNodeSerDe(null));
// record last backup window id for heartbeat
StramChild.this.backupInfo.put(id, windowId);
node.emitCheckpoint(windowId);
if (operator instanceof CheckpointListener) {
((CheckpointListener)operator).checkpointed(windowId);
((CheckpointListener)operator).committed(snr.getRecoveryCheckpoint());
}
}
});
break;
default:
logger.error("Unknown request from stram {}", snr);
}
}
private synchronized void deploy(List<OperatorDeployInfo> nodeList) throws Exception
{
/*
* A little bit of up front sanity check would reduce the percentage of deploy failures later.
*/
for (OperatorDeployInfo ndi: nodeList) {
if (nodes.containsKey(ndi.id)) {
throw new IllegalStateException("Node with id: " + ndi.id + " already present in the container");
}
}
deployNodes(nodeList);
HashMap<String, ArrayList<String>> groupedInputStreams = new HashMap<String, ArrayList<String>>();
for (OperatorDeployInfo ndi: nodeList) {
groupInputStreams(groupedInputStreams, ndi);
}
deployOutputStreams(nodeList, groupedInputStreams);
deployInputStreams(nodeList);
activate(nodeList);
}
private void massageUnifierDeployInfo(OperatorDeployInfo odi)
{
for (OperatorDeployInfo.InputDeployInfo idi: odi.inputs) {
idi.portName += "(" + idi.sourceNodeId + NODE_PORT_CONCAT_SEPARATOR + idi.sourcePortName + ")";
}
}
@SuppressWarnings("unchecked")
private void deployNodes(List<OperatorDeployInfo> nodeList) throws Exception
{
OperatorCodec operatorSerDe = StramUtils.getNodeSerDe(null);
BackupAgent backupAgent = new HdfsBackupAgent(this.conf, this.checkpointFsPath);
for (OperatorDeployInfo ndi: nodeList) {
try {
final Object foreignObject;
if (ndi.checkpointWindowId > 0) {
logger.debug("Restoring node {} to checkpoint {}", ndi.id, Codec.getStringWindowId(ndi.checkpointWindowId));
foreignObject = backupAgent.restore(ndi.id, ndi.checkpointWindowId, operatorSerDe);
}
else {
foreignObject = operatorSerDe.read(new ByteArrayInputStream(ndi.serializedNode));
}
String nodeid = Integer.toString(ndi.id).concat("/").concat(ndi.declaredId).concat(":").concat(foreignObject.getClass().getSimpleName());
if (foreignObject instanceof InputOperator && ndi.type == OperatorDeployInfo.OperatorType.INPUT) {
nodes.put(ndi.id, new InputNode(nodeid, (InputOperator)foreignObject));
}
else if (foreignObject instanceof Unifier && ndi.type == OperatorDeployInfo.OperatorType.UNIFIER) {
nodes.put(ndi.id, new UnifierNode(nodeid, (Unifier<Object>)foreignObject));
massageUnifierDeployInfo(ndi);
}
else {
nodes.put(ndi.id, new GenericNode(nodeid, (Operator)foreignObject));
}
}
catch (Exception e) {
logger.error(e.getLocalizedMessage());
throw e;
}
}
}
private void deployOutputStreams(List<OperatorDeployInfo> nodeList, HashMap<String, ArrayList<String>> groupedInputStreams) throws Exception
{
/*
* We proceed to deploy all the output streams. At the end of this block, our streams collection
* will contain all the streams which originate at the output port of the operators. The streams
* are generally mapped against the "nodename.portname" string. But the BufferOutputStreams which
* share the output port with other inline streams are mapped against the Buffer Server port to
* avoid collision and at the same time keep track of these buffer streams.
*/
for (OperatorDeployInfo ndi: nodeList) {
Node<?> node = nodes.get(ndi.id);
for (OperatorDeployInfo.OutputDeployInfo nodi: ndi.outputs) {
String sourceIdentifier = Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nodi.portName);
String sinkIdentifier;
StreamContext context = new StreamContext(nodi.declaredStreamId);
Stream<Object> stream;
ArrayList<String> collection = groupedInputStreams.get(sourceIdentifier);
if (collection == null) {
/*
* Let's create a stream to carry the data to the Buffer Server.
* Nobody in this container is interested in the output placed on this stream, but
* this stream exists. That means someone outside of this container must be interested.
*/
assert (nodi.isInline() == false);
context.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
stream = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName));
stream.setup(context);
logger.debug("deployed a buffer stream {}", stream);
sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
}
else if (collection.size() == 1) {
if (nodi.isInline()) {
/**
* Let's create an inline stream to carry data from output port to input port of some other node.
* There is only one node interested in output placed on this stream, and that node is in this container.
*/
stream = new InlineStream();
stream.setup(context);
sinkIdentifier = null;
}
else {
/**
* Let's create 2 streams: 1 inline and 1 going to the Buffer Server.
* Although there is a node in this container interested in output placed on this stream, there
* seems to at least one more party interested but placed in a container other than this one.
*/
sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
StreamContext bssc = new StreamContext(nodi.declaredStreamId);
bssc.setSourceId(sourceIdentifier);
bssc.setSinkId(sinkIdentifier);
bssc.setStartingWindowId(ndi.checkpointWindowId > 0? ndi.checkpointWindowId + 1: 0); // TODO: next window after checkpoint
bssc.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName));
bsos.setup(bssc);
logger.debug("deployed a buffer stream {}", bsos);
streams.put(sinkIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(bsos, bssc));
// should we create inline stream here or wait for the input deployments to create the inline streams?
stream = new MuxStream();
stream.setup(context);
stream.setSink(sinkIdentifier, bsos);
logger.debug("stored stream {} against key {}", bsos, sinkIdentifier);
}
}
else {
/**
* Since there are multiple parties interested in this node itself, we are going to come
* to this block multiple times. The actions we take subsequent times are going to be different
* than the first time. We create the MuxStream only the first time.
*/
ComponentContextPair<Stream<Object>, StreamContext> pair = streams.get(sourceIdentifier);
if (pair == null) {
/**
* Let's multiplex the output placed on this stream.
* This container itself contains more than one parties interested.
*/
stream = new MuxStream();
stream.setup(context);
}
else {
stream = pair.component;
}
if (nodi.isInline()) {
sinkIdentifier = null;
}
else {
sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
StreamContext bssc = new StreamContext(nodi.declaredStreamId);
bssc.setSourceId(sourceIdentifier);
bssc.setSinkId(sinkIdentifier);
bssc.setStartingWindowId(ndi.checkpointWindowId > 0? ndi.checkpointWindowId + 1: 0); // TODO: next window after checkpoint
bssc.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName));
bsos.setup(bssc);
logger.debug("deployed a buffer stream {}", bsos);
streams.put(sinkIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(bsos, bssc));
logger.debug("stored stream {} against key {}", bsos, sinkIdentifier);
stream.setup(context);
stream.setSink(sinkIdentifier, bsos);
}
}
if (!streams.containsKey(sourceIdentifier)) {
node.connectOutputPort(nodi.portName, stream);
context.setSourceId(sourceIdentifier);
context.setSinkId(sinkIdentifier);
context.setStartingWindowId(ndi.checkpointWindowId > 0? ndi.checkpointWindowId + 1: 0); // TODO: next window after checkpoint
streams.put(sourceIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(stream, context));
logger.debug("stored stream {} against key {}", stream, sourceIdentifier);
}
}
}
}
private void deployInputStreams(List<OperatorDeployInfo> nodeList) throws Exception
{
// collect any input operators along with their smallest window id,
// those are subsequently used to setup the window generator
ArrayList<OperatorDeployInfo> inputNodes = new ArrayList<OperatorDeployInfo>();
long smallestCheckpointedWindowId = Long.MAX_VALUE;
/*
* Hook up all the downstream ports. There are 2 places where we deal with more than 1
* downstream ports. The first one follows immediately for WindowGenerator. The second
* case is when source for the input port of some node in this container is in another
* container. So we need to create the stream. We need to track this stream along with
* other streams,and many such streams may exist, we hash them against buffer server
* info as we did for outputs but throw in the sinkid in the mix as well.
*/
for (OperatorDeployInfo ndi: nodeList) {
if (ndi.inputs == null || ndi.inputs.isEmpty()) {
/**
* This has to be InputNode, so let's hook the WindowGenerator to it.
* A node which does not take any input cannot exist in the DAG since it would be completely
* unaware of the windows. So for that reason, AbstractInputNode allows Component.INPUT port.
*/
inputNodes.add(ndi);
/*
* When we activate the window Generator, we plan to activate it only from required windowId.
*/
if (ndi.checkpointWindowId < smallestCheckpointedWindowId) {
smallestCheckpointedWindowId = ndi.checkpointWindowId;
}
}
else {
Node<?> node = nodes.get(ndi.id);
for (OperatorDeployInfo.InputDeployInfo nidi: ndi.inputs) {
String sourceIdentifier = Integer.toString(nidi.sourceNodeId).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName);
String sinkIdentifier = Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName);
ComponentContextPair<Stream<Object>, StreamContext> pair = streams.get(sourceIdentifier);
if (pair == null) {
/*
* We connect to the buffer server for the input on this port.
* We have already placed all the output streams for all the operators in this container.
* Yet, there is no stream which can source this port so it has to come from the buffer
* server, so let's make a connection to it.
*/
assert (nidi.isInline() == false);
StreamContext context = new StreamContext(nidi.declaredStreamId);
context.setPartitions(nidi.partitionMask, nidi.partitionKeys);
context.setSourceId(sourceIdentifier);
context.setSinkId(sinkIdentifier);
context.setStartingWindowId(ndi.checkpointWindowId > 0? ndi.checkpointWindowId + 1: 0); // TODO: next window after checkpoint
context.setBufferServerAddress(InetSocketAddress.createUnresolved(nidi.bufferServerHost, nidi.bufferServerPort));
@SuppressWarnings("unchecked")
Stream<Object> stream = (Stream)new BufferServerInputStream(StramUtils.getSerdeInstance(nidi.serDeClassName));
stream.setup(context);
logger.debug("deployed buffer input stream {}", stream);
Sink<Object> s = node.connectInputPort(nidi.portName, stream);
stream.setSink(sinkIdentifier,
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(stream, sinkIdentifier, s, ndi.checkpointWindowId) : s);
streams.put(sinkIdentifier,
new ComponentContextPair<Stream<Object>, StreamContext>(stream, context));
logger.debug("put input stream {} against key {}", stream, sinkIdentifier);
}
else {
String streamSinkId = pair.context.getSinkId();
Sink<Object> s;
if (streamSinkId == null) {
s = node.connectInputPort(nidi.portName, pair.component);
pair.context.setSinkId(sinkIdentifier);
}
else if (pair.component.isMultiSinkCapable()) {
s = node.connectInputPort(nidi.portName, pair.component);
pair.context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier));
}
else {
/**
* we are trying to tap into existing InlineStream or BufferServerOutputStream.
* Since none of those streams are MultiSinkCapable, we need to replace them with Mux.
*/
StreamContext context = new StreamContext(nidi.declaredStreamId);
context.setSourceId(sourceIdentifier);
context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier));
context.setStartingWindowId(ndi.checkpointWindowId > 0? ndi.checkpointWindowId + 1: 0); // TODO: next window after checkpoint
Stream<Object> stream = new MuxStream();
stream.setup(context);
logger.debug("deployed input mux stream {}", stream);
s = node.connectInputPort(nidi.portName, stream);
streams.put(sourceIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(stream, context));
logger.debug("stored input stream {} against key {}", stream, sourceIdentifier);
/**
* Lets wire the MuxStream to upstream node.
*/
String[] nodeport = sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR);
Node<?> upstreamNode = nodes.get(nodeport[0]);
upstreamNode.connectOutputPort(nodeport[1], stream);
Sink<Object> existingSink;
if (pair.component instanceof InlineStream) {
String[] np = streamSinkId.split(NODE_PORT_SPLIT_SEPARATOR);
Node<?> anotherNode = nodes.get(np[0]);
existingSink = anotherNode.connectInputPort(np[1], stream);
/*
* we do not need to do this but looks bad if leave it in limbo.
*/
pair.component.deactivate();
pair.component.teardown();
}
else {
existingSink = pair.component;
/*
* we got this stream since it was mapped against sourceId, but since
* we took that place for MuxStream, we give this a new place of its own.
*/
streams.put(pair.context.getSinkId(), pair);
logger.debug("relocated stream {} against key {}", pair.context.getSinkId());
}
stream.setSink(streamSinkId, existingSink);
}
if (nidi.partitionKeys == null || nidi.partitionKeys.isEmpty()) {
pair.component.setSink(sinkIdentifier,
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(pair.component, sinkIdentifier, s, ndi.checkpointWindowId) : s);
}
else {
/*
* generally speaking we do not have partitions on the inline streams so the control should not
* come here but if it comes, then we are ready to handle it using the partition aware streams.
*/
PartitionAwareSink<Object> pas = new PartitionAwareSink<Object>(StramUtils.getSerdeInstance(nidi.serDeClassName), nidi.partitionKeys, nidi.partitionMask, s);
pair.component.setSink(sinkIdentifier,
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(pair.component, sinkIdentifier, pas, ndi.checkpointWindowId) : pas);
}
}
}
}
}
if (!inputNodes.isEmpty()) {
WindowGenerator windowGenerator = setupWindowGenerator(smallestCheckpointedWindowId);
for (OperatorDeployInfo ndi: inputNodes) {
generators.put(ndi.id, windowGenerator);
Node<?> node = nodes.get(ndi.id);
Sink<Object> s = node.connectInputPort(Node.INPUT, windowGenerator);
windowGenerator.setSink(Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(Node.INPUT),
ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(windowGenerator, Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(Node.INPUT), s, ndi.checkpointWindowId) : s);
}
}
}
/**
* Create the window generator for the given start window id.
* This is a hook for tests to control the window generation.
*
* @param smallestWindowId
* @return WindowGenerator
*/
protected WindowGenerator setupWindowGenerator(long smallestWindowId)
{
WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1, "WindowGenerator"));
/**
* let's make sure that we send the same window Ids with the same reset windows.
*/
windowGenerator.setResetWindow(firstWindowMillis);
long millisAtFirstWindow = (smallestWindowId >> 32) * 1000 + windowWidthMillis * (smallestWindowId & WindowGenerator.MAX_WINDOW_ID);
windowGenerator.setFirstWindow(millisAtFirstWindow > firstWindowMillis ? millisAtFirstWindow : firstWindowMillis);
windowGenerator.setWindowWidth(windowWidthMillis);
return windowGenerator;
}
@SuppressWarnings({"SleepWhileInLoop", "SleepWhileHoldingLock"})
public synchronized void activate(List<OperatorDeployInfo> nodeList)
{
for (ComponentContextPair<Stream<Object>, StreamContext> pair: streams.values()) {
if (!(pair.component instanceof SocketInputStream || activeStreams.containsKey(pair.component))) {
activeStreams.put(pair.component, pair.context);
pair.component.activate(pair.context);
}
}
final AtomicInteger activatedNodeCount = new AtomicInteger(activeNodes.size());
for (final OperatorDeployInfo ndi: nodeList) {
final Node<?> node = nodes.get(ndi.id);
assert (!activeNodes.containsKey(ndi.id));
new Thread(node.id)
{
@Override
public void run()
{
try {
OperatorContext context = new OperatorContext(new Integer(ndi.id), this, ndi.contextAttributes, applicationAttributes);
node.getOperator().setup(context);
activeNodes.put(ndi.id, context);
activatedNodeCount.incrementAndGet();
logger.info("activating {} in container {}", node, containerId);
node.activate(context);
}
catch (Throwable ex) {
logger.error("Node stopped abnormally because of exception", ex);
} finally {
activeNodes.remove(ndi.id);
node.getOperator().teardown();
logger.info("deactivated {}", node.id);
}
}
}.start();
}
/**
* we need to make sure that before any of the operators gets the first message, it's activate.
*/
try {
do {
Thread.sleep(SPIN_MILLIS);
}
while (activatedNodeCount.get() < nodes.size());
}
catch (InterruptedException ex) {
logger.debug(ex.getLocalizedMessage());
}
for (ComponentContextPair<Stream<Object>, StreamContext> pair: streams.values()) {
if (pair.component instanceof SocketInputStream && !activeStreams.containsKey(pair.component)) {
activeStreams.put(pair.component, pair.context);
pair.component.activate(pair.context);
}
}
for (WindowGenerator wg: generators.values()) {
if (!activeGenerators.containsKey(wg)) {
activeGenerators.put(wg, generators);
wg.activate(null);
}
}
}
private void groupInputStreams(HashMap<String, ArrayList<String>> groupedInputStreams, OperatorDeployInfo ndi)
{
for (OperatorDeployInfo.InputDeployInfo nidi: ndi.inputs) {
String source = Integer.toString(nidi.sourceNodeId).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName);
/*
* if we do not want to combine multiple streams with different partitions from the
* same upstream node, we could also use the partition to group the streams together.
* This logic comes with the danger that the performance of the group which shares
* the same stream is bounded on the higher side by the performance of the lowest
* performer upstream port. May be combining the streams is not such a good thing
* but let's see if we allow this as an option to the user, what they end up choosing
* the most.
*/
ArrayList<String> collection = groupedInputStreams.get(source);
if (collection == null) {
collection = new ArrayList<String>();
groupedInputStreams.put(source, collection);
}
collection.add(Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName));
}
}
}
|
package nuclibook.server;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import nuclibook.constants.C;
import nuclibook.models.User;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SqlServerConnection {
/* singleton pattern */
private SqlServerConnection() {
}
private static ConnectionSource connection = null;
public static ConnectionSource acquireConnection() {
if (connection == null) {
try {
connection = new JdbcConnectionSource(C.MYSQL_URI);
((JdbcConnectionSource)connection).setUsername(C.MYSQL_USERNAME);
((JdbcConnectionSource)connection).setPassword(C.MYSQL_PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
}
initDB(connection);
return connection;
}
public static void initDB(ConnectionSource connectionSource) {
try {
TableUtils.createTableIfNotExists(connectionSource, User.class);
} catch (SQLException e) {
System.out.println(e.getStackTrace());
// TODO deal with exception
}
}
}
|
package org.amc.servlet.model;
public class PartSearchForm implements WebPageForm
{
private String partName;
private String qSSNumber;
private String company;
/**
* @return the part
*/
public String getPartName()
{
return partName;
}
/**
* @return the qSSNumber
*/
public String getQSSNumber()
{
return qSSNumber;
}
/**
* @return the company
*/
public String getCompany()
{
return company;
}
/**
* @param part the part to set
*/
public void setPartName(String part)
{
this.partName = part;
}
/**
* @param qSSNumber the qSSNumber to set
*/
public void setQSSNumber(String qSSNumber)
{
this.qSSNumber = qSSNumber;
}
/**
* @param company the company to set
*/
public void setCompany(String company)
{
this.company = company;
}
}
|
/**
Khalid
*/
package org.sikuli.slides.sikuli;
import static org.sikuli.api.API.browse;
import java.awt.Color;
import java.awt.Dimension;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import org.sikuli.api.DesktopScreenRegion;
import org.sikuli.api.ImageTarget;
import org.sikuli.api.ScreenRegion;
import org.sikuli.api.robot.Keyboard;
import org.sikuli.api.robot.Mouse;
import org.sikuli.api.robot.desktop.DesktopKeyboard;
import org.sikuli.api.robot.desktop.DesktopMouse;
import org.sikuli.api.visual.Canvas;
import org.sikuli.api.visual.DesktopCanvas;
import org.sikuli.api.visual.ScreenRegionCanvas;
import org.sikuli.slides.core.SlideComponent;
import org.sikuli.slides.media.Sound;
import org.sikuli.slides.screenshots.SlideTargetRegion;
import org.sikuli.slides.shapes.SlideShape;
import org.sikuli.slides.utils.Constants;
import org.sikuli.slides.utils.Constants.DesktopEvent;
import org.sikuli.slides.utils.MyScreen;
import org.sikuli.slides.utils.UnitConverter;
import org.sikuli.slides.utils.UserPreferencesEditor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Slide action that performs input events operation specified in each slide.
* @author Khalid
*
*/
public class SlideAction {
private static final Logger logger = (Logger) LoggerFactory.getLogger(SlideAction.class);
private UserPreferencesEditor prefsEditor = new UserPreferencesEditor();
private File targetFile, labelFile;
private SlideShape slideShape;
private SlideTargetRegion slideTargetRegion, slideLabelRegion;
private Sound sound;
private SlideShape slideLabel;
public SlideAction(SlideComponent slideComponent){
this.targetFile = slideComponent.getTargetFile();
this.slideShape = slideComponent.getSlideShape();
this.slideTargetRegion = slideComponent.getSlideTargetRegion();
this.sound = slideComponent.getSound();
this.slideLabel = slideComponent.getSlideLabel();
this.labelFile = slideComponent.getLabelFile();
this.slideLabelRegion = slideComponent.getSlideLabelRegion();
}
public void doSlideAction(DesktopEvent desktopEvent){
// if the required action is one of the following actions, no need to search for target on the screen
// #1 Wait action
if(desktopEvent==DesktopEvent.WAIT){
performNonSikuliAction();
performSikuliAction(null, desktopEvent);
}
// #2 Open default browser
else if(desktopEvent==DesktopEvent.LAUNCH_BROWSER){
performNonSikuliAction();
performSikuliAction(null, desktopEvent);
}
// if the action is to find a target on the screen
// if the action is to interact with a target, find the target and perform the action
else{
ScreenRegion targetRegion=findTargetRegion(this.targetFile, this.slideTargetRegion);
performNonSikuliAction();
if(desktopEvent==DesktopEvent.EXIST){
logger.info("Checking whether the target image is visible on the screen.");
if(targetRegion==null){
logger.error("Test failed. Target image was not found on the screen.");
System.exit(1);
}
else{
logger.info("Test passed. Target image was found on the screen.");
return;
}
}
else if(desktopEvent==DesktopEvent.NOT_EXIST){
logger.info("Checking whether the target image is invisible on the screen.");
if(targetRegion==null){
logger.info("Test passed. Target image was invisible on the screen.");
return;
}
else{
logger.error("Test failed. Target image was visible on the screen.");
System.exit(1);
}
}
else{
/*if(targetRegion==null){
if(Constants.TUTORIAL_MODE){
logger.error("Couldn't find target on the screen.");
}
}*/
if(Constants.HELP_MODE){
new SlideTutorial(targetRegion, slideShape, desktopEvent).performTutorialSlideAction();
}
else if(Constants.TUTORIAL_MODE){
new SlideTutorial(targetRegion, slideShape, desktopEvent).performTutorialSlideAction();
}
else{
performSikuliAction(targetRegion, desktopEvent);
}
}
}
}
private ScreenRegion findTargetRegion(File targetFile, SlideTargetRegion slideTargetRegion){
final ImageTarget imageTarget=new ImageTarget(targetFile);
imageTarget.setMinScore(prefsEditor.getPreciseSearchScore());
if(imageTarget!=null){
ScreenRegion fullScreenRegion = new DesktopScreenRegion(Constants.ScreenId);
ScreenRegion targetRegion=fullScreenRegion.wait(imageTarget, prefsEditor.getMaxWaitTime());
if(targetRegion!=null){
// check if there are more than one occurrence of the target image.
SearchMultipleTarget searchMultipleTarget=new SearchMultipleTarget();
if(searchMultipleTarget.hasMultipleOccurance(imageTarget)){
ScreenRegion newScreenRegion=searchMultipleTarget.findNewScreenRegion(slideTargetRegion, imageTarget);
if(newScreenRegion!=null){
ScreenRegion newtargetRegion=newScreenRegion.find(imageTarget);
return newtargetRegion;
}
else{
logger.error("Failed to determine the target image among multiple similar targets on the screen."
+"\nTry to resize the shape in slide number "+slideTargetRegion.getslideNumber() + " or use the precision option to make the search more accurate.");
}
}
else{
return targetRegion;
}
}
else{
logger.error("Failed to find target on the screen. Slide no. "+slideTargetRegion.getslideNumber());
}
}
return null;
}
/**
* Performs non sikuli actions such as playing background sound and displaying annotations
* @param targetRegion
*/
private void performNonSikuliAction(){
// if the slide contains a sound, play it in background
if(sound!=null){
new Thread(new Runnable() {
@Override
public void run() {
sound.playSound();
}
}).start();
}
if(slideLabel!=null){
ScreenRegion labelScreenRegion = null;
if(this.labelFile !=null && this.slideLabelRegion != null){
labelScreenRegion = findTargetRegion(this.labelFile, this.slideLabelRegion);
}
displayLabel(labelScreenRegion);
}
}
private void performSikuliAction(ScreenRegion targetRegion,Constants.DesktopEvent desktopEvent){
if(desktopEvent==Constants.DesktopEvent.LEFT_CLICK){
performLeftClick(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.RIGHT_CLICK){
performRightClick(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.DOUBLE_CLICK){
performDoubleClick(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.DRAG_N_DROP){
performDragDrop(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.KEYBOARD_TYPING){
performKeyboardTyping(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.LAUNCH_BROWSER){
performLaunchWebBrowser();
}
else if(desktopEvent==Constants.DesktopEvent.WAIT){
performWaitAction();
}
}
/**
* display a label on a target region
* @param targetRegion the target region to display the label on
*/
private void displayLabel(ScreenRegion targetRegion) {
/* if the target region is null or ther's no target to work on, use the default desktop region.
This is important in case of opening the default browser or label target region could not be found.
*/
if(targetRegion==null){
logger.error("Failed to find the target to display a label on.");
logger.info("Displaying the label on the center of the screen.");
Dimension dimension = MyScreen.getScreenDimensions();
int width = UnitConverter.emuToPixels(slideLabel.getCx());
int height = UnitConverter.emuToPixels(slideLabel.getCy());
int x = (dimension.width-width)/2;
int y = (dimension.height-height)/2;
targetRegion = new DesktopScreenRegion(x, y, width, height);
}
double fontSize=UnitConverter.WholePointsToPoints(slideLabel.getTextSize());
if(fontSize==0){
fontSize=prefsEditor.getInstructionHintFontSize();
}
Canvas canvas = new DesktopCanvas();
canvas.addLabel(targetRegion, slideLabel.getText()).
withColor(Color.black).withFontSize((int)fontSize).withLineWidth(prefsEditor.getCanvasWidthSize());
canvas.display(prefsEditor.getLabelDisplayTime());
}
/**
* perform left click
* @param targetRegion the region to perform left click input event on.
*/
private void performLeftClick(ScreenRegion targetRegion){
logger.info("performing left click event on target...");
Mouse mouse = new DesktopMouse();
displayBoxOnRegion(targetRegion);
mouse.click(targetRegion.getCenter());
}
/**
* perform right click
* @param targetRegion the region to perform right click input event on.
*/
private void performRightClick(ScreenRegion targetRegion){
logger.info("performing right click event on target...");
Mouse mouse = new DesktopMouse();
displayBoxOnRegion(targetRegion);
mouse.rightClick(targetRegion.getCenter());
}
/**
* perform double click
* @param targetRegion the region to perform double click input event on.
*/
private void performDoubleClick(ScreenRegion targetRegion){
logger.info("performing double click event on target...");
Mouse mouse = new DesktopMouse();
displayBoxOnRegion(targetRegion);
mouse.doubleClick(targetRegion.getCenter());
}
/**
* perform drag and drop
* @param targetRegion the region to perform drag or drop input event on.
*/
private void performDragDrop(ScreenRegion targetRegion){
logger.info("performing drag and drop event on targets...");
Mouse mouse = new DesktopMouse();
if(slideShape.getOrder()==0){
displayBoxOnRegion(targetRegion);
mouse.drag(targetRegion.getCenter());
}
else if(slideShape.getOrder()==1){
displayBoxOnRegion(targetRegion);
mouse.drop(targetRegion.getCenter());
}
else{
logger.error("Couldn't find the start and end of the straight arrow connector " +
"that is used to connect the rounded rectangles. Make sure the arrow is connected to the two rounded rectangles.");
}
}
/**
* perform keyboard typing
* @param targetRegion the region to perform keyboard typing input event on.
*/
private void performKeyboardTyping(ScreenRegion targetRegion){
logger.info("performing keyboard typing event on target...");
Mouse mouse = new DesktopMouse();
Keyboard keyboard=new DesktopKeyboard();
displayBoxOnRegion(targetRegion);
mouse.click(targetRegion.getCenter());
keyboard.type(slideShape.getText());
}
/**
* launch the default browser
*/
private void performLaunchWebBrowser(){
logger.info("launching the default browser...");
try {
String userURL=slideShape.getText();
URL url=null;
if(userURL.startsWith("http:
url=new URL(userURL);
}
else{
url=new URL("http://"+userURL);
}
browse(url);
} catch (MalformedURLException e) {
logger.error("The text body of the Cloud shape doesn't contain a valid URL.");
System.exit(1);
}
}
/**
* Perform wait action. It waits for the specified time in seconds
*/
private void performWaitAction(){
logger.info("Performing wait operation...");
// extract the time unit
TimeUnit timeUnit=UnitConverter.extractTimeUnitFromString(slideShape.getText());
// if the time unit was not specified, default to seconds
if(timeUnit==null){
timeUnit=TimeUnit.SECONDS;
}
// extract the wait time string value, replace all non digits with blank
String waitTimeString=slideShape.getText().replaceAll("\\D", "");
if(waitTimeString==null){
logger.error("Error: Please enter the wait time value in a shape."
+" Valid examples include: 10 seconds, 10 minutes, 10 hours, or even 2 days.");
return;
}
try {
long timeout=Long.parseLong(waitTimeString);
if(Constants.TUTORIAL_MODE){
// Disable controllers UI buttons to prevent tutorial mode from navigating through steps.
Constants.IsWaitAction=true;
}
// display a label
Dimension dimension=MyScreen.getScreenDimensions();
ScreenRegion canvasRegion=new DesktopScreenRegion(Constants.ScreenId, 0, dimension.height-200,50,200);
Canvas canvas=new ScreenRegionCanvas(new DesktopScreenRegion(Constants.ScreenId));
String readyTime=getReadyDate(timeUnit, timeout);
String waitMessage="Please wait for "+timeout+" "+timeUnit.toString().toLowerCase()+"...."+
"This might end at "+readyTime;
logger.info(waitMessage);
canvas.addLabel(canvasRegion, waitMessage).withFontSize(prefsEditor.getInstructionHintFontSize());
canvas.show();
timeUnit.sleep(timeout);
Constants.IsWaitAction=false;
canvas.hide();
logger.info("Waking up...");
}
catch(NumberFormatException e){
logger.error("Error: Invalid wait time.");
}
catch (InterruptedException e) {
logger.error("Error in wait operation");
}
}
private String getReadyDate(TimeUnit timeUnit,long timeout) {
if(timeUnit != null){
// set timeout format
String dateFormat="HH:mm:ss";
if(timeUnit == TimeUnit.DAYS){
dateFormat="yyyy-MM-dd HH:mm:ss";
}
// get the end time in milli seconds
long waitTimeInMilliSeconds=timeUnit.toMillis(timeout);
logger.info("Wait time in milli seconds: "+waitTimeInMilliSeconds);
Calendar nowCalendar=Calendar.getInstance();
Calendar timeoutCalendar = Calendar.getInstance();
timeoutCalendar.setTimeInMillis(waitTimeInMilliSeconds+nowCalendar.getTimeInMillis());
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(timeoutCalendar.getTime()).toString();
}
return null;
}
private void displayBoxOnRegion(ScreenRegion screenRegion){
Canvas canvas=new ScreenRegionCanvas(new DesktopScreenRegion(Constants.ScreenId));
// Display the canvas around the target
canvas.addBox(screenRegion);
canvas.display(2);
}
}
|
import com.messagebird.MessageBirdClient;
import com.messagebird.MessageBirdService;
import com.messagebird.MessageBirdServiceImpl;
import com.messagebird.exceptions.GeneralException;
import com.messagebird.exceptions.NotFoundException;
import com.messagebird.exceptions.UnauthorizedException;
import com.messagebird.objects.PhoneNumberFeature;
import com.messagebird.objects.PhoneNumberType;
import com.messagebird.objects.PhoneNumberSearchPattern;
import com.messagebird.objects.PhoneNumbersLookup;
import java.util.EnumSet;;
import java.util.LinkedHashMap;
import java.util.Map;
public class ExampleListNumbersForPurchase {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please specify your access key.");
return;
}
// First create your service object
final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]);
// Add the service to the client
final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr);
try {
if (args.length > 1) {
PhoneNumbersLookup options = new PhoneNumbersLookup();
options.setFeatures(PhoneNumberFeature.VOICE, PhoneNumberFeature.SMS);
options.setType(PhoneNumberType.MOBILE);
options.setLimit(10);
options.setNumber(562);
options.setSearchPattern(PhoneNumberSearchPattern.START);
System.out.print(options.toString());
System.out.println(String.format("Request Made With Params: %s", messageBirdClient.listNumbersForPurchase("US", options)));
} else {
System.out.println(String.format("Request Made Without Params: %s", messageBirdClient.listNumbersForPurchase("NL")));
}
} catch (UnauthorizedException | GeneralException | NotFoundException exception) {
if (exception.getErrors() != null) {
System.out.println(exception.getErrors().toString());
}
exception.printStackTrace();
}
}
}
|
package seedu.jimi.model.task;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.jimi.commons.util.CollectionUtil;
import seedu.jimi.commons.exceptions.DuplicateDataException;
import java.util.*;
/**
* A list of tasks that enforces uniqueness between its elements and does not allow nulls.
*
* Supports a minimal set of list operations.
*
* @see FloatingTask#equals(Object)
* @see CollectionUtil#elementsAreUnique(Collection)
*/
public class UniqueTaskList implements Iterable<FloatingTask> {
/**
* Signals that an operation would have violated the 'no duplicates' property of the list.
*/
public static class DuplicateTaskException extends DuplicateDataException {
protected DuplicateTaskException() {
super("Operation would result in duplicate tasks");
}
}
/**
* Signals that an operation targeting a specified task in the list would fail because
* there is no such matching task in the list.
*/
public static class TaskNotFoundException extends Exception {}
private final ObservableList<FloatingTask> internalList = FXCollections.observableArrayList();
/**
* Constructs empty TaskList.
*/
public UniqueTaskList() {}
/**
* Returns true if the list contains an equivalent task as the given argument.
*/
public boolean contains(ReadOnlyTask toCheck) {
assert toCheck != null;
return internalList.contains(toCheck);
}
/**
* Adds a task to the list.
*
* @throws DuplicateTaskException if the task to add is a duplicate of an existing task in the list.
*/
public void add(FloatingTask toAdd) throws DuplicateTaskException {
assert toAdd != null;
if (contains(toAdd)) {
throw new DuplicateTaskException();
}
internalList.add(toAdd);
}
/**
* Removes the equivalent task from the list.
*
* @throws TaskNotFoundException if no such task could be found in the list.
*/
public boolean remove(ReadOnlyTask toRemove) throws TaskNotFoundException {
assert toRemove != null;
final boolean taskFoundAndDeleted = internalList.remove(toRemove);
if (!taskFoundAndDeleted) {
throw new TaskNotFoundException();
}
return taskFoundAndDeleted;
}
/**
*
* @return
*/
public void edit(FloatingTask toEdit, int targetIndex) {
assert toEdit != null;
internalList.set(targetIndex, toEdit);
}
public ObservableList<FloatingTask> getInternalList() {
return internalList;
}
@Override
public Iterator<FloatingTask> iterator() {
return internalList.iterator();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueTaskList // instanceof handles nulls
&& this.internalList.equals(
((UniqueTaskList) other).internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
}
|
package seedu.task.model.task;
import java.util.Iterator;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.task.commons.core.UnmodifiableObservableList;
import seedu.task.commons.exceptions.DuplicateDataException;
import seedu.task.commons.util.CollectionUtil;
/**
* A list of tasks that enforces uniqueness between its elements and does not
* allow nulls.
*
* Supports a minimal set of list operations.
*
* @see Task#equals(Object)
* @see CollectionUtil#elementsAreUnique(Collection)
*/
public class UniqueTaskList implements Iterable<Task> {
private final ObservableList<Task> internalList = FXCollections.observableArrayList();
/**
* Returns true if the list contains an equivalent task as the given
* argument.
*/
public boolean contains(ReadOnlyTask toCheck) {
assert toCheck != null;
return internalList.contains(toCheck);
}
/**
* Adds a task to the list.
*
* @throws DuplicateTaskException
* if the task to add is a duplicate of an existing task in the
* list.
*/
public void add(Task toAdd) throws DuplicateTaskException {
assert toAdd != null;
if (contains(toAdd)) {
throw new DuplicateTaskException();
}
internalList.add(toAdd);
FXCollections.sort(internalList, Task.TaskComparator);
}
/**
* Updates the task in the list at position {@code index} with
* {@code editedPerson}.
*
* @throws DuplicateTaskException
* if updating the task's details causes the task to be
* equivalent to another existing task in the list.
* @throws IndexOutOfBoundsException
* if {@code index} < 0 or >= the size of the list.
*/
public void updateTask(int index, ReadOnlyTask editedTask) throws DuplicateTaskException {
assert editedTask != null;
Task taskToUpdate = internalList.get(index);
if (!taskToUpdate.equals(editedTask) && internalList.contains(editedTask)) {
throw new DuplicateTaskException();
}
taskToUpdate.resetData(editedTask);
// TODO: The code below is just a workaround to notify observers of the
// updated task.
// The right way is to implement observable properties in the Task
// class.
// Then, PersonCard should then bind its text labels to those observable
// properties.
internalList.set(index, taskToUpdate);
FXCollections.sort(internalList, Task.TaskComparator);
}
/**
* Removes the equivalent task from the list.
*
* @throws TaskNotFoundException
* if no such task could be found in the list.
*/
public boolean remove(ReadOnlyTask toRemove) throws TaskNotFoundException {
assert toRemove != null;
final boolean taskFoundAndDeleted = internalList.remove(toRemove);
if (!taskFoundAndDeleted) {
throw new TaskNotFoundException();
}
return taskFoundAndDeleted;
}
public void setTasks(UniqueTaskList replacement) {
this.internalList.setAll(replacement.internalList);
FXCollections.sort(internalList, Task.TaskComparator);
}
public void setTasks(List<? extends ReadOnlyTask> tasks) throws DuplicateTaskException {
final UniqueTaskList replacement = new UniqueTaskList();
for (final ReadOnlyTask task : tasks) {
replacement.add(new Task(task));
}
setTasks(replacement);
}
public UnmodifiableObservableList<Task> asObservableList() {
return new UnmodifiableObservableList<>(internalList);
}
@Override
public Iterator<Task> iterator() {
return internalList.iterator();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueTaskList // instanceof handles nulls
&& this.internalList.equals(((UniqueTaskList) other).internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
/**
* Signals that an operation would have violated the 'no duplicates'
* property of the list.
*/
public static class DuplicateTaskException extends DuplicateDataException {
protected DuplicateTaskException() {
super("Operation would result in duplicate tasks");
}
}
/**
* Signals that an operation targeting a specified task in the list would
* fail because there is no such matching task in the list.
*/
public static class TaskNotFoundException extends Exception {
}
}
|
package net.katsuster.ememu.board;
import java.io.*;
import net.katsuster.ememu.generic.*;
import net.katsuster.ememu.riscv.*;
import net.katsuster.ememu.riscv.core.*;
public class RISCVUnleashed extends AbstractBoard {
private RV64[] cpu;
private Bus64 bus;
private RAM cl0_ddr;
private InputStream[] uartIn = new InputStream[4];
private OutputStream[] uartOut = new OutputStream[4];
public RISCVUnleashed() {
//do nothing
}
@Override
public CPU getMainCPU() {
return cpu[0];
}
@Override
public Bus64 getMainBus() {
return bus;
}
@Override
public RAM getMainRAM() {
return cl0_ddr;
}
@Override
public InputStream getUARTInputStream(int index) {
return uartIn[index];
}
@Override
public void setUARTInputStream(int index, InputStream is) {
uartIn[index] = is;
}
@Override
public OutputStream getUARTOutputStream(int index) {
return uartOut[index];
}
@Override
public void setUARTOutputStream(int index, OutputStream os) {
uartOut[index] = os;
}
@Override
public void setup() {
cpu = new RV64[5];
bus = new Bus64();
RAM mode_select = new RAM32(4 * 1024);
RAM mask_rom = new RAM32(32 * 1024);
CLINT clint = new CLINT(cpu);
RAM l2lim = new RAM32(32 * 1024 * 1024);
cl0_ddr = new RAM32(64 * 1024 * 1024);
PRCI prci = new PRCI(cpu);
UART uart0 = new UART();
UART uart1 = new UART();
//Master core
for (int i = 0; i < cpu.length; i++) {
cpu[i] = new RV64();
cpu[i].setThreadID(i);
bus.addMasterCore(cpu[i]);
}
//Memory map of Unleashed
// 0x0000_0100 - 0x0000_0fff: Debug
// 0x0000_1000 - 0x0000_1fff: Mode Select
// 0x0001_0000 - 0x0001_7fff: Mask ROM
// 0x0800_0000 - 0x09ff_ffff: L2 LIM
// 0x1000_0000 - 0x1000_0fff: PRCI
// 0x1001_0000 - 0x1001_0fff: UART0
// 0x1001_1000 - 0x1001_1fff: UART1
bus.addSlaveCore(mode_select, 0x00001000L, 0x00001fffL);
bus.addSlaveCore(mask_rom, 0x00010000L, 0x00017fffL);
bus.addSlaveCore(clint.getSlaveCore(), 0x02000000L, 0x0200ffffL);
bus.addSlaveCore(l2lim, 0x08000000L, 0x09ffffffL);
bus.addSlaveCore(prci.getSlaveCore(), 0x10000000L, 0x10000fffL);
bus.addSlaveCore(uart0.getSlaveCore(), 0x10010000L, 0x10010fffL);
bus.addSlaveCore(uart1.getSlaveCore(), 0x10011000L, 0x10011fffL);
//reset CPU
for (int i = 0; i < cpu.length; i++) {
cpu[i].setEnabledDisasm(false);
cpu[i].setPrintInstruction(false);
cpu[i].setPrintRegs(false);
cpu[i].init();
}
}
@Override
public void start() {
//start cores
bus.startAllSlaveCores();
bus.startAllMasterCores();
//wait CPU halted
try {
for (int i = 0; i < cpu.length; i++) {
cpu[i].join();
}
} catch (InterruptedException e) {
e.printStackTrace(System.err);
//ignored
}
}
@Override
public void stop() {
bus.haltAllMasterCores();
bus.haltAllSlaveCores();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.nelen_schuurmans.aquo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import nl.services.rws.domaintablews._2010._10.DomainTableServiceGetDomainTableChangesDomainTableFaultFaultFaultMessage;
import nl.services.rws.domaintablews._2010._10.DomainTableServiceGetDomainTableDomainTableFaultFaultFaultMessage;
import nl.services.rws.domaintablews.contracts._2010._10.Data;
import nl.services.rws.domaintablews.contracts._2010._10.DataField;
import nl.services.rws.domaintablews.contracts._2010._10.DataRow;
import nl.services.rws.domaintablews.contracts._2010._10.IntegerField;
import nl.services.rws.domaintablews.contracts._2010._10.StringField;
import org.apache.log4j.Logger;
/**
*
* @author carsten.byrman@nelen-schuurmans.nl
*/
public class ParameterSynchronizer extends Synchronizer {
private static final Logger logger = Logger.getLogger(ParameterSynchronizer.class);
private static final String TABLE_NAME = "Parameter";
public static void main(String[] args) throws Exception {
new ParameterSynchronizer().synchronize();
}
@Override
public void synchronize()
throws DomainTableServiceGetDomainTableDomainTableFaultFaultFaultMessage,
DomainTableServiceGetDomainTableChangesDomainTableFaultFaultFaultMessage {
Parameter mostRecent = ParameterController.mostRecent();
Data data;
if (mostRecent == null) {
// Retrieve all records
data = getTable(TABLE_NAME, new Date());
} else {
// Retrieve new records
data = getTableChanges(TABLE_NAME, tomorrow(mostRecent.getBeginDate()));
}
List<Parameter> parameters = new ArrayList<Parameter>();
for (DataRow dataRow : data.getDataRow()) {
Parameter parameter = new Parameter();
parameter.setBeginDate(dataRow.getBeginDate());
parameter.setEndDate(dataRow.getEndDate());
for (DataField dataField : dataRow.getFields().getDataField()) {
if (dataField.getName().equals("Code")) {
StringField stringDataField = (StringField) dataField;
parameter.setCode(stringDataField.getData());
} else if (dataField.getName().equals("Omschrijving")) {
StringField stringDataField = (StringField) dataField;
parameter.setDescription(stringDataField.getData());
} else if (dataField.getName().equals("CASnummer")) {
StringField stringDataField = (StringField) dataField;
parameter.setCasNumber(stringDataField.getData());
} else if (dataField.getName().equals("Groep")) {
StringField stringDataField = (StringField) dataField;
parameter.setGroup(stringDataField.getData());
} else if (dataField.getName().equals("SIKBid") && !dataField.isIsNull()) {
IntegerField integerDataField = (IntegerField) dataField;
parameter.setSikbId(integerDataField.getData());
} else {
logger.warn("Unknown field: " + dataField.getName());
}
}
parameters.add(parameter);
}
ParameterController.synchronize(parameters);
}
}
|
package se.l4.crayon;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import com.google.inject.AbstractModule;
import com.google.inject.Binder;
import com.google.inject.Binding;
import com.google.inject.Key;
import com.google.inject.MembersInjector;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.Stage;
import com.google.inject.TypeLiteral;
import com.google.inject.binder.AnnotatedBindingBuilder;
import com.google.inject.binder.AnnotatedConstantBindingBuilder;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.matcher.Matcher;
import com.google.inject.spi.Message;
import com.google.inject.spi.ProvisionListener;
import com.google.inject.spi.TypeConverter;
import com.google.inject.spi.TypeListener;
/**
* Module that can be used that works like {@link AbstractModule} but uses
* {@link CrayonBinder} as well.
*
* @author Andreas Holstenson
*
*/
public abstract class CrayonModule
implements Module
{
private Binder binder;
private CrayonBinder crayon;
@Override
public final synchronized void configure(Binder builder)
{
binder = setupBinder(
builder.skipSources(CrayonModule.class)
);
crayon = CrayonBinder.newBinder(binder, this);
configure();
}
/**
* Setup the given binder for use within this module. This is intended
* for abstract subclasses of this module so that they can use things
* such as {@link Binder#skipSources(Class...)}.
*
* @param binder
* the binder to setup
* @return
* the binder used by the module
*/
protected Binder setupBinder(Binder binder)
{
return binder;
}
/**
* Perform configuration.
*/
protected abstract void configure();
/**
* Get the {@link Binder} in use.
*/
protected Binder binder()
{
return binder;
}
/**
* Get the {@link CrayonBinder} for this module.
*
* @return
*/
protected CrayonBinder crayon()
{
return crayon;
}
/**
* Bind a {@link Contributions} instance. It will be bound so that the
* instance is annotated with the specified annotation.
*
* <p>
* For example, calling this:
*
* <pre>
* bindContributions(Test.class)
* </pre>
*
* you can later access the instance via
* <p>
* class TestClass {
* public TestClass({@literal @Test} Contributions contributions) {
* ...
* }
* }
* </p>
*
* @see CrayonBinder#bindContributions(Class)
* @param annotation
*/
protected void bindContributions(Class<? extends Annotation> annotation)
{
crayon.bindContributions(annotation);
}
/**
* @see Binder#bindScope(Class, Scope)
*/
protected void bindScope(Class<? extends Annotation> scopeAnnotation,
Scope scope)
{
binder.bindScope(scopeAnnotation, scope);
}
/**
* @see Binder#bind(Key)
*/
protected <T> LinkedBindingBuilder<T> bind(Key<T> key)
{
return binder.bind(key);
}
/**
* @see Binder#bind(TypeLiteral)
*/
protected <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral)
{
return binder.bind(typeLiteral);
}
/**
* @see Binder#bind(Class)
*/
protected <T> AnnotatedBindingBuilder<T> bind(Class<T> clazz)
{
return binder.bind(clazz);
}
/**
* @see Binder#bindConstant()
*/
protected AnnotatedConstantBindingBuilder bindConstant()
{
return binder.bindConstant();
}
/**
* @see Binder#install(Module)
*/
protected void install(Module module)
{
binder.install(module);
}
/**
* @see Binder#addError(String, Object[])
*/
protected void addError(String message, Object... arguments)
{
binder.addError(message, arguments);
}
/**
* @see Binder#addError(Throwable)
*/
protected void addError(Throwable t)
{
binder.addError(t);
}
/**
* @see Binder#addError(Message)
*/
protected void addError(Message message)
{
binder.addError(message);
}
/**
* @see Binder#requestInjection(Object)
*/
protected void requestInjection(Object instance)
{
binder.requestInjection(instance);
}
/**
* @see Binder#requestStaticInjection(Class[])
*/
protected void requestStaticInjection(Class<?>... types)
{
binder.requestStaticInjection(types);
}
/* if[AOP] */
/**
* @see Binder#bindInterceptor(com.google.inject.matcher.Matcher,
* com.google.inject.matcher.Matcher,
* org.aopalliance.intercept.MethodInterceptor[])
*/
protected void bindInterceptor(Matcher<? super Class<?>> classMatcher,
Matcher<? super Method> methodMatcher,
org.aopalliance.intercept.MethodInterceptor... interceptors)
{
binder.bindInterceptor(classMatcher, methodMatcher, interceptors);
}
/* end[AOP] */
/**
* Adds a dependency from this module to {@code key}. When the injector is
* created, Guice will report an error if {@code key} cannot be injected.
* Note that this requirement may be satisfied by implicit binding, such as
* a public no-arguments constructor.
*/
protected void requireBinding(Key<?> key)
{
binder.getProvider(key);
}
/**
* Adds a dependency from this module to {@code type}. When the injector is
* created, Guice will report an error if {@code type} cannot be injected.
* Note that this requirement may be satisfied by implicit binding, such as
* a public no-arguments constructor.
*/
protected void requireBinding(Class<?> type)
{
binder.getProvider(type);
}
/**
* @see Binder#getProvider(Key)
*/
protected <T> Provider<T> getProvider(Key<T> key)
{
return binder.getProvider(key);
}
/**
* @see Binder#getProvider(Class)
*/
protected <T> Provider<T> getProvider(Class<T> type)
{
return binder.getProvider(type);
}
/**
* @see Binder#convertToTypes
*/
protected void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher,
TypeConverter converter)
{
binder.convertToTypes(typeMatcher, converter);
}
/**
* @see Binder#currentStage()
*/
protected Stage currentStage()
{
return binder.currentStage();
}
/**
* @see Binder#getMembersInjector(Class)
*/
protected <T> MembersInjector<T> getMembersInjector(Class<T> type)
{
return binder.getMembersInjector(type);
}
/**
* @see Binder#getMembersInjector(TypeLiteral)
* @since 2.0
*/
protected <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type)
{
return binder.getMembersInjector(type);
}
/**
* @see Binder#bindListener(com.google.inject.matcher.Matcher,
* com.google.inject.spi.TypeListener)
*/
protected void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher,
TypeListener listener)
{
binder.bindListener(typeMatcher, listener);
}
/**
* @see Binder#bindListener(Matcher, ProvisionListener...)
*/
protected void bindListener(Matcher<? super Binding<?>> bindingMatcher, ProvisionListener... listener)
{
binder().bindListener(bindingMatcher, listener);
}
@Override
public int hashCode()
{
return getClass().hashCode();
}
@Override
public boolean equals(Object obj)
{
return obj.getClass() == getClass();
}
}
|
package org.androidfromfrankfurt.archnews;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.http.util.LangUtils;
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import at.theengine.android.simple_rss2_android.RSSItem;
import at.theengine.android.simple_rss2_android.SimpleRss2Parser;
import at.theengine.android.simple_rss2_android.SimpleRss2ParserCallback;
public class NewsActivity extends ListActivity implements OnNavigationListener {
private ActionBar actionBar;
private MultiStateListView listView;
private View headerView;
private TextView tvErrorMessage;
private int justLaunched = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ListView
listView = new MultiStateListView.Builder(this)
.loadingView(R.layout.loading)
.errorView(R.layout.error)
.build();
listView.setId(android.R.id.list);
listView.setScrollBarStyle(ListView.SCROLLBARS_OUTSIDE_INSET);
listView.setDivider(null);
listView.setDividerHeight(10);
setContentView(listView);
LayoutParams listViewParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
listViewParams.setMargins(20, 0, 0, 0);
getListView().setLayoutParams(listViewParams);
// ListView Header
headerView = getLayoutInflater().inflate(R.layout.header, null, false);
getListView().addHeaderView(headerView);
// ActionBar
actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ArrayAdapter<CharSequence> distroAdapter = ArrayAdapter.createFromResource(this, R.array.distros, R.layout.nav_spinner_item);
actionBar.setListNavigationCallbacks(distroAdapter, this);
actionBar.setSelectedNavigationItem(Arrays.asList(getResources()
.getStringArray(R.array.distros))
.indexOf(PreferenceManager.getDefaultSharedPreferences(this)
.getString(getResources().getString(R.string.pref_key_distro), "Arch Linux")));
// Layout
tvErrorMessage = (TextView)listView.getErrorView().findViewById(R.id.tv_errormessage);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.news, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_reload) {
}
else if(id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
else if(id == R.id.action_about) {
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
Resources resources = getResources();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String selectedDistro = resources.getStringArray(R.array.distros)[itemPosition];
preferences.edit().putString("distro", selectedDistro).commit();
String selectedLang = preferences.getString(resources.getString(R.string.pref_key_language), "English");
Drawable distroIcon = null;
String distroFeedUrl;
int distroColor;
if(selectedDistro.equals("Debian Planet")) {
distroIcon = resources.getDrawable(R.drawable.ic_distro_debian);
distroColor = resources.getColor(R.color.distro_color_debian);
distroFeedUrl = resources.getString(R.string.distro_url_debian);
}
else if(selectedDistro.equals("Fedora")) {
distroIcon = resources.getDrawable(R.drawable.ic_distro_fedora);
distroColor = resources.getColor(R.color.distro_color_fedora);
if(selectedLang.equals(resources.getStringArray(R.array.languages)[1])) {
distroFeedUrl = resources.getString(R.string.distro_url_fedora_de);
}
else if(selectedLang.equals(resources.getStringArray(R.array.languages)[2])) {
distroFeedUrl = resources.getString(R.string.distro_url_fedora_fr);
}
else if(selectedLang.equals(resources.getStringArray(R.array.languages)[3])) {
distroFeedUrl = resources.getString(R.string.distro_url_fedora_es);
}
else {
distroFeedUrl = resources.getString(R.string.distro_url_fedora);
}
}
else if(selectedDistro.equals("Gentoo Planet")) {
distroIcon = resources.getDrawable(R.drawable.ic_distro_gentoo);
distroColor = resources.getColor(R.color.distro_color_gentoo);
distroFeedUrl = resources.getString(R.string.distro_url_gentoo);
}
else if(selectedDistro.equals("Parabola")) {
distroIcon = resources.getDrawable(R.drawable.ic_distro_linux);
distroColor = resources.getColor(R.color.distro_color_parabola);
distroFeedUrl = resources.getString(R.string.distro_url_parabola);
}
else if(selectedDistro.equals("Ubuntu Planet")) {
distroIcon = resources.getDrawable(R.drawable.ic_distro_ubuntu);
distroColor = resources.getColor(R.color.distro_color_ubuntu);
distroFeedUrl = resources.getString(R.string.distro_url_ubuntu);
}
else {
// default (else) is Arch Linux
distroIcon = resources.getDrawable(R.drawable.ic_distro_arch);
distroColor = resources.getColor(R.color.distro_color_arch);
if(selectedLang.equals(resources.getStringArray(R.array.languages)[1])) {
distroFeedUrl = resources.getString(R.string.distro_url_arch_de);
}
else if(selectedLang.equals(resources.getStringArray(R.array.languages)[2])) {
distroFeedUrl = resources.getString(R.string.distro_url_arch_fr);
}
else if(selectedLang.equals(resources.getStringArray(R.array.languages)[3])) {
distroFeedUrl = resources.getString(R.string.distro_url_arch_es);
}
else if(selectedLang.equals(resources.getStringArray(R.array.languages)[4])) {
distroFeedUrl = resources.getString(R.string.distro_url_arch_ru);
}
else if(selectedLang.equals(resources.getStringArray(R.array.languages)[5])) {
distroFeedUrl = resources.getString(R.string.distro_url_arch_br);
}
else if(selectedLang.equals(resources.getStringArray(R.array.languages)[6])) {
distroFeedUrl = resources.getString(R.string.distro_url_arch_cn);
}
else if(selectedLang.equals(resources.getStringArray(R.array.languages)[7])) {
distroFeedUrl = resources.getString(R.string.distro_url_arch_ro);
}
else {
distroFeedUrl = resources.getString(R.string.distro_url_arch);
}
}
getActionBar().setIcon(distroIcon);
// Doesn't look good, disable for now
// getActionBar().setBackgroundDrawable(new ColorDrawable(distroColor));
parseRss(distroFeedUrl);
final Uri distroFeedUri = Uri.parse(distroFeedUrl);
headerView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_VIEW, distroFeedUri);
startActivity(intent);
}
});
return true;
}
private void parseRss(String urlToParse) {
// show loading dialog
listView.setAdapter(null);
listView.showLoadingView();
SimpleRss2Parser newsParser = new SimpleRss2Parser(urlToParse,
new SimpleRss2ParserCallback() {
@Override
public void onFeedParsed(List<RSSItem> arg0) {
setListAdapter(new NewsAdapter(getApplicationContext(), R.layout.news_item, (ArrayList<RSSItem>) arg0));
loadingFinished(true, null);
}
@Override
public void onError(Exception arg0) {
listView.showErrorView();
tvErrorMessage.setText(arg0.getMessage());
}
});
newsParser.parseAsync();
}
private void loadingFinished(boolean successful, String errorMessage) {
if (!successful && errorMessage != null) {
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.