answer
stringlengths 17
10.2M
|
|---|
package test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;
import java.util.Map;
import org.junit.runner.Result;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
/**
* Test state class used to keep a memory of the tests that get executed
* in the face of the test cases continually being refreshed.
*
* NOTE: This bundle must not require any other test packages or bundles
* so it doesn't get refreshed when test punits get refreshed.
*
* @author mkeith
*/
public class TestState implements BundleActivator {
public static String GEMINI_TEST_CLASSES = "GEMINI_TESTS";
public static boolean isDsfOnline = false;
public static Set<Class<?>> dsfQueuedTests = new HashSet<Class<?>>();
static Set<String> incompletedTests = new HashSet<String>();
static Map<String,Result> completedTests = new HashMap<String,Result>();
static boolean initialized = initTests();
static boolean initTests() {
incompletedTests = new HashSet<String>();
completedTests = new HashMap<String,Result>();
// If test property provided then just run comma-separated list
// of unqualified JpaTest subclasses in org.eclipse.gemini.jpa.tests
String tests = System.getProperty(GEMINI_TEST_CLASSES, null);
if (tests != null) {
incompletedTests.addAll(Arrays.asList(tests.split(",")));
} else {
// Enumerate the tests to run - Comment out tests to disable them.
// Each test is the name of a JpaTest subclass in the
// org.eclipse.gemini.jpa.tests package
incompletedTests.add("TestStaticPersistence");
incompletedTests.add("TestEMFService");
incompletedTests.add("TestEMFBuilderService");
incompletedTests.add("TestEMFBuilderServiceProperties");
incompletedTests.add("TestEMFBuilderExternalDataSource");
incompletedTests.add("TestEmbeddedPUnit");
incompletedTests.add("TestOrmMappingFile");
incompletedTests.add("TestMappingFileElement");
incompletedTests.add("TestEmptyPersistence");
incompletedTests.add("TestEmptyPersistenceWithProps");
incompletedTests.add("TestWeaving");
incompletedTests.add("TestEmbeddedJdbc");
}
return true;
}
public static void resetTests() {
initTests();
}
public static void startTest(String s) {
incompletedTests.remove(s);
}
public static void completedTest(String s, Result r) {
completedTests.put(s, r);
}
public static Set<String> getIncompletedTests() {
return incompletedTests;
}
public static boolean isTested(String s) {
return !incompletedTests.contains(s);
}
public static Map<String,Result> getAllTestResults() {
return completedTests;
}
public void start(BundleContext context) throws Exception {
System.out.println("TestState active");
System.out.println("Tests in run list: ");
System.out.println("" + incompletedTests);
}
public void stop(BundleContext context) throws Exception {}
}
|
package org.jgrapes.portal;
import freemarker.template.Configuration;
import freemarker.template.SimpleScalar;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.CharBuffer;
import java.text.Collator;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.StreamSupport;
import javax.json.Json;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus;
import org.jdrupes.httpcodec.protocols.http.HttpField;
import org.jdrupes.httpcodec.protocols.http.HttpRequest;
import org.jdrupes.httpcodec.protocols.http.HttpResponse;
import org.jdrupes.httpcodec.types.Converters;
import org.jdrupes.httpcodec.types.Directive;
import org.jdrupes.httpcodec.types.MediaType;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Component;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.http.LanguageSelector.Selection;
import org.jgrapes.http.Session;
import org.jgrapes.http.annotation.RequestHandler;
import org.jgrapes.http.events.GetRequest;
import org.jgrapes.http.events.Response;
import org.jgrapes.http.events.WebSocketAccepted;
import org.jgrapes.io.IOSubchannel;
import org.jgrapes.io.events.Input;
import org.jgrapes.io.util.ByteBufferOutputStream;
import org.jgrapes.io.util.CharBufferWriter;
import org.jgrapes.io.util.InputStreamPipeline;
import org.jgrapes.io.util.LinkedIOSubchannel;
import org.jgrapes.io.util.ManagedCharBuffer;
import org.jgrapes.portal.Portlet.RenderMode;
import org.jgrapes.portal.events.AddPortletType;
import org.jgrapes.portal.events.DeletePortlet;
import org.jgrapes.portal.events.JsonRequest;
import org.jgrapes.portal.events.NotifyPortletView;
import org.jgrapes.portal.events.PortletResourceRequest;
import org.jgrapes.portal.events.PortletResourceResponse;
import org.jgrapes.portal.events.RenderPortletFromProvider;
import org.jgrapes.portal.events.RenderPortletFromString;
import org.jgrapes.portal.events.RetrieveDataFromPortal;
import org.jgrapes.portal.events.SetLocale;
import org.jgrapes.portal.events.SetTheme;
import org.jgrapes.portal.events.StoreDataInPortal;
import org.jgrapes.portal.themes.base.Provider;
import org.jgrapes.portal.util.JsonUtil;
public class PortalView extends Component {
private Portal portal;
private static ServiceLoader<ThemeProvider> themeLoader
= ServiceLoader.load(ThemeProvider.class);
private static Configuration fmConfig = null;
private Function<Locale,ResourceBundle> resourceSupplier;
private Set<Locale> supportedLocales;
private ThemeProvider baseTheme;
private Map<String,Object> portalBaseModel = new HashMap<>();
private RenderSupport renderSupport = new RenderSupportImpl();
/**
* @param componentChannel
*/
public PortalView(Portal portal, Channel componentChannel) {
super(componentChannel);
this.portal = portal;
if (fmConfig == null) {
fmConfig = new Configuration(Configuration.VERSION_2_3_26);
fmConfig.setClassLoaderForTemplateLoading(
getClass().getClassLoader(), "org/jgrapes/portal");
fmConfig.setDefaultEncoding("utf-8");
fmConfig.setTemplateExceptionHandler(
TemplateExceptionHandler.RETHROW_HANDLER);
fmConfig.setLogTemplateExceptions(false);
}
baseTheme = new Provider();
supportedLocales = new HashSet<>();
for (Locale locale: Locale.getAvailableLocales()) {
if (locale.getLanguage().equals("")) {
continue;
}
if (resourceSupplier != null) {
ResourceBundle rb = resourceSupplier.apply(locale);
if (rb.getLocale().equals(locale)) {
supportedLocales.add(locale);
}
}
ResourceBundle rb = ResourceBundle.getBundle(getClass()
.getPackage().getName() + ".l10n", locale);
if (rb.getLocale().equals(locale)) {
supportedLocales.add(locale);
}
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
try (Reader in = reader) {
JsonReader reader = Json.createReader(in);
fire(new JsonRequest(reader.readObject()), channel);
} catch (IOException e) {
// Shouldn't happen
}
}
}
}
public static class LanguageInfo {
private Locale locale;
/**
* @param locale
*/
public LanguageInfo(Locale locale) {
this.locale = locale;
}
/**
* @return the locale
*/
public Locale getLocale() {
return locale;
}
public String getLabel() {
String str = locale.getDisplayName(locale);
return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
}
public static class ThemeInfo implements Comparable<ThemeInfo> {
private String id;
private String name;
/**
* @param id
* @param name
*/
public ThemeInfo(String id, String name) {
super();
this.id = id;
this.name = name;
}
/**
* @return the id
*/
public String id() {
return id;
}
/**
* @return the name
*/
public String name() {
return name;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(ThemeInfo other) {
return name().compareToIgnoreCase(other.name());
}
}
public static URI uriFromPath(String path) throws IllegalArgumentException {
try {
return new URI(null, null, path, null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
private class RenderSupportImpl implements RenderSupport {
/* (non-Javadoc)
* @see org.jgrapes.portal.RenderSupport#portletResource(java.lang.String, java.net.URI)
*/
@Override
public URI portletResource(String portletType, URI uri) {
return portal.prefix().resolve(uriFromPath(
"portlet-resource/" + portletType + "/")).resolve(uri);
}
}
}
|
package com.clearlyspam23.GLE.basic.layers.tile.edit;
import java.util.ArrayList;
import java.util.List;
import org.piccolo2d.PCamera;
import org.piccolo2d.event.PInputEvent;
import com.clearlyspam23.GLE.basic.layers.tile.TileData;
import com.clearlyspam23.GLE.basic.layers.tile.edit.commands.PlaceTileAction;
import com.clearlyspam23.GLE.basic.layers.tile.gui.TileLayerPNode;
import com.clearlyspam23.GLE.basic.layers.tile.gui.TilePNode;
import com.clearlyspam23.GLE.util.Pair;
public class FloodFillTileCommand extends TileDragCommand {
protected List<Pair<TilePNode, TileData>> replacedList;
public FloodFillTileCommand(TileLayerEditManager data){
super(data);
}
protected void setTile(TilePNode tile, PCamera cam){
// tile.setImage((Image)null);
floodFill(tile, tile.getTileData(), ((TileLayerPNode)tile.getParent()).getNodeGrid());
// tile.invalidatePaint();
}
private boolean aChangeExists(){
for(Pair<TilePNode, TileData> p : replacedList){
if(!p.second.equals(data.getCurrentTileset(), data.getSelectedX(), data.getSelectedY()))
return true;
}
return false;
}
private void floodFill(TilePNode node, TileData target, TilePNode[][] grid){
if(!target.equals(node.getTileData()))
return;
Pair<TilePNode, TileData> pair = new Pair<TilePNode, TileData>(node, node.getTileData());
if(!node.setTileset(data.getCurrentTileset(), data.getSelectedX(), data.getSelectedY()))
return;
replacedList.add(pair);
int x = node.getGridX();
int y = node.getGridY();
if(x-1>=0)
floodFill(grid[x-1][y], target, grid);
if(x+1<grid.length)
floodFill(grid[x+1][y], target, grid);
if(y-1>=0)
floodFill(grid[x][y-1], target, grid);
if(y+1<grid[x].length)
floodFill(grid[x][y+1], target, grid);
}
@Override
protected void onFinish(PInputEvent event) {
if(aChangeExists()){
PlaceTileAction action = new PlaceTileAction(replacedList, new TileData(data.getCurrentTileset(), data.getSelectedX(), data.getSelectedY()));
data.registerEditAction(action);
}
}
@Override
protected boolean onStart(PInputEvent event) {
replacedList = new ArrayList<Pair<TilePNode, TileData>>();
return true;
}
}
|
package org.spoofax.terms;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermPrinter;
import org.spoofax.interpreter.terms.TermType;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.List;
import static org.spoofax.terms.TermFactory.EMPTY_LIST;
public abstract class StrategoTerm extends AbstractSimpleTerm implements IStrategoTerm, Cloneable {
private static final long serialVersionUID = -2803845954655431574L;
private static final int UNKNOWN_HASH = -1;
private transient int hashCode = UNKNOWN_HASH;
@Nullable private IStrategoList annotations = null;
protected StrategoTerm(@Nullable IStrategoList annotations) {
if(annotations != null && !annotations.isEmpty())
this.annotations = annotations;
}
protected StrategoTerm() {
this(null);
}
@Override
public List<IStrategoTerm> getSubterms() {
// Override this implementation to provide a more efficient one.
return TermList.ofUnsafe(getAllSubterms());
}
/**
* Equality test.
*/
@Override
public final boolean match(IStrategoTerm second) {
if(this == second)
return true;
if(second == null)
return false;
return hashCode() == second.hashCode() && doSlowMatch(second);
}
protected abstract boolean doSlowMatch(IStrategoTerm second);
@Override
public final boolean equals(Object obj) {
if(obj == this)
return true;
if(!(obj instanceof IStrategoTerm))
return false;
return match((IStrategoTerm) obj);
}
@Override
public int hashCode() {
if(hashCode == UNKNOWN_HASH) {
initImmutableHashCode();
}
return hashCode;
}
protected final void initImmutableHashCode() {
int hashCode = hashFunction();
if(annotations == null || annotations.isEmpty()) {
this.hashCode = hashCode;
} else {
this.hashCode = hashCode * 2423 + annotations.hashCode();
}
}
protected abstract int hashFunction();
@Override
public String toString() {
return toString(-1);
}
@Override
public String toString(int maxDepth) {
StringBuilder result = new StringBuilder();
try {
writeAsString(result, maxDepth);
} catch(IOException e) {
throw new RuntimeException(e); // shan't happen
}
return result.toString();
}
public final void writeToString(Appendable output) throws IOException {
writeAsString(output, -1);
}
protected void appendAnnotations(Appendable sb, int maxDepth) throws IOException {
IStrategoList annos = getAnnotations();
if(annos.size() == 0)
return;
sb.append('{');
annos.getSubterm(0).writeAsString(sb, maxDepth);
for(annos = annos.tail(); !annos.isEmpty(); annos = annos.tail()) {
sb.append(',');
annos.head().writeAsString(sb, maxDepth);
}
sb.append('}');
}
@Deprecated
protected void printAnnotations(ITermPrinter pp) {
IStrategoList annos = getAnnotations();
if(annos.size() == 0)
return;
pp.print("{");
annos.head().prettyPrint(pp);
for(annos = annos.tail(); !annos.isEmpty(); annos = annos.tail()) {
pp.print(",");
annos.head().prettyPrint(pp);
}
pp.print("}");
}
@Override
protected StrategoTerm clone() {
try {
return (StrategoTerm) super.clone();
} catch(CloneNotSupportedException e) {
throw new RuntimeException(e); // silly checked exceptions...
}
}
public StrategoTerm clone(boolean stripAttachments) {
StrategoTerm result = clone();
if(stripAttachments)
result.clearAttachments();
return result;
}
@Override
public final IStrategoList getAnnotations() {
return annotations == null ? TermFactory.EMPTY_LIST : annotations;
}
public final void internalSetAnnotations(IStrategoList annotations) {
if(annotations != null && !annotations.isEmpty() && this == EMPTY_LIST) {
throw new IllegalArgumentException("Attempting to internally mutate the shared EMPTY_LIST");
}
if(annotations == TermFactory.EMPTY_LIST || annotations == null || annotations.isEmpty())
annotations = null; // essential for hash code calculation
if(this.annotations != annotations) {
this.annotations = annotations;
this.hashCode = UNKNOWN_HASH;
}
}
@Override
@Deprecated
public int getTermType() {
return getType().getValue();
}
@Override
public abstract TermType getType();
@Deprecated
@Override
public final boolean isList() {
return getType() == TermType.LIST;
}
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
// Set hashCode to UNKNOWN_HASH here because the no-arg constructor of this class is not called when an object
// of this class is deserialized, causing the hashCode to be instantiated with the default value for an int: 0,
// instead of UNKNOWN_HASH, which then causes all equality checks against this object to fail. The no-arg
// constructor is not called because according to the JLS on serialization "For serializable objects, the no-arg
// constructor for the first non-serializable supertype is run.", which in this case is the Object class.
this.hashCode = UNKNOWN_HASH;
}
}
|
package part.offline.control;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import data.DataDump;
import data.Entity;
import data.control.FileOutput;
import data.control.StanfordNER;
public class CrawlerUnit implements Runnable {
private int[] textIDs;
private int start, end, acPos;
private int id;
private SQLConnector connector;
private StanfordNER ner;
private FileOutput out;
private int maxLength = 0;
private String splitSymbol = ";
private Status status;
public CrawlerUnit(int[] textIDs, int start, int end, SQLConnector connector, StanfordNER ner, int id, FileOutput out, Status status){
this.textIDs = textIDs;
this.start = start;
this.end = end;
this.connector = connector;
this.ner = ner;
this.setId(id);
this.out = out;
this.status = status;
}
public void run() {
LatitudeLongitudeParser llp = new LatitudeLongitudeParser();
CityCreator cc = new CityCreator(ner, llp);
String text;
DataDump dump;
int revID;
String pageTitle;
StringBuilder builder = new StringBuilder();
for (int i = this.start; i <= this.end ; i++) {
status.setWorkForEachDone(i - start, id);
System.out.println(i + " / " + end);
try {
text = connector.getText(this.textIDs[i]);
dump = cc.getCity(text);
if(dump != null){
revID = connector.getRevID(this.textIDs[i]);
pageTitle = connector.getPageTitle(revID);
dump.getCity().setName(pageTitle);
builder.append(dump.getCity().cityToString());
entitesToString(dump, builder);
out.writeToFile(builder);
builder = new StringBuilder();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void entitesToString(DataDump dump, StringBuilder temp) {
for (Entity ent : dump.getEntityList()) {
temp.append(splitSymbol);
temp.append(ent.getName());
temp.append(splitSymbol);
temp.append(ent.getType());
temp.append(splitSymbol);
temp.append(ent.getCount());
}
}
/**
* deletes multiple rev_ids
*
* @param bilder
* @return
*/
public int[] filter(int[] bilder) {
Set<Integer> temp = new TreeSet<Integer>();
for (int i : bilder) {
temp.add(i);
}
int[] result = new int[temp.size()];
int index = 0;
for (Integer i : temp) {
result[index++] = i;
}
return result;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAcPos() {
return acPos;
}
public void setAcPos(int acPos) {
this.acPos = acPos;
}
}
|
package com.redhat.ceylon.compiler.typechecker.analyzer;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkAssignable;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkAssignableWithWarning;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkCallable;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkIsExactly;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.checkSupertype;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.declaredInPackage;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.eliminateParensAndWidening;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.getTypeArguments;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.getTypeDeclaration;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.getTypeMember;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.getTypedDeclaration;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.getTypedMember;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.hasError;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.inLanguageModule;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.isIndirectInvocation;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.isInstantiationExpression;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.typeDescription;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.typeNamesAsIntersection;
import static com.redhat.ceylon.compiler.typechecker.model.SiteVariance.IN;
import static com.redhat.ceylon.compiler.typechecker.model.SiteVariance.OUT;
import static com.redhat.ceylon.compiler.typechecker.model.Util.addToIntersection;
import static com.redhat.ceylon.compiler.typechecker.model.Util.addToUnion;
import static com.redhat.ceylon.compiler.typechecker.model.Util.findMatchingOverloadedClass;
import static com.redhat.ceylon.compiler.typechecker.model.Util.getContainingClassOrInterface;
import static com.redhat.ceylon.compiler.typechecker.model.Util.getOuterClassOrInterface;
import static com.redhat.ceylon.compiler.typechecker.model.Util.intersectionOfSupertypes;
import static com.redhat.ceylon.compiler.typechecker.model.Util.intersectionType;
import static com.redhat.ceylon.compiler.typechecker.model.Util.isAbstraction;
import static com.redhat.ceylon.compiler.typechecker.model.Util.isOverloadedVersion;
import static com.redhat.ceylon.compiler.typechecker.model.Util.isTypeUnknown;
import static com.redhat.ceylon.compiler.typechecker.model.Util.producedType;
import static com.redhat.ceylon.compiler.typechecker.model.Util.unionType;
import static com.redhat.ceylon.compiler.typechecker.tree.Util.MISSING_NAME;
import static com.redhat.ceylon.compiler.typechecker.tree.Util.hasUncheckedNulls;
import static com.redhat.ceylon.compiler.typechecker.tree.Util.name;
import static java.util.Collections.emptyList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Generic;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.NothingType;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedReference;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeAlias;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.UnknownType;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.PositionalArgument;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.TypeVariance;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
/**
* Third and final phase of type analysis.
* Finally visit all expressions and determine their types.
* Use type inference to assign types to declarations with
* the local modifier. Finally, assigns types to the
* associated model objects of declarations declared using
* the local modifier.
*
* @author Gavin King
*
*/
public class ExpressionVisitor extends Visitor {
private Tree.Type returnType;
private Tree.Expression switchExpression;
private Declaration returnDeclaration;
private boolean isCondition;
private boolean dynamic;
private boolean inExtendsClause = false;
private Unit unit;
@Override public void visit(Tree.CompilationUnit that) {
unit = that.getUnit();
super.visit(that);
}
private Declaration beginReturnDeclaration(Declaration d) {
Declaration od = returnDeclaration;
returnDeclaration = d;
return od;
}
private void endReturnDeclaration(Declaration od) {
returnDeclaration = od;
}
private Tree.Type beginReturnScope(Tree.Type t) {
Tree.Type ort = returnType;
returnType = t;
if (returnType instanceof Tree.FunctionModifier ||
returnType instanceof Tree.ValueModifier) {
returnType.setTypeModel( unit.getNothingDeclaration().getType() );
}
return ort;
}
private void endReturnScope(Tree.Type t, TypedDeclaration td) {
if (returnType instanceof Tree.FunctionModifier ||
returnType instanceof Tree.ValueModifier) {
td.setType( returnType.getTypeModel() );
}
returnType = t;
}
@Override public void visit(Tree.FunctionArgument that) {
Tree.Expression e = that.getExpression();
if (e==null) {
Tree.Type rt = beginReturnScope(that.getType());
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, that.getDeclarationModel());
}
else {
super.visit(that);
ProducedType t = unit.denotableType(e.getTypeModel());
that.getDeclarationModel().setType(t);
//if (that.getType() instanceof Tree.FunctionModifier) {
that.getType().setTypeModel(t);
/*}
else {
checkAssignable(t, that.getType().getTypeModel(), e,
"expression type must be assignable to specified return type");
}*/
if (that.getType() instanceof Tree.VoidModifier &&
!isSatementExpression(e)) {
e.addError("anonymous function is declared void so specified expression must be a statement");
}
}
if (that.getType() instanceof Tree.VoidModifier) {
ProducedType vt = unit.getType(unit.getAnythingDeclaration());
that.getDeclarationModel().setType(vt);
}
that.setTypeModel(that.getDeclarationModel()
.getTypedReference()
.getFullType());
}
@Override public void visit(Tree.ExpressionComprehensionClause that) {
super.visit(that);
that.setTypeModel(that.getExpression().getTypeModel());
that.setFirstTypeModel(unit.getNothingDeclaration().getType());
}
@Override public void visit(Tree.ForComprehensionClause that) {
super.visit(that);
that.setPossiblyEmpty(true);
Tree.ComprehensionClause cc = that.getComprehensionClause();
if (cc!=null) {
that.setTypeModel(cc.getTypeModel());
Tree.ForIterator fi = that.getForIterator();
if (fi!=null) {
Tree.SpecifierExpression se = fi.getSpecifierExpression();
if (se!=null) {
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType it = e.getTypeModel();
if (it!=null) {
ProducedType et = unit.getIteratedType(it);
boolean nonemptyIterable = et!=null &&
it.isSubtypeOf(unit.getNonemptyIterableType(et));
that.setPossiblyEmpty(!nonemptyIterable ||
cc.getPossiblyEmpty());
ProducedType firstType = unionType(unit.getFirstType(it),
cc.getFirstTypeModel(), unit);
that.setFirstTypeModel(firstType);
}
}
}
}
}
}
@Override public void visit(Tree.IfComprehensionClause that) {
super.visit(that);
that.setPossiblyEmpty(true);
that.setFirstTypeModel(unit.getType(unit.getNullDeclaration()));
Tree.ComprehensionClause cc = that.getComprehensionClause();
if (cc!=null) {
that.setTypeModel(cc.getTypeModel());
}
}
@Override public void visit(Tree.Variable that) {
super.visit(that);
if (that.getSpecifierExpression()!=null) {
inferType(that, that.getSpecifierExpression());
if (that.getType()!=null) {
ProducedType t = that.getType().getTypeModel();
if (!isTypeUnknown(t)) {
checkType(t, that.getSpecifierExpression());
}
}
}
}
@Override public void visit(Tree.ConditionList that) {
if (that.getConditions().isEmpty()) {
that.addError("empty condition list");
}
super.visit(that);
}
@Override public void visit(Tree.ResourceList that) {
if (that.getResources().isEmpty()) {
that.addError("empty resource list");
}
super.visit(that);
}
private void initOriginalDeclaration(Tree.Variable that) {
if (that.getType() instanceof Tree.SyntheticVariable) {
Tree.BaseMemberExpression bme = (Tree.BaseMemberExpression) that
.getSpecifierExpression().getExpression().getTerm();
((TypedDeclaration) that.getDeclarationModel())
.setOriginalDeclaration((TypedDeclaration) bme.getDeclaration());
}
}
@Override public void visit(Tree.IsCondition that) {
//don't recurse to the Variable, since we don't
//want to check that the specifier expression is
//assignable to the declared variable type
//(nor is it possible to infer the variable type)
isCondition=true;
Tree.Type t = that.getType();
if (t!=null) {
t.visit(this);
}
isCondition=false;
Tree.Variable v = that.getVariable();
ProducedType type = t==null ? null : t.getTypeModel();
if (v!=null) {
// if (type!=null && !that.getNot()) {
// v.getType().setTypeModel(type);
// v.getDeclarationModel().setType(type);
//v.getType().visit(this);
Tree.SpecifierExpression se = v.getSpecifierExpression();
ProducedType knownType;
if (se==null) {
knownType = null;
}
else {
se.visit(this);
checkReferenceIsNonVariable(v, se);
/*checkAssignable( se.getExpression().getTypeModel(),
getOptionalType(getObjectDeclaration().getType()),
se.getExpression(),
"expression may not be of void type");*/
initOriginalDeclaration(v);
//this is a bit ugly (the parser sends us a SyntheticVariable
//instead of the real StaticType which it very well knows!)
Tree.Expression e = se.getExpression();
knownType = e==null ? null : e.getTypeModel();
//TODO: what to do here in case of !is
if (knownType!=null) {
String help = " (expression is already of the specified type)";
if (that.getNot()) {
if (intersectionType(type,knownType, unit).isNothing()) {
that.addError("does not narrow type: intersection of '" + type.getProducedTypeName(unit) +
"' and '" + knownType.getProducedTypeName(unit) + "' is empty" + help);
}
else if (knownType.isSubtypeOf(type)) {
that.addError("tests assignability to bottom type 'Nothing': '" + knownType.getProducedTypeName(unit) +
"' is a subtype of '" + type.getProducedTypeName(unit) + "'");
}
}
else {
if (knownType.isSubtypeOf(type)) {
that.addError("does not narrow type: '" + knownType.getProducedTypeName(unit) +
"' is a subtype of '" + type.getProducedTypeName(unit) + "'" + help);
}
}
}
}
defaultTypeToAnything(v);
if (knownType==null) {
knownType = unit.getType(unit.getAnythingDeclaration()); //or should we use unknown?
}
ProducedType it = narrow(that, type, knownType);
//check for disjointness
if (it.getDeclaration() instanceof NothingType) {
if (that.getNot()) {
/*that.addError("tests assignability to Nothing type: " +
knownType.getProducedTypeName(unit) + " is a subtype of " +
type.getProducedTypeName(unit));*/
}
else {
that.addError("tests assignability to bottom type 'Nothing': intersection of '" +
knownType.getProducedTypeName(unit) + "' and '" +
type.getProducedTypeName(unit) + "' is empty");
}
}
//do this *after* checking for disjointness!
knownType=unit.denotableType(knownType);
//now recompute the narrowed type!
it = narrow(that, type, knownType);
v.getType().setTypeModel(it);
v.getDeclarationModel().setType(it);
}
}
private ProducedType narrow(Tree.IsCondition that, ProducedType type,
ProducedType knownType) {
ProducedType it;
if (that.getNot()) {
//a !is condition, narrow to complement
it = unit.denotableType(knownType.minus(type));
}
else {
//narrow to the intersection of the outer type
//and the type specified in the condition
it = intersectionType(type, knownType, that.getUnit());
}
return it;
}
@Override public void visit(Tree.SatisfiesCondition that) {
super.visit(that);
that.addUnsupportedError("satisfies conditions not yet supported");
}
@Override public void visit(Tree.ExistsOrNonemptyCondition that) {
//don't recurse to the Variable, since we don't
//want to check that the specifier expression is
//assignable to the declared variable type
//(nor is it possible to infer the variable type)
ProducedType t = null;
Node n = that;
Tree.Term term = null;
Tree.Variable v = that.getVariable();
if (v!=null) {
//v.getType().visit(this);
defaultTypeToAnything(v);
Tree.SpecifierExpression se = v.getSpecifierExpression();
if (se!=null && se.getExpression()!=null) {
se.visit(this);
if (that instanceof Tree.ExistsCondition) {
inferDefiniteType(v, se);
checkOptionalType(v, se);
}
else if (that instanceof Tree.NonemptyCondition) {
inferNonemptyType(v, se);
checkEmptyOptionalType(v, se);
}
t = se.getExpression().getTypeModel();
n = v;
checkReferenceIsNonVariable(v, se);
initOriginalDeclaration(v);
term = se.getExpression().getTerm();
}
}
if (that instanceof Tree.ExistsCondition) {
checkOptional(t, term, n);
}
else if (that instanceof Tree.NonemptyCondition) {
checkEmpty(t, term, n);
}
}
private void defaultTypeToAnything(Tree.Variable v) {
/*if (v.getType().getTypeModel()==null) {
v.getType().setTypeModel( getAnythingDeclaration().getType() );
}*/
v.getType().visit(this);
if (v.getDeclarationModel().getType()==null) {
v.getDeclarationModel().setType( defaultType() );
}
}
private void checkReferenceIsNonVariable(Tree.Variable v,
Tree.SpecifierExpression se) {
if (v.getType() instanceof Tree.SyntheticVariable) {
Tree.BaseMemberExpression term = (Tree.BaseMemberExpression) se.getExpression().getTerm();
checkReferenceIsNonVariable(term, false);
}
}
private void checkReferenceIsNonVariable(Tree.BaseMemberExpression ref,
boolean isSwitch) {
Declaration d = ref.getDeclaration();
if (d!=null) {
int code = isSwitch ? 3101:3100;
String help=" (assign to a new local value to narrow type)";
if (!(d instanceof Value)) {
ref.addError("referenced declaration is not a value: '" +
d.getName(unit) + "'", code);
}
else if (isNonConstant(d)) {
ref.addError("referenced value is non-constant: '" +
d.getName(unit) + "'" + help, code);
}
else if (d.isDefault() || d.isFormal()) {
ref.addError("referenced value may be refined by a non-constant value: '" +
d.getName(unit) + "'" + help, code);
}
}
}
private boolean isNonConstant(Declaration d) {
return d instanceof Value &&
(((Value) d).isVariable() || ((Value) d).isTransient());
}
private void checkEmpty(ProducedType t, Tree.Term term, Node n) {
/*if (t==null) {
n.addError("expression must be a type with fixed size: type not known");
}
else*/ if (!isTypeUnknown(t) && !unit.isPossiblyEmptyType(t)) {
term.addError("expression must be a possibly-empty type: '" +
t.getProducedTypeName(unit) + "' is not possibly-empty");
}
}
private void checkOptional(ProducedType t, Tree.Term term, Node n) {
/*if (t==null) {
n.addError("expression must be of optional type: type not known");
}
else*/
if (!isTypeUnknown(t) && !unit.isOptionalType(t) &&
!hasUncheckedNulls(term)) {
term.addError("expression must be of optional type: '" +
t.getProducedTypeName(unit) + "' is not optional");
}
}
@Override public void visit(Tree.BooleanCondition that) {
super.visit(that);
if (that.getExpression()!=null) {
ProducedType t = that.getExpression().getTypeModel();
if (!isTypeUnknown(t)) {
checkAssignable(t, unit.getType(unit.getBooleanDeclaration()), that,
"expression must be of boolean type");
}
}
}
@Override public void visit(Tree.Resource that) {
super.visit(that);
ProducedType t = null;
Node typedNode = null;
Tree.Expression e = that.getExpression();
Tree.Variable v = that.getVariable();
if (e!=null) {
t = e.getTypeModel();
typedNode = e;
}
else if (v!=null) {
t = v.getType().getTypeModel();
typedNode = v.getType();
Tree.SpecifierExpression se = v.getSpecifierExpression();
if (se==null) {
v.addError("missing resource specifier");
}
else {
e = se.getExpression();
if (typedNode instanceof Tree.ValueModifier) {
typedNode = se.getExpression();
}
}
}
else {
that.addError("missing resource expression");
}
if (typedNode!=null) {
if (!isTypeUnknown(t)) {
if (e != null) {
ProducedType ot = unit.getType(unit.getObtainableDeclaration());
ProducedType dt = unit.getType(unit.getDestroyableDeclaration());
if (isInstantiationExpression(e)) {
if (!t.isSubtypeOf(dt) && !t.isSubtypeOf(ot)) {
typedNode.addError("resource must be either obtainable or destroyable: '" +
t.getProducedTypeName(unit) + "' is neither 'Obtainable' nor 'Destroyable'");
}
}
else {
checkAssignable(t, ot, typedNode, "resource must be obtainable");
}
}
}
}
}
@Override public void visit(Tree.ForIterator that) {
super.visit(that);
Tree.SpecifierExpression se = that.getSpecifierExpression();
if (se!=null) {
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType et = e.getTypeModel();
if (!isTypeUnknown(et)) {
if (!unit.isIterableType(et)) {
se.addError("expression is not iterable: '" +
et.getProducedTypeName(unit) +
"' is not a subtype of 'Iterable'");
}
else if (et!=null && unit.isEmptyType(et)) {
se.addError("iterated expression is definitely empty");
}
}
}
}
}
@Override public void visit(Tree.ValueIterator that) {
super.visit(that);
Tree.Variable v = that.getVariable();
if (v!=null) {
inferContainedType(v, that.getSpecifierExpression());
checkContainedType(v, that.getSpecifierExpression());
}
}
@Override public void visit(Tree.KeyValueIterator that) {
super.visit(that);
Tree.SpecifierExpression se = that.getSpecifierExpression();
if (se!=null) {
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType et = e.getTypeModel();
if (!isTypeUnknown(et)) {
ProducedType it = unit.getIteratedType(et);
if (it!=null && !isTypeUnknown(it)) {
if (!unit.isEntryType(it)) {
se.addError("iterated element type is not an entry type: '" +
it.getProducedTypeName(unit) +
"' is not a subtype of 'Entry'");
}
}
}
}
}
Tree.Variable kv = that.getKeyVariable();
Tree.Variable vv = that.getValueVariable();
if (kv!=null && vv!=null) {
inferKeyType(kv, that.getSpecifierExpression());
inferValueType(vv, that.getSpecifierExpression());
checkKeyValueType(kv, vv, that.getSpecifierExpression());
}
}
@Override public void visit(Tree.AttributeDeclaration that) {
super.visit(that);
Value dec = that.getDeclarationModel();
Tree.SpecifierOrInitializerExpression sie = that.getSpecifierOrInitializerExpression();
inferType(that, sie);
Tree.Type type = that.getType();
if (type!=null) {
ProducedType t = type.getTypeModel();
if (type instanceof Tree.LocalModifier) {
if (dec.isParameter()) {
type.addError("parameter may not have inferred type: '" +
dec.getName() + "'");
}
else {
if (sie==null) {
type.addError("value must specify an explicit type or definition", 200);
}
else if (isTypeUnknown(t)) {
if (!hasError(sie)) {
type.addError("value type could not be inferred");
}
}
}
}
if (!isTypeUnknown(t)) {
checkType(t, dec.getName(), sie, 2100);
}
}
Setter setter = dec.getSetter();
if (setter!=null) {
setter.getParameter().getModel().setType(dec.getType());
}
}
@Override public void visit(Tree.ParameterizedExpression that) {
super.visit(that);
Tree.Term p = that.getPrimary();
if (p instanceof Tree.QualifiedMemberExpression ||
p instanceof Tree.BaseMemberExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) p;
if (p.getTypeModel()!=null && mte.getDeclaration()!=null) {
ProducedType pt = p.getTypeModel();
if (pt!=null) {
for (int j=0; j<that.getParameterLists().size(); j++) {
Tree.ParameterList pl = that.getParameterLists().get(j);
ProducedType ct = pt.getSupertype(unit.getCallableDeclaration());
String refName = mte.getDeclaration().getName();
if (ct==null) {
pl.addError("no matching parameter list in referenced declaration: '" +
refName + "'");
}
else if (ct.getTypeArgumentList().size()>=2) {
ProducedType tupleType = ct.getTypeArgumentList().get(1);
List<ProducedType> argTypes = unit.getTupleElementTypes(tupleType);
boolean variadic = unit.isTupleLengthUnbounded(tupleType);
boolean atLeastOne = unit.isTupleVariantAtLeastOne(tupleType);
List<Tree.Parameter> params = pl.getParameters();
if (argTypes.size()!=params.size()) {
pl.addError("wrong number of declared parameters: '" + refName +
"' has " + argTypes.size() + " parameters");
}
for (int i=0; i<argTypes.size()&&i<params.size(); i++) {
ProducedType at = argTypes.get(i);
Tree.Parameter param = params.get(i);
ProducedType t = param.getParameterModel().getModel()
.getTypedReference()
.getFullType();
checkAssignable(at, t, param, "type of parameter '" + param.getParameterModel().getName() +
"' must be a supertype of parameter type in declaration of '" + refName + "'");
}
if (!params.isEmpty()) {
Tree.Parameter lastParam = params.get(params.size()-1);
boolean refSequenced = lastParam.getParameterModel().isSequenced();
boolean refAtLeastOne = lastParam.getParameterModel().isAtLeastOne();
if (refSequenced && !variadic) {
lastParam.addError("parameter list in declaration of '" + refName +
"' does not have a variadic parameter");
}
else if (!refSequenced && variadic) {
lastParam.addError("parameter list in declaration of '" + refName +
"' has a variadic parameter");
}
else if (refAtLeastOne && !atLeastOne) {
lastParam.addError("variadic parameter in declaration of '" + refName +
"' is optional");
}
else if (!refAtLeastOne && atLeastOne) {
lastParam.addError("variadic parameter in declaration of '" + refName +
"' is not optional");
}
}
pt = ct.getTypeArgumentList().get(0);
that.setTypeModel(pt);
}
}
}
}
}
}
@Override public void visit(Tree.SpecifierStatement that) {
super.visit(that);
boolean hasParams = false;
Tree.Term me = that.getBaseMemberExpression();
while (me instanceof Tree.ParameterizedExpression) {
hasParams = true;
me = ((Tree.ParameterizedExpression) me).getPrimary();
}
assign(me);
Tree.SpecifierExpression sie = that.getSpecifierExpression();
if (me instanceof Tree.BaseMemberExpression) {
Declaration d = that.getDeclaration();
if (d instanceof TypedDeclaration) {
if (that.getRefinement()) {
// interpret this specification as a
// refinement of an inherited member
if (d instanceof Value) {
refineValue(that);
}
else if (d instanceof Method) {
refineMethod(that);
}
Tree.BaseMemberExpression bme = (Tree.BaseMemberExpression) me;
bme.setDeclaration(that.getDeclaration());
}
else if (d instanceof MethodOrValue) {
MethodOrValue mv = (MethodOrValue) d;
if (mv.isShortcutRefinement()) {
that.getBaseMemberExpression().addError("already specified: '" +
d.getName(unit) + "'");
}
else if (d.isToplevel() && !mv.isVariable() && !mv.isLate()) {
that.addError("cannot specify non-variable toplevel value here: '" +
d.getName(unit) + "' is not variable or late", 803);
}
}
if (hasParams && d instanceof Method &&
((Method) d).isDeclaredVoid() &&
!isSatementExpression(sie.getExpression())) {
that.addError("function is declared void so specified expression must be a statement: '" +
d.getName(unit) + "' is declared void");
}
if (d instanceof Value &&
that.getSpecifierExpression() instanceof Tree.LazySpecifierExpression) {
((Value) d).setTransient(true);
}
ProducedType t = that.getBaseMemberExpression().getTypeModel();
if (that.getBaseMemberExpression()==me && d instanceof Method) {
//if the declaration of the method has
//defaulted parameters, we should ignore
//that when determining if the RHS is
//an acceptable implementation of the
//method
//TODO: this is a pretty nasty way to
// handle the problem
t = eraseDefaultedParameters(t);
}
if (!isTypeUnknown(t)) {
checkType(t, d.getName(unit), sie, 2100);
}
}
if (that.getBaseMemberExpression() instanceof Tree.ParameterizedExpression) {
if (!(sie instanceof Tree.LazySpecifierExpression)) {
that.addError("functions with parameters must be specified using =>");
}
}
else {
if (sie instanceof Tree.LazySpecifierExpression && d instanceof Method) {
that.addError("functions without parameters must be specified using =");
}
}
}
else {
me.addError("illegal specification statement: only a function or value may be specified");
}
}
boolean isSatementExpression(Tree.Expression e) {
if (e==null) {
return false;
}
else {
Tree.Term t = e.getTerm();
return t instanceof Tree.InvocationExpression ||
t instanceof Tree.PostfixOperatorExpression ||
t instanceof Tree.AssignmentOp ||
t instanceof Tree.PrefixOperatorExpression;
}
}
/*boolean isVoidMethodReference(Tree.Expression e) {
//TODO: correctly handle multiple parameter lists!
Tree.Term term = e.getTerm();
ProducedType tm = term.getTypeModel();
if (tm!=null && tm.isExactly(unit.getType(unit.getAnythingDeclaration()))) {
if (term instanceof Tree.InvocationExpression) {
Tree.InvocationExpression ie = (Tree.InvocationExpression) term;
if (ie.getPrimary() instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) ie.getPrimary();
if (mte.getDeclaration() instanceof Functional) {
return ((Functional) mte.getDeclaration()).isDeclaredVoid();
}
}
}
}
return false;
}*/
private ProducedType eraseDefaultedParameters(ProducedType t) {
ProducedType ct = t.getSupertype(unit.getCallableDeclaration());
if (ct!=null) {
List<ProducedType> typeArgs = ct.getTypeArgumentList();
if (typeArgs.size()>=2) {
ProducedType rt = typeArgs.get(0);
ProducedType pts = typeArgs.get(1);
List<ProducedType> argTypes = unit.getTupleElementTypes(pts);
boolean variadic = unit.isTupleLengthUnbounded(pts);
boolean atLeastOne = unit.isTupleVariantAtLeastOne(pts);
if (variadic) {
ProducedType spt = argTypes.get(argTypes.size()-1);
argTypes.set(argTypes.size()-1, unit.getIteratedType(spt));
}
return producedType(unit.getCallableDeclaration(), rt,
unit.getTupleType(argTypes, variadic, atLeastOne, -1));
}
}
return t;
}
static ProducedReference getRefinedMember(MethodOrValue d,
ClassOrInterface classOrInterface) {
ProducedType supertype = classOrInterface.getType()
.getSupertype((TypeDeclaration) d.getContainer());
return d.getProducedReference(supertype,
Collections.<ProducedType>emptyList());
}
private void refineValue(Tree.SpecifierStatement that) {
Value sv = (Value) that.getRefined();
Value v = (Value) that.getDeclaration();
ProducedReference rv = getRefinedMember(sv,
(ClassOrInterface) v.getContainer());
v.setType(rv.getType());
}
private void refineMethod(Tree.SpecifierStatement that) {
Method sm = (Method) that.getRefined();
Method m = (Method) that.getDeclaration();
ClassOrInterface ci = (ClassOrInterface) m.getContainer();
ProducedReference rm = getRefinedMember(sm, ci);
m.setType(rm.getType());
List<Tree.ParameterList> tpls;
Tree.Term me = that.getBaseMemberExpression();
if (me instanceof Tree.ParameterizedExpression) {
tpls = ((Tree.ParameterizedExpression) me).getParameterLists();
}
else {
tpls = emptyList();
}
for (int i=0; i<sm.getParameterLists().size(); i++) {
ParameterList pl = sm.getParameterLists().get(i);
ParameterList l = m.getParameterLists().get(i);
Tree.ParameterList tpl = tpls.size()<=i ?
null : tpls.get(i);
for (int j=0; j<pl.getParameters().size(); j++) {
Parameter p = pl.getParameters().get(j);
ProducedType pt = rm.getTypedParameter(p).getFullType();
if (tpl==null || tpl.getParameters().size()<=j) {
Parameter vp = l.getParameters().get(j);
vp.getModel().setType(pt);
}
else {
Tree.Parameter tp = tpl.getParameters().get(j);
Parameter rp = tp.getParameterModel();
ProducedType rpt = rp.getModel()
.getTypedReference()
.getFullType();
checkIsExactly(rpt, pt, tp,
"type of parameter " + rp.getName() + " of " + m.getName() +
" declared by " + ci.getName() +
" is different to type of corresponding parameter " +
p.getName() + " of refined method " + sm.getName() + " of " +
((Declaration) sm.getContainer()).getName());
}
}
}
}
@Override public void visit(Tree.TypeParameterDeclaration that) {
super.visit(that);
TypeParameter tpd = that.getDeclarationModel();
ProducedType dta = tpd.getDefaultTypeArgument();
if (dta!=null) {
for (ProducedType st: tpd.getSatisfiedTypes()) {
checkAssignable(dta, st, that.getTypeSpecifier().getType(),
"default type argument does not satisfy type constraint");
}
}
}
@Override public void visit(Tree.ParameterDeclaration that) {
super.visit(that);
Tree.Type type = that.getTypedDeclaration().getType();
if (type instanceof Tree.LocalModifier) {
Parameter p = that.getParameterModel();
type.setTypeModel(new UnknownType(unit).getType());
type.addError("parameter may not have inferred type: '" +
p.getName() + "' must declare an explicit type");
}
}
@Override public void visit(Tree.InitializerParameter that) {
super.visit(that);
MethodOrValue model = that.getParameterModel().getModel();
if (model!=null) {
ProducedType type =
model.getTypedReference().getFullType();
if (type!=null && !isTypeUnknown(type)) {
checkType(type, that.getSpecifierExpression());
}
}
}
private void checkType(ProducedType declaredType,
Tree.SpecifierOrInitializerExpression sie) {
if (sie!=null && sie.getExpression()!=null) {
ProducedType t = sie.getExpression().getTypeModel();
if (!isTypeUnknown(t)) {
checkAssignable(t, declaredType, sie,
"specified expression must be assignable to declared type");
}
}
}
private void checkType(ProducedType declaredType, String name,
Tree.SpecifierOrInitializerExpression sie, int code) {
if (sie!=null && sie.getExpression()!=null) {
ProducedType t = sie.getExpression().getTypeModel();
if (!isTypeUnknown(t)) {
checkAssignable(t, declaredType, sie,
"specified expression must be assignable to declared type of '" + name + "'",
code);
}
}
}
private void checkFunctionType(ProducedType et, Tree.Type that,
Tree.SpecifierExpression se) {
if (!isTypeUnknown(et)) {
checkAssignable(et, that.getTypeModel(), se,
"specified expression type must be assignable to declared return type",
2100);
}
}
private void checkOptionalType(Tree.Variable var,
Tree.SpecifierExpression se) {
if (var.getType()!=null) {
ProducedType vt = var.getType().getTypeModel();
Tree.Expression e = se.getExpression();
if (se!=null && e!=null) {
ProducedType set = e.getTypeModel();
if (set!=null) {
if (!isTypeUnknown(vt) && !isTypeUnknown(set)) {
checkAssignable(unit.getDefiniteType(set), vt, se,
"specified expression must be assignable to declared type");
}
}
}
}
}
private void checkEmptyOptionalType(Tree.Variable var,
Tree.SpecifierExpression se) {
if (var.getType()!=null) {
ProducedType vt = var.getType().getTypeModel();
Tree.Expression e = se.getExpression();
if (se!=null && e!=null) {
ProducedType set = e.getTypeModel();
if (!isTypeUnknown(vt) && !isTypeUnknown(set)) {
checkType(unit.getOptionalType(unit.getPossiblyNoneType(vt)), se);
}
}
}
}
private void checkContainedType(Tree.Variable var,
Tree.SpecifierExpression se) {
if (var.getType()!=null) {
ProducedType vt = var.getType().getTypeModel();
if (!isTypeUnknown(vt)) {
checkType(unit.getIterableType(vt), se);
}
}
}
private void checkKeyValueType(Tree.Variable key, Tree.Variable value,
Tree.SpecifierExpression se) {
if (key.getType()!=null && value.getType()!=null) {
ProducedType kt = key.getType().getTypeModel();
ProducedType vt = value.getType().getTypeModel();
if (!isTypeUnknown(kt) && !isTypeUnknown(vt)) {
checkType(unit.getIterableType(unit.getEntryType(kt, vt)), se);
}
}
}
@Override public void visit(Tree.AttributeGetterDefinition that) {
Tree.Type type = that.getType();
Tree.Type rt = beginReturnScope(type);
Value dec = that.getDeclarationModel();
Declaration od = beginReturnDeclaration(dec);
super.visit(that);
endReturnScope(rt, dec);
endReturnDeclaration(od);
Setter setter = dec.getSetter();
if (setter!=null) {
setter.getParameter().getModel().setType(dec.getType());
}
if (type instanceof Tree.LocalModifier) {
if (isTypeUnknown(type.getTypeModel())) {
type.addError("getter type could not be inferred");
}
}
}
@Override public void visit(Tree.AttributeArgument that) {
Tree.SpecifierExpression se = that.getSpecifierExpression();
Tree.Type type = that.getType();
if (se==null) {
Tree.Type rt = beginReturnScope(type);
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, that.getDeclarationModel());
}
else {
super.visit(that);
inferType(that, se);
if (type!=null) {
ProducedType t = type.getTypeModel();
if (!isTypeUnknown(t)) {
checkType(t, that.getDeclarationModel().getName(), se, 2100);
}
}
}
if (type instanceof Tree.LocalModifier) {
if (isTypeUnknown(type.getTypeModel())) {
if (se==null || !hasError(se)) {
Node node = type.getToken()==null ? that : type;
node.addError("argument type could not be inferred");
}
}
}
}
@Override public void visit(Tree.AttributeSetterDefinition that) {
Tree.Type rt = beginReturnScope(that.getType());
Setter sd = that.getDeclarationModel();
Declaration od = beginReturnDeclaration(sd);
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, sd);
Tree.SpecifierExpression se = that.getSpecifierExpression();
if (se!=null) {
Tree.Expression e = se.getExpression();
if (e!=null) {
if (!isSatementExpression(e)) {
se.addError("function is declared void so specified expression must be a statement: '" +
sd.getName() + "'");
}
}
}
}
@Override public void visit(Tree.MethodDeclaration that) {
super.visit(that);
Tree.Type type = that.getType();
Tree.SpecifierExpression se = that.getSpecifierExpression();
if (se!=null) {
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType returnType = e.getTypeModel();
inferFunctionType(that, returnType);
if (type!=null &&
!(type instanceof Tree.DynamicModifier)) {
checkFunctionType(returnType, type, se);
}
if (type instanceof Tree.VoidModifier &&
!isSatementExpression(e)) {
se.addError("function is declared void so specified expression must be a statement: '" +
that.getDeclarationModel().getName() + "'");
}
}
}
if (type instanceof Tree.LocalModifier) {
if (isTypeUnknown(type.getTypeModel())) {
if (se==null) {
type.addError("function must specify an explicit return type or definition", 200);
}
else if (!hasError(se)) {
type.addError("function type could not be inferred");
}
}
}
}
@Override public void visit(Tree.MethodDefinition that) {
Tree.Type type = that.getType();
Tree.Type rt = beginReturnScope(type);
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, that.getDeclarationModel());
if (type instanceof Tree.LocalModifier) {
if (isTypeUnknown(type.getTypeModel())) {
type.addError("function type could not be inferred");
}
}
}
@Override public void visit(Tree.MethodArgument that) {
Tree.SpecifierExpression se = that.getSpecifierExpression();
Method d = that.getDeclarationModel();
Tree.Type type = that.getType();
if (se==null) {
Tree.Type rt = beginReturnScope(type);
Declaration od = beginReturnDeclaration(d);
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, d);
}
else {
super.visit(that);
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType returnType = e.getTypeModel();
inferFunctionType(that, returnType);
if (type!=null &&
!(type instanceof Tree.DynamicModifier)) {
checkFunctionType(returnType, type, se);
}
if (d.isDeclaredVoid() && !isSatementExpression(e)) {
se.addError("functional argument is declared void so specified expression must be a statement: '" +
d.getName() + "'");
}
}
}
if (type instanceof Tree.LocalModifier) {
if (isTypeUnknown(type.getTypeModel())) {
if (se==null || hasError(type)) {
Node node = type.getToken()==null ? that : type;
node.addError("argument type could not be inferred");
}
}
}
}
@Override public void visit(Tree.ClassDefinition that) {
Tree.Type rt = beginReturnScope(new Tree.VoidModifier(that.getToken()));
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, null);
validateEnumeratedSupertypes(that, that.getDeclarationModel());
}
@Override public void visit(Tree.ClassOrInterface that) {
super.visit(that);
validateEnumeratedSupertypeArguments(that, that.getDeclarationModel());
}
@Override public void visit(Tree.InterfaceDefinition that) {
Tree.Type rt = beginReturnScope(null);
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, null);
validateEnumeratedSupertypes(that, that.getDeclarationModel());
}
@Override public void visit(Tree.ObjectDefinition that) {
Tree.Type rt = beginReturnScope(new Tree.VoidModifier(that.getToken()));
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, null);
validateEnumeratedSupertypes(that, that.getAnonymousClass());
}
@Override public void visit(Tree.ObjectArgument that) {
Tree.Type rt = beginReturnScope(new Tree.VoidModifier(that.getToken()));
Declaration od = beginReturnDeclaration(that.getDeclarationModel());
super.visit(that);
endReturnDeclaration(od);
endReturnScope(rt, null);
validateEnumeratedSupertypes(that, that.getAnonymousClass());
}
@Override public void visit(Tree.ClassDeclaration that) {
super.visit(that);
Class alias = that.getDeclarationModel();
Class c = alias.getExtendedTypeDeclaration();
if (c!=null) {
if (c.isAbstract()) {
if (!alias.isFormal() && !alias.isAbstract()) {
that.addError("alias of abstract class must be annotated abstract", 310);
}
}
if (c.isAbstraction()) {
that.addError("class alias may not alias overloaded class");
}
else {
//TODO: all this can be removed once the backend
// implements full support for the new class
// alias stuff
ProducedType at = alias.getExtendedType();
ParameterList cpl = c.getParameterList();
ParameterList apl = alias.getParameterList();
if (cpl!=null && apl!=null) {
int cps = cpl.getParameters().size();
int aps = apl.getParameters().size();
if (cps!=aps) {
that.getParameterList()
.addUnsupportedError("wrong number of initializer parameters declared by class alias: " +
alias.getName());
}
for (int i=0; i<cps && i<aps; i++) {
Parameter ap = apl.getParameters().get(i);
Parameter cp = cpl.getParameters().get(i);
ProducedType pt = at.getTypedParameter(cp).getType();
//TODO: properly check type of functional parameters!!
checkAssignableWithWarning(ap.getType(), pt, that, "alias parameter " +
ap.getName() + " must be assignable to corresponding class parameter " +
cp.getName());
}
//temporary restrictions
if (that.getClassSpecifier()!=null) {
Tree.InvocationExpression ie = that.getClassSpecifier().getInvocationExpression();
if (ie!=null) {
Tree.PositionalArgumentList pal = ie.getPositionalArgumentList();
if (pal!=null) {
List<PositionalArgument> pas = pal.getPositionalArguments();
if (cps!=pas.size()) {
pal.addUnsupportedError("wrong number of arguments for aliased class: " +
alias.getName() + " has " + cps + " parameters");
}
for (int i=0; i<pas.size() && i<cps && i<aps; i++) {
Tree.PositionalArgument pa = pas.get(i);
Parameter aparam = apl.getParameters().get(i);
Parameter cparam = cpl.getParameters().get(i);
if (pa instanceof Tree.ListedArgument) {
if (cparam.isSequenced()) {
pa.addUnsupportedError("argument to variadic parameter of aliased class must be spread");
}
Tree.Expression e = ((Tree.ListedArgument) pa).getExpression();
checkAliasArg(aparam, e);
}
else if (pa instanceof Tree.SpreadArgument) {
if (!cparam.isSequenced()) {
pa.addUnsupportedError("argument to non-variadic parameter of aliased class may not be spread");
}
Tree.Expression e = ((Tree.SpreadArgument) pa).getExpression();
checkAliasArg(aparam, e);
}
else if (pa!=null) {
pa.addUnsupportedError("argument to parameter or aliased class must be listed or spread");
}
}
}
}
}
}
}
}
}
private void checkAliasArg(Parameter param, Tree.Expression e) {
if (e!=null && param!=null) {
MethodOrValue p = param.getModel();
if (p!=null) {
Tree.Term term = e.getTerm();
if (term instanceof Tree.BaseMemberExpression) {
Declaration d = ((Tree.BaseMemberExpression) term).getDeclaration();
if (d!=null && !d.equals(p)) {
e.addUnsupportedError("argument must be a parameter reference to " +
p.getName());
}
}
else {
e.addUnsupportedError("argument must be a parameter reference to " +
p.getName());
}
}
}
}
private void inferType(Tree.TypedDeclaration that,
Tree.SpecifierOrInitializerExpression spec) {
if (that.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) that.getType();
if (spec!=null) {
setType(local, spec, that);
}
}
}
private void inferType(Tree.AttributeArgument that,
Tree.SpecifierOrInitializerExpression spec) {
if (that.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) that.getType();
if (spec!=null) {
setType(local, spec, that);
}
}
}
private void inferFunctionType(Tree.TypedDeclaration that, ProducedType et) {
if (that.getType() instanceof Tree.FunctionModifier) {
Tree.FunctionModifier local = (Tree.FunctionModifier) that.getType();
if (et!=null) {
setFunctionType(local, et, that);
}
}
}
private void inferFunctionType(Tree.MethodArgument that, ProducedType et) {
if (that.getType() instanceof Tree.FunctionModifier) {
Tree.FunctionModifier local = (Tree.FunctionModifier) that.getType();
if (et!=null) {
setFunctionType(local, et, that);
}
}
}
private void inferDefiniteType(Tree.Variable that,
Tree.SpecifierExpression se) {
if (that.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) that.getType();
if (se!=null) {
setTypeFromOptionalType(local, se, that);
}
}
}
private void inferNonemptyType(Tree.Variable that,
Tree.SpecifierExpression se) {
if (that.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) that.getType();
if (se!=null) {
setTypeFromEmptyType(local, se, that);
}
}
}
private void inferContainedType(Tree.Variable that,
Tree.SpecifierExpression se) {
if (that.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) that.getType();
if (se!=null) {
setTypeFromIterableType(local, se, that);
}
}
}
private void inferKeyType(Tree.Variable key,
Tree.SpecifierExpression se) {
if (key.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) key.getType();
if (se!=null) {
setTypeFromKeyType(local, se, key);
}
}
}
private void inferValueType(Tree.Variable value,
Tree.SpecifierExpression se) {
if (value.getType() instanceof Tree.LocalModifier) {
Tree.LocalModifier local = (Tree.LocalModifier) value.getType();
if (se!=null) {
setTypeFromValueType(local, se, value);
}
}
}
private void setTypeFromOptionalType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType expressionType = e.getTypeModel();
if (!isTypeUnknown(expressionType)) {
ProducedType t;
if (unit.isOptionalType(expressionType)) {
t = unit.getDefiniteType(expressionType);
}
else {
t=expressionType;
}
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
}
}
private void setTypeFromEmptyType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType expressionType = e.getTypeModel();
if (!isTypeUnknown(expressionType)) {
// if (expressionType.getDeclaration() instanceof Interface &&
// expressionType.getDeclaration().equals(unit.getSequentialDeclaration())) {
// expressionType = unit.getEmptyType(unit.getSequenceType(expressionType.getTypeArgumentList().get(0)));
ProducedType t;
if (unit.isPossiblyEmptyType(expressionType)) {
t = unit.getNonemptyDefiniteType(expressionType);
}
else {
t = expressionType;
}
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
}
}
private void setTypeFromIterableType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
if (se.getExpression()!=null) {
ProducedType expressionType = se.getExpression().getTypeModel();
if (expressionType!=null) {
ProducedType t = unit.getIteratedType(expressionType);
if (t!=null) {
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
}
}
}
private void setTypeFromKeyType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType expressionType = e.getTypeModel();
if (expressionType!=null) {
ProducedType entryType = unit.getIteratedType(expressionType);
if (entryType!=null) {
ProducedType kt = unit.getKeyType(entryType);
if (kt!=null) {
local.setTypeModel(kt);
that.getDeclarationModel().setType(kt);
}
}
}
}
}
private void setTypeFromValueType(Tree.LocalModifier local,
Tree.SpecifierExpression se, Tree.Variable that) {
Tree.Expression e = se.getExpression();
if (e!=null) {
ProducedType expressionType = e.getTypeModel();
if (expressionType!=null) {
ProducedType entryType = unit.getIteratedType(expressionType);
if (entryType!=null) {
ProducedType vt = unit.getValueType(entryType);
if (vt!=null) {
local.setTypeModel(vt);
that.getDeclarationModel().setType(vt);
}
}
}
}
}
private void setType(Tree.LocalModifier local,
Tree.SpecifierOrInitializerExpression s,
Tree.TypedDeclaration that) {
Tree.Expression e = s.getExpression();
if (e!=null) {
ProducedType type = e.getTypeModel();
if (type!=null) {
ProducedType t = unit.denotableType(type).withoutUnderlyingType();
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
}
}
private void setType(Tree.LocalModifier local,
Tree.SpecifierOrInitializerExpression s,
Tree.AttributeArgument that) {
Tree.Expression e = s.getExpression();
if (e!=null) {
ProducedType type = e.getTypeModel();
if (type!=null) {
ProducedType t = unit.denotableType(type).withoutUnderlyingType();
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
}
}
private void setFunctionType(Tree.FunctionModifier local,
ProducedType et, Tree.TypedDeclaration that) {
ProducedType t = unit.denotableType(et).withoutUnderlyingType();
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
private void setFunctionType(Tree.FunctionModifier local,
ProducedType et, Tree.MethodArgument that) {
ProducedType t = unit.denotableType(et).withoutUnderlyingType();
local.setTypeModel(t);
that.getDeclarationModel().setType(t);
}
@Override public void visit(Tree.Throw that) {
super.visit(that);
Tree.Expression e = that.getExpression();
if (e!=null) {
ProducedType et = e.getTypeModel();
if (!isTypeUnknown(et)) {
checkAssignable(et, unit.getType(unit.getThrowableDeclaration()),
e, "thrown expression must be a throwable");
// if (et.getDeclaration().isParameterized()) {
// e.addUnsupportedError("parameterized types in throw not yet supported");
}
}
}
@Override public void visit(Tree.Return that) {
super.visit(that);
if (returnType==null) {
//misplaced return statements are already handled by ControlFlowVisitor
//missing return types declarations already handled by TypeVisitor
//that.addError("could not determine expected return type");
}
else {
that.setDeclaration(returnDeclaration);
Tree.Expression e = that.getExpression();
String name = returnDeclaration.getName();
if (name==null) name = "anonymous function";
if (e==null) {
if (!(returnType instanceof Tree.VoidModifier)) {
that.addError("non-void function or getter must return a value: '" +
name + "' is not a void function");
}
}
else {
ProducedType et = returnType.getTypeModel();
ProducedType at = e.getTypeModel();
if (returnType instanceof Tree.VoidModifier) {
that.addError("void function, setter, or class initializer may not return a value: '" +
name + "' is declared void");
}
else if (returnType instanceof Tree.LocalModifier) {
inferReturnType(et, at);
}
else {
if (!isTypeUnknown(et) && !isTypeUnknown(at)) {
checkAssignable(at, et, e,
"returned expression must be assignable to return type of '" +
name + "'", 2100);
}
}
}
}
}
private void inferReturnType(ProducedType et, ProducedType at) {
if (at!=null) {
at = unit.denotableType(at);
if (et==null || et.isSubtypeOf(at)) {
returnType.setTypeModel(at);
}
else {
if (!at.isSubtypeOf(et)) {
UnionType ut = new UnionType(unit);
List<ProducedType> list = new ArrayList<ProducedType>(2);
addToUnion(list, et);
addToUnion(list, at);
ut.setCaseTypes(list);
returnType.setTypeModel( ut.getType() );
}
}
}
}
ProducedType unwrap(ProducedType pt, Tree.QualifiedMemberOrTypeExpression mte) {
ProducedType result;
Tree.MemberOperator op = mte.getMemberOperator();
Tree.Primary p = mte.getPrimary();
if (op instanceof Tree.SafeMemberOp) {
checkOptional(pt, p, p);
result = unit.getDefiniteType(pt);
}
else if (op instanceof Tree.SpreadOp) {
if (unit.isIterableType(pt)) {
result = unit.getIteratedType(pt);
}
else {
p.addError("expression must be of iterable type: '" +
pt.getProducedTypeName(unit) +
"' is not a subtype of 'Iterable'");
result = pt;
}
}
else {
result = pt;
}
if (result==null) {
result = new UnknownType(mte.getUnit()).getType();
}
return result;
}
ProducedType wrap(ProducedType pt, ProducedType receivingType,
Tree.QualifiedMemberOrTypeExpression mte) {
Tree.MemberOperator op = mte.getMemberOperator();
if (op instanceof Tree.SafeMemberOp) {
return unit.getOptionalType(pt);
}
else if (op instanceof Tree.SpreadOp) {
//note: the following is nice, even though
// it is not actually blessed by the
// language spec!
return unit.isSequenceType(receivingType) ?
unit.getSequenceType(pt) :
unit.getSequentialType(pt);
}
else {
return pt;
}
}
@Override public void visit(Tree.InvocationExpression that) {
Tree.PositionalArgumentList pal = that.getPositionalArgumentList();
if (pal!=null) {
pal.visit(this);
visitInvocationPositionalArgs(that);
}
Tree.NamedArgumentList nal = that.getNamedArgumentList();
if (nal!=null) {
nal.visit(this);
}
Tree.Primary p = that.getPrimary();
if (p==null) {
//TODO: can this actually occur??
that.addError("malformed invocation expression");
}
else {
p.visit(this);
visitInvocationPrimary(that, p);
if (isIndirectInvocation(that)) {
visitIndirectInvocation(that);
}
else {
visitDirectInvocation(that);
}
}
}
private void visitInvocationPositionalArgs(Tree.InvocationExpression that) {
Tree.Primary p = that.getPrimary();
Tree.PositionalArgumentList pal = that.getPositionalArgumentList();
if (p instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) p;
//set up the "signature" on the primary
//so that we can resolve the correct
//overloaded declaration
List<Tree.PositionalArgument> args = pal.getPositionalArguments();
List<ProducedType> sig = new ArrayList<ProducedType>(args.size());
for (Tree.PositionalArgument pa: args) {
sig.add(pa.getTypeModel());
}
mte.setSignature(sig);
mte.setEllipsis(hasSpreadArgument(args));
}
}
private void checkSuperInvocation(Tree.MemberOrTypeExpression qmte) {
Declaration member = qmte.getDeclaration();
if (member!=null) {
if (member.isFormal() && !inExtendsClause) {
qmte.addError("supertype member is declared formal: '" + member.getName() +
"' of '" + ((TypeDeclaration) member.getContainer()).getName() + "'");
}
else {
ClassOrInterface ci = getContainingClassOrInterface(qmte.getScope());
Declaration etm = ci.getExtendedTypeDeclaration()
.getMember(member.getName(), null, false);
if (etm!=null && !etm.equals(member) && etm.refines(member)) {
qmte.addError("inherited member is refined by intervening superclass: '" +
((TypeDeclaration) etm.getContainer()).getName() +
"' refines '" + member.getName() + "' declared by '" +
((TypeDeclaration) member.getContainer()).getName() + "'");
}
for (TypeDeclaration td: ci.getSatisfiedTypeDeclarations()) {
Declaration stm = td.getMember(member.getName(), null, false);
if (stm!=null && !stm.equals(member) && stm.refines(member)) {
qmte.addError("inherited member is refined by intervening superinterface: '" +
((TypeDeclaration) stm.getContainer()).getName() +
"' refines '" + member.getName() + "' declared by '" +
((TypeDeclaration) member.getContainer()).getName() + "'");
}
}
}
}
}
private void visitInvocationPrimary(Tree.InvocationExpression that,
Tree.Primary pr) {
Tree.Term term = Util.unwrapExpressionUntilTerm(pr);
if (term instanceof Tree.StaticMemberOrTypeExpression) {
Tree.StaticMemberOrTypeExpression mte = (Tree.StaticMemberOrTypeExpression) term;
Declaration dec = mte.getDeclaration();
if ( mte.getTarget()==null && dec instanceof Functional &&
mte.getTypeArguments() instanceof Tree.InferredTypeArguments ) {
List<ProducedType> typeArgs = getInferedTypeArguments(that, (Functional) dec);
mte.getTypeArguments().setTypeModels(typeArgs);
if (term instanceof Tree.BaseTypeExpression) {
visitBaseTypeExpression((Tree.BaseTypeExpression) term,
(TypeDeclaration) dec, typeArgs, mte.getTypeArguments());
}
else if (term instanceof Tree.QualifiedTypeExpression) {
Tree.QualifiedTypeExpression qte = (Tree.QualifiedTypeExpression) term;
if (qte.getPrimary() instanceof Tree.Package) {
visitBaseTypeExpression(qte, (TypeDeclaration) dec,
typeArgs, mte.getTypeArguments());
}
else {
visitQualifiedTypeExpression(qte, qte.getPrimary().getTypeModel(),
(TypeDeclaration) dec, typeArgs, mte.getTypeArguments());
}
}
else if (term instanceof Tree.BaseMemberExpression) {
visitBaseMemberExpression((Tree.BaseMemberExpression) term,
(TypedDeclaration) dec, typeArgs, mte.getTypeArguments());
}
else if (term instanceof Tree.QualifiedMemberExpression) {
Tree.QualifiedMemberExpression qme = (Tree.QualifiedMemberExpression) term;
if (qme.getPrimary() instanceof Tree.Package) {
visitBaseMemberExpression(qme, (TypedDeclaration) dec,
typeArgs, mte.getTypeArguments());
}
else {
visitQualifiedMemberExpression(qme, qme.getPrimary().getTypeModel(),
(TypedDeclaration) dec, typeArgs, mte.getTypeArguments());
}
}
}
}
}
private List<ProducedType> getInferedTypeArguments(Tree.InvocationExpression that,
Functional dec) {
List<ProducedType> typeArgs = new ArrayList<ProducedType>();
if (!dec.getParameterLists().isEmpty()) {
ParameterList parameters = dec.getParameterLists().get(0);
for (TypeParameter tp: dec.getTypeParameters()) {
ProducedType it = inferTypeArgument(that,
that.getPrimary().getTypeModel(),
tp, parameters);
if (it.containsUnknowns()) {
that.addError("could not infer type argument from given arguments: type parameter'" +
tp.getName() + "' could not be inferred");
}
else {
it = constrainInferredType(dec, tp, it);
}
typeArgs.add(it);
}
}
return typeArgs;
}
private ProducedType constrainInferredType(Functional dec,
TypeParameter tp, ProducedType ta) {
//Note: according to the language spec we should only
// do this for contravariant parameters, but in
// fact it also helps for special cases like
// emptyOrSingleton(null)
List<ProducedType> list = new ArrayList<ProducedType>();
addToIntersection(list, ta, unit);
//Intersect the inferred type with any
//upper bound constraints on the type.
for (ProducedType st: tp.getSatisfiedTypes()) {
//TODO: substitute in the other inferred type args
// of the invocation
//TODO: st.getProducedType(receiver, dec, typeArgs);
if (!st.containsTypeParameters()) {
addToIntersection(list, st, unit);
}
}
IntersectionType it = new IntersectionType(unit);
it.setSatisfiedTypes(list);
ProducedType type = it.canonicalize().getType();
return type;
}
private ProducedType inferTypeArgument(Tree.InvocationExpression that,
ProducedReference pr, TypeParameter tp, ParameterList parameters) {
List<ProducedType> inferredTypes = new ArrayList<ProducedType>();
if (that.getPositionalArgumentList()!=null) {
inferTypeArgumentFromPositionalArgs(tp, parameters, pr,
that.getPositionalArgumentList(), inferredTypes);
}
else if (that.getNamedArgumentList()!=null) {
inferTypeArgumentFromNamedArgs(tp, parameters, pr,
that.getNamedArgumentList(), inferredTypes);
}
return formUnionOrIntersection(tp, inferredTypes);
}
private void inferTypeArgumentFromNamedArgs(TypeParameter tp, ParameterList parameters,
ProducedReference pr, Tree.NamedArgumentList args,
List<ProducedType> inferredTypes) {
Set<Parameter> foundParameters = new HashSet<Parameter>();
for (Tree.NamedArgument arg: args.getNamedArguments()) {
inferTypeArgFromNamedArg(arg, tp, pr, parameters, inferredTypes,
foundParameters);
}
Parameter sp = getUnspecifiedParameter(null, parameters,
foundParameters);
if (sp!=null) {
Tree.SequencedArgument sa = args.getSequencedArgument();
inferTypeArgFromSequencedArg(sa, tp, sp, inferredTypes);
}
}
private void inferTypeArgFromSequencedArg(Tree.SequencedArgument sa, TypeParameter tp,
Parameter sp, List<ProducedType> inferredTypes) {
ProducedType att;
if (sa==null) {
att = unit.getEmptyDeclaration().getType();
}
else {
List<Tree.PositionalArgument> args = sa.getPositionalArguments();
att = getTupleType(args, false);
}
ProducedType spt = sp.getType();
addToUnionOrIntersection(tp, inferredTypes, inferTypeArg(tp, spt, att,
new ArrayList<TypeParameter>()));
}
private void inferTypeArgFromNamedArg(Tree.NamedArgument arg, TypeParameter tp,
ProducedReference pr, ParameterList parameters,
List<ProducedType> inferredTypes, Set<Parameter> foundParameters) {
ProducedType type = null;
if (arg instanceof Tree.SpecifiedArgument) {
Tree.Expression e = ((Tree.SpecifiedArgument) arg).getSpecifierExpression()
.getExpression();
if (e!=null) {
type = e.getTypeModel();
}
}
else if (arg instanceof Tree.TypedArgument) {
//copy/pasted from checkNamedArgument()
Tree.TypedArgument ta = (Tree.TypedArgument) arg;
type = ta.getDeclarationModel()
.getTypedReference() //argument can't have type parameters
.getFullType();
}
if (type!=null) {
Parameter parameter = getMatchingParameter(parameters, arg, foundParameters);
if (parameter!=null) {
foundParameters.add(parameter);
ProducedType pt = pr.getTypedParameter(parameter)
.getFullType();
// if (parameter.isSequenced()) pt = unit.getIteratedType(pt);
addToUnionOrIntersection(tp,inferredTypes, inferTypeArg(tp, pt, type,
new ArrayList<TypeParameter>()));
}
}
}
private void inferTypeArgumentFromPositionalArgs(TypeParameter tp, ParameterList parameters,
ProducedReference pr, Tree.PositionalArgumentList pal,
List<ProducedType> inferredTypes) {
List<Parameter> params = parameters.getParameters();
for (int i=0; i<params.size(); i++) {
Parameter parameter = params.get(i);
List<Tree.PositionalArgument> args = pal.getPositionalArguments();
if (args.size()>i) {
Tree.PositionalArgument a = args.get(i);
ProducedType at = a.getTypeModel();
if (a instanceof Tree.SpreadArgument) {
at = spreadType(at, unit, true);
ProducedType ptt = unit.getParameterTypesAsTupleType(params.subList(i, params.size()), pr);
addToUnionOrIntersection(tp, inferredTypes, inferTypeArg(tp, ptt, at,
new ArrayList<TypeParameter>()));
}
else if (a instanceof Tree.Comprehension) {
if (parameter.isSequenced()) {
inferTypeArgFromComprehension(tp, parameter, ((Tree.Comprehension) a),
inferredTypes);
}
}
else {
if (parameter.isSequenced()) {
inferTypeArgFromPositionalArgs(tp, parameter, args.subList(i, args.size()),
inferredTypes);
break;
}
else {
ProducedType pt = pr.getTypedParameter(parameter)
.getFullType();
addToUnionOrIntersection(tp, inferredTypes, inferTypeArg(tp, pt, at,
new ArrayList<TypeParameter>()));
}
}
}
}
}
private void inferTypeArgFromPositionalArgs(TypeParameter tp, Parameter parameter,
List<Tree.PositionalArgument> args, List<ProducedType> inferredTypes) {
for (int k=0; k<args.size(); k++) {
Tree.PositionalArgument sa = args.get(k);
ProducedType sat = sa.getTypeModel();
if (sat!=null) {
ProducedType pt = parameter.getType();
if (sa instanceof Tree.SpreadArgument) {
sat = spreadType(sat, unit, true);
addToUnionOrIntersection(tp, inferredTypes, inferTypeArg(tp, pt, sat,
new ArrayList<TypeParameter>()));
}
else {
ProducedType spt = unit.getIteratedType(pt);
addToUnionOrIntersection(tp, inferredTypes, inferTypeArg(tp, spt, sat,
new ArrayList<TypeParameter>()));
}
}
}
}
private void inferTypeArgFromComprehension(TypeParameter tp, Parameter parameter,
Tree.Comprehension c, List<ProducedType> inferredTypes) {
ProducedType sat = c.getTypeModel();
if (sat!=null) {
ProducedType pt = parameter.getType();
ProducedType spt = unit.getIteratedType(pt);
addToUnionOrIntersection(tp, inferredTypes, inferTypeArg(tp, spt, sat,
new ArrayList<TypeParameter>()));
}
}
private ProducedType formUnionOrIntersection(TypeParameter tp,
List<ProducedType> inferredTypes) {
if (tp.isContravariant()) {
return formIntersection(inferredTypes);
}
else {
return formUnion(inferredTypes);
}
}
private ProducedType unionOrIntersection(TypeParameter tp,
List<ProducedType> inferredTypes) {
if (inferredTypes.isEmpty()) {
return null;
}
else {
return formUnionOrIntersection(tp, inferredTypes);
}
}
private void addToUnionOrIntersection(TypeParameter tp, List<ProducedType> list,
ProducedType pt) {
if (tp.isContravariant()) {
addToIntersection(list, pt, unit);
}
else {
addToUnion(list, pt);
}
}
private ProducedType union(List<ProducedType> types) {
if (types.isEmpty()) {
return null;
}
return formUnion(types);
}
private ProducedType intersection(List<ProducedType> types) {
if (types.isEmpty()) {
return null;
}
return formIntersection(types);
}
private ProducedType formUnion(List<ProducedType> types) {
UnionType ut = new UnionType(unit);
ut.setCaseTypes(types);
return ut.getType();
}
private ProducedType formIntersection(List<ProducedType> types) {
IntersectionType it = new IntersectionType(unit);
it.setSatisfiedTypes(types);
return it.canonicalize().getType();
}
private ProducedType inferTypeArg(TypeParameter tp, ProducedType paramType,
ProducedType argType, List<TypeParameter> visited) {
if (paramType!=null && argType!=null) {
paramType = paramType.resolveAliases();
argType = argType.resolveAliases();
if (paramType.getDeclaration() instanceof TypeParameter &&
paramType.getDeclaration().equals(tp)) {
return unit.denotableType(argType);
}
else if (paramType.getDeclaration() instanceof TypeParameter) {
TypeParameter tp2 = (TypeParameter) paramType.getDeclaration();
if (!visited.contains(tp2)) {
visited.add(tp2);
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType pt: tp2.getSatisfiedTypes()) {
addToUnionOrIntersection(tp, list, inferTypeArg(tp, pt, argType, visited));
ProducedType st = argType.getSupertype(pt.getDeclaration());
if (st!=null) {
for (int j=0; j<pt.getTypeArgumentList().size(); j++) {
if (st.getTypeArgumentList().size()>j) {
addToUnionOrIntersection(tp, list, inferTypeArg(tp,
pt.getTypeArgumentList().get(j),
st.getTypeArgumentList().get(j),
visited));
}
}
}
}
return unionOrIntersection(tp, list);
}
else {
return null;
}
}
else if (paramType.getDeclaration() instanceof UnionType) {
List<ProducedType> list = new ArrayList<ProducedType>();
//If there is more than one type parameter in
//the union, ignore this union when inferring
//types.
//TODO: This is all a bit adhoc. The problem is that
// when a parameter type involves a union of type
// parameters, it in theory imposes a compound
// constraint upon the type parameters, but our
// algorithm doesn't know how to deal with compound
// constraints
/*ProducedType typeParamType = null;
boolean found = false;
for (ProducedType ct: paramType.getDeclaration().getCaseTypes()) {
TypeDeclaration ctd = ct.getDeclaration();
if (ctd instanceof TypeParameter) {
typeParamType = ct;
}
if (ct.containsTypeParameters()) { //TODO: check that they are "free" type params
if (found) {
//the parameter type involves two type
//parameters which are being inferred
return null;
}
else {
found = true;
}
}
}*/
ProducedType pt = paramType;
ProducedType apt = argType;
if (argType.getDeclaration() instanceof UnionType) {
for (ProducedType act: argType.getDeclaration().getCaseTypes()) {
//some element of the argument union is already a subtype
//of the parameter union, so throw it away from both unions
if (act.substitute(argType.getTypeArguments()).isSubtypeOf(paramType)) {
pt = pt.shallowMinus(act);
apt = apt.shallowMinus(act);
}
}
}
if (pt.getDeclaration() instanceof UnionType) {
boolean found = false;
for (TypeDeclaration td: pt.getDeclaration().getCaseTypeDeclarations()) {
if (td instanceof TypeParameter) {
if (found) return null;
found = true;
}
}
//just one type parameter left in the union
for (ProducedType ct: pt.getDeclaration().getCaseTypes()) {
addToUnionOrIntersection(tp, list, inferTypeArg(tp,
ct.substitute(pt.getTypeArguments()),
apt, visited));
}
}
else {
addToUnionOrIntersection(tp, list, inferTypeArg(tp,
pt, apt, visited));
}
return unionOrIntersection(tp, list);
/*else {
//if the param type is of form T|A1 and the arg type is
//of form A2|B then constrain T by B and A1 by A2
ProducedType pt = paramType.minus(typeParamType);
addToUnionOrIntersection(tp, list, inferTypeArg(tp,
paramType.minus(pt), argType.minus(pt), visited));
addToUnionOrIntersection(tp, list, inferTypeArg(tp,
paramType.minus(typeParamType), pt, visited));
//return null;
}*/
}
else if (paramType.getDeclaration() instanceof IntersectionType) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType ct: paramType.getDeclaration().getSatisfiedTypes()) {
addToUnionOrIntersection(tp, list, inferTypeArg(tp,
ct.substitute(paramType.getTypeArguments()),
argType, visited));
}
return unionOrIntersection(tp,list);
}
else if (argType.getDeclaration() instanceof UnionType) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType ct: argType.getDeclaration().getCaseTypes()) {
addToUnion(list, inferTypeArg(tp, paramType,
ct.substitute(paramType.getTypeArguments()),
visited));
}
return union(list);
}
else if (argType.getDeclaration() instanceof IntersectionType) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType ct: argType.getDeclaration().getSatisfiedTypes()) {
addToIntersection(list, inferTypeArg(tp, paramType,
ct.substitute(paramType.getTypeArguments()),
visited), unit);
}
return intersection(list);
}
else {
ProducedType st = argType.getSupertype(paramType.getDeclaration());
if (st!=null) {
List<ProducedType> list = new ArrayList<ProducedType>();
if (paramType.getQualifyingType()!=null &&
st.getQualifyingType()!=null) {
addToUnionOrIntersection(tp, list, inferTypeArg(tp,
paramType.getQualifyingType(),
st.getQualifyingType(),
visited));
}
for (int j=0; j<paramType.getTypeArgumentList().size(); j++) {
if (st.getTypeArgumentList().size()>j) {
addToUnionOrIntersection(tp, list, inferTypeArg(tp,
paramType.getTypeArgumentList().get(j),
st.getTypeArgumentList().get(j),
visited));
}
}
return unionOrIntersection(tp, list);
}
else {
return null;
}
}
}
else {
return null;
}
}
private void visitDirectInvocation(Tree.InvocationExpression that) {
Tree.Term p = Util.unwrapExpressionUntilTerm(that.getPrimary());
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) p;
ProducedReference prf = mte.getTarget();
Functional dec = (Functional) mte.getDeclaration();
if (dec==null) return;
if (!(p instanceof Tree.ExtendedTypeExpression)) {
if (dec instanceof Class && ((Class) dec).isAbstract()) {
that.addError("abstract class may not be instantiated: '" +
dec.getName(unit) + "'");
}
}
if (that.getNamedArgumentList()!=null &&
dec.isAbstraction()) {
//TODO: this is not really right - it's the fact
// that we're calling Java and don't have
// meaningful parameter names that is the
// real problem, not the overload
that.addError("overloaded declarations may not be called using named arguments: '" +
dec.getName(unit) + "'");
}
//that.setTypeModel(prf.getType());
ProducedType ct = p.getTypeModel();
if (ct!=null && !ct.getTypeArgumentList().isEmpty()) {
//pull the return type out of the Callable
that.setTypeModel(ct.getTypeArgumentList().get(0));
}
if (that.getNamedArgumentList() != null) {
List<ParameterList> parameterLists = dec.getParameterLists();
if(!parameterLists.isEmpty()
&& !parameterLists.get(0).isNamedParametersSupported()) {
that.addError("named invocations of Java methods not supported");
}
}
if (dec.isAbstraction()) {
//nothing to check the argument types against
//that.addError("no matching overloaded declaration");
}
else {
//typecheck arguments using the parameter list
//of the target declaration
checkInvocationArguments(that, prf, dec);
}
}
private void visitIndirectInvocation(Tree.InvocationExpression that) {
if (that.getNamedArgumentList()!=null) {
that.addError("named arguments not supported for indirect invocations");
}
Tree.PositionalArgumentList pal = that.getPositionalArgumentList();
if (pal==null) {
return;
}
Tree.Primary p = that.getPrimary();
ProducedType pt = p.getTypeModel();
if (!isTypeUnknown(pt)) {
if (checkCallable(pt, p, "invoked expression must be callable")) {
List<ProducedType> typeArgs = pt.getSupertype(unit.getCallableDeclaration())
.getTypeArgumentList();
if (!typeArgs.isEmpty()) {
that.setTypeModel(typeArgs.get(0));
}
//typecheck arguments using the type args of Callable
if (typeArgs.size()>=2) {
ProducedType paramTypesAsTuple = typeArgs.get(1);
if (paramTypesAsTuple!=null) {
TypeDeclaration pttd = paramTypesAsTuple.getDeclaration();
if (pttd instanceof ClassOrInterface &&
(pttd.equals(unit.getTupleDeclaration()) ||
pttd.equals(unit.getSequenceDeclaration()) ||
pttd.equals(unit.getSequentialDeclaration()) ||
pttd.equals(unit.getEmptyDeclaration()))) {
//we have a plain tuple type so we can check the
//arguments individually
checkIndirectInvocationArguments(that, paramTypesAsTuple,
unit.getTupleElementTypes(paramTypesAsTuple),
unit.isTupleLengthUnbounded(paramTypesAsTuple),
unit.isTupleVariantAtLeastOne(paramTypesAsTuple),
unit.getTupleMinimumLength(paramTypesAsTuple));
}
else {
//we have something exotic, a union of tuple types
//or whatever, so just check the whole argument tuple
checkAssignable(getTupleType(pal.getPositionalArguments(), false),
paramTypesAsTuple, pal,
"argument list type must be assignable to parameter list type");
}
}
}
}
}
}
private void checkInvocationArguments(Tree.InvocationExpression that,
ProducedReference prf, Functional dec) {
List<ParameterList> pls = dec.getParameterLists();
if (pls.isEmpty()) {
if (dec instanceof TypeDeclaration) {
that.addError("type has no parameter list: '" +
dec.getName(unit) + "'");
}
else {
that.addError("function has no parameter list: '" +
dec.getName(unit) + "'");
}
}
else /*if (!dec.isOverloaded())*/ {
ParameterList pl = pls.get(0);
Tree.PositionalArgumentList args = that.getPositionalArgumentList();
if (args!=null) {
checkPositionalArguments(pl, prf, args, that);
}
Tree.NamedArgumentList namedArgs = that.getNamedArgumentList();
if (namedArgs!=null) {
if (pl.isNamedParametersSupported()) {
namedArgs.getNamedArgumentList().setParameterList(pl);
checkNamedArguments(pl, prf, namedArgs);
}
}
}
}
/*private void checkSpreadArgumentSequential(Tree.SpreadArgument arg,
ProducedType argTuple) {
if (!unit.isSequentialType(argTuple)) {
arg.addError("spread argument expression is not sequential: " +
argTuple.getProducedTypeName(unit) + " is not a sequence type");
}
}*/
private void checkNamedArguments(ParameterList pl, ProducedReference pr,
Tree.NamedArgumentList nal) {
List<Tree.NamedArgument> na = nal.getNamedArguments();
Set<Parameter> foundParameters = new HashSet<Parameter>();
for (Tree.NamedArgument a: na) {
checkNamedArg(a, pl, pr, foundParameters);
}
Tree.SequencedArgument sa = nal.getSequencedArgument();
if (sa!=null) {
checkSequencedArg(sa, pl, pr, foundParameters);
}
else {
Parameter sp = getUnspecifiedParameter(pr, pl, foundParameters);
if (sp!=null && !unit.isNonemptyIterableType(sp.getType())) {
foundParameters.add(sp);
}
}
for (Parameter p: pl.getParameters()) {
if (!foundParameters.contains(p) &&
!p.isDefaulted() && (!p.isSequenced() || p.isAtLeastOne())) {
nal.addError("missing named argument to parameter '" +
p.getName() + "' of '" + pr.getDeclaration().getName(unit) + "'");
}
}
}
private void checkSequencedArg(Tree.SequencedArgument sa, ParameterList pl,
ProducedReference pr, Set<Parameter> foundParameters) {
Parameter sp = getUnspecifiedParameter(pr, pl, foundParameters);
if (sp==null) {
sa.addError("all iterable parameters specified by named argument list: '" +
pr.getDeclaration().getName(unit) +
"' does not declare any additional parameters of type 'Iterable'");
}
else {
if (!foundParameters.add(sp)) {
sa.addError("duplicate argument for parameter: '" +
sp + "' of '" + pr.getDeclaration().getName(unit) + "'");
}
else if (!dynamic && isTypeUnknown(sp.getType())) {
sa.addError("parameter type could not be determined: '" +
sp.getName() + "' of '" + sp.getDeclaration().getName(unit) + "'");
}
checkSequencedArgument(sa, pr, sp);
}
}
private void checkNamedArg(Tree.NamedArgument a, ParameterList pl,
ProducedReference pr, Set<Parameter> foundParameters) {
Parameter p = getMatchingParameter(pl, a, foundParameters);
if (p==null) {
if (a.getIdentifier()==null) {
a.addError("all parameters specified by named argument list: '" +
pr.getDeclaration().getName(unit) +
"' does not declare any additional parameters");
}
else {
a.addError("no matching parameter for named argument '" +
name(a.getIdentifier()) + "' declared by '" +
pr.getDeclaration().getName(unit) + "'", 101);
}
}
else {
if (!foundParameters.add(p)) {
a.addError("duplicate argument for parameter: '" +
p + "' of '" + pr.getDeclaration().getName(unit) + "'");
}
else if (!dynamic && isTypeUnknown(p.getType())) {
a.addError("parameter type could not be determined: '" +
p.getName() + "' of '" + p.getDeclaration().getName(unit) + "'");
}
checkNamedArgument(a, pr, p);
}
}
private void checkNamedArgument(Tree.NamedArgument a, ProducedReference pr,
Parameter p) {
a.setParameter(p);
ProducedType argType = null;
if (a instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument sa = (Tree.SpecifiedArgument) a;
Tree.Expression e = sa.getSpecifierExpression().getExpression();
if (e!=null) {
argType = e.getTypeModel();
}
}
else if (a instanceof Tree.TypedArgument) {
Tree.TypedArgument ta = (Tree.TypedArgument) a;
argType = ta.getDeclarationModel()
.getTypedReference() //argument can't have type parameters
.getFullType();
checkArgumentToVoidParameter(p, ta);
}
ProducedType pt = pr.getTypedParameter(p).getFullType();
// if (p.isSequenced()) pt = unit.getIteratedType(pt);
if (!isTypeUnknown(argType) && !isTypeUnknown(pt)) {
Node node;
if (a instanceof Tree.SpecifiedArgument) {
node = ((Tree.SpecifiedArgument) a).getSpecifierExpression();
}
else {
node = a;
}
checkAssignable(argType, pt, node,
"named argument must be assignable to parameter " +
p.getName() + " of " + pr.getDeclaration().getName(unit) +
(pr.getQualifyingType()==null ? "" :
" in '" + pr.getQualifyingType().getProducedTypeName(unit)) + "'",
2100);
}
}
private void checkArgumentToVoidParameter(Parameter p, Tree.TypedArgument ta) {
if (ta instanceof Tree.MethodArgument) {
Tree.MethodArgument ma = (Tree.MethodArgument) ta;
Tree.SpecifierExpression se = ma.getSpecifierExpression();
if (se!=null && se.getExpression()!=null) {
Tree.Type t = ta.getType();
// if the argument is explicitly declared
// using the function modifier, it should
// be allowed, even if the parameter is
// declared void
//TODO: what is a better way to check that
// this is really the "shortcut" form
if (t instanceof Tree.FunctionModifier &&
t.getToken()==null &&
p.isDeclaredVoid() &&
!isSatementExpression(se.getExpression())) {
ta.addError("functional parameter is declared void so argument may not evaluate to a value: '" +
p.getName() + "'");
}
}
}
}
private void checkSequencedArgument(Tree.SequencedArgument sa, ProducedReference pr,
Parameter p) {
sa.setParameter(p);
List<Tree.PositionalArgument> args = sa.getPositionalArguments();
ProducedType paramType = pr.getTypedParameter(p).getFullType();
ProducedType att = getTupleType(args, false)
.getSupertype(unit.getIterableDeclaration());
if (!isTypeUnknown(att) && !isTypeUnknown(paramType)) {
checkAssignable(att, paramType, sa,
"iterable arguments must be assignable to iterable parameter " +
p.getName() + " of " + pr.getDeclaration().getName(unit) +
(pr.getQualifyingType()==null ? "" :
" in '" + pr.getQualifyingType().getProducedTypeName(unit)) + "'");
}
}
private Parameter getMatchingParameter(ParameterList pl, Tree.NamedArgument na,
Set<Parameter> foundParameters) {
String name = name(na.getIdentifier());
if (MISSING_NAME.equals(name)) {
for (Parameter p: pl.getParameters()) {
if (!foundParameters.contains(p)) {
Tree.Identifier node = new Tree.Identifier(null);
node.setScope(na.getScope());
node.setUnit(na.getUnit());
node.setText(p.getName());
na.setIdentifier(node);
return p;
}
}
}
else {
for (Parameter p: pl.getParameters()) {
if (p.getName()!=null &&
p.getName().equals(name)) {
return p;
}
}
}
return null;
}
private Parameter getUnspecifiedParameter(ProducedReference pr,
ParameterList pl, Set<Parameter> foundParameters) {
for (Parameter p: pl.getParameters()) {
ProducedType t = pr==null ?
p.getType() :
pr.getTypedParameter(p).getFullType();
if (t!=null) {
t = t.resolveAliases();
if (!foundParameters.contains(p) &&
unit.isIterableParameterType(t)) {
return p;
}
}
}
return null;
}
private void checkPositionalArguments(ParameterList pl, ProducedReference pr,
Tree.PositionalArgumentList pal, Tree.InvocationExpression that) {
List<Tree.PositionalArgument> args = pal.getPositionalArguments();
List<Parameter> params = pl.getParameters();
for (int i=0; i<params.size(); i++) {
Parameter p = params.get(i);
if (i>=args.size()) {
if (!p.isDefaulted() && (!p.isSequenced() || p.isAtLeastOne())) {
Node n = that instanceof Tree.Annotation && args.isEmpty() ? that : pal;
n.addError("missing argument to required parameter '" +
p.getName() + "' of '" + pr.getDeclaration().getName(unit) + "'");
}
}
else {
Tree.PositionalArgument a = args.get(i);
if (!dynamic && isTypeUnknown(p.getType())) {
a.addError("parameter type could not be determined: '" +
p.getName() + "' of '" + p.getDeclaration().getName(unit) + "'");
}
if (a instanceof Tree.SpreadArgument) {
checkSpreadArgument(pr, p, a,
(Tree.SpreadArgument) a,
params.subList(i, params.size()));
break;
}
else if (a instanceof Tree.Comprehension) {
if (p.isSequenced()) {
checkComprehensionPositionalArgument(p, pr,
(Tree.Comprehension) a, p.isAtLeastOne());
}
else {
a.addError("not a variadic parameter: parameter '" +
p.getName() + "' of '" + pr.getDeclaration().getName() + "'");
}
break;
}
else {
if (p.isSequenced()) {
checkSequencedPositionalArgument(p, pr,
args.subList(i, args.size()));
return; //Note: early return!
}
else {
checkPositionalArgument(p, pr, (Tree.ListedArgument) a);
}
}
}
}
for (int i=params.size(); i<args.size(); i++) {
Tree.PositionalArgument arg = args.get(i);
if (arg instanceof Tree.SpreadArgument) {
if (unit.isEmptyType(arg.getTypeModel())) {
continue;
}
}
arg.addError("no matching parameter declared by '" +
pr.getDeclaration().getName(unit) + "': '" +
pr.getDeclaration().getName(unit) + "' has " +
params.size() + " parameters", 2000);
}
}
private void checkSpreadArgument(ProducedReference pr, Parameter p,
Tree.PositionalArgument a, Tree.SpreadArgument arg,
List<Parameter> psl) {
a.setParameter(p);
ProducedType rat = arg.getTypeModel();
if (!isTypeUnknown(rat)) {
if (!unit.isIterableType(rat)) {
//note: check already done by visit(SpreadArgument)
/*arg.addError("spread argument is not iterable: " +
rat.getProducedTypeName(unit) +
" is not a subtype of Iterable");*/
}
else {
ProducedType at = spreadType(rat, unit, true);
//checkSpreadArgumentSequential(arg, at);
ProducedType ptt = unit.getParameterTypesAsTupleType(psl, pr);
if (!isTypeUnknown(at) && !isTypeUnknown(ptt)) {
checkAssignable(at, ptt, arg,
"spread argument not assignable to parameter types");
}
}
}
}
private void checkIndirectInvocationArguments(Tree.InvocationExpression that,
ProducedType paramTypesAsTuple, List<ProducedType> paramTypes,
boolean sequenced, boolean atLeastOne, int firstDefaulted) {
Tree.PositionalArgumentList pal = that.getPositionalArgumentList();
List<Tree.PositionalArgument> args = pal.getPositionalArguments();
for (int i=0; i<paramTypes.size(); i++) {
if (isTypeUnknown(paramTypes.get(i))) {
that.addError("parameter types cannot be determined from function reference");
return;
}
}
for (int i=0; i<paramTypes.size(); i++) {
if (i>=args.size()) {
if (i<firstDefaulted && (!sequenced || atLeastOne || i!=paramTypes.size()-1)) {
pal.addError("missing argument for required parameter " + i);
}
}
else {
Tree.PositionalArgument arg = args.get(i);
ProducedType at = arg.getTypeModel();
if (arg instanceof Tree.SpreadArgument) {
int fd = firstDefaulted<0?-1:firstDefaulted<i?0:firstDefaulted-i;
checkSpreadIndirectArgument((Tree.SpreadArgument) arg,
paramTypes.subList(i, paramTypes.size()),
sequenced, atLeastOne, fd, at);
break;
}
else if (arg instanceof Tree.Comprehension) {
ProducedType paramType = paramTypes.get(i);
if (sequenced && i==paramTypes.size()-1) {
checkComprehensionIndirectArgument((Tree.Comprehension) arg,
paramType, atLeastOne);
}
else {
arg.addError("not a variadic parameter: parameter " + i);
}
break;
}
else {
ProducedType paramType = paramTypes.get(i);
if (sequenced && i==paramTypes.size()-1) {
checkSequencedIndirectArgument(args.subList(i, args.size()),
paramType);
return; //Note: early return!
}
else if (at!=null && paramType!=null &&
!isTypeUnknown(at) && !isTypeUnknown(paramType)) {
checkAssignable(at, paramType, arg,
"argument must be assignable to parameter type");
}
}
}
}
for (int i=paramTypes.size(); i<args.size(); i++) {
Tree.PositionalArgument arg = args.get(i);
if (arg instanceof Tree.SpreadArgument) {
if (unit.isEmptyType(arg.getTypeModel())) {
continue;
}
}
arg.addError("no matching parameter: function reference has " +
paramTypes.size() + " parameters", 2000);
}
}
private void checkSpreadIndirectArgument(Tree.SpreadArgument sa,
List<ProducedType> psl, boolean sequenced,
boolean atLeastOne, int firstDefaulted, ProducedType at) {
//checkSpreadArgumentSequential(sa, at);
if (!isTypeUnknown(at)) {
if (!unit.isIterableType(at)) {
//note: check already done by visit(SpreadArgument)
/*sa.addError("spread argument is not iterable: " +
at.getProducedTypeName(unit) +
" is not a subtype of Iterable");*/
}
else {
ProducedType sat = spreadType(at, unit, true);
//TODO: this ultimately repackages the parameter
// information as a tuple - it would be
// better to just truncate the original
// tuple type we started with
List<ProducedType> pts = new ArrayList<ProducedType>(psl);
if (sequenced) {
pts.set(pts.size()-1,
unit.getIteratedType(pts.get(pts.size()-1)));
}
ProducedType ptt = unit.getTupleType(pts, sequenced, atLeastOne,
firstDefaulted);
if (!isTypeUnknown(sat) && !isTypeUnknown(ptt)) {
checkAssignable(sat, ptt, sa,
"spread argument not assignable to parameter types");
}
}
}
}
private void checkSequencedIndirectArgument(List<Tree.PositionalArgument> args,
ProducedType paramType) {
ProducedType set = paramType==null ? null : unit.getIteratedType(paramType);
for (int j=0; j<args.size(); j++) {
Tree.PositionalArgument a = args.get(j);
ProducedType at = a.getTypeModel();
if (!isTypeUnknown(at) && !isTypeUnknown(paramType)) {
if (a instanceof Tree.SpreadArgument) {
at = spreadType(at, unit, true);
checkAssignable(at, paramType, a,
"spread argument must be assignable to variadic parameter",
2101);
}
else {
checkAssignable(at, set, a,
"argument must be assignable to variadic parameter",
2101);
//if we already have an arg to a nonempty variadic parameter,
//we can treat it like a possibly-empty variadic now
paramType = paramType.getSupertype(unit.getSequentialDeclaration());
}
}
}
}
private void checkComprehensionIndirectArgument(Tree.Comprehension c,
ProducedType paramType, boolean atLeastOne) {
Tree.InitialComprehensionClause icc = ((Tree.Comprehension) c).getInitialComprehensionClause();
if (icc.getPossiblyEmpty() && atLeastOne) {
c.addError("variadic parameter is required but comprehension is possibly empty");
}
ProducedType at = c.getTypeModel();
ProducedType set = paramType==null ? null : unit.getIteratedType(paramType);
if (!isTypeUnknown(at) && !isTypeUnknown(set)) {
checkAssignable(at, set, c,
"argument must be assignable to variadic parameter");
}
}
private void checkSequencedPositionalArgument(Parameter p, ProducedReference pr,
List<Tree.PositionalArgument> args) {
ProducedType paramType = pr.getTypedParameter(p).getFullType();
ProducedType set = paramType==null ? null : unit.getIteratedType(paramType);
for (int j=0; j<args.size(); j++) {
Tree.PositionalArgument a = args.get(j);
a.setParameter(p);
ProducedType at = a.getTypeModel();
if (!isTypeUnknown(at) && !isTypeUnknown(paramType)) {
if (a instanceof Tree.SpreadArgument) {
at = spreadType(at, unit, true);
checkAssignable(at, paramType, a,
"spread argument must be assignable to variadic parameter " +
p.getName()+ " of " + pr.getDeclaration().getName(unit) +
(pr.getQualifyingType()==null ? "" :
" in '" + pr.getQualifyingType().getProducedTypeName(unit)) + "'",
2101);
}
else {
checkAssignable(at, set, a,
"argument must be assignable to variadic parameter " +
p.getName()+ " of " + pr.getDeclaration().getName(unit) +
(pr.getQualifyingType()==null ? "" :
" in '" + pr.getQualifyingType().getProducedTypeName(unit)) + "'",
2101);
//if we already have an arg to a nonempty variadic parameter,
//we can treat it like a possibly-empty variadic now
paramType = paramType.getSupertype(unit.getSequentialDeclaration());
}
}
}
}
private void checkComprehensionPositionalArgument(Parameter p, ProducedReference pr,
Tree.Comprehension c, boolean atLeastOne) {
Tree.InitialComprehensionClause icc = ((Tree.Comprehension) c).getInitialComprehensionClause();
if (icc.getPossiblyEmpty() && atLeastOne) {
c.addError("variadic parameter is required but comprehension is possibly empty");
}
ProducedType paramType = pr.getTypedParameter(p).getFullType();
c.setParameter(p);
ProducedType at = c.getTypeModel();
if (!isTypeUnknown(at) && !isTypeUnknown(paramType)) {
ProducedType set = paramType==null ? null : unit.getIteratedType(paramType);
checkAssignable(at, set, c,
"argument must be assignable to variadic parameter '" +
p.getName() + "' of '" + pr.getDeclaration().getName(unit) +
(pr.getQualifyingType()==null ? "'" :
"' in '" + pr.getQualifyingType().getProducedTypeName(unit)) + "'",
2101);
}
}
private boolean hasSpreadArgument(List<Tree.PositionalArgument> args) {
int size = args.size();
if (size>0) {
return args.get(size-1) instanceof Tree.SpreadArgument;
}
else {
return false;
}
}
private void checkPositionalArgument(Parameter p, ProducedReference pr,
Tree.ListedArgument a) {
ProducedType paramType = pr.getTypedParameter(p).getFullType();
a.setParameter(p);
ProducedType at = a.getTypeModel();
if (!isTypeUnknown(at) && !isTypeUnknown(paramType)) {
checkAssignable(at, paramType, a,
"argument must be assignable to parameter '" +
p.getName() + "' of '" + pr.getDeclaration().getName(unit) +
(pr.getQualifyingType()==null ? "'" :
"' in '" + pr.getQualifyingType().getProducedTypeName(unit)) + "'",
2100);
}
}
@Override public void visit(Tree.Comprehension that) {
super.visit(that);
that.setTypeModel(that.getInitialComprehensionClause().getTypeModel());
}
@Override public void visit(Tree.SpreadArgument that) {
super.visit(that);
Tree.Expression e = that.getExpression();
if (e!=null) {
ProducedType t = e.getTypeModel();
if (t!=null) {
if (!isTypeUnknown(t)) {
if (!unit.isIterableType(t)) {
e.addError("spread argument is not iterable: '" +
t.getProducedTypeName(unit) +
"' is not a subtype of 'Iterable'");
}
}
that.setTypeModel(t);
}
}
}
@Override public void visit(Tree.ListedArgument that) {
super.visit(that);
if (that.getExpression()!=null) {
that.setTypeModel(that.getExpression().getTypeModel());
}
}
private boolean involvesUnknownTypes(Tree.ElementOrRange eor) {
if (eor instanceof Tree.Element) {
return isTypeUnknown(((Tree.Element) eor).getExpression().getTypeModel());
}
else {
Tree.ElementRange er = (Tree.ElementRange) eor;
return er.getLowerBound()!=null && isTypeUnknown(er.getLowerBound().getTypeModel()) ||
er.getUpperBound()!=null && isTypeUnknown(er.getUpperBound().getTypeModel());
}
}
@Override public void visit(Tree.IndexExpression that) {
super.visit(that);
ProducedType pt = type(that);
if (pt==null) {
that.addError("could not determine type of receiver");
}
else {
/*if (that.getIndexOperator() instanceof Tree.SafeIndexOp) {
if (unit.isOptionalType(pt)) {
pt = unit.getDefiniteType(pt);
}
else {
that.getPrimary().addError("receiving type not of optional type: " +
pt.getDeclaration().getName(unit) + " is not a subtype of Optional");
}
}*/
if (that.getElementOrRange()==null) {
that.addError("malformed index expression");
}
else if (!isTypeUnknown(pt) &&
!involvesUnknownTypes(that.getElementOrRange())) {
if (that.getElementOrRange() instanceof Tree.Element) {
ProducedType cst = pt.getSupertype(unit.getCorrespondenceDeclaration());
if (cst==null) {
that.getPrimary().addError("illegal receiving type for index expression: '" +
pt.getDeclaration().getName(unit) + "' is not a subtype of 'Correspondence'");
}
else {
List<ProducedType> args = cst.getTypeArgumentList();
ProducedType kt = args.get(0);
ProducedType vt = args.get(1);
Tree.Element e = (Tree.Element) that.getElementOrRange();
checkAssignable(e.getExpression().getTypeModel(), kt,
e.getExpression(),
"index must be assignable to key type");
ProducedType rt = unit.getOptionalType(vt);
that.setTypeModel(rt);
Tree.Term t = e.getExpression().getTerm();
//TODO: in theory we could do a whole lot
// more static-execution of the
// expression, but this seems
// perfectly sufficient
refineTypeForTupleElement(that, pt, t);
}
}
else {
ProducedType rst = pt.getSupertype(unit.getRangedDeclaration());
if (rst==null) {
that.getPrimary().addError("illegal receiving type for index range expression: '" +
pt.getDeclaration().getName(unit) + "' is not a subtype of 'Ranged'");
}
else {
List<ProducedType> args = rst.getTypeArgumentList();
ProducedType kt = args.get(0);
ProducedType rt = args.get(2);
Tree.ElementRange er = (Tree.ElementRange) that.getElementOrRange();
if (er.getLowerBound()!=null) {
checkAssignable(er.getLowerBound().getTypeModel(), kt,
er.getLowerBound(),
"lower bound must be assignable to index type");
}
if (er.getUpperBound()!=null) {
checkAssignable(er.getUpperBound().getTypeModel(), kt,
er.getUpperBound(),
"upper bound must be assignable to index type");
}
if (er.getLength()!=null) {
checkAssignable(er.getLength().getTypeModel(),
unit.getType(unit.getIntegerDeclaration()),
er.getLength(),
"length must be an integer");
}
that.setTypeModel(rt);
// if (er.getLowerBound()!=null && er.getUpperBound()!=null) {
// refineTypeForTupleRange(that, pt,
// er.getLowerBound().getTerm(),
// er.getUpperBound().getTerm());
// else if (er.getLowerBound()!=null) {
if (er.getLowerBound()!=null &&
er.getUpperBound()==null &&
er.getLength()==null) {
refineTypeForTupleOpenRange(that, pt,
er.getLowerBound().getTerm());
}
/*if (that.getIndexOperator() instanceof Tree.SafeIndexOp) {
that.setTypeModel(unit.getOptionalType(that.getTypeModel()));
}*/
}
}
}
}
}
private void refineTypeForTupleElement(Tree.IndexExpression that,
ProducedType pt, Tree.Term t) {
boolean negated = false;
if (t instanceof Tree.NegativeOp) {
t = ((Tree.NegativeOp) t).getTerm();
negated = true;
}
else if (t instanceof Tree.PositiveOp) {
t = ((Tree.PositiveOp) t).getTerm();
}
ProducedType tt = pt;
if (unit.isSequentialType(tt)) {
if (t instanceof Tree.NaturalLiteral) {
int index = Integer.parseInt(t.getText());
if (negated) index = -index;
List<ProducedType> elementTypes = unit.getTupleElementTypes(tt);
boolean variadic = unit.isTupleLengthUnbounded(tt);
int minimumLength = unit.getTupleMinimumLength(tt);
boolean atLeastOne = unit.isTupleVariantAtLeastOne(tt);
if (elementTypes!=null) {
if (elementTypes.isEmpty()) {
that.setTypeModel(unit.getType(unit.getNullDeclaration()));
}
else if (index<0) {
that.setTypeModel(unit.getType(unit.getNullDeclaration()));
}
else if (index<elementTypes.size()-(variadic?1:0)) {
ProducedType iet = elementTypes.get(index);
if (iet==null) return;
if (index>=minimumLength) {
iet = unionType(iet,
unit.getType(unit.getNullDeclaration()),
unit);
}
that.setTypeModel(iet);
}
else if (variadic) {
ProducedType iet = elementTypes.get(elementTypes.size()-1);
if (iet==null) return;
ProducedType it = unit.getIteratedType(iet);
if (it==null) return;
if (!atLeastOne || index>=elementTypes.size()) {
it = unionType(it,
unit.getType(unit.getNullDeclaration()),
unit);
}
that.setTypeModel(it);
}
else {
that.setTypeModel(unit.getType(unit.getNullDeclaration()));
}
}
}
}
}
private void refineTypeForTupleOpenRange(Tree.IndexExpression that,
ProducedType pt, Tree.Term l) {
boolean lnegated = false;
if (l instanceof Tree.NegativeOp) {
l = ((Tree.NegativeOp) l).getTerm();
lnegated = true;
}
else if (l instanceof Tree.PositiveOp) {
l = ((Tree.PositiveOp) l).getTerm();
}
ProducedType tt = pt;
if (unit.isSequentialType(tt)) {
if (l instanceof Tree.NaturalLiteral) {
int lindex = Integer.parseInt(l.getText());
if (lnegated) lindex = -lindex;
List<ProducedType> elementTypes = unit.getTupleElementTypes(tt);
boolean variadic = unit.isTupleLengthUnbounded(tt);
boolean atLeastOne = unit.isTupleVariantAtLeastOne(tt);
int minimumLength = unit.getTupleMinimumLength(tt);
List<ProducedType> list = new ArrayList<ProducedType>();
if (elementTypes!=null) {
if (lindex<0) {
lindex=0;
}
for (int index=lindex;
index<elementTypes.size()-(variadic?1:0);
index++) {
ProducedType et = elementTypes.get(index);
if (et==null) return;
list.add(et);
}
if (variadic) {
ProducedType it = elementTypes.get(elementTypes.size()-1);
if (it==null) return;
ProducedType rt = unit.getIteratedType(it);
if (rt==null) return;
list.add(rt);
}
ProducedType rt = unit.getTupleType(list, variadic,
atLeastOne && lindex<elementTypes.size(),
minimumLength-lindex);
//intersect with the type determined using
//Ranged, which may be narrower, for example,
//for String
that.setTypeModel(intersectionType(rt,
that.getTypeModel(), unit));
}
}
}
}
private ProducedType type(Tree.PostfixExpression that) {
Tree.Primary p = that.getPrimary();
return p==null ? null : p.getTypeModel();
}
private void assign(Tree.Term term) {
if (term instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression m =
(Tree.MemberOrTypeExpression) term;
m.setAssigned(true);
}
}
@Override public void visit(Tree.PostfixOperatorExpression that) {
assign(that.getTerm());
super.visit(that);
ProducedType type = type(that);
visitIncrementDecrement(that, type, that.getTerm());
checkAssignability(that.getTerm(), that);
}
@Override public void visit(Tree.PrefixOperatorExpression that) {
assign(that.getTerm());
super.visit(that);
ProducedType type = type(that);
if (that.getTerm()!=null) {
visitIncrementDecrement(that, type, that.getTerm());
checkAssignability(that.getTerm(), that);
}
}
private void visitIncrementDecrement(Tree.Term that,
ProducedType pt, Tree.Term term) {
if (!isTypeUnknown(pt)) {
ProducedType ot = checkSupertype(pt, unit.getOrdinalDeclaration(),
term, "operand expression must be of enumerable type");
if (ot!=null) {
ProducedType ta = ot.getTypeArgumentList().get(0);
checkAssignable(ta, pt, that,
"result type must be assignable to declared type");
}
that.setTypeModel(pt);
}
}
/*@Override public void visit(Tree.SumOp that) {
super.visit( (Tree.BinaryOperatorExpression) that );
ProducedType lhst = leftType(that);
if (lhst!=null) {
//take into account overloading of + operator
if (lhst.isSubtypeOf(getStringDeclaration().getType())) {
visitBinaryOperator(that, getStringDeclaration());
}
else {
visitBinaryOperator(that, getNumericDeclaration());
}
}
}*/
private void visitScaleOperator(Tree.ScaleOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
TypeDeclaration sd = unit.getScalableDeclaration();
ProducedType st = checkSupertype(rhst, sd, that,
"right operand must be of scalable type");
if (st!=null) {
ProducedType ta = st.getTypeArgumentList().get(0);
ProducedType rt = st.getTypeArgumentList().get(1);
//hardcoded implicit type conversion Integer->Float
TypeDeclaration fd = unit.getFloatDeclaration();
TypeDeclaration id = unit.getIntegerDeclaration();
if (lhst.getDeclaration().inherits(id) &&
ta.getDeclaration().inherits(fd)) {
lhst = fd.getType();
}
checkAssignable(lhst, ta, that,
"scale factor must be assignable to scale type");
that.setTypeModel(rt);
}
}
}
private void checkComparable(Tree.BinaryOperatorExpression that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
checkOperandTypes(lhst, rhst, unit.getComparableDeclaration(), that,
"operand expressions must be comparable");
}
}
private void visitComparisonOperator(Tree.BinaryOperatorExpression that) {
checkComparable(that);
that.setTypeModel( unit.getType(unit.getBooleanDeclaration()) );
}
private void visitCompareOperator(Tree.CompareOp that) {
checkComparable(that);
that.setTypeModel( unit.getType(unit.getComparisonDeclaration()) );
}
private void visitWithinOperator(Tree.WithinOp that) {
Tree.Term lbt = that.getLowerBound().getTerm();
Tree.Term ubt = that.getUpperBound().getTerm();
ProducedType lhst = lbt==null ? null : lbt.getTypeModel();
ProducedType rhst = ubt==null ? null : ubt.getTypeModel();
ProducedType t = that.getTerm().getTypeModel();
if (!isTypeUnknown(t) &&
!isTypeUnknown(lhst) && !isTypeUnknown(rhst)) {
checkOperandTypes(t, lhst, rhst, unit.getComparableDeclaration(),
that, "operand expressions must be comparable");
}
that.setTypeModel( unit.getType(unit.getBooleanDeclaration()) );
}
private void visitSpanOperator(Tree.RangeOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
ProducedType ot = checkOperandTypes(lhst, rhst,
unit.getEnumerableDeclaration(), that,
"operand expressions must be of compatible enumerable type");
if (ot!=null) {
that.setTypeModel(unit.getSpanType(ot));
}
}
private void visitMeasureOperator(Tree.SegmentOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
ProducedType ot = checkSupertype(lhst, unit.getEnumerableDeclaration(),
that.getLeftTerm(), "left operand must be of enumerable type");
if (!isTypeUnknown(rhst)) {
checkAssignable(rhst, unit.getType(unit.getIntegerDeclaration()),
that.getRightTerm(), "right operand must be an integer");
}
if (ot!=null) {
ProducedType ta = ot.getTypeArgumentList().get(0);
that.setTypeModel(unit.getMeasureType(ta));
}
}
private void visitEntryOperator(Tree.EntryOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
ProducedType ot = unit.getType(unit.getObjectDeclaration());
checkAssignable(lhst, ot, that.getLeftTerm(),
"operand expression must not be an optional type");
checkAssignable(rhst, ot, that.getRightTerm(),
"operand expression must not be an optional type");
that.setTypeModel( unit.getEntryType(unit.denotableType(lhst),
unit.denotableType(rhst)) );
}
private void visitIdentityOperator(Tree.BinaryOperatorExpression that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
TypeDeclaration id = unit.getIdentifiableDeclaration();
checkAssignable(lhst, id.getType(), that.getLeftTerm(),
"operand expression must be of type 'Identifiable'");
checkAssignable(rhst, id.getType(), that.getRightTerm(),
"operand expression must be of type 'Identifiable'");
if (intersectionType(lhst, rhst, unit).isNothing()) {
that.addError("values of disjoint types are never identical: '" +
lhst.getProducedTypeName(unit) +
"' has empty intersection with '" +
rhst.getProducedTypeName(unit) + "'");
}
}
that.setTypeModel(unit.getType(unit.getBooleanDeclaration()));
}
private void visitEqualityOperator(Tree.BinaryOperatorExpression that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
TypeDeclaration od = unit.getObjectDeclaration();
checkAssignable(lhst, od.getType(), that.getLeftTerm(),
"operand expression must be of type Object");
checkAssignable(rhst, od.getType(), that.getRightTerm(),
"operand expression must be of type Object");
}
that.setTypeModel(unit.getType(unit.getBooleanDeclaration()));
}
private void visitAssignOperator(Tree.AssignOp that) {
ProducedType rhst = rightType(that);
ProducedType lhst = leftType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
ProducedType leftHandType = lhst;
// allow assigning null to java properties that could after all be null
if (hasUncheckedNulls(that.getLeftTerm()))
leftHandType = unit.getOptionalType(leftHandType);
checkAssignable(rhst, leftHandType, that.getRightTerm(),
"assigned expression must be assignable to declared type",
2100);
}
that.setTypeModel(rhst);
// that.setTypeModel(lhst); //this version is easier on backend
}
private ProducedType checkOperandTypes(ProducedType lhst, ProducedType rhst,
TypeDeclaration td, Node node, String message) {
ProducedType lhsst = checkSupertype(lhst, td, node, message);
if (lhsst!=null) {
ProducedType at = lhsst.getTypeArgumentList().get(0);
checkAssignable(rhst, at, node, message);
return at;
}
else {
return null;
}
}
private ProducedType checkOperandTypes(ProducedType t,
ProducedType lhst, ProducedType rhst,
TypeDeclaration td, Node node, String message) {
ProducedType st = checkSupertype(t, td, node, message);
if (st!=null) {
ProducedType at = st.getTypeArgumentList().get(0);
checkAssignable(lhst, at, node, message);
checkAssignable(rhst, at, node, message);
return at;
}
else {
return null;
}
}
private void visitArithmeticOperator(Tree.BinaryOperatorExpression that,
TypeDeclaration type) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
//hardcoded implicit type conversion Integer->Float
TypeDeclaration fd = unit.getFloatDeclaration();
TypeDeclaration id = unit.getIntegerDeclaration();
if (rhst.getDeclaration().inherits(fd) &&
lhst.getDeclaration().inherits(id)) {
lhst = fd.getType();
}
else if (rhst.getDeclaration().inherits(id) &&
lhst.getDeclaration().inherits(fd)) {
rhst = fd.getType();
}
ProducedType nt = checkSupertype(lhst, type, that.getLeftTerm(),
that instanceof Tree.SumOp ?
"left operand must be of summable type" :
"left operand must be of numeric type");
if (nt!=null) {
List<ProducedType> tal = nt.getTypeArgumentList();
if (tal.isEmpty()) return;
ProducedType tt = tal.get(0);
that.setTypeModel(tt);
ProducedType ot;
if (that instanceof Tree.PowerOp) {
if (tal.size()<2) return;
ot = tal.get(1);
}
else {
ot = tt;
}
checkAssignable(rhst, ot, that,
that instanceof Tree.SumOp ?
"right operand must be of compatible summable type" :
"right operand must be of compatible numeric type");
}
}
}
private void visitArithmeticAssignOperator(Tree.BinaryOperatorExpression that,
TypeDeclaration type) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
//hardcoded implicit type conversion Integer->Float
TypeDeclaration fd = unit.getFloatDeclaration();
TypeDeclaration id = unit.getIntegerDeclaration();
if (rhst.getDeclaration().inherits(id) &&
lhst.getDeclaration().inherits(fd)) {
rhst = fd.getType();
}
ProducedType nt = checkSupertype(lhst, type, that.getLeftTerm(),
that instanceof Tree.AddAssignOp ?
"operand expression must be of summable type" :
"operand expression must be of numeric type");
that.setTypeModel(lhst);
if (nt!=null) {
ProducedType t = nt.getTypeArgumentList().get(0);
//that.setTypeModel(t); //stef requests lhst to make it easier on backend
checkAssignable(rhst, t, that,
that instanceof Tree.AddAssignOp ?
"right operand must be of compatible summable type" :
"right operand must be of compatible numeric type");
checkAssignable(t, lhst, that,
"result type must be assignable to declared type");
}
}
}
private void visitSetOperator(Tree.BitwiseOp that) {
//TypeDeclaration sd = unit.getSetDeclaration();
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
checkAssignable(lhst, unit.getSetType(unit.getType(unit.getObjectDeclaration())),
that.getLeftTerm(), "set operand expression must be a set");
checkAssignable(lhst, unit.getSetType(unit.getType(unit.getObjectDeclaration())),
that.getRightTerm(), "set operand expression must be a set");
ProducedType lhset = unit.getSetElementType(lhst);
ProducedType rhset = unit.getSetElementType(rhst);
ProducedType et;
if (that instanceof Tree.IntersectionOp) {
et = intersectionType(rhset, lhset, unit);
}
else if (that instanceof Tree.ComplementOp) {
et = lhset;
}
else {
et = unionType(rhset, lhset, unit);
}
that.setTypeModel(unit.getSetType(et));
}
}
private void visitSetAssignmentOperator(Tree.BitwiseAssignmentOp that) {
//TypeDeclaration sd = unit.getSetDeclaration();
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
checkAssignable(lhst, unit.getSetType(unit.getType(unit.getObjectDeclaration())),
that.getLeftTerm(), "set operand expression must be a set");
checkAssignable(lhst, unit.getSetType(unit.getType(unit.getObjectDeclaration())),
that.getRightTerm(), "set operand expression must be a set");
ProducedType lhset = unit.getSetElementType(lhst);
ProducedType rhset = unit.getSetElementType(rhst);
if (that instanceof Tree.UnionAssignOp) {
checkAssignable(rhset, lhset, that.getRightTerm(),
"resulting set element type must be assignable to to declared set element type");
}
that.setTypeModel(unit.getSetType(lhset)); //in theory, we could make this narrower
}
}
private void visitLogicalOperator(Tree.BinaryOperatorExpression that) {
ProducedType bt = unit.getType(unit.getBooleanDeclaration());
ProducedType lt = leftType(that);
ProducedType rt = rightType(that);
if (!isTypeUnknown(rt) && !isTypeUnknown(lt)) {
checkAssignable(lt, bt, that,
"logical operand expression must be a boolean value");
checkAssignable(rt, bt, that,
"logical operand expression must be a boolean value");
}
that.setTypeModel(bt);
}
private void visitDefaultOperator(Tree.DefaultOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
checkOptional(lhst, that.getLeftTerm(), that.getLeftTerm());
List<ProducedType> list = new ArrayList<ProducedType>(2);
addToUnion(list, unit.denotableType(rhst));
addToUnion(list, unit.getDefiniteType(unit.denotableType(lhst)));
UnionType ut = new UnionType(unit);
ut.setCaseTypes(list);
ProducedType rt = ut.getType();
that.setTypeModel(rt);
/*that.setTypeModel(rhst);
ProducedType ot;
if (isOptionalType(rhst)) {
ot = rhst;
}
else {
ot = getOptionalType(rhst);
}
if (!lhst.isSubtypeOf(ot)) {
that.getLeftTerm().addError("must be of type: " +
ot.getProducedTypeName(unit));
}*/
}
}
private void visitThenOperator(Tree.ThenOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(lhst)) {
checkAssignable(lhst, unit.getType(unit.getBooleanDeclaration()), that.getLeftTerm(),
"operand expression must be a boolean value");
}
if ( rhst!=null && !isTypeUnknown(rhst)) {
checkAssignable(rhst, unit.getType(unit.getObjectDeclaration()), that.getRightTerm(),
"operand expression may not be an optional type");
that.setTypeModel(unit.getOptionalType(unit.denotableType(rhst)));
}
}
private void visitInOperator(Tree.InOp that) {
ProducedType lhst = leftType(that);
ProducedType rhst = rightType(that);
if (!isTypeUnknown(rhst) && !isTypeUnknown(lhst)) {
ProducedType ct = checkSupertype(rhst,unit.getCategoryDeclaration(),
that.getRightTerm(), "operand expression must be a category");
if (ct!=null) {
ProducedType at = ct.getTypeArguments().isEmpty() ?
null : ct.getTypeArgumentList().get(0);
checkAssignable(lhst, at, that.getLeftTerm(),
"operand expression must be assignable to category type");
}
}
that.setTypeModel( unit.getType(unit.getBooleanDeclaration()) );
}
private void visitUnaryOperator(Tree.UnaryOperatorExpression that,
TypeDeclaration type) {
ProducedType t = type(that);
if (!isTypeUnknown(t)) {
ProducedType nt = checkSupertype(t, type, that.getTerm(),
"operand expression must be of correct type");
if (nt!=null) {
ProducedType at = nt.getTypeArguments().isEmpty() ?
nt : nt.getTypeArgumentList().get(0);
that.setTypeModel(at);
}
}
}
private void visitExistsOperator(Tree.Exists that) {
checkOptional(type(that), that.getTerm(), that);
that.setTypeModel(unit.getType(unit.getBooleanDeclaration()));
}
private void visitNonemptyOperator(Tree.Nonempty that) {
checkEmpty(type(that), that.getTerm(), that);
that.setTypeModel(unit.getType(unit.getBooleanDeclaration()));
}
private void visitOfOperator(Tree.OfOp that) {
Tree.Type rt = that.getType();
if (rt!=null) {
ProducedType t = rt.getTypeModel();
if (!isTypeUnknown(t)) {
that.setTypeModel(t);
Tree.Term tt = that.getTerm();
if (tt!=null) {
if (tt!=null) {
ProducedType pt = tt.getTypeModel();
if (!isTypeUnknown(pt)) {
if (!t.covers(pt)) {
that.addError("specified type does not cover the cases of the operand expression: '" +
t.getProducedTypeName(unit) + "' does not cover '" +
pt.getProducedTypeName(unit) + "'");
}
}
}
}
}
/*else if (dynamic) {
that.addError("static type not known");
}*/
}
}
private void visitIsOperator(Tree.IsOp that) {
Tree.Type rt = that.getType();
if (rt!=null) {
ProducedType t = rt.getTypeModel();
if (t!=null) {
if (that.getTerm()!=null) {
ProducedType pt = that.getTerm().getTypeModel();
if (pt!=null && pt.isSubtypeOf(t)) {
that.addError("expression type is a subtype of the type: '" +
pt.getProducedTypeName(unit) + "' is assignable to '" +
t.getProducedTypeName(unit) + "'");
}
else {
if (intersectionType(t, pt, unit).isNothing()) {
that.addError("tests assignability to bottom type 'Nothing': intersection of '" +
pt.getProducedTypeName(unit) + "' and '" +
t.getProducedTypeName(unit) + "' is empty");
}
}
}
}
}
that.setTypeModel(unit.getType(unit.getBooleanDeclaration()));
}
private void checkAssignability(Tree.Term that, Node node) {
if (that instanceof Tree.BaseMemberExpression ||
that instanceof Tree.QualifiedMemberExpression) {
ProducedReference pr = ((Tree.MemberOrTypeExpression) that).getTarget();
if (pr!=null) {
Declaration dec = pr.getDeclaration();
if (!(dec instanceof Value)) {
that.addError("member cannot be assigned: '"
+ dec.getName(unit) + "'");
}
else if (!((MethodOrValue) dec).isVariable() &&
!((MethodOrValue) dec).isLate()) {
that.addError("value is not variable: '"
+ dec.getName(unit) + "'", 800);
}
}
if (that instanceof Tree.QualifiedMemberOrTypeExpression) {
if (!(((Tree.QualifiedMemberOrTypeExpression) that).getMemberOperator() instanceof Tree.MemberOp)) {
that.addUnsupportedError("assignment to expression involving ?. and *. not supported");
}
}
}
else {
that.addError("expression cannot be assigned");
}
}
private ProducedType rightType(Tree.BinaryOperatorExpression that) {
Tree.Term rt = that.getRightTerm();
return rt==null? null : rt.getTypeModel();
}
private ProducedType leftType(Tree.BinaryOperatorExpression that) {
Tree.Term lt = that.getLeftTerm();
return lt==null ? null : lt.getTypeModel();
}
private ProducedType type(Tree.UnaryOperatorExpression that) {
Tree.Term t = that.getTerm();
return t==null ? null : t.getTypeModel();
}
private Interface getArithmeticDeclaration(Tree.ArithmeticOp that) {
if (that instanceof Tree.PowerOp) {
return unit.getExponentiableDeclaration();
}
else if (that instanceof Tree.SumOp) {
return unit.getSummableDeclaration();
}
else if (that instanceof Tree.DifferenceOp) {
return unit.getInvertableDeclaration();
}
else if (that instanceof Tree.RemainderOp) {
return unit.getIntegralDeclaration();
}
else {
return unit.getNumericDeclaration();
}
}
private Interface getArithmeticDeclaration(Tree.ArithmeticAssignmentOp that) {
if (that instanceof Tree.AddAssignOp) {
return unit.getSummableDeclaration();
}
else if (that instanceof Tree.SubtractAssignOp) {
return unit.getInvertableDeclaration();
}
else if (that instanceof Tree.RemainderAssignOp) {
return unit.getIntegralDeclaration();
}
else {
return unit.getNumericDeclaration();
}
}
@Override public void visit(Tree.ArithmeticOp that) {
super.visit(that);
visitArithmeticOperator(that, getArithmeticDeclaration(that));
}
@Override public void visit(Tree.BitwiseOp that) {
super.visit(that);
visitSetOperator(that);
}
@Override public void visit(Tree.ScaleOp that) {
super.visit(that);
visitScaleOperator(that);
}
@Override public void visit(Tree.LogicalOp that) {
super.visit(that);
visitLogicalOperator(that);
}
@Override public void visit(Tree.EqualityOp that) {
super.visit(that);
visitEqualityOperator(that);
}
@Override public void visit(Tree.ComparisonOp that) {
super.visit(that);
visitComparisonOperator(that);
}
@Override public void visit(Tree.WithinOp that) {
super.visit(that);
visitWithinOperator(that);
}
@Override public void visit(Tree.IdenticalOp that) {
super.visit(that);
visitIdentityOperator(that);
}
@Override public void visit(Tree.CompareOp that) {
super.visit(that);
visitCompareOperator(that);
}
@Override public void visit(Tree.DefaultOp that) {
super.visit(that);
visitDefaultOperator(that);
}
@Override public void visit(Tree.ThenOp that) {
super.visit(that);
visitThenOperator(that);
}
@Override public void visit(Tree.NegativeOp that) {
super.visit(that);
visitUnaryOperator(that, unit.getInvertableDeclaration());
}
@Override public void visit(Tree.PositiveOp that) {
super.visit(that);
visitUnaryOperator(that, unit.getInvertableDeclaration());
}
@Override public void visit(Tree.NotOp that) {
super.visit(that);
visitUnaryOperator(that, unit.getBooleanDeclaration());
}
@Override public void visit(Tree.AssignOp that) {
assign(that.getLeftTerm());
super.visit(that);
visitAssignOperator(that);
checkAssignability(that.getLeftTerm(), that);
}
@Override public void visit(Tree.ArithmeticAssignmentOp that) {
assign(that.getLeftTerm());
super.visit(that);
visitArithmeticAssignOperator(that, getArithmeticDeclaration(that));
checkAssignability(that.getLeftTerm(), that);
}
@Override public void visit(Tree.LogicalAssignmentOp that) {
assign(that.getLeftTerm());
super.visit(that);
visitLogicalOperator(that);
checkAssignability(that.getLeftTerm(), that);
}
@Override public void visit(Tree.BitwiseAssignmentOp that) {
assign(that.getLeftTerm());
super.visit(that);
visitSetAssignmentOperator(that);
checkAssignability(that.getLeftTerm(), that);
}
@Override public void visit(Tree.RangeOp that) {
super.visit(that);
visitSpanOperator(that);
}
@Override public void visit(Tree.SegmentOp that) {
super.visit(that);
visitMeasureOperator(that);
}
@Override public void visit(Tree.EntryOp that) {
super.visit(that);
visitEntryOperator(that);
}
@Override public void visit(Tree.Exists that) {
super.visit(that);
visitExistsOperator(that);
}
@Override public void visit(Tree.Nonempty that) {
super.visit(that);
visitNonemptyOperator(that);
}
@Override public void visit(Tree.IsOp that) {
super.visit(that);
visitIsOperator(that);
}
@Override public void visit(Tree.OfOp that) {
super.visit(that);
visitOfOperator(that);
}
@Override public void visit(Tree.Extends that) {
super.visit(that);
that.addUnsupportedError("extends operator not yet supported");
}
@Override public void visit(Tree.Satisfies that) {
super.visit(that);
that.addUnsupportedError("satisfies operator not yet supported");
}
@Override public void visit(Tree.InOp that) {
super.visit(that);
visitInOperator(that);
}
@Override
public void visit(Tree.BaseType that) {
super.visit(that);
TypeDeclaration type = that.getDeclarationModel();
if (type!=null) {
if (!type.isVisible(that.getScope())) {
that.addError("type is not visible: " +
baseDescription(that), 400);
}
else if (type.isPackageVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("package private type is not visible: " +
baseDescription(that));
}
//don't need to consider "protected" because
//toplevel types can't be declared protected
//and inherited protected member types are
//visible to subclasses
}
}
@Override
public void visit(Tree.QualifiedType that) {
super.visit(that);
TypeDeclaration type = that.getDeclarationModel();
if (type!=null) {
if (!type.isVisible(that.getScope())) {
that.addError("member type is not visible: " +
qualifiedDescription(that), 400);
}
else if (type.isPackageVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("package private member type is not visible: " +
qualifiedDescription(that));
}
//this is actually slightly too restrictive
//since a qualified type may in fact be an
//inherited member type, but in that case
//you can just get rid of the qualifier, so
//in fact this restriction is OK
else if (type.isProtectedVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("protected member type is not visible: " +
qualifiedDescription(that));
}
//Note: we should remove this check if we ever
// make qualified member types like T.Member
// into a sort of virtual type
Tree.StaticType outerType = that.getOuterType();
if (outerType instanceof Tree.SimpleType) {
if (((Tree.SimpleType) outerType).getDeclarationModel() instanceof TypeParameter) {
outerType.addError("type parameter should not occur as qualifying type: " +
qualifiedDescription(that));
}
}
}
}
private void checkBaseVisibility(Node that, TypedDeclaration member,
String name) {
if (!member.isVisible(that.getScope())) {
that.addError("function or value is not visible: '" +
name + "'", 400);
}
else if (member.isPackageVisibility() &&
!declaredInPackage(member, unit)) {
that.addError("package private function or value is not visible: '" +
name + "'");
}
//don't need to consider "protected" because
//there are no toplevel members in Java and
//inherited protected members are visible to
//subclasses
}
private void checkQualifiedVisibility(Node that, TypedDeclaration member,
String name, String container, boolean selfReference) {
if (!member.isVisible(that.getScope())) {
that.addError("method or attribute is not visible: '" +
name + "' of " + container, 400);
}
else if (member.isPackageVisibility() &&
!declaredInPackage(member, unit)) {
that.addError("package private method or attribute is not visible: '" +
name + "' of " + container);
}
//this is actually too restrictive since
//it doesn't take into account "other
//instance" access (access from a different
//instance of the same type)
else if (member.isProtectedVisibility() &&
!selfReference &&
!declaredInPackage(member, unit)) {
that.addError("protected method or attribute is not visible: '" +
name + "' of " + container);
}
}
private void checkBaseTypeAndConstructorVisibility(
Tree.BaseTypeExpression that, String name, TypeDeclaration type) {
//Note: the handling of "protected" here looks
// wrong because Java has a crazy rule
// that you can't instantiate protected
// member classes from a subclass
if (isOverloadedVersion(type)) {
//it is a Java constructor
//get the actual type that
//owns the constructor
//Declaration at = type.getContainer().getDirectMember(type.getName(), null, false);
Declaration at = type.getExtendedTypeDeclaration();
if (!at.isVisible(that.getScope())) {
that.addError("type is not visible: '" + name + "'");
}
else if (at.isPackageVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("package private type is not visible: '" + name + "'");
}
else if (at.isProtectedVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("protected type is not visible: '" + name + "'");
}
else if (!type.isVisible(that.getScope())) {
that.addError("type constructor is not visible: '" + name + "'");
}
else if (type.isPackageVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("package private constructor is not visible: '" + name + "'");
}
else if (type.isProtectedVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("protected constructor is not visible: '" + name + "'");
}
}
else {
if (!type.isVisible(that.getScope())) {
that.addError("type is not visible: '" + name + "'", 400);
}
else if (type.isPackageVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("package private type is not visible: '" + name + "'");
}
else if (type.isProtectedVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("protected type is not visible: '" + name + "'");
}
}
}
private void checkQualifiedTypeAndConstructorVisibility(
Tree.QualifiedTypeExpression that, TypeDeclaration type,
String name, String container) {
//Note: the handling of "protected" here looks
// wrong because Java has a crazy rule
// that you can't instantiate protected
// member classes from a subclass
if (isOverloadedVersion(type)) {
//it is a Java constructor
//get the actual type that
//owns the constructor
//Declaration at = type.getContainer().getDirectMember(type.getName(), null, false);
Declaration at = type.getExtendedTypeDeclaration();
if (!at.isVisible(that.getScope())) {
that.addError("member type is not visible: '" +
name + "' of '" + container);
}
else if (at.isPackageVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("package private member type is not visible: '" +
name + "' of type " + container);
}
else if (at.isProtectedVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("protected member type is not visible: '" +
name + "' of type " + container);
}
else if (!type.isVisible(that.getScope())) {
that.addError("member type constructor is not visible: '" +
name + "' of " + container);
}
else if (type.isPackageVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("package private member type constructor is not visible: '" +
name + "' of " + container);
}
else if (type.isProtectedVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("protected member type constructor is not visible: '" +
name + "' of " + container);
}
}
else {
if (!type.isVisible(that.getScope())) {
that.addError("member type is not visible: '" +
name + "' of " + container, 400);
}
else if (type.isPackageVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("package private member type is not visible: '" +
name + "' of " + container);
}
else if (type.isProtectedVisibility() &&
!declaredInPackage(type, unit)) {
that.addError("protected member type is not visible: '" +
name + "' of " + container);
}
}
}
private static String baseDescription(Tree.BaseType that) {
return "'" + name(that.getIdentifier()) +"'";
}
private static String qualifiedDescription(Tree.QualifiedType that) {
String name = name(that.getIdentifier());
Declaration d = that.getOuterType().getTypeModel().getDeclaration();
return "'" + name + "' of type '" + d.getName() + "'";
}
@Override public void visit(Tree.BaseMemberExpression that) {
/*if (that.getTypeArgumentList()!=null)
that.getTypeArgumentList().visit(this);*/
super.visit(that);
String name = name(that.getIdentifier());
TypedDeclaration member = getTypedDeclaration(that.getScope(),
name, that.getSignature(), that.getEllipsis(),
that.getUnit());
if (member==null) {
if (!dynamic) {
that.addError("function or value does not exist: '" +
name + "'", 100);
unit.getUnresolvedReferences().add(that.getIdentifier());
}
}
else {
member = (TypedDeclaration) handleAbstraction(member, that);
that.setDeclaration(member);
checkBaseVisibility(that, member, name);
Tree.TypeArguments tal = that.getTypeArguments();
if (explicitTypeArguments(member, tal, that)) {
List<ProducedType> ta = getTypeArguments(tal,
getTypeParameters(member), null);
tal.setTypeModels(ta);
visitBaseMemberExpression(that, member, ta, tal);
//otherwise infer type arguments later
}
else {
typeArgumentsImplicit(that);
}
/*if (defaultArgument) {
if (member.isClassOrInterfaceMember()) {
that.addWarning("references to this from default argument expressions not yet supported");
}
}*/
// checkOverloadedReference(that);
}
}
private List<TypeParameter> getTypeParameters(Declaration member) {
return member instanceof Generic ?
((Generic) member).getTypeParameters() :
Collections.<TypeParameter>emptyList();
}
@Override public void visit(Tree.QualifiedMemberExpression that) {
/*that.getPrimary().visit(this);
if (that.getTypeArgumentList()!=null)
that.getTypeArgumentList().visit(this);*/
super.visit(that);
Tree.Primary p = that.getPrimary();
ProducedType pt = p.getTypeModel();
boolean packageQualified = p instanceof Tree.Package;
boolean check = packageQualified ||
// that.getStaticMethodReference() ||
pt!=null &&
//account for dynamic blocks
(!pt.getType().isUnknown() ||
that.getMemberOperator() instanceof Tree.SpreadOp);
boolean nameNonempty = that.getIdentifier()!=null &&
!that.getIdentifier().getText().equals("");
if (nameNonempty && check) {
TypedDeclaration member;
String name = name(that.getIdentifier());
String container;
boolean ambiguous;
List<ProducedType> signature = that.getSignature();
boolean ellipsis = that.getEllipsis();
if (packageQualified) {
container = "package '" + unit.getPackage().getNameAsString() + "'";
Declaration pm = unit.getPackage()
.getMember(name, signature, ellipsis);
if (pm instanceof TypedDeclaration) {
member = (TypedDeclaration) pm;
}
else {
member = null;
}
ambiguous = false;
}
else {
pt = pt.resolveAliases(); //needed for aliases like "alias Id<T> => T"
TypeDeclaration d = getDeclaration(that, pt);
container = "type '" + d.getName(unit) + "'";
ClassOrInterface ci = getContainingClassOrInterface(that.getScope());
if (ci!=null && d.inherits(ci)) {
Declaration direct = ci.getDirectMember(name, signature, ellipsis);
if (direct instanceof TypedDeclaration) {
member = (TypedDeclaration) direct;
}
else {
member = getTypedMember(d, name, signature, ellipsis, unit);
}
}
else {
member = getTypedMember(d, name, signature, ellipsis, unit);
}
ambiguous = member==null && d.isMemberAmbiguous(name, unit,
signature, ellipsis);
}
if (member==null) {
if (ambiguous) {
that.addError("method or attribute is ambiguous: '" +
name + "' for " + container);
}
else {
that.addError("method or attribute does not exist: '" +
name + "' in " + container, 100);
unit.getUnresolvedReferences().add(that.getIdentifier());
}
}
else {
member = (TypedDeclaration) handleAbstraction(member, that);
that.setDeclaration(member);
boolean selfReference = isSelfReference(p);
checkQualifiedVisibility(that, member, name, container,
selfReference);
if (!selfReference && !member.isShared()) {
member.setOtherInstanceAccess(true);
}
Tree.TypeArguments tal = that.getTypeArguments();
if (explicitTypeArguments(member, tal, that)) {
List<ProducedType> ta = getTypeArguments(tal,
getTypeParameters(member), pt);
tal.setTypeModels(ta);
if (packageQualified) {
visitBaseMemberExpression(that, member, ta, tal);
}
else {
visitQualifiedMemberExpression(that, pt, member, ta, tal);
}
//otherwise infer type arguments later
}
else {
typeArgumentsImplicit(that);
}
// checkOverloadedReference(that);
}
checkSuperMember(that);
}
}
private boolean isSelfReference(Tree.Primary p) {
return
p instanceof Tree.This ||
p instanceof Tree.Outer ||
p instanceof Tree.Super;
}
private void checkSuperMember(Tree.QualifiedMemberOrTypeExpression that) {
Tree.Term t = eliminateParensAndWidening(that.getPrimary());
if (t instanceof Tree.Super) {
checkSuperInvocation(that);
}
}
private void typeArgumentsImplicit(Tree.MemberOrTypeExpression that) {
if (!that.getDirectlyInvoked()) {
Functional dec = (Functional) that.getDeclaration();
StringBuilder params = new StringBuilder();
for (TypeParameter tp: dec.getTypeParameters()) {
if (params.length()>0) params.append(", ");
params.append("'").append(tp.getName()).append("'");
}
that.addError("missing type arguments to generic declaration: '" +
dec.getName(unit) + "' declares type parameters " + params);
}
}
private void visitQualifiedMemberExpression(Tree.QualifiedMemberExpression that,
ProducedType receivingType, TypedDeclaration member,
List<ProducedType> typeArgs, Tree.TypeArguments tal) {
ProducedType receiverType = accountForStaticReferenceReceiverType(that,
unwrap(receivingType, that));
if (acceptsTypeArguments(receiverType, member, typeArgs, tal, that, false)) {
ProducedTypedReference ptr =
receiverType.getTypedMember(member, typeArgs,
that.getAssigned());
/*if (ptr==null) {
that.addError("member method or attribute does not exist: " +
member.getName(unit) + " of type " +
receiverType.getDeclaration().getName(unit));
}
else {*/
ProducedType t =
ptr.getFullType(wrap(ptr.getType(),
receivingType, that));
that.setTarget(ptr); //TODO: how do we wrap ptr???
if (!dynamic && isTypeUnknown(t)) {
//this occurs with an ambiguous reference
//to a member of an intersection type
that.addError("could not determine type of method or attribute reference: '" +
member.getName(unit) + "' of '" +
receiverType.getDeclaration().getName(unit) + "'");
}
that.setTypeModel(accountForStaticReferenceType(that, member, t));
}
}
private ProducedType accountForStaticReferenceReceiverType(Tree.QualifiedMemberOrTypeExpression that,
ProducedType receivingType) {
if (that.getStaticMethodReference()) {
ProducedReference target = ((Tree.MemberOrTypeExpression) that.getPrimary()).getTarget();
return target==null ? new UnknownType(unit).getType() : target.getType();
}
else {
return receivingType;
}
}
private ProducedType accountForStaticReferenceType(Tree.QualifiedMemberOrTypeExpression that,
Declaration member, ProducedType type) {
if (that.getStaticMethodReference()) {
Tree.MemberOrTypeExpression qmte = (Tree.MemberOrTypeExpression) that.getPrimary();
if (member.isStaticallyImportable()) {
return type;
}
else {
ProducedReference target = qmte.getTarget();
if (target==null) {
return new UnknownType(unit).getType();
}
else {
return getStaticReferenceType(type, target.getType());
}
}
}
else {
return type;
}
}
private ProducedType getStaticReferenceType(ProducedType type, ProducedType rt) {
return producedType(unit.getCallableDeclaration(), type,
producedType(unit.getTupleDeclaration(),
rt, rt, unit.getType(unit.getEmptyDeclaration())));
}
private void visitBaseMemberExpression(Tree.StaticMemberOrTypeExpression that,
TypedDeclaration member, List<ProducedType> typeArgs, Tree.TypeArguments tal) {
if (acceptsTypeArguments(member, typeArgs, tal, that, false)) {
ProducedType outerType =
that.getScope().getDeclaringType(member);
ProducedTypedReference pr =
member.getProducedTypedReference(outerType, typeArgs,
that.getAssigned());
that.setTarget(pr);
ProducedType t = pr.getFullType();
if (isTypeUnknown(t)) {
if (!dynamic) {
that.addError("could not determine type of function or value reference: '" +
member.getName(unit) + "'");
}
}
else {
that.setTypeModel(t);
}
}
}
@Override public void visit(Tree.BaseTypeExpression that) {
super.visit(that);
/*if (that.getTypeArgumentList()!=null)
that.getTypeArgumentList().visit(this);*/
String name = name(that.getIdentifier());
TypeDeclaration type = getTypeDeclaration(that.getScope(),
name, that.getSignature(), that.getEllipsis(),
that.getUnit());
if (type==null) {
if (!dynamic) {
that.addError("type does not exist: '" + name + "'", 102);
unit.getUnresolvedReferences().add(that.getIdentifier());
}
}
else {
type = (TypeDeclaration) handleAbstraction(type, that);
that.setDeclaration(type);
checkBaseTypeAndConstructorVisibility(that, name, type);
checkConcreteClass(type, that);
Tree.TypeArguments tal = that.getTypeArguments();
if (explicitTypeArguments(type, tal, that)) {
List<ProducedType> ta = getTypeArguments(tal,
type.getTypeParameters(), null);
tal.setTypeModels(ta);
visitBaseTypeExpression(that, type, ta, tal);
//otherwise infer type arguments later
}
else {
typeArgumentsImplicit(that);
}
// checkOverloadedReference(that);
checkSealedReference(type, that);
}
}
private void checkConcreteClass(TypeDeclaration type,
Tree.MemberOrTypeExpression that) {
if (that.getStaticMethodReferencePrimary()) {
if (!(type instanceof ClassOrInterface)) {
that.addError("type cannot be instantiated: '" +
type.getName(unit) + "' is not a class or interface");
}
}
else {
if (type instanceof Class) {
if (((Class) type).isAbstract()) {
that.addError("class cannot be instantiated: '" +
type.getName(unit) + "' is abstract");
}
}
else if (type instanceof TypeParameter) {
if (((TypeParameter) type).getParameterList()==null) {
that.addError("type parameter cannot be instantiated: '" +
type.getName(unit) + "'");
}
}
else {
that.addError("type cannot be instantiated: '" +
type.getName(unit) + "' is not a class");
}
}
}
private void checkSealedReference(TypeDeclaration type,
Tree.MemberOrTypeExpression that) {
if (type.isSealed() && !inSameModule(type) &&
(!that.getStaticMethodReferencePrimary())) {
that.addError("invokes or references a sealed class in a different module: '" +
type.getName(unit) + "' in '" +
type.getUnit().getPackage().getModule().getNameAsString() + "'");
}
}
@Override public void visit(Tree.ExtendedTypeExpression that) {
super.visit(that);
Declaration dec = that.getDeclaration();
if (dec instanceof Class) {
Class c = (Class) dec;
if (c.isAbstraction()) {
//if the constructor is overloaded
//resolve the right overloaded version
Declaration result = findMatchingOverloadedClass(c, that.getSignature(),
that.getEllipsis());
if (result!=null && result!=dec) {
//patch the reference, which was already
//initialized to the abstraction
that.setDeclaration((TypeDeclaration) result);
if (isOverloadedVersion(result)) {
//it is a Java constructor
if (result.isPackageVisibility() &&
!declaredInPackage(result, unit)) {
that.addError("package private constructor is not visible: '" +
result.getName() + "'");
}
}
}
//else report to user that we could not
//find a matching overloaded constructor
}
// checkOverloadedReference(that);
}
}
@Override public void visit(Tree.QualifiedMemberOrTypeExpression that) {
super.visit(that);
Tree.Primary p = that.getPrimary();
if (p instanceof Tree.MemberOrTypeExpression) {
Declaration pd = ((Tree.MemberOrTypeExpression) p).getDeclaration();
if (!(pd instanceof TypeDeclaration) &&
pd instanceof Functional) {
//this is a direct function ref
//its not a type, it can't have members
that.addError("direct function references do not have members");
}
}
}
@Override public void visit(Tree.QualifiedTypeExpression that) {
super.visit(that);
/*that.getPrimary().visit(this);
if (that.getTypeArgumentList()!=null)
that.getTypeArgumentList().visit(this);*/
Tree.Primary p = that.getPrimary();
ProducedType pt = p.getTypeModel();
boolean packageQualified = p instanceof Tree.Package;
boolean check = packageQualified ||
that.getStaticMethodReference() ||
pt!=null &&
//account for dynamic blocks
(!pt.isUnknown() ||
that.getMemberOperator() instanceof Tree.SpreadOp);
if (check) {
TypeDeclaration type;
String name = name(that.getIdentifier());
String container;
boolean ambiguous;
List<ProducedType> signature = that.getSignature();
boolean ellipsis = that.getEllipsis();
if (packageQualified) {
container = "package '" + unit.getPackage().getNameAsString() + "'";
Declaration pm = unit.getPackage()
.getMember(name, signature, ellipsis);
if (pm instanceof TypeDeclaration) {
type = (TypeDeclaration) pm;
}
else {
type = null;
}
ambiguous = false;
}
else {
pt = pt.resolveAliases(); //needed for aliases like "alias Id<T> => T"
TypeDeclaration d = getDeclaration(that, pt);
container = "type '" + d.getName(unit) + "'";
ClassOrInterface ci = getContainingClassOrInterface(that.getScope());
if (ci!=null && d.inherits(ci)) {
Declaration direct = ci.getDirectMember(name, signature, ellipsis);
if (direct instanceof TypeDeclaration) {
type = (TypeDeclaration) direct;
}
else {
type = getTypeMember(d, name, signature, ellipsis, unit);
}
}
else {
type = getTypeMember(d, name, signature, ellipsis, unit);
}
ambiguous = type==null && d.isMemberAmbiguous(name, unit,
signature, ellipsis);
}
if (type==null) {
if (ambiguous) {
that.addError("member type is ambiguous: '" +
name + "' for " + container);
}
else {
that.addError("member type does not exist: '" +
name + "' in " + container, 100);
unit.getUnresolvedReferences().add(that.getIdentifier());
}
}
else {
type = (TypeDeclaration) handleAbstraction(type, that);
that.setDeclaration(type);
checkQualifiedTypeAndConstructorVisibility(that, type, name, container);
if (!isSelfReference(p) && !type.isShared()) {
type.setOtherInstanceAccess(true);
}
checkConcreteClass(type, that);
Tree.TypeArguments tal = that.getTypeArguments();
if (explicitTypeArguments(type, tal, that)) {
List<ProducedType> ta = getTypeArguments(tal,
type.getTypeParameters(), pt);
tal.setTypeModels(ta);
if (packageQualified) {
visitBaseTypeExpression(that, type, ta, tal);
}
else {
visitQualifiedTypeExpression(that, pt, type, ta, tal);
}
//otherwise infer type arguments later
}
else {
typeArgumentsImplicit(that);
}
// checkOverloadedReference(that);
checkSealedReference(type, that);
}
//TODO: this is temporary until we get metamodel reference expressions!
/*if (p instanceof Tree.BaseTypeExpression ||
p instanceof Tree.QualifiedTypeExpression) {
ProducedReference target = that.getTarget();
if (target!=null) {
checkTypeBelongsToContainingScope(target.getType(),
that.getScope(), that);
}
}*/
if (!inExtendsClause) {
checkSuperMember(that);
}
}
}
private TypeDeclaration getDeclaration(Tree.QualifiedMemberOrTypeExpression that,
ProducedType pt) {
if (that.getStaticMethodReference()) {
TypeDeclaration td = (TypeDeclaration) ((Tree.MemberOrTypeExpression) that.getPrimary()).getDeclaration();
return td==null ? new UnknownType(unit) : td;
}
else {
return unwrap(pt, that).getDeclaration();
}
}
private boolean explicitTypeArguments(Declaration dec, Tree.TypeArguments tal,
Tree.MemberOrTypeExpression that) {
return !dec.isParameterized() ||
tal instanceof Tree.TypeArgumentList;
//TODO: enable this line to enable
// typechecking of references
// without type arguments
//|| !that.getDirectlyInvoked();
}
@Override public void visit(Tree.SimpleType that) {
//this one is a declaration, not an expression!
//we are only validating type arguments here
super.visit(that);
ProducedType pt = that.getTypeModel();
if (pt!=null) {
TypeDeclaration type = that.getDeclarationModel();//pt.getDeclaration()
Tree.TypeArgumentList tal = that.getTypeArgumentList();
//No type inference for declarations
if (type!=null) {
List<TypeParameter> params = type.getTypeParameters();
List<ProducedType> ta = getTypeArguments(tal,
params, pt.getQualifyingType());
acceptsTypeArguments(type, ta, tal, that, that.getMetamodel());
//the type has already been set by TypeVisitor
if (tal!=null) {
List<Tree.Type> args = tal.getTypes();
for (int i = 0; i<args.size(); i++) {
Tree.Type t = args.get(i);
if (t instanceof Tree.StaticType) {
TypeVariance variance =
((Tree.StaticType) t).getTypeVariance();
if (variance!=null) {
TypeParameter p = params.get(i);
if (p.isInvariant()) {
if (variance.getText().equals("out")) {
pt.setVariance(p, OUT);
}
else if (variance.getText().equals("in")) {
pt.setVariance(p, IN);
}
}
else {
variance.addError("type parameter is not declared invariant: '" +
p.getName() + "' of '" + type.getName(unit) + "'");
}
}
}
}
}
}
}
}
@Override public void visit(Tree.EntryType that) {
super.visit(that);
checkAssignable(that.getKeyType().getTypeModel(), unit.getType(unit.getObjectDeclaration()),
that.getKeyType(), "entry key type must not be an optional type");
checkAssignable(that.getValueType().getTypeModel(), unit.getType(unit.getObjectDeclaration()),
that.getValueType(), "entry item type must not be an optional type");
}
private void visitQualifiedTypeExpression(Tree.QualifiedTypeExpression that,
ProducedType receivingType, TypeDeclaration type,
List<ProducedType> typeArgs, Tree.TypeArguments tal) {
ProducedType receiverType = accountForStaticReferenceReceiverType(that,
unwrap(receivingType, that));
if (acceptsTypeArguments(receiverType, type, typeArgs, tal, that, false)) {
ProducedType t = receiverType.getTypeMember(type, typeArgs);
boolean abs = isAbstractType(t) || isAbstraction(type);
ProducedType ft = abs ?
producedType(unit.getCallableDeclaration(), t,
new UnknownType(unit).getType()) :
t.getFullType(wrap(t, receivingType, that));
that.setTarget(t);
if (!dynamic && !abs && !that.getStaticMethodReference() && isTypeUnknown(ft)) {
//this occurs with an ambiguous reference
//to a member of an intersection type
that.addError("could not determine type of member class reference: '" +
type.getName(unit) + "' of '" +
receiverType.getDeclaration().getName(unit) + "'");
}
that.setTypeModel(accountForStaticReferenceType(that, type, ft));
}
}
private void visitBaseTypeExpression(Tree.StaticMemberOrTypeExpression that,
TypeDeclaration type, List<ProducedType> typeArgs, Tree.TypeArguments tal) {
ProducedType outerType = that.getScope().getDeclaringType(type);
ProducedType t = type.getProducedType(outerType, typeArgs);
// if (!type.isAlias()) {
//TODO: remove this awful hack which means
// we can't define aliases for types
// with sequenced type parameters
type = t.getDeclaration();
if (acceptsTypeArguments(type, typeArgs, tal, that, false)) {
ProducedType ft = isAbstractType(t) || isAbstraction(type) ?
producedType(unit.getCallableDeclaration(), t,
new UnknownType(unit).getType()) :
t.getFullType();
that.setTypeModel(ft);
that.setTarget(t);
}
}
private boolean isAbstractType(ProducedType t) {
if (t.getDeclaration() instanceof Class) {
return ((Class) t.getDeclaration()).isAbstract();
}
else if (t.getDeclaration() instanceof TypeParameter) {
return ((TypeParameter) t.getDeclaration()).getParameterList()==null;
}
else {
return true;
}
}
@Override public void visit(Tree.Expression that) {
//i.e. this is a parenthesized expression
super.visit(that);
Tree.Term term = that.getTerm();
if (term==null) {
that.addError("expression not well formed");
}
else {
ProducedType t = term.getTypeModel();
if (t==null) {
//that.addError("could not determine type of expression");
}
else {
that.setTypeModel(t);
}
}
}
@Override public void visit(Tree.Outer that) {
ProducedType ci = getOuterClassOrInterface(that.getScope());
if (ci==null) {
that.addError("outer appears outside a nested class or interface definition");
}
else {
that.setTypeModel(ci);
}
/*if (defaultArgument) {
that.addError("reference to outer from default argument expression");
}*/
}
@Override public void visit(Tree.Super that) {
ClassOrInterface ci = getContainingClassOrInterface(that.getScope());
if (inExtendsClause) {
if (ci!=null) {
if (ci.isClassOrInterfaceMember()) {
ClassOrInterface oci = (ClassOrInterface) ci.getContainer();
that.setTypeModel(intersectionOfSupertypes(oci));
}
}
}
else {
//TODO: for consistency, move these errors to SelfReferenceVisitor
if (ci==null) {
that.addError("super occurs outside any type definition");
}
else {
that.setTypeModel(intersectionOfSupertypes(ci));
}
}
}
@Override public void visit(Tree.This that) {
ClassOrInterface ci = getContainingClassOrInterface(that.getScope());
if (inExtendsClause) {
if (ci!=null) {
if (ci.isClassOrInterfaceMember()) {
ClassOrInterface s = (ClassOrInterface) ci.getContainer();
that.setTypeModel(s.getType());
}
}
}
else {
if (ci==null) {
that.addError("this appears outside a class or interface definition");
}
else {
that.setTypeModel(ci.getType());
}
}
}
@Override public void visit(Tree.Package that) {
if (!that.getQualifier()) {
that.addError("package must qualify a reference to a toplevel declaration");
}
super.visit(that);
}
private ProducedType getTupleType(List<Tree.PositionalArgument> es,
boolean requireSequential) {
ProducedType result = unit.getType(unit.getEmptyDeclaration());
ProducedType ut = unit.getNothingDeclaration().getType();
for (int i=es.size()-1; i>=0; i
Tree.PositionalArgument a = es.get(i);
ProducedType t = a.getTypeModel();
if (t!=null) {
ProducedType et = unit.denotableType(t);
if (a instanceof Tree.SpreadArgument) {
/*if (requireSequential) {
checkSpreadArgumentSequential((Tree.SpreadArgument) a, et);
}*/
ut = unit.getIteratedType(et);
result = spreadType(et, unit, requireSequential);
}
else if (a instanceof Tree.Comprehension) {
ut = et;
Tree.InitialComprehensionClause icc = ((Tree.Comprehension) a).getInitialComprehensionClause();
result = icc.getPossiblyEmpty() ?
unit.getSequentialType(et) :
unit.getSequenceType(et);
if (!requireSequential) {
ProducedType it = producedType(unit.getIterableDeclaration(),
et, icc.getFirstTypeModel());
result = intersectionType(result, it, unit);
}
}
else {
ut = unionType(ut, et, unit);
result = producedType(unit.getTupleDeclaration(), ut, et, result);
}
}
}
return result;
}
private ProducedType spreadType(ProducedType et, Unit unit,
boolean requireSequential) {
if (et==null) return null;
if (requireSequential) {
if (unit.isSequentialType(et)) {
//if (et.getDeclaration() instanceof TypeParameter) {
return et;
/*}
else {
// if it's already a subtype of Sequential, erase
// out extraneous information, like that it is a
// String, just keeping information about what
// kind of tuple it is
List<ProducedType> elementTypes = unit.getTupleElementTypes(et);
boolean variadic = unit.isTupleLengthUnbounded(et);
boolean atLeastOne = unit.isTupleVariantAtLeastOne(et);
int minimumLength = unit.getTupleMinimumLength(et);
if (variadic) {
ProducedType spt = elementTypes.get(elementTypes.size()-1);
elementTypes.set(elementTypes.size()-1, unit.getIteratedType(spt));
}
return unit.getTupleType(elementTypes, variadic,
atLeastOne, minimumLength);
}*/
}
else {
// transform any Iterable into a Sequence without
// losing the information that it is nonempty, in
// the case that we know that for sure
ProducedType st = unit.isNonemptyIterableType(et) ?
unit.getSequenceType(unit.getIteratedType(et)) :
unit.getSequentialType(unit.getIteratedType(et));
// unless this is a tuple constructor, remember
// the original Iterable type arguments, to
// account for the possibility that the argument
// to Absent is a type parameter
//return intersectionType(et.getSupertype(unit.getIterableDeclaration()), st, unit);
// for now, just return the sequential type:
return st;
}
}
else {
return et;
}
}
@Override public void visit(Tree.Dynamic that) {
super.visit(that);
if (dynamic) {
Tree.NamedArgumentList nal = that.getNamedArgumentList();
if (nal!=null) {
for (Tree.NamedArgument na: nal.getNamedArguments()) {
if (na instanceof Tree.SpecifiedArgument) {
if (na.getIdentifier()==null) {
na.addError("missing argument name in dynamic instantiation expression");
}
}
}
}
}
else {
that.addError("dynamic instantiation expression occurs outside dynamic block");
}
}
@Override public void visit(Tree.Tuple that) {
super.visit(that);
ProducedType tt = null;
Tree.SequencedArgument sa = that.getSequencedArgument();
if (sa!=null) {
tt = getTupleType(sa.getPositionalArguments(), true);
}
else {
tt = unit.getType(unit.getEmptyDeclaration());
}
if (tt!=null) {
that.setTypeModel(tt);
if (tt.containsUnknowns()) {
that.addError("tuple element type could not be inferred");
}
}
}
@Override public void visit(Tree.SequenceEnumeration that) {
super.visit(that);
ProducedType st = null;
Tree.SequencedArgument sa = that.getSequencedArgument();
if (sa!=null) {
ProducedType tt = getTupleType(sa.getPositionalArguments(), false);
if (tt!=null) {
st = tt.getSupertype(unit.getIterableDeclaration());
if (st==null) {
st = unit.getIterableType(new UnknownType(unit).getType());
}
}
}
else {
st = unit.getIterableType(unit.getNothingDeclaration().getType());
}
if (st!=null) {
that.setTypeModel(st);
if (st.containsUnknowns()) {
that.addError("iterable element type could not be inferred");
}
}
}
/*private ProducedType getGenericElementType(List<Tree.Expression> es,
Tree.Ellipsis ell) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (int i=0; i<es.size(); i++) {
Tree.Expression e = es.get(i);
if (e.getTypeModel()!=null) {
ProducedType et = e.getTypeModel();
if (i==es.size()-1 && ell!=null) {
ProducedType it = unit.getIteratedType(et);
if (it==null) {
ell.addError("last element expression is not iterable: " +
et.getProducedTypeName(unit) + " is not an iterable type");
}
else {
addToUnion(list, it);
}
}
else {
addToUnion(list, unit.denotableType(e.getTypeModel()));
}
}
}
if (list.isEmpty()) {
return unit.getType(unit.getBooleanDeclaration());
}
else if (list.size()==1) {
return list.get(0);
}
else {
UnionType ut = new UnionType(unit);
ut.setExtendedType( unit.getType(unit.getObjectDeclaration()) );
ut.setCaseTypes(list);
return ut.getType();
}
}*/
@Override public void visit(Tree.CatchVariable that) {
super.visit(that);
Tree.Variable var = that.getVariable();
if (var!=null) {
Tree.Type vt = var.getType();
if (vt instanceof Tree.LocalModifier) {
ProducedType et = unit.getType(unit.getExceptionDeclaration());
vt.setTypeModel(et);
var.getDeclarationModel().setType(et);
}
else {
ProducedType tt = unit.getType(unit.getThrowableDeclaration());
checkAssignable(vt.getTypeModel(), tt, vt,
"catch type must be a throwable type");
// TypeDeclaration d = vt.getTypeModel().getDeclaration();
// if (d instanceof IntersectionType) {
// vt.addUnsupportedError("intersection types in catch not yet supported");
// else if (d.isParameterized()) {
// vt.addUnsupportedError("parameterized types in catch not yet supported");
}
}
}
@Override public void visit(Tree.StringTemplate that) {
super.visit(that);
for (Tree.Expression e: that.getExpressions()) {
ProducedType et = e.getTypeModel();
if (!isTypeUnknown(et)) {
checkAssignable(et, unit.getType(unit.getObjectDeclaration()), e,
"interpolated expression must not be an optional type");
}
}
setLiteralType(that, unit.getStringDeclaration());
}
@Override public void visit(Tree.StringLiteral that) {
setLiteralType(that, unit.getStringDeclaration());
}
@Override public void visit(Tree.NaturalLiteral that) {
setLiteralType(that, unit.getIntegerDeclaration());
}
@Override public void visit(Tree.FloatLiteral that) {
setLiteralType(that, unit.getFloatDeclaration());
}
@Override public void visit(Tree.CharLiteral that) {
String result = that.getText();
if (result.codePointCount(1, result.length()-1)!=1) {
that.addError("character literal must contain exactly one character");
}
setLiteralType(that, unit.getCharacterDeclaration());
}
@Override public void visit(Tree.QuotedLiteral that) {
setLiteralType(that, unit.getStringDeclaration());
}
private void setLiteralType(Tree.Atom that, TypeDeclaration languageType) {
that.setTypeModel(unit.getType(languageType));
}
@Override
public void visit(Tree.CompilerAnnotation that) {
//don't visit the argument
}
@Override
public void visit(Tree.MatchCase that) {
super.visit(that);
for (Tree.Expression e: that.getExpressionList().getExpressions()) {
if (e!=null) {
ProducedType t = e.getTypeModel();
if (!isTypeUnknown(t)) {
if (switchExpression!=null) {
ProducedType st = switchExpression.getTypeModel();
if (!isTypeUnknown(st)) {
if (!hasUncheckedNulls(switchExpression.getTerm()) || !isNullCase(t)) {
checkAssignable(t, st, e,
"case must be assignable to switch expression type");
}
}
}
Tree.Term term = e.getTerm();
if (term instanceof Tree.NegativeOp) {
term = ((Tree.NegativeOp) term).getTerm();
}
if (term instanceof Tree.Literal) {
if (term instanceof Tree.FloatLiteral) {
e.addError("literal case may not be a 'Float' literal");
}
}
else if (term instanceof Tree.MemberOrTypeExpression) {
ProducedType ut = unionType(unit.getType(unit.getNullDeclaration()),
unit.getType(unit.getIdentifiableDeclaration()), unit);
TypeDeclaration dec = t.getDeclaration();
if ((!dec.isToplevel() && !dec.isStaticallyImportable()) || !dec.isAnonymous()) {
e.addError("case must refer to a toplevel object declaration or literal value");
}
else {
checkAssignable(t, ut, e, "case must be identifiable or null");
}
}
else if (term!=null) {
e.addError("case must be a literal value or refer to a toplevel object declaration");
}
}
}
}
}
@Override
public void visit(Tree.SatisfiesCase that) {
super.visit(that);
that.addUnsupportedError("satisfies cases are not yet supported");
}
@Override
public void visit(Tree.IsCase that) {
Tree.Type t = that.getType();
if (t!=null) {
t.visit(this);
}
Tree.Variable v = that.getVariable();
if (v!=null) {
v.visit(this);
initOriginalDeclaration(v);
}
if (switchExpression!=null) {
ProducedType st = switchExpression.getTypeModel();
if (t!=null) {
ProducedType pt = t.getTypeModel();
ProducedType it = intersectionType(pt, st, unit);
if (!hasUncheckedNulls(switchExpression.getTerm()) || !isNullCase(pt)) {
if (it.isExactly(unit.getNothingDeclaration().getType())) {
that.addError("narrows to Nothing type: '" +
pt.getProducedTypeName(unit) + "' has empty intersection with '" +
st.getProducedTypeName(unit) + "'");
}
/*checkAssignable(ct, switchType, cc.getCaseItem(),
"case type must be a case of the switch type");*/
}
if (v!=null) {
v.getType().setTypeModel(it);
v.getDeclarationModel().setType(it);
}
}
}
}
@Override
public void visit(Tree.SwitchStatement that) {
Tree.Expression ose = switchExpression;
switchExpression = that.getSwitchClause().getExpression();
super.visit(that);
Tree.SwitchCaseList switchCaseList = that.getSwitchCaseList();
if (switchCaseList!=null && switchExpression!=null) {
checkCases(switchCaseList);
if (switchCaseList.getElseClause()==null) {
checkCasesExhaustive(switchCaseList, that.getSwitchClause());
}
}
switchExpression = ose;
}
private void checkCases(Tree.SwitchCaseList switchCaseList) {
List<Tree.CaseClause> cases = switchCaseList.getCaseClauses();
boolean hasIsCase = false;
for (Tree.CaseClause cc: cases) {
if (cc.getCaseItem() instanceof Tree.IsCase) {
hasIsCase = true;
}
for (Tree.CaseClause occ: cases) {
if (occ==cc) break;
checkCasesDisjoint(cc, occ);
}
}
if (hasIsCase) {
Tree.Term st = switchExpression.getTerm();
if (st instanceof Tree.BaseMemberExpression) {
checkReferenceIsNonVariable((Tree.BaseMemberExpression) st, true);
}
else if (st!=null) {
st.addError("switch expression must be a value reference in switch with type cases", 3102);
}
}
}
private void checkCasesExhaustive(Tree.SwitchCaseList switchCaseList,
Tree.SwitchClause switchClause) {
ProducedType st = switchExpression.getTypeModel();
if (!isTypeUnknown(st)) {
//form the union of all the case types
List<Tree.CaseClause> caseClauses = switchCaseList.getCaseClauses();
List<ProducedType> list = new ArrayList<ProducedType>(caseClauses.size());
for (Tree.CaseClause cc: caseClauses) {
ProducedType ct = getTypeIgnoringLiterals(cc);
if (isTypeUnknown(ct)) {
return; //Note: early exit!
}
else {
addToUnion(list, ct);
}
}
UnionType ut = new UnionType(unit);
ut.setCaseTypes(list);
//if the union of the case types covers
//the switch expression type then the
//switch is exhaustive
if (!ut.getType().covers(st)) {
switchClause.addError("case types must cover all cases of the switch type or an else clause must appear: '" +
ut.getType().getProducedTypeName(unit) + "' does not cover '" +
st.getProducedTypeName(unit) + "'");
}
}
/*else if (dynamic) {
that.addError("else clause must appear: static type not known");
}*/
}
private void checkCasesDisjoint(Tree.CaseClause cc, Tree.CaseClause occ) {
Tree.CaseItem cci = cc.getCaseItem();
Tree.CaseItem occi = occ.getCaseItem();
if (cci instanceof Tree.IsCase || occi instanceof Tree.IsCase) {
checkCasesDisjoint(getType(cc), getType(occ), cci);
}
else {
checkCasesDisjoint(getTypeIgnoringLiterals(cc),
getTypeIgnoringLiterals(occ), cci);
}
if (cci instanceof Tree.MatchCase && occi instanceof Tree.MatchCase) {
checkLiteralsDisjoint((Tree.MatchCase) cci, (Tree.MatchCase) occi);
}
}
private void checkLiteralsDisjoint(Tree.MatchCase cci, Tree.MatchCase occi) {
for (Tree.Expression e: cci.getExpressionList().getExpressions()) {
for (Tree.Expression f: occi.getExpressionList().getExpressions()) {
Tree.Term et = e.getTerm();
Tree.Term ft = f.getTerm();
boolean eneg = et instanceof Tree.NegativeOp;
boolean fneg = ft instanceof Tree.NegativeOp;
if (eneg) {
et = ((Tree.NegativeOp) et).getTerm();
}
if (fneg) {
ft = ((Tree.NegativeOp) ft).getTerm();
}
if (et instanceof Tree.Literal && ft instanceof Tree.Literal) {
String ftv = getLiteralText(ft);
String etv = getLiteralText(et);
if (et instanceof Tree.NaturalLiteral &&
ft instanceof Tree.NaturalLiteral &&
((ftv.startsWith("#") && !etv.startsWith("#")) ||
(!ftv.startsWith("#") && etv.startsWith("#")) ||
(ftv.startsWith("$") && !etv.startsWith("$")) ||
(!ftv.startsWith("$") && etv.startsWith("$")))) {
cci.addUnsupportedError("literal cases with mixed bases not yet supported");
}
else if (etv.equals(ftv) && eneg==fneg) {
cci.addError("literal cases must be disjoint: " +
(eneg?"-":"") +
etv.replaceAll("\\p{Cntrl}","?") +
" occurs in multiple cases");
}
}
}
}
}
private static String getLiteralText(Tree.Term et) {
String etv = et.getText();
if (et instanceof Tree.CharLiteral) {
return "'" + etv + "'";
}
else if (et instanceof Tree.StringLiteral) {
return "\"" + etv + "\"";
}
else {
return etv;
}
}
private boolean isNullCase(ProducedType ct) {
TypeDeclaration d = ct.getDeclaration();
return d!=null && d instanceof Class &&
d.equals(unit.getNullDeclaration());
}
private ProducedType getType(Tree.CaseItem ci) {
Tree.Type t = ((Tree.IsCase) ci).getType();
if (t!=null) {
return t.getTypeModel().getUnionOfCases();
}
else {
return null;
}
}
private ProducedType getType(Tree.CaseClause cc) {
Tree.CaseItem ci = cc.getCaseItem();
if (ci instanceof Tree.IsCase) {
return getType(ci);
}
else if (ci instanceof Tree.MatchCase) {
List<Tree.Expression> es = ((Tree.MatchCase) ci).getExpressionList().getExpressions();
List<ProducedType> list = new ArrayList<ProducedType>(es.size());
for (Tree.Expression e: es) {
if (e.getTypeModel()!=null) {
addToUnion(list, e.getTypeModel());
}
}
return formUnion(list);
}
else {
return null;
}
}
private ProducedType getTypeIgnoringLiterals(Tree.CaseClause cc) {
Tree.CaseItem ci = cc.getCaseItem();
if (ci instanceof Tree.IsCase) {
return getType(ci);
}
else if (ci instanceof Tree.MatchCase) {
List<Tree.Expression> es = ((Tree.MatchCase) ci).getExpressionList().getExpressions();
List<ProducedType> list = new ArrayList<ProducedType>(es.size());
for (Tree.Expression e: es) {
if (e.getTypeModel()!=null &&
!(e.getTerm() instanceof Tree.Literal) &&
!(e.getTerm() instanceof Tree.NegativeOp)) {
addToUnion(list, e.getTypeModel());
}
}
return formUnion(list);
}
else {
return null;
}
}
@Override
public void visit(Tree.TryCatchStatement that) {
super.visit(that);
for (Tree.CatchClause cc: that.getCatchClauses()) {
if (cc.getCatchVariable()!=null &&
cc.getCatchVariable().getVariable()!=null) {
ProducedType ct = cc.getCatchVariable()
.getVariable().getType().getTypeModel();
if (ct!=null) {
for (Tree.CatchClause ecc: that.getCatchClauses()) {
if (ecc.getCatchVariable()!=null &&
ecc.getCatchVariable().getVariable()!=null) {
if (cc==ecc) break;
ProducedType ect = ecc.getCatchVariable()
.getVariable().getType().getTypeModel();
if (ect!=null) {
if (ct.isSubtypeOf(ect)) {
cc.getCatchVariable().getVariable().getType()
.addError("exception type is already handled by earlier catch clause: '"
+ ct.getProducedTypeName(unit) + "'");
}
if (ct.getDeclaration() instanceof UnionType) {
for (ProducedType ut: ct.getDeclaration().getCaseTypes()) {
if ( ut.substitute(ct.getTypeArguments()).isSubtypeOf(ect) ) {
cc.getCatchVariable().getVariable().getType()
.addError("exception type is already handled by earlier catch clause: '"
+ ut.getProducedTypeName(unit) + "'");
}
}
}
}
}
}
}
}
}
}
@Override
public void visit(Tree.DynamicStatement that) {
boolean od = dynamic;
dynamic = true;
super.visit(that);
dynamic = od;
}
private boolean acceptsTypeArguments(Declaration member, List<ProducedType> typeArguments,
Tree.TypeArguments tal, Node parent, boolean metamodel) {
return acceptsTypeArguments(null, member, typeArguments, tal, parent, metamodel);
}
private static boolean isGeneric(Declaration member) {
return member instanceof Generic &&
!((Generic) member).getTypeParameters().isEmpty();
}
private boolean acceptsTypeArguments(ProducedType receiver, Declaration dec,
List<ProducedType> typeArguments, Tree.TypeArguments tal, Node parent,
boolean metamodel) {
if (dec==null) return false;
if (isGeneric(dec)) {
List<TypeParameter> params = ((Generic) dec).getTypeParameters();
int min = 0;
for (TypeParameter tp: params) {
if (!tp.isDefaulted()) min++;
}
int max = params.size();
int args = typeArguments.size();
if (args<=max && args>=min) {
for (int i=0; i<args; i++) {
TypeParameter param = params.get(i);
ProducedType argType = typeArguments.get(i);
//Map<TypeParameter, ProducedType> self = Collections.singletonMap(param, arg);
boolean argTypeMeaningful = argType!=null &&
!(argType.getDeclaration() instanceof UnknownType);
for (ProducedType st: param.getSatisfiedTypes()) {
//sts = sts.substitute(self);
ProducedType sts = st.getProducedType(receiver, dec, typeArguments);
if (argType!=null) {
if (!isCondition && !argType.isSubtypeOf(sts)) {
if (argTypeMeaningful) {
if (tal instanceof Tree.InferredTypeArguments) {
parent.addError("inferred type argument '" + argType.getProducedTypeName(unit)
+ "' to type parameter '" + param.getName()
+ "' of declaration '" + dec.getName(unit)
+ "' not assignable to upper bound '" + sts.getProducedTypeName(unit)
+ "' of '" + param.getName() + "'");
}
else {
((Tree.TypeArgumentList) tal).getTypes()
.get(i).addError("type parameter '" + param.getName()
+ "' of declaration '" + dec.getName(unit)
+ "' has argument '" + argType.getProducedTypeName(unit)
+ "' not assignable to upper bound '" + sts.getProducedTypeName(unit)
+ "' of '" + param.getName() + "'", 2102);
}
}
return false;
}
}
}
if (!isCondition &&
!argumentSatisfiesEnumeratedConstraint(receiver, dec,
typeArguments, argType, param)) {
if (argTypeMeaningful) {
if (tal instanceof Tree.InferredTypeArguments) {
parent.addError("inferred type argument '" + argType.getProducedTypeName(unit)
+ "' to type parameter '" + param.getName()
+ "' of declaration '" + dec.getName(unit)
+ "' not one of the enumerated cases of '" + param.getName() + "'");
}
else {
((Tree.TypeArgumentList) tal).getTypes()
.get(i).addError("type parameter '" + param.getName()
+ "' of declaration '" + dec.getName(unit)
+ "' has argument '" + argType.getProducedTypeName(unit)
+ "' not one of the enumerated cases of '" + param.getName() + "'");
}
}
return false;
}
}
return true;
}
else {
if (tal==null || tal instanceof Tree.InferredTypeArguments) {
if (!metamodel) {
parent.addError("missing type arguments to generic type: '" +
dec.getName(unit) + "' declares type parameters");
}
}
else {
String help="";
if (args<min) {
help = " requires at least " + min + " type arguments";
}
else if (args>max) {
help = " allows at most " + max + " type arguments";
}
tal.addError("wrong number of type arguments: '" +
dec.getName(unit) + "'" + help);
}
return false;
}
}
else {
boolean empty = typeArguments.isEmpty();
if (!empty) {
tal.addError("does not accept type arguments: '" +
dec.getName(unit) + "'");
}
return empty;
}
}
public static boolean argumentSatisfiesEnumeratedConstraint(ProducedType receiver,
Declaration member, List<ProducedType> typeArguments, ProducedType argType,
TypeParameter param) {
List<ProducedType> caseTypes = param.getCaseTypes();
if (caseTypes==null || caseTypes.isEmpty()) {
//no enumerated constraint
return true;
}
//if the type argument is a subtype of one of the cases
//of the type parameter then the constraint is satisfied
for (ProducedType ct: caseTypes) {
ProducedType cts = ct.getProducedType(receiver, member, typeArguments);
if (argType.isSubtypeOf(cts)) {
return true;
}
}
//if the type argument is itself a type parameter with
//an enumerated constraint, and every enumerated case
//is a subtype of one of the cases of the type parameter,
//then the constraint is satisfied
if (argType.getDeclaration() instanceof TypeParameter) {
List<ProducedType> argCaseTypes = argType.getDeclaration().getCaseTypes();
if (argCaseTypes!=null && !argCaseTypes.isEmpty()) {
for (ProducedType act: argCaseTypes) {
boolean foundCase = false;
for (ProducedType ct: caseTypes) {
ProducedType cts = ct.getProducedType(receiver, member, typeArguments);
if (act.isSubtypeOf(cts)) {
foundCase = true;
break;
}
}
if (!foundCase) {
return false;
}
}
return true;
}
}
return false;
}
private void visitExtendedOrAliasedType(Tree.SimpleType et,
Tree.InvocationExpression ie) {
if (et!=null && ie!=null) {
ProducedType type = et.getTypeModel();
if (type!=null) {
Tree.Primary pr = ie.getPrimary();
if (pr instanceof Tree.InvocationExpression) {
Tree.InvocationExpression iie = (Tree.InvocationExpression) pr;
pr = iie.getPrimary();
}
if (pr instanceof Tree.ExtendedTypeExpression) {
Tree.ExtendedTypeExpression ete = (Tree.ExtendedTypeExpression) pr;
ete.setDeclaration(et.getDeclarationModel());
ete.setTarget(type);
ProducedType qt = type.getQualifyingType();
ProducedType ft = type.getFullType();
if (ete.getStaticMethodReference()) {
ft = producedType(unit.getCallableDeclaration(), ft,
producedType(unit.getTupleDeclaration(), qt, qt,
unit.getType(unit.getEmptyDeclaration())));
}
pr.setTypeModel(ft);
}
}
}
}
@Override
public void visit(Tree.ClassSpecifier that) {
Tree.InvocationExpression ie = that.getInvocationExpression();
visitExtendedOrAliasedType(that.getType(), ie);
inExtendsClause = true;
super.visit(that);
inExtendsClause = false;
//Dupe check:
/*if (ie!=null &&
ie.getPrimary() instanceof Tree.MemberOrTypeExpression) {
checkOverloadedReference((Tree.MemberOrTypeExpression) ie.getPrimary());
}*/
}
@Override
public void visit(Tree.ExtendedType that) {
visitExtendedOrAliasedType(that.getType(),
that.getInvocationExpression());
inExtendsClause = true;
super.visit(that);
inExtendsClause = false;
TypeDeclaration td = (TypeDeclaration) that.getScope();
Tree.SimpleType et = that.getType();
if (et!=null) {
ProducedType type = et.getTypeModel();
if (type!=null) {
checkSelfTypes(et, td, type);
checkExtensionOfMemberType(et, td, type);
//checkCaseOfSupertype(et, td, type);
if (!td.isAlias()) {
TypeDeclaration etd = td.getExtendedTypeDeclaration();
while (etd!=null && etd.isAlias()) {
etd = etd.getExtendedTypeDeclaration();
}
if (etd!=null) {
if (etd.isFinal()) {
et.addError("extends a final class: '" +
etd.getName(unit) + "'");
}
if (etd.isSealed() && !inSameModule(etd)) {
et.addError("extends a sealed class in a different module: '" +
etd.getName(unit) + "' in '" +
etd.getUnit().getPackage().getModule().getNameAsString() + "'");
}
}
}
// if (td.isParameterized() &&
// type.getDeclaration().inherits(unit.getExceptionDeclaration())) {
// et.addUnsupportedError("generic exception types not yet supported");
}
checkSupertypeVarianceAnnotations(et);
}
}
private void checkSupertypeVarianceAnnotations(Tree.SimpleType et) {
Tree.TypeArgumentList tal = et.getTypeArgumentList();
if (tal!=null) {
for (Tree.Type t: tal.getTypes()) {
if (t instanceof Tree.StaticType) {
TypeVariance variance = ((Tree.StaticType) t).getTypeVariance();
if (variance!=null) {
variance.addError("supertype expression may not specify variance");
}
}
}
}
}
private boolean inSameModule(TypeDeclaration etd) {
return etd.getUnit().getPackage().getModule()
.equals(unit.getPackage().getModule());
}
@Override
public void visit(Tree.SatisfiedTypes that) {
super.visit(that);
TypeDeclaration td = (TypeDeclaration) that.getScope();
Set<TypeDeclaration> set = new HashSet<TypeDeclaration>();
if (td.getSatisfiedTypes().isEmpty()) return; //handle undecidability case
for (Tree.StaticType t: that.getTypes()) {
ProducedType type = t.getTypeModel();
if (type!=null && type.getDeclaration()!=null) {
type = type.resolveAliases();
TypeDeclaration std = type.getDeclaration();
if (td instanceof ClassOrInterface &&
!inLanguageModule(that.getUnit())) {
if (unit.isCallableType(type)) {
t.addError("satisfies 'Callable'");
}
if (type.getDeclaration().equals(unit.getConstrainedAnnotationDeclaration())) {
t.addError("directly satisfies 'ConstrainedAnnotation'");
}
}
if (!set.add(type.getDeclaration())) {
//this error is not really truly necessary
//but the spec says it is an error, and
//the backend doesn't like it
t.addError("duplicate satisfied type: '" +
type.getDeclaration().getName(unit) +
"' of '" + td.getName() + "'");
}
if (td instanceof ClassOrInterface &&
std.isSealed() && !inSameModule(std)) {
t.addError("satisfies a sealed interface in a different module: '" +
std.getName(unit) + "' in '" +
std.getUnit().getPackage().getModule().getNameAsString() + "'");
}
checkSelfTypes(t, td, type);
checkExtensionOfMemberType(t, td, type);
/*if (!(td instanceof TypeParameter)) {
checkCaseOfSupertype(t, td, type);
}*/
}
if (t instanceof Tree.SimpleType) {
checkSupertypeVarianceAnnotations((Tree.SimpleType) t);
}
}
//Moved to RefinementVisitor, which
//handles this kind of stuff:
/*if (td instanceof TypeParameter) {
List<ProducedType> list = new ArrayList<ProducedType>();
for (ProducedType st: td.getSatisfiedTypes()) {
addToIntersection(list, st, unit);
}
IntersectionType it = new IntersectionType(unit);
it.setSatisfiedTypes(list);
if (it.getType().getDeclaration() instanceof NothingType) {
that.addError("upper bound constraints cannot be satisfied by any type except Nothing");
}
}*/
}
/*void checkCaseOfSupertype(Tree.StaticType t, TypeDeclaration td,
ProducedType type) {
//TODO: I think this check is a bit too restrictive, since
// it doesn't allow intermediate types between the
// enumerated type and the case type, but since the
// similar check below doesn't work, we need it
if (type.getDeclaration().getCaseTypes()!=null) {
for (ProducedType ct: type.getDeclaration().getCaseTypes()) {
if (ct.substitute(type.getTypeArguments())
.isExactly(td.getType())) {
return;
}
}
t.addError("not a case of supertype: " +
type.getDeclaration().getName(unit));
}
}*/
@Override
public void visit(Tree.CaseTypes that) {
super.visit(that);
//this forces every case to be a subtype of the
//enumerated type, so that we can make use of the
//enumerated type is equivalent to its cases
TypeDeclaration td = (TypeDeclaration) that.getScope();
//TODO: get rid of this awful hack:
List<ProducedType> cases = td.getCaseTypes();
td.setCaseTypes(null);
if (td instanceof TypeParameter) {
for (Tree.StaticType t: that.getTypes()) {
for (Tree.StaticType ot: that.getTypes()) {
if (t==ot) break;
checkCasesDisjoint(t.getTypeModel(), ot.getTypeModel(), ot);
}
}
}
else {
Set<TypeDeclaration> set = new HashSet<TypeDeclaration>();
for (Tree.StaticType st: that.getTypes()) {
ProducedType type = st.getTypeModel();
TypeDeclaration ctd = type.getDeclaration();
if (type!=null && ctd!=null) {
type = type.resolveAliases();
if (!set.add(ctd)) {
//this error is not really truly necessary
st.addError("duplicate case type: '" +
ctd.getName(unit) +
"' of '" + td.getName() + "'");
}
if (!(ctd instanceof TypeParameter)) {
//it's not a self type
if (type!=null) {
checkAssignable(type, td.getType(), st,
getCaseTypeExplanation(td, type));
//note: this is a better, faster way to call
// validateEnumeratedSupertypeArguments()
// but unfortunately it winds up displaying
// the error on the wrong node, confusing
// the user
/*ProducedType supertype = type.getDeclaration().getType().getSupertype(td);
validateEnumeratedSupertypeArguments(t, type.getDeclaration(), supertype);*/
}
}
if (ctd instanceof ClassOrInterface && st instanceof Tree.SimpleType) {
Tree.TypeArgumentList tal = ((Tree.SimpleType) st).getTypeArgumentList();
if (tal!=null) {
List<Tree.Type> args = tal.getTypes();
List<TypeParameter> typeParameters = ctd.getTypeParameters();
for (int i=0; i<args.size() && i<typeParameters.size(); i++) {
Tree.Type arg = args.get(i);
TypeParameter typeParameter = ctd.getTypeParameters().get(i);
ProducedType argType = arg.getTypeModel();
if (argType!=null) {
TypeDeclaration argTypeDec = argType.getDeclaration();
if (argTypeDec instanceof TypeParameter) {
if (!((TypeParameter) argTypeDec).getDeclaration().equals(td)) {
arg.addError("type argument is not a type parameter of the enumerated type: '" +
argTypeDec.getName() + "' is not a type parameter of '" + td.getName());
}
}
else if (typeParameter.isCovariant()) {
checkAssignable(typeParameter.getType(), argType, arg,
"type argument not an upper bound of the type parameter");
}
else if (typeParameter.isContravariant()) {
checkAssignable(argType, typeParameter.getType(), arg,
"type argument not a lower bound of the type parameter");
}
else {
arg.addError("type argument is not a type parameter of the enumerated type: '" +
argTypeDec.getName() + "'");
}
}
}
}
}
}
}
for (Tree.BaseMemberExpression bme: that.getBaseMemberExpressions()) {
ProducedType type = bme.getTypeModel();
Declaration d = bme.getDeclaration();
if (d!=null && type!=null &&
!type.getDeclaration().isAnonymous()) {
bme.addError("case must be a toplevel anonymous class: '" +
d.getName(unit) + "' is not an anonymous class");
}
else if (d!=null && !d.isToplevel()) {
bme.addError("case must be a toplevel anonymous class: '" +
d.getName(unit) + "' is not toplevel");
}
if (type!=null) {
checkAssignable(type, td.getType(), bme,
getCaseTypeExplanation(td, type));
}
}
}
//TODO: get rid of this awful hack:
td.setCaseTypes(cases);
}
private String getCaseTypeExplanation(TypeDeclaration td,
ProducedType type) {
String message = "case type must be a subtype of enumerated type";
if (!td.getTypeParameters().isEmpty() &&
type.getDeclaration().inherits(td)) {
message += " for every type argument of the generic enumerated type";
}
return message;
}
private void checkCasesDisjoint(ProducedType type, ProducedType other,
Node ot) {
if (!isTypeUnknown(type) && !isTypeUnknown(other)) {
if (!intersectionType(type.resolveAliases(), other.resolveAliases(), unit).isNothing()) {
ot.addError("cases are not disjoint: '" +
type.getProducedTypeName(unit) + "' and '" +
other.getProducedTypeName(unit) + "'");
}
}
}
private void checkExtensionOfMemberType(Node that, TypeDeclaration td,
ProducedType type) {
ProducedType qt = type.getQualifyingType();
if (qt!=null && td instanceof ClassOrInterface &&
!type.getDeclaration().isStaticallyImportable()) {
Scope s = td;
while (s!=null) {
s = s.getContainer();
if (s instanceof TypeDeclaration) {
TypeDeclaration otd = (TypeDeclaration) s;
if (otd.getType().isSubtypeOf(qt)) {
return;
}
}
}
that.addError("qualifying type '" + qt.getProducedTypeName(unit) +
"' of supertype '" + type.getProducedTypeName(unit) +
"' is not an outer type or supertype of any outer type of '" +
td.getName(unit) + "'");
}
}
private void checkSelfTypes(Tree.StaticType that, TypeDeclaration td, ProducedType type) {
if (!(td instanceof TypeParameter)) { //TODO: is this really ok?!
List<TypeParameter> params = type.getDeclaration().getTypeParameters();
List<ProducedType> args = type.getTypeArgumentList();
for (int i=0; i<params.size(); i++) {
TypeParameter param = params.get(i);
if ( param.isSelfType() && args.size()>i ) {
ProducedType arg = args.get(i);
if (arg==null) arg = new UnknownType(unit).getType();
TypeDeclaration std = param.getSelfTypedDeclaration();
ProducedType at;
TypeDeclaration mtd;
if (param.getContainer().equals(std)) {
at = td.getType();
mtd = td;
}
else {
//TODO: lots wrong here?
mtd = (TypeDeclaration) td.getMember(std.getName(), null, false);
at = mtd==null ? null : mtd.getType();
}
if (at!=null && !at.isSubtypeOf(arg) &&
!(mtd.getSelfType()!=null &&
mtd.getSelfType().isExactly(arg))) {
String help;
TypeDeclaration ad = arg.getDeclaration();
if (ad instanceof TypeParameter &&
((TypeParameter) ad).getDeclaration().equals(td)) {
help = " (try making " + ad.getName() + " a self type of " + td.getName() + ")";
}
else if (ad instanceof Interface) {
help = " (try making " + td.getName() + " satisfy " + ad.getName() + ")";
}
else if (ad instanceof Class && td instanceof Class) {
help = " (try making " + td.getName() + " extend " + ad.getName() + ")";
}
else {
help = "";
}
that.addError("type argument does not satisfy self type constraint on type parameter '" +
param.getName() + "' of '" + type.getDeclaration().getName(unit) + "': '" +
arg.getProducedTypeName(unit) + "' is not a supertype or self type of '" +
td.getName(unit) + "'" + help);
}
}
}
}
}
private void validateEnumeratedSupertypes(Node that, ClassOrInterface d) {
ProducedType type = d.getType();
for (ProducedType supertype: type.getSupertypes()) {
if (!type.isExactly(supertype)) {
TypeDeclaration std = supertype.getDeclaration();
if (std.getCaseTypes()!=null && !std.getCaseTypes().isEmpty()) {
if (std.getCaseTypes().size()==1 &&
std.getCaseTypeDeclarations().get(0).isSelfType()) {
continue;
}
List<ProducedType> types=new ArrayList<ProducedType>(std.getCaseTypes().size());
for (ProducedType ct: std.getCaseTypes()) {
ProducedType cst = type.getSupertype(ct.getDeclaration());
if (cst!=null) {
types.add(cst);
}
}
if (types.isEmpty()) {
that.addError("not a subtype of any case of enumerated supertype: '" +
d.getName(unit) + "' is a subtype of '" + std.getName(unit) + "'");
}
else if (types.size()>1) {
StringBuilder sb = new StringBuilder();
for (ProducedType pt: types) {
sb.append("'").append(pt.getProducedTypeName(unit)).append("' and ");
}
sb.setLength(sb.length()-5);
that.addError("concrete type is a subtype of multiple cases of enumerated supertype: '" +
d.getName(unit) + "' is a subtype of " + sb);
}
}
}
}
}
private void validateEnumeratedSupertypeArguments(Node that, ClassOrInterface d) {
//note: I hate doing the whole traversal here, but it is the
// only way to get the error in the right place (see
// the note in visit(CaseTypes) for more)
ProducedType type = d.getType();
for (ProducedType supertype: type.getSupertypes()) { //traverse the entire supertype hierarchy of the declaration
if (!type.isExactly(supertype)) {
List<TypeDeclaration> ctds = supertype.getDeclaration().getCaseTypeDeclarations();
if (ctds!=null) {
for (TypeDeclaration ct: ctds) {
if (ct.equals(d)) { //the declaration is a case of the current enumerated supertype
validateEnumeratedSupertypeArguments(that, d, supertype);
break;
}
}
}
}
}
}
private void validateEnumeratedSupertypeArguments(Node that, TypeDeclaration d,
ProducedType supertype) {
for (TypeParameter p: supertype.getDeclaration().getTypeParameters()) {
ProducedType arg = supertype.getTypeArguments().get(p); //the type argument that the declaration (indirectly) passes to the enumerated supertype
if (arg!=null) {
validateEnumeratedSupertypeArgument(that, d, supertype, p, arg);
}
}
}
private void validateEnumeratedSupertypeArgument(Node that, TypeDeclaration d,
ProducedType supertype, TypeParameter p, ProducedType arg) {
TypeDeclaration td = arg.getDeclaration();
if (td instanceof TypeParameter) {
TypeParameter tp = (TypeParameter) td;
if (tp.getDeclaration().equals(d)) { //the argument is a type parameter of the declaration
//check that the variance of the argument type parameter is
//the same as the type parameter of the enumerated supertype
if (p.isCovariant() && !tp.isCovariant()) {
that.addError("argument to covariant type parameter of enumerated supertype must be covariant: " +
typeDescription(p, unit));
}
if (p.isContravariant() && !tp.isContravariant()) {
that.addError("argument to contravariant type parameter of enumerated supertype must be contravariant: " +
typeDescription(p, unit));
}
}
else {
that.addError("argument to type parameter of enumerated supertype must be a type parameter of '" +
d.getName() + "': " + typeDescription(p, unit));
}
}
else if (p.isCovariant()) {
if (!(td instanceof NothingType)) {
//TODO: let it be the union of the lower bounds on p
that.addError("argument to covariant type parameter of enumerated supertype must be a type parameter or 'Nothing': " +
typeDescription(p, unit));
}
}
else if (p.isContravariant()) {
List<ProducedType> sts = p.getSatisfiedTypes();
//TODO: do I need to do type arg substitution here??
ProducedType ub = formIntersection(sts);
if (!(arg.isExactly(ub))) {
that.addError("argument to contravariant type parameter of enumerated supertype must be a type parameter or '" +
typeNamesAsIntersection(sts, unit) + "': " +
typeDescription(p, unit));
}
}
else {
that.addError("argument to type parameter of enumerated supertype must be a type parameter: " +
typeDescription(p, unit));
}
}
@Override public void visit(Tree.Term that) {
super.visit(that);
if (that.getTypeModel()==null) {
that.setTypeModel( defaultType() );
}
}
@Override public void visit(Tree.Type that) {
super.visit(that);
if (that.getTypeModel()==null) {
that.setTypeModel( defaultType() );
}
}
private ProducedType defaultType() {
TypeDeclaration ut = new UnknownType(unit);
Class ad = unit.getAnythingDeclaration();
if (ad!=null) {
ut.setExtendedType(ad.getType());
}
return ut.getType();
}
@Override
public void visit(Tree.PackageLiteral that) {
super.visit(that);
Package p = TypeVisitor.getPackage(that.getImportPath());
that.getImportPath().setModel(p);
that.setTypeModel(unit.getPackageDeclarationType());
}
@Override
public void visit(Tree.ModuleLiteral that) {
super.visit(that);
Module m = TypeVisitor.getModule(that.getImportPath());
that.getImportPath().setModel(m);
that.setTypeModel(unit.getModuleDeclarationType());
}
@Override
public void visit(Tree.TypeLiteral that) {
super.visit(that);
ProducedType t = null;
TypeDeclaration d = null;
Tree.StaticType type = that.getType();
Tree.BaseMemberExpression oe = that.getObjectExpression();
if (type != null) {
t = type.getTypeModel();
d = t.getDeclaration();
}
else if (oe != null ) {
t = oe.getTypeModel();
d = t.getDeclaration();
if (!d.isAnonymous()) {
oe.addError("must be a reference to an anonymous class");
}
}
// FIXME: should we disallow type parameters in there?
if (t != null) {
that.setDeclaration(d);
that.setWantsDeclaration(true);
if (that instanceof Tree.ClassLiteral) {
if (!(d instanceof Class)) {
if(type != null)
type.addError("referenced declaration is not a class" +
getDeclarationReferenceSuggestion(d));
}
else {
// checkNonlocal(that, d);
}
that.setTypeModel(unit.getClassDeclarationType());
}
else if (that instanceof Tree.InterfaceLiteral) {
if (!(d instanceof Interface)) {
type.addError("referenced declaration is not an interface" +
getDeclarationReferenceSuggestion(d));
}
that.setTypeModel(unit.getInterfaceDeclarationType());
}
else if (that instanceof Tree.AliasLiteral) {
if (!(d instanceof TypeAlias)) {
type.addError("referenced declaration is not a type alias" +
getDeclarationReferenceSuggestion(d));
}
that.setTypeModel(unit.getAliasDeclarationType());
}
else if (that instanceof Tree.TypeParameterLiteral) {
if (!(d instanceof TypeParameter)) {
type.addError("referenced declaration is not a type parameter" +
getDeclarationReferenceSuggestion(d));
}
that.setTypeModel(unit.getTypeParameterDeclarationType());
}
else if (d != null) {
that.setWantsDeclaration(false);
t = t.resolveAliases();
//checkNonlocalType(that.getType(), t.getDeclaration());
if (d instanceof Class) {
// checkNonlocal(that, t.getDeclaration());
if (((Class) d).isAbstraction()) {
that.addError("class constructor is overloaded");
}
else {
that.setTypeModel(unit.getClassMetatype(t));
}
}
else if (d instanceof Interface) {
that.setTypeModel(unit.getInterfaceMetatype(t));
}
else {
that.setTypeModel(unit.getTypeMetaType(t));
}
}
}
}
@Override
public void visit(Tree.MemberLiteral that) {
super.visit(that);
if (that.getIdentifier() != null) {
String name = name(that.getIdentifier());
ProducedType qt = null;
TypeDeclaration qtd = null;
Tree.StaticType type = that.getType();
Tree.BaseMemberExpression oe = that.getObjectExpression();
if (type != null) {
qt = type.getTypeModel();
qtd = qt.getDeclaration();
}
else if (oe != null) {
qt = oe.getTypeModel();
qtd = qt.getDeclaration();
if (!qtd.isAnonymous()) {
oe.addError("must be a reference to an anonymous class");
}
}
if (qt != null) {
qt = qt.resolveAliases();
if (qtd instanceof UnknownType) {
// let it go, we already logged an error for the missing type
return;
}
//checkNonlocalType(that.getType(), qtd);
String container = "type '" + qtd.getName(unit) + "'";
TypedDeclaration member = getTypedMember(qtd, name, null, false, unit);
if (member==null) {
if (qtd.isMemberAmbiguous(name, unit, null, false)) {
that.addError("method or attribute is ambiguous: '" +
name + "' for " + container);
}
else {
that.addError("method or attribute does not exist: '" +
name + "' in " + container);
}
}
else {
checkQualifiedVisibility(that, member, name, container, false);
setMemberMetatype(that, member);
}
}
else {
TypedDeclaration result = getTypedDeclaration(that.getScope(),
name, null, false, unit);
if (result!=null) {
checkBaseVisibility(that, result, name);
setMemberMetatype(that, result);
}
else {
that.addError("function or value does not exist: '" +
name(that.getIdentifier()) + "'", 100);
unit.getUnresolvedReferences().add(that.getIdentifier());
}
}
}
}
private void setMemberMetatype(Tree.MemberLiteral that, TypedDeclaration result) {
that.setDeclaration(result);
if (that instanceof Tree.ValueLiteral) {
if (result instanceof Value) {
checkNonlocal(that, result);
}
else {
that.getIdentifier().addError("referenced declaration is not a value" +
getDeclarationReferenceSuggestion(result));
}
if (that.getBroken()) {
that.addError("keyword object may not appear here: " +
"use the value keyword to refer to anonymous class declarations");
}
that.setWantsDeclaration(true);
that.setTypeModel(unit.getValueDeclarationType(result));
}
else if (that instanceof Tree.FunctionLiteral) {
if (result instanceof Method) {
checkNonlocal(that, result);
}
else {
that.getIdentifier().addError("referenced declaration is not a function" +
getDeclarationReferenceSuggestion(result));
}
that.setWantsDeclaration(true);
that.setTypeModel(unit.getFunctionDeclarationType());
}
else {
checkNonlocal(that, result);
setMetamodelType(that, result);
}
}
private String getDeclarationReferenceSuggestion(Declaration result) {
String name = ": " + result.getName(unit);
if (result instanceof Method) {
return name + " is a function";
}
else if (result instanceof Value) {
return name + " is a value";
}
else if (result instanceof Class) {
return name + " is a class";
}
else if (result instanceof Interface) {
return name + " is an interface";
}
else if (result instanceof TypeAlias) {
return name + " is a type alias";
}
else if (result instanceof TypeParameter) {
return name + " is a type parameter";
}
return "";
}
private void setMetamodelType(Tree.MemberLiteral that, Declaration result) {
ProducedType outerType;
if (result.isClassOrInterfaceMember()) {
outerType = that.getType()==null ?
that.getScope().getDeclaringType(result) :
that.getType().getTypeModel();
}
else {
outerType = null;
}
if (result instanceof Method) {
Method method = (Method) result;
if (method.isAbstraction()) {
that.addError("method is overloaded");
}
else {
Tree.TypeArgumentList tal = that.getTypeArgumentList();
if (explicitTypeArguments(method, tal, null)) {
List<ProducedType> ta = getTypeArguments(tal,
getTypeParameters(method), outerType);
if (tal != null) {
tal.setTypeModels(ta);
}
if (acceptsTypeArguments(outerType, method, ta, tal, that, false)) {
ProducedTypedReference pr = outerType==null ?
method.getProducedTypedReference(null, ta) :
outerType.getTypedMember(method, ta);
that.setTarget(pr);
that.setTypeModel(unit.getFunctionMetatype(pr));
}
}
else {
that.addError("missing type arguments to: '" + method.getName(unit) + "'");
}
}
}
else if (result instanceof Value) {
Value value = (Value) result;
if (that.getTypeArgumentList() != null) {
that.addError("does not accept type arguments: '" + result.getName(unit) + "'");
}
else {
ProducedTypedReference pr = value.getProducedTypedReference(outerType,
Collections.<ProducedType>emptyList());
that.setTarget(pr);
that.setTypeModel(unit.getValueMetatype(pr));
}
}
}
private void checkNonlocal(Node that, Declaration declaration) {
if ((!declaration.isClassOrInterfaceMember() || !declaration.isShared())
&& !declaration.isToplevel()) {
that.addError("metamodel reference to local declaration");
}
}
/*private void checkNonlocalType(Node that, TypeDeclaration declaration) {
if (declaration instanceof UnionType) {
for (TypeDeclaration ctd: declaration.getCaseTypeDeclarations()) {
checkNonlocalType(that, ctd);
}
}
if (declaration instanceof IntersectionType) {
for (TypeDeclaration std: declaration.getSatisfiedTypeDeclarations()) {
checkNonlocalType(that, std);
}
}
else if (declaration instanceof ClassOrInterface &&
(!declaration.isClassOrInterfaceMember()||!declaration.isShared())
&& !declaration.isToplevel()) {
that.addWarning("metamodel reference to local type not yet supported");
}
else if (declaration.getContainer() instanceof TypeDeclaration) {
checkNonlocalType(that, (TypeDeclaration) declaration.getContainer());
}
}*/
private Declaration handleAbstraction(Declaration dec, Tree.MemberOrTypeExpression that) {
//NOTE: if this is the qualifying type of a static method
// reference, don't do anything special here, since
// we're not actually calling the constructor
if (!that.getStaticMethodReferencePrimary() &&
isAbstraction(dec)) {
//first handle the case where it's not _really_ overloaded,
//it's just a constructor with a different visibility
List<Declaration> overloads = ((Functional) dec).getOverloads();
if (overloads.size()==1) {
return overloads.get(0);
}
}
return dec;
}
}
|
package nallar.tickthreading.minecraft.tickregion;
import java.util.Iterator;
import nallar.collections.LinkedHashSetTempSetNoClear;
import nallar.tickthreading.Log;
import nallar.tickthreading.minecraft.TickManager;
import nallar.tickthreading.minecraft.profiling.EntityTickProfiler;
import nallar.tickthreading.util.TableFormatter;
import nallar.unsafe.UnsafeAccess;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.ChunkProviderServer;
import sun.misc.Unsafe;
public class EntityTickRegion extends TickRegion {
private final LinkedHashSetTempSetNoClear<Entity> entitySet = new LinkedHashSetTempSetNoClear<Entity>();
public EntityTickRegion(World world, TickManager manager, int regionX, int regionZ) {
super(world, manager, regionX, regionZ);
}
@Override
public void doTick() {
ChunkProviderServer chunkProvider = (ChunkProviderServer) world.getChunkProvider();
boolean profilingEnabled = manager.profilingEnabled || this.profilingEnabled;
EntityTickProfiler entityTickProfiler = profilingEnabled ? EntityTickProfiler.ENTITY_TICK_PROFILER : null;
long startTime = 0;
Iterator<Entity> entitiesIterator = entitySet.startIteration();
try {
while (entitiesIterator.hasNext()) {
if (profilingEnabled) {
startTime = System.nanoTime();
}
Entity entity = entitiesIterator.next();
try {
Entity ridingEntity = entity.ridingEntity;
if (ridingEntity != null) {
if (!ridingEntity.isDead && ridingEntity.riddenByEntity == entity) {
continue;
}
ridingEntity.riddenByEntity = null;
entity.ridingEntity = null;
}
if (!entity.isDead) {
if (entity instanceof EntityPlayerMP) {
Unsafe $ = UnsafeAccess.$;
Object lock = ((EntityPlayerMP) entity).playerNetServerHandler;
if ($.tryMonitorEnter(lock)) {
try {
world.updateEntity(entity);
} finally {
$.monitorExit(lock);
}
}
} else {
world.updateEntity(entity);
}
}
if (entity.isDead) {
int entityX = entity.chunkCoordX;
int entityZ = entity.chunkCoordZ;
synchronized (entity) {
if (entity.addedToChunk) {
Chunk chunk = entity.chunk;
if (chunk == null) {
chunkProvider.getChunkIfExists(entityX, entityZ);
}
if (chunk != null) {
chunk.removeEntity(entity);
}
}
}
entitiesIterator.remove();
manager.removed(entity);
world.onEntityRemoved(entity);
} else if (TickManager.getHashCode(entity) != hashCode) {
entitiesIterator.remove();
manager.add(entity, false);
//Log.severe("Inconsistent state: " + entity + " is in the wrong TickRegion.");
// Note to self for when I decide this is wrong later:
// Entities are supposed to move, of course this will happen!
}
} catch (Throwable throwable) {
Log.severe("Exception ticking entity " + entity + " in " + toString() + '/' + Log.name(entity.worldObj) + ':', throwable);
if (entity.worldObj != world) {
Log.severe("Seems to be caused by an entity being in a broken state, set to an impossible/incorrect world. Killing this entity.");
entity.setDead();
}
}
if (profilingEnabled) {
entityTickProfiler.record(entity, System.nanoTime() - startTime);
}
}
} finally {
entitySet.done();
}
}
@Override
protected String getShortTypeName() {
return "E";
}
public boolean add(Entity entity) {
return entitySet.add(entity);
}
public boolean remove(Entity entity) {
return entitySet.remove(entity);
}
@Override
public boolean isEmpty() {
return entitySet.isEmpty();
}
@Override
public int size() {
return entitySet.size();
}
@Override
public void die() {
entitySet.clear();
}
@Override
public void dump(final TableFormatter tf) {
synchronized (entitySet) {
for (Entity e : entitySet) {
//DumpCommand.dump(tf, e, tf.stringFiller == StringFiller.CHAT ? 35 : 70);
tf.sb.append("Entity ").append(String.valueOf(e)).append(" in ").append(hashCode).append(", new ").append(TickManager.getHashCode(e)).append('\n');
}
}
}
}
|
package de.lmu.ifi.dbs.elki.datasource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.datasource.bundle.BundleMeta;
import de.lmu.ifi.dbs.elki.datasource.bundle.BundleStreamSource;
import de.lmu.ifi.dbs.elki.datasource.bundle.BundleStreamSource.Event;
import de.lmu.ifi.dbs.elki.datasource.bundle.MultipleObjectsBundle;
import de.lmu.ifi.dbs.elki.datasource.bundle.StreamFromBundle;
import de.lmu.ifi.dbs.elki.datasource.filter.ObjectFilter;
import de.lmu.ifi.dbs.elki.datasource.parser.NumberVectorLabelParser;
import de.lmu.ifi.dbs.elki.datasource.parser.Parser;
import de.lmu.ifi.dbs.elki.datasource.parser.StreamingParser;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.utilities.FileUtil;
import de.lmu.ifi.dbs.elki.utilities.exceptions.AbortException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.FileListParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.FileListParameter.FilesType;
/**
* Database that will loading multiple files, concatenating the results.
*
* @author Erich Schubert
*/
public class ConcatenateFilesDatabaseConnection extends AbstractDatabaseConnection {
/**
* Class logger.
*/
private static final Logging LOG = Logging.getLogger(ConcatenateFilesDatabaseConnection.class);
/**
* Input file list.
*/
private List<File> files;
/**
* The parser.
*/
private Parser parser;
/**
* Constructor.
*
* @param files Input files
* @param parser Parser
* @param filters Filters
*/
public ConcatenateFilesDatabaseConnection(List<File> files, Parser parser, List<ObjectFilter> filters) {
super(filters);
this.files = files;
this.parser = parser;
}
@Override
public MultipleObjectsBundle loadData() {
MultipleObjectsBundle objects = new MultipleObjectsBundle();
objects.appendColumn(TypeUtil.STRING, new ArrayList<Object>());
for(File file : files) {
String filestr = file.getPath();
try {
InputStream inputStream = new FileInputStream(file);
inputStream = FileUtil.tryGzipInput(inputStream);
final BundleStreamSource source;
if(parser instanceof StreamingParser) {
final StreamingParser streamParser = (StreamingParser) parser;
streamParser.initStream(inputStream);
source = streamParser;
}
else {
MultipleObjectsBundle parsingResult = parser.parse(inputStream);
// normalize objects and transform labels
source = new StreamFromBundle(parsingResult);
}
BundleMeta meta = null; // NullPointerException on invalid streams
loop: for(Event e = source.nextEvent();; e = source.nextEvent()) {
switch(e){
case END_OF_STREAM:
break loop;
case META_CHANGED:
meta = source.getMeta();
for(int i = 0; i < meta.size(); i++) {
if(i + 1 >= objects.metaLength()) {
objects.appendColumn(meta.get(i), new ArrayList<Object>());
}
else {
// Ensure compatibility:
if(!objects.meta(i + 1).isAssignableFromType(meta.get(i))) {
throw new AbortException("Incompatible files loaded. Cannot concatenate with unaligned columns, please preprocess manually.");
}
}
}
break;
case NEXT_OBJECT:
Object[] o = new Object[objects.metaLength()];
o[0] = filestr;
for(int i = 0; i < meta.size(); i++) {
o[i + 1] = source.data(i);
}
objects.appendSimple(o);
}
}
}
catch(IOException e) {
throw new AbortException("Loading file " + filestr + " failed: " + e.toString(), e);
}
}
// Invoke filters
if(LOG.isDebugging()) {
LOG.debugFine("Invoking filters.");
}
return invokeFilters(objects);
}
@Override
protected Logging getLogger() {
return LOG;
}
/**
* Parameterization class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class Parameterizer extends AbstractDatabaseConnection.Parameterizer {
/**
* The input files.
*/
private List<File> files;
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
FileListParameter filesP = new FileListParameter(FileBasedDatabaseConnection.INPUT_ID, FilesType.INPUT_FILES);
if(config.grab(filesP)) {
files = filesP.getValue();
}
configFilters(config);
configParser(config, Parser.class, NumberVectorLabelParser.class);
}
@Override
protected ConcatenateFilesDatabaseConnection makeInstance() {
return new ConcatenateFilesDatabaseConnection(files, parser, filters);
}
}
}
|
package edu.northwestern.bioinformatics.studycalendar.web;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import edu.northwestern.bioinformatics.studycalendar.web.security.TestUserDetails;
import edu.northwestern.bioinformatics.studycalendar.web.security.LoginCredentials;
import gov.nih.nci.security.AuthenticationManager;
import gov.nih.nci.security.SecurityServiceProvider;
import gov.nih.nci.security.exceptions.CSException;
import org.apache.log4j.Logger;
/**
* @author Padmaja Vedula
*/
public class LoginController extends SimpleFormController {
static final Logger log = Logger.getLogger(LoginController.class.getName());
static AuthenticationManager authMgr = null;
public static final String CSM_STUDYCAL_CONTEXT_NAME = "study_calendar";
public LoginController() {
}
protected ModelAndView onSubmit(Object loginData) throws Exception{
LoginCredentials loginCredentials = (LoginCredentials) loginData;
log.debug("Login ID: " + loginCredentials.getUserId());
log.debug("System Config file is: "
+ System.getProperty("gov.nih.nci.security.configFile"));
//check login credentials using Authentication Manager of CSM
boolean loginSuccess = false;
try {
loginSuccess = getAuthenticationManager().login(
loginCredentials.getUserId(), loginCredentials.getPassword());
} catch (CSException ex) {
loginSuccess = false;
log.debug("The user was denied access to the study calendar application." + ex);
}
if (loginSuccess) {
return new ModelAndView(getSuccessView());
} else {
// have to add an error page or redirect to login page with error msg
loginCredentials = new LoginCredentials();
return new ModelAndView(getFormView(), "loginCredentials", loginCredentials);
}
}
/**
* Returns the AuthenticationManager for the csm authentication. This method follows the
* singleton pattern so that only one AuthenticationManager is created for
* the app.
*
* @return
* @throws CSException
*/
protected AuthenticationManager getAuthenticationManager()
throws CSException {
if (authMgr == null) {
synchronized (LoginController.class) {
if (authMgr == null) {
authMgr = SecurityServiceProvider
.getAuthenticationManager(CSM_STUDYCAL_CONTEXT_NAME);
}
}
}
log.debug("AuthenticationManager Class||"+authMgr);
return authMgr;
}
}
|
package com.couchbase.cblite.testapp.tests;
import android.test.InstrumentationTestCase;
import junit.framework.Assert;
import java.io.IOException;
public class TestBase64 extends InstrumentationTestCase {
public void testDecode() throws IOException {
String input1 = "eyJwdWJsaWMta2V5Ijp7ImFsZ29yaXRobSI6IkRTIiwieSI6ImNhNWJiYTYzZmI4MDQ2OGE0MjFjZjgxYTIzN2VlMDcwYTJlOTM4NTY0ODhiYTYzNTM0ZTU4NzJjZjllMGUwMDk0ZWQ2NDBlOGNhYmEwMjNkYjc5ODU3YjkxMzBlZGNmZGZiNmJiNTUwMWNjNTk3MTI1Y2NiMWQ1ZWQzOTVjZTMyNThlYjEwN2FjZTM1ODRiOWIwN2I4MWU5MDQ4NzhhYzBhMjFlOWZkYmRjYzNhNzNjOTg3MDAwYjk4YWUwMmZmMDQ4ODFiZDNiOTBmNzllYzVlNDU1YzliZjM3NzFkYjEzMTcxYjNkMTA2ZjM1ZDQyZmZmZjQ2ZWZiZDcwNjgyNWQiLCJwIjoiZmY2MDA0ODNkYjZhYmZjNWI0NWVhYjc4NTk0YjM1MzNkNTUwZDlmMWJmMmE5OTJhN2E4ZGFhNmRjMzRmODA0NWFkNGU2ZTBjNDI5ZDMzNGVlZWFhZWZkN2UyM2Q0ODEwYmUwMGU0Y2MxNDkyY2JhMzI1YmE4MWZmMmQ1YTViMzA1YThkMTdlYjNiZjRhMDZhMzQ5ZDM5MmUwMGQzMjk3NDRhNTE3OTM4MDM0NGU4MmExOGM0NzkzMzQzOGY4OTFlMjJhZWVmODEyZDY5YzhmNzVlMzI2Y2I3MGVhMDAwYzNmNzc2ZGZkYmQ2MDQ2MzhjMmVmNzE3ZmMyNmQwMmUxNyIsInEiOiJlMjFlMDRmOTExZDFlZDc5OTEwMDhlY2FhYjNiZjc3NTk4NDMwOWMzIiwiZyI6ImM1MmE0YTBmZjNiN2U2MWZkZjE4NjdjZTg0MTM4MzY5YTYxNTRmNGFmYTkyOTY2ZTNjODI3ZTI1Y2ZhNmNmNTA4YjkwZTVkZTQxOWUxMzM3ZTA3YTJlOWUyYTNjZDVkZWE3MDRkMTc1ZjhlYmY2YWYzOTdkNjllMTEwYjk2YWZiMTdjN2EwMzI1OTMyOWU0ODI5YjBkMDNiYmM3ODk2YjE1YjRhZGU1M2UxMzA4NThjYzM0ZDk2MjY5YWE4OTA0MWY0MDkxMzZjNzI0MmEzODg5NWM5ZDViY2NhZDRmMzg5YWYxZDdhNGJkMTM5OGJkMDcyZGZmYTg5NjIzMzM5N2EifSwicHJpbmNpcGFsIjp7ImVtYWlsIjoiamVuc0Btb29zZXlhcmQuY29tIn0sImlhdCI6MTM1ODI5NjIzNzU3NywiZXhwIjoxMzU4MzgyNjM3NTc3LCJpc3MiOiJsb2dpbi5wZXJzb25hLm9yZyJ9";
String expected1 = "{\"public-key\":{\"algorithm\":\"DS\",\"y\":\"ca5bba63fb80468a421cf81a237ee070a2e93856488ba63534e5872cf9e0e0094ed640e8caba023db79857b9130edcfdfb6bb5501cc597125ccb1d5ed395ce3258eb107ace3584b9b07b81e904878ac0a21e9fdbdcc3a73c987000b98ae02ff04881bd3b90f79ec5e455c9bf3771db13171b3d106f35d42ffff46efbd706825d\",\"p\":\"ff600483db6abfc5b45eab78594b3533d550d9f1bf2a992a7a8daa6dc34f8045ad4e6e0c429d334eeeaaefd7e23d4810be00e4cc1492cba325ba81ff2d5a5b305a8d17eb3bf4a06a349d392e00d329744a5179380344e82a18c47933438f891e22aeef812d69c8f75e326cb70ea000c3f776dfdbd604638c2ef717fc26d02e17\",\"q\":\"e21e04f911d1ed7991008ecaab3bf775984309c3\",\"g\":\"c52a4a0ff3b7e61fdf1867ce84138369a6154f4afa92966e3c827e25cfa6cf508b90e5de419e1337e07a2e9e2a3cd5dea704d175f8ebf6af397d69e110b96afb17c7a03259329e4829b0d03bbc7896b15b4ade53e130858cc34d96269aa89041f409136c7242a38895c9d5bccad4f389af1d7a4bd1398bd072dffa896233397a\"},\"principal\":{\"email\":\"jens@mooseyard.com\"},\"iat\":1358296237577,\"exp\":1358382637577,\"iss\":\"login.persona.org\"}";
String output1a = new String(android.util.Base64.decode(input1, android.util.Base64.DEFAULT));
Assert.assertEquals(expected1, output1a);
String output1b = new String(com.couchbase.cblite.util.Base64.decode(input1, com.couchbase.cblite.util.Base64.DEFAULT));
Assert.assertEquals(expected1, output1b);
String input2 = "eyJleHAiOjEzNTgyOTY0Mzg0OTUsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDk4NC8ifQ";
String expected2 = "{\"exp\":1358296438495,\"aud\":\"http://localhost:4984/\"}";
String output2a = new String(android.util.Base64.decode(input2, android.util.Base64.DEFAULT));
Assert.assertEquals(expected2, output2a);
String output2b = new String(com.couchbase.cblite.util.Base64.decode(input2, com.couchbase.cblite.util.Base64.DEFAULT));
Assert.assertEquals(expected2, output2b);
}
}
|
package com.thinkbiganalytics.esbulkloader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
public class ElasticsearchRecordWriter extends RecordWriter<Text, Text> {
private static final int DEFAULT_BUFFER_SIZE = 100000;
private static final String ESBL_BUFFER_SIZE = "esbl.buffer_size";
private static final String DEFAULT_ES_PORT = "9200";
private static final String DEFAULT_ES_HOST = "localhost";
private static final String ESBL_PORT = "esbl.port";
private static final String ESBL_HOST = "esbl.host";
private static Log log = LogFactory.getLog(ElasticsearchRecordWriter.class);
private PostMethod method;
private final String apiUrl;
private final int bufferSize;
private final StringBuffer buffer ;
public ElasticsearchRecordWriter(TaskAttemptContext context) {
String host = context.getConfiguration().get(ESBL_HOST);
String port = context.getConfiguration().get(ESBL_PORT);
String size = context.getConfiguration().get(ESBL_BUFFER_SIZE);
host = (null == host ? DEFAULT_ES_HOST : host);
port = (null == port ? DEFAULT_ES_PORT : port);
bufferSize = (null == size ? DEFAULT_BUFFER_SIZE : Integer.parseInt(size));
buffer = new StringBuffer(bufferSize);
apiUrl = String.format("http://%s:%s/_bulk", host, port);
}
@Override
public void write(Text key, Text value) throws IOException,
InterruptedException {
buffer.append(value.toString());
log.info(value.toString());
checkFlush();
}
@Override
public void close(TaskAttemptContext arg0) throws IOException,
InterruptedException {
flush();
method.releaseConnection();
}
private void checkFlush() throws UnsupportedEncodingException {
if (buffer.length()>this.bufferSize) {
flush();
buffer.setLength(0);
}
}
private void flush() throws UnsupportedEncodingException {
method = new PostMethod(apiUrl);
method.setRequestEntity(new StringRequestEntity(buffer.toString(),
"text/json", "UTF-8"));
BufferedReader br = null;
HttpClient client = new HttpClient();
try {
int returnCode = client.executeMethod(method);
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
log.error(String.format(
"The Post method is not implemented by this URI (%s)",
apiUrl));
// still consume the response body
method.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(
method.getResponseBodyAsStream()));
// if (log.isInfoEnabled()) {
String readLine;
while (((readLine = br.readLine()) != null)) {
System.out.println(readLine);
}
}
} catch (Exception e) {
log.error(e);
} finally {
if (br != null) {
try {
br.close();
} catch (Exception fe) {
log.error(fe);
}
}
}
}
}
|
package alien4cloud.plugin.marathon.service.builders;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.log4j.Log4j;
import mesosphere.marathon.client.model.v2.*;
import org.springframework.util.StringUtils;
/**
* @author Adrian Fraisse
*/
@Log4j
public class AppBuilder {
private App app;
private AppBuilder(String id) {
// Initialize the app as a docker container
this.app = new App();
app.setId(id.toLowerCase());
Container container = new Container();
app.setContainer(container);
}
public App build() {
assert !StringUtils.isEmpty(app.getId());
assert app.getContainer().getDocker() == null || !StringUtils.isEmpty(app.getContainer().getDocker().getImage());
if (!app.getId().matches("^(([a-z0-9]|[a-z0-9][a-z0-9\\-]*[a-z0-9])\\.)*([a-z0-9]|[a-z0-9][a-z0-9\\-]*[a-z0-9])|(\\.|\\.\\.)$")) {
throw new IllegalArgumentException("Node ID is invalid. Allowed: lowercase letters, digits, hyphens, \".\", \"..\"");
}
return this.app;
}
public static AppBuilder builder(String id) {
return new AppBuilder(id);
}
public AppBuilder docker(String image) {
Docker docker = new Docker();
docker.setImage(image);
app.getContainer().setDocker(docker);
app.getContainer().setType("DOCKER");
return this;
}
public AppBuilder instances(Integer instances) {
app.setInstances(instances);
return this;
}
public AppBuilder cpu(Double cpu) {
app.setCpus(cpu);
return this;
}
public AppBuilder mem(Double mem) {
app.setMem(mem);
return this;
}
public AppBuilder cmd(String cmd) {
app.setCmd(cmd);
return this;
}
public AppBuilder bridgeNetworking() {
getDocker().setNetwork("BRIDGE");
return this;
}
public AppBuilder hostNetworking() {
// Only set to host if not already set as bridged
if (getDocker().getNetwork() == null)
getDocker().setNetwork("HOST");
return this;
}
public AppBuilder portMapping(Port portMapping) {
if (getDocker().getPortMappings() == null)
getDocker().setPortMappings(Lists.newArrayList());
getDocker().getPortMappings().add(portMapping);
return this;
}
public AppBuilder internallyLoadBalanced() {
app.addLabel("HAPROXY_GROUP", "internal");
return this;
}
public AppBuilder envVariable(String varName, String value) {
if (app.getEnv() == null) app.setEnv(Maps.newHashMap());
app.getEnv().put(varName, value);
return this;
}
public AppBuilder dockerOption(String optName, String value) {
if (getDocker().getParameters() == null)
getDocker().setParameters(Lists.newArrayList());
getDocker().getParameters().add(new Parameter(optName, value));
return this;
}
public AppBuilder dockerArgs(String... args) {
if (app.getArgs() == null)
app.setArgs(Lists.newArrayList(args));
else
app.getArgs().addAll(Lists.newArrayList(args));
return this;
}
public AppBuilder input(final String key, final String value) {
if (key.startsWith("ENV_")) {
// Input as environment variable within the container
if (app.getEnv() == null) app.setEnv(Maps.newHashMap());
app.getEnv().put(key.replaceFirst("^ENV_", ""), value);
} else if (key.startsWith("OPT_")) {
// Input as a docker option given to the docker cli
if (getDocker().getParameters() == null) getDocker().setParameters(Lists.newArrayList());
getDocker().getParameters().add(new Parameter(key.replaceFirst("OPT_", ""), value));
} else if (key.startsWith("ARG_")) {
// Input as an argument to the docker run command
if (app.getArgs() == null) app.setArgs(Lists.newArrayList());
this.app.getArgs().add(value); // Arguments are unnamed
} else
log.warn("Unrecognized prefix for input : <" + key + ">");
return this;
}
public AppBuilder dependency(String appId) {
app.addDependency(appId);
return this;
}
public AppBuilder defaultHealthCheck() {
if (app.getHealthChecks() == null)
app.setHealthChecks(Lists.newArrayList());
HealthCheck healthCheck = new HealthCheck();
healthCheck.setPortIndex(0);
healthCheck.setProtocol("TCP");
healthCheck.setGracePeriodSeconds(300);
healthCheck.setIntervalSeconds(15);
healthCheck.setMaxConsecutiveFailures(1);
app.getHealthChecks().add(healthCheck);
return this;
}
public AppBuilder externalVolume(ExternalVolume externalVolume) {
if (app.getContainer().getVolumes() == null) app.getContainer().setVolumes(Lists.newArrayList());
app.getContainer().getVolumes().add(externalVolume);
return this;
}
private Docker getDocker() {
return app.getContainer().getDocker();
}
}
|
package br.com.caelum.brutal.controllers;
import static java.util.Arrays.asList;
import java.util.List;
import br.com.caelum.brutal.auth.Access;
import br.com.caelum.brutal.auth.FacebookAuthService;
import br.com.caelum.brutal.auth.SignupInfo;
import br.com.caelum.brutal.dao.LoginMethodDAO;
import br.com.caelum.brutal.dao.UserDAO;
import br.com.caelum.brutal.factory.MessageFactory;
import br.com.caelum.brutal.model.LoginMethod;
import br.com.caelum.brutal.model.MethodType;
import br.com.caelum.brutal.model.User;
import br.com.caelum.brutal.validators.UrlValidator;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.validator.I18nMessage;
@Resource
public class FacebookAuthController extends Controller{
private final FacebookAuthService facebook;
private final UserDAO users;
private final LoginMethodDAO loginMethods;
private final Result result;
private final Access access;
private final MessageFactory messageFactory;
private UrlValidator urlValidator;
public FacebookAuthController(FacebookAuthService facebook, UserDAO users,
LoginMethodDAO loginMethods, Result result, Access access,
MessageFactory messageFactory, UrlValidator urlValidator) {
this.facebook = facebook;
this.users = users;
this.loginMethods = loginMethods;
this.result = result;
this.access = access;
this.messageFactory = messageFactory;
this.urlValidator = urlValidator;
}
@Get("/cadastrar/facebook")
public void signupViaFacebook(String code, String state) {
if (code == null){
redirectTo(ListController.class).home();
return;
}
String rawToken = facebook.buildToken(code);
SignupInfo signupInfo = facebook.getSignupInfo();
User existantFacebookUser = users.findByEmailAndMethod(signupInfo.getEmail(), MethodType.FACEBOOK);
if (existantFacebookUser != null) {
access.login(existantFacebookUser);
redirectToRightUrl(state);
return;
}
User existantBrutalUser = users.findByEmailAndMethod(signupInfo.getEmail(), MethodType.BRUTAL);
if (existantBrutalUser != null) {
mergeLoginMethods(rawToken, existantBrutalUser);
redirectToRightUrl(state);
return;
}
createNewUser(rawToken, signupInfo);
redirectToRightUrl(state);
}
private void redirectToRightUrl(String state) {
boolean valid = urlValidator.isValid(state);
if (!valid) {
includeAsList("messages", i18n("error", "error.invalid.url", state));
}
if (state != null && !state.isEmpty() && valid) {
redirectTo(state);
} else {
redirectTo(ListController.class).home();
}
}
private void createNewUser(String rawToken, SignupInfo signupInfo) {
User user = new User(signupInfo.getName(), signupInfo.getEmail());
LoginMethod facebookLogin = new LoginMethod(MethodType.FACEBOOK, signupInfo.getEmail(), rawToken, user);
user.add(facebookLogin);
users.save(user);
loginMethods.save(facebookLogin);
access.login(user);
}
private void mergeLoginMethods(String rawToken, User existantBrutalUser) {
LoginMethod facebookLogin = LoginMethod.facebookLogin(existantBrutalUser, existantBrutalUser.getEmail(), rawToken);
List<I18nMessage> messages = asList(messageFactory.build("confirmation", "signup.facebook.existant_brutal", existantBrutalUser.getEmail()));
result.include("messages", messages);
existantBrutalUser.add(facebookLogin);
loginMethods.save(facebookLogin);
access.login(existantBrutalUser);
}
}
|
package com.aaomidi.justskyblock.api.command;
import com.aaomidi.justskyblock.JustSkyblock;
import com.aaomidi.justskyblock.api.command.objects.SkyblockCommand;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.HashMap;
/**
* @author aaomidi
*/
public class SkyblockCommandAPI implements CommandExecutor {
private final JustSkyblock instance;
private final HashMap<String, SkyblockCommand> registeredCommands;
public SkyblockCommandAPI(JustSkyblock instance) {
this.instance = instance;
registeredCommands = new HashMap<>();
instance.getCommand("is").setExecutor(this);
}
public void registerCommand(SkyblockCommand skyblockCommand) {
registeredCommands.put(skyblockCommand.getCommandLabel(), skyblockCommand);
if (skyblockCommand.getAliases() == null || skyblockCommand.getAliases().length == 0) {
return;
}
for (String alias : skyblockCommand.getAliases()) {
registeredCommands.put(alias, skyblockCommand);
}
}
@Override
public boolean onCommand(CommandSender commandSender, Command cmd, String commandLabel, String[] args) {
if (!cmd.getName().equalsIgnoreCase("is")) return true;
if (args.length == 0) {
// Send information about all the registered commands.
return true;
}
String subCommand = args[0];
if (!registeredCommands.containsKey(subCommand)) {
// Send command not found.
return true;
}
SkyblockCommand skyblockCommand = registeredCommands.get(subCommand);
String[] newArray = Arrays.copyOfRange(args, 1, args.length);
if (skyblockCommand.isForcePlayer()) {
if (!(commandSender instanceof Player)) {
// Send error.
return true;
}
}
skyblockCommand.getExecutor().execute(commandSender, newArray);
return true;
}
}
|
package raptor.pref;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.resource.StringConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import raptor.Quadrant;
import raptor.Raptor;
import raptor.chat.ChatEvent;
import raptor.chat.ChatType;
import raptor.swt.BugPartners;
import raptor.swt.GamesWindowItem;
import raptor.swt.SWTUtils;
import raptor.swt.SeekTableWindowItem;
import raptor.swt.chess.controller.InactiveMouseAction;
import raptor.swt.chess.controller.ObservingMouseAction;
import raptor.swt.chess.controller.PlayingMouseAction;
import raptor.util.OSUtils;
import raptor.util.RaptorStringUtils;
/**
* The RaptorPreferenceStore. Automatically loads and saves itself at
* Raptor.USER_RAPTOR_DIR/raptor.properties . Had additional data type support.
*/
public class RaptorPreferenceStore extends PreferenceStore implements
PreferenceKeys {
private static final Log LOG = LogFactory
.getLog(RaptorPreferenceStore.class);
public static final String PREFERENCE_PROPERTIES_FILE = "raptor.properties";
public static final File RAPTOR_PROPERTIES = new File(
Raptor.USER_RAPTOR_DIR, "raptor.properties");
protected String defaultMonospacedFontName;
protected String defaultFontName;
protected int defaultLargeFontSize;
protected int defaultSmallFontSize;
protected int defaultMediumFontSize;
protected int defaultTinyFontSize;
private IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String key = event.getProperty();
if (key.endsWith("color")) {
Raptor.getInstance().getColorRegistry().put(
key,
PreferenceConverter.getColor(
RaptorPreferenceStore.this, key));
} else if (key.endsWith("font")) {
// Adjust all the zoomed fonts, as well as the font being
// changed,
// in the FontRegistry.
// Add all the fonts to change to a list to avoid the
// concurrency issues.
List<String> fontKeysToChange = new ArrayList<String>();
for (Object fontRegistryKey : Raptor.getInstance()
.getFontRegistry().getKeySet()) {
String fontKey = fontRegistryKey.toString();
if (fontKey.startsWith(key)) {
fontKeysToChange.add(fontKey);
}
}
for (String fontKey : fontKeysToChange) {
if (fontKey.equals(key)) {
Raptor.getInstance().getFontRegistry().put(
key,
PreferenceConverter.getFontDataArray(
RaptorPreferenceStore.this, key));
} else {
double zoomFactor = Double.parseDouble(fontKey
.substring(key.length() + 1));
Raptor.getInstance().getFontRegistry().put(fontKey,
zoomFont(key, zoomFactor));
}
}
}
}
};
protected void resetChessSetIfDeleted() {
String chessSet = getString(BOARD_CHESS_SET_NAME);
File file = new File(Raptor.RESOURCES_DIR + "set/" + chessSet);
if (!file.exists() || !file.isDirectory()) {
setValue(BOARD_CHESS_SET_NAME,
getDefaultString(BOARD_CHESS_SET_NAME));
}
}
public RaptorPreferenceStore() {
super();
FileInputStream fileIn = null;
FileOutputStream fileOut = null;
try {
LOG.info("Loading RaptorPreferenceStore store "
+ PREFERENCE_PROPERTIES_FILE);
loadDefaults();
if (RAPTOR_PROPERTIES.exists()) {
load(fileIn = new FileInputStream(RAPTOR_PROPERTIES));
resetChessSetIfDeleted();
} else {
RAPTOR_PROPERTIES.getParentFile().mkdir();
RAPTOR_PROPERTIES.createNewFile();
save(fileOut = new FileOutputStream(RAPTOR_PROPERTIES),
"Last saved on " + new Date());
}
} catch (Exception e) {
LOG.error("Error reading or writing to file ", e);
throw new RuntimeException(e);
} finally {
if (fileIn != null) {
try {
fileIn.close();
} catch (Throwable t) {
}
}
if (fileOut != null) {
try {
fileOut.flush();
fileOut.close();
} catch (Throwable t) {
}
}
}
addPropertyChangeListener(propertyChangeListener);
LOG.info("Loaded preferences from "
+ RAPTOR_PROPERTIES.getAbsolutePath());
}
/**
* Returns null for CHANNEL_TELL type.
*/
public Color getColor(ChatType type) {
String key = null;
if (type == ChatType.CHANNEL_TELL) {
return null;
} else {
key = getKeyForChatType(type);
}
return getColorForKeyWithoutDefault(key);
}
protected Color getColorForKeyWithoutDefault(String key) {
Color result = null;
try {
if (!Raptor.getInstance().getColorRegistry().hasValueFor(key)) {
// We don't want the default color if not found we want to
// return null, so use
// StringConverter instead of PreferenceConverter.
String value = getString(key);
if (StringUtils.isNotBlank(value)) {
RGB rgb = StringConverter.asRGB(value, null);
if (rgb != null) {
Raptor.getInstance().getColorRegistry().put(key, rgb);
} else {
return null;
}
} else {
return null;
}
}
result = Raptor.getInstance().getColorRegistry().get(key);
} catch (Throwable t) {
result = null;
}
return result;
}
/**
* Returns the foreground color to use for the specified chat event. Returns
* null if no special color should be used.
*/
public Color getColor(ChatEvent event) {
String key = null;
if (event.getType() == ChatType.CHANNEL_TELL) {
key = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + event.getType() + "-"
+ event.getChannel() + "-color";
} else {
key = getKeyForChatType(event.getType());
}
return getColorForKeyWithoutDefault(key);
}
/**
* Returns null for CHANNEL_TELL type.
*
* @return
*/
public String getKeyForChatType(ChatType type) {
String result = null;
if (type == ChatType.CHANNEL_TELL) {
result = null;
} else if (type == ChatType.BUGWHO_AVAILABLE_TEAMS
|| type == ChatType.BUGWHO_GAMES
|| type == ChatType.BUGWHO_UNPARTNERED_BUGGERS) {
result = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.BUGWHO_ALL
+ "-color";
} else if (type == ChatType.NOTIFICATION_DEPARTURE) {
result = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO
+ ChatType.NOTIFICATION_ARRIVAL + "-color";
} else {
result = CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + type + "-color";
}
return result;
}
/**
* Returns the color for the specified key. Returns BLACK if the key was not
* found.
*/
public Color getColor(String key) {
try {
if (!Raptor.getInstance().getColorRegistry().hasValueFor(key)) {
RGB rgb = PreferenceConverter.getColor(this, key);
if (rgb != null) {
Raptor.getInstance().getColorRegistry().put(key, rgb);
}
}
return Raptor.getInstance().getColorRegistry().get(key);
} catch (Throwable t) {
LOG.error("Error in getColor(" + key + ") Returning black.", t);
return new Color(Display.getCurrent(), new RGB(0, 0, 0));
}
}
public Rectangle getCurrentLayoutRectangle(String key) {
key = "app-" + getString(APP_LAYOUT) + "-" + key;
return getRectangle(key);
}
public int[] getCurrentLayoutSashWeights(String key) {
key = "app-" + getString(APP_LAYOUT) + "-" + key;
return getIntArray(key);
}
public RGB getDefaultColor(String key) {
return PreferenceConverter.getDefaultColor(this, key);
}
public int[] getDefaultIntArray(String key) {
return RaptorStringUtils.intArrayFromString(getDefaultString(key));
}
public String[] getDefaultStringArray(String key) {
return RaptorStringUtils.stringArrayFromString(getDefaultString(key));
}
public String getDefauultMonospacedFont() {
FontData[] fonts = Raptor.getInstance().getDisplay().getFontList(null,
true);
String[] preferredFontNames = null;
String osName = System.getProperty("os.name");
if (osName.startsWith("Mac OS")) {
preferredFontNames = SWTUtils.OSX_MONOSPACED_FONTS;
} else if (osName.startsWith("Windows")) {
preferredFontNames = SWTUtils.WINDOWS_MONOSPACED_FONTS;
} else {
preferredFontNames = SWTUtils.OTHER_MONOSPACED_FONTS;
}
String result = null;
outer: for (int i = 0; i < preferredFontNames.length; i++) {
for (FontData fontData : fonts) {
if (fontData.getName().equalsIgnoreCase(preferredFontNames[i])) {
result = preferredFontNames[i];
break outer;
}
}
}
if (result == null) {
result = "Courier";
}
return result;
}
protected FontData[] zoomFont(String key, double zoomFactor) {
FontData[] fontData = PreferenceConverter.getFontDataArray(this, key);
// Convert font to zoom factor.
for (int i = 0; i < fontData.length; i++) {
fontData[i].setHeight((int) (fontData[i].getHeight() * zoomFactor));
}
return fontData;
}
protected String getZoomFontKey(String key, double zoomFactor) {
return key + "-" + zoomFactor;
}
public Font getFont(String key, boolean isAdjustingForZoomFactor) {
try {
String adjustedKey = key;
if (isAdjustingForZoomFactor) {
double zoomFactor = getDouble(APP_ZOOM_FACTOR);
adjustedKey = getZoomFontKey(key, zoomFactor);
}
if (!Raptor.getInstance().getFontRegistry()
.hasValueFor(adjustedKey)) {
FontData[] fontData = null;
if (!isAdjustingForZoomFactor) {
fontData = PreferenceConverter.getFontDataArray(this, key);
} else {
fontData = zoomFont(key, getDouble(APP_ZOOM_FACTOR));
}
Raptor.getInstance().getFontRegistry().put(adjustedKey,
fontData);
}
return Raptor.getInstance().getFontRegistry().get(adjustedKey);
} catch (Throwable t) {
LOG.error("Error in getFont(" + key + ") Returning default font.",
t);
return Raptor.getInstance().getFontRegistry().defaultFont();
}
}
/**
* Returns the font for the specified key. Returns the default font if key
* was not found.
*
* Fonts returned from this method will be adjusted to the APP_ZOOM_FACTOR
* preference.
*/
public Font getFont(String key) {
return getFont(key, true);
}
public int[] getIntArray(String key) {
return RaptorStringUtils.intArrayFromString(getString(key));
}
public Point getPoint(String key) {
return PreferenceConverter.getPoint(this, key);
}
public Quadrant getQuadrant(String key) {
return Quadrant.valueOf(getString(key));
}
public Rectangle getRectangle(String key) {
return PreferenceConverter.getRectangle(this, key);
}
public String[] getStringArray(String key) {
return RaptorStringUtils.stringArrayFromString(getString(key));
}
public void loadDefaults() {
defaultFontName = Raptor.getInstance().getFontRegistry().defaultFont()
.getFontData()[0].getName();
defaultMonospacedFontName = getDefauultMonospacedFont();
setDefaultMonitorBasedSizes();
// Action
setDefault(ACTION_SEPARATOR_SEQUENCE, 400);
// App settings.
setDefault(APP_NAME, "Raptor .98");
setDefault(APP_IS_SHOWING_CHESS_PIECE_UNICODE_CHARS, !OSUtils
.isLikelyWindowsXP());
setDefault(APP_SASH_WIDTH, 8);
PreferenceConverter.setDefault(this, APP_PING_FONT,
new FontData[] { new FontData(defaultFontName,
defaultSmallFontSize, 0) });
PreferenceConverter.setDefault(this, APP_PING_COLOR, new RGB(0, 0, 0));
PreferenceConverter.setDefault(this, APP_STATUS_BAR_FONT,
new FontData[] { new FontData(defaultFontName,
defaultSmallFontSize, 0) });
PreferenceConverter.setDefault(this, APP_STATUS_BAR_COLOR, new RGB(0,
0, 0));
setDefault(APP_HOME_URL,
"http://code.google.com/p/raptor-chess-interface/");
setDefault(APP_SOUND_ENABLED, true);
setDefault(APP_USER_TAGS,
"+Partner,-Partner,Cool,Dupe,Friend,Jerk,Lagger,Noob,Premover,Troll,Strange");
setDefault(APP_IS_LOGGING_GAMES, true);
setDefault(APP_LAYOUT, "Layout1");
setDefault(APP_OPEN_LINKS_IN_EXTERNAL_BROWSER, false);
setDefault(APP_BROWSER_QUADRANT, Quadrant.II);
setDefault(APP_CHESS_BOARD_QUADRANTS, new String[] {
Quadrant.II.toString(), Quadrant.III.toString(),
Quadrant.IV.toString(), Quadrant.V.toString() });
setDefault(APP_PGN_RESULTS_QUADRANT, Quadrant.III);
setDefault(APP_IS_LAUNCHNG_HOME_PAGE, true);
setDefault(APP_WINDOW_ITEM_POLL_INTERVAL, 5);
setDefault(APP_IS_LOGGING_CONSOLE, false);
setDefault(APP_IS_LOGGING_PERSON_TELLS, false);
setDefault(APP_IS_LOGGING_CHANNEL_TELLS, false);
// Layout 1 settings.
setDefault(APP_WINDOW_BOUNDS, new Rectangle(0, 0, -1, -1));
setDefault(APP_QUAD9_QUAD12345678_SASH_WEIGHTS, new int[] { 10, 90 });
setDefault(APP_QUAD1_QUAD2345678_SASH_WEIGHTS, new int[] { 50, 50 });
setDefault(APP_QUAD2345_QUAD678_SASH_WEIGHTS, new int[] { 70, 30 });
setDefault(APP_QUAD2_QUAD3_QUAD4_QUAD5_SASH_WEIGHTS, new int[] { 25,
25, 25, 25 });
setDefault(APP_QUAD67_QUAD8_SASH_WEIGHTS, new int[] { 70, 30 });
setDefault(APP_QUAD6_QUAD7_SASH_WEIGHTS, new int[] { 50, 50 });
setDefault(APP_ZOOM_FACTOR, 1.0);
if (OSUtils.isLikelyWindows() && !OSUtils.isLikelyWindows7()) {
setDefault(SPEECH_PROCESS_NAME, "SayStatic");
}
if (OSUtils.isLikelyLinux()) {
try {
if (Runtime.getRuntime().exec(new String[] { "which", "play" })
.waitFor() == 0) {
setDefault(PreferenceKeys.SOUND_PROCESS_NAME, "aplay");
} else if (Runtime.getRuntime().exec(
new String[] { "which", "aplay" }).waitFor() == 0) {
setDefault(PreferenceKeys.SOUND_PROCESS_NAME, "play");
}
} catch (Throwable t) {
LOG
.warn(
"Error launching which to determine sound process in linux.",
t);
}
}
// Board
setDefault(BOARD_ALLOW_MOUSE_WHEEL_NAVIGATION_WHEEL_PLAYING, false);
setDefault(BOARD_SHOW_PLAYING_GAME_STATS_ON_GAME_END, true);
setDefault(BOARD_PLAY_CHALLENGE_SOUND, true);
setDefault(BOARD_PLAY_ABORT_REQUEST_SOUND, true);
setDefault(BOARD_PLAY_DRAW_OFFER_SOUND, true);
setDefault(BOARD_USER_MOVE_INPUT_MODE, "DragAndDrop");
setDefault(BOARD_SHOW_BUGHOUSE_SIDE_UP_TIME, true);
setDefault(BOARD_PIECE_JAIL_LABEL_PERCENTAGE, 40);
setDefault(BOARD_COOLBAR_MODE, true);
setDefault(BOARD_COOLBAR_ON_TOP, true);
setDefault(BOARD_CHESS_SET_NAME, "Wiki");
setDefault(BOARD_SQUARE_BACKGROUND_NAME, "GreenMarble");
setDefault(BOARD_IS_SHOW_COORDINATES, true);
setDefault(BOARD_PIECE_SIZE_ADJUSTMENT, .06);
setDefault(BOARD_IS_SHOWING_PIECE_JAIL, false);
setDefault(BOARD_CLOCK_SHOW_MILLIS_WHEN_LESS_THAN, Integer.MIN_VALUE);
setDefault(BOARD_CLOCK_SHOW_SECONDS_WHEN_LESS_THAN,
1000L * 60L * 60L + 1L);
setDefault(BOARD_IS_PLAYING_10_SECOND_COUNTDOWN_SOUNDS, true);
setDefault(BOARD_PREMOVE_ENABLED, true);
setDefault(BOARD_PLAY_MOVE_SOUND_WHEN_OBSERVING, true);
setDefault(BOARD_QUEUED_PREMOVE_ENABLED, false);
setDefault(BOARD_IS_USING_CROSSHAIRS_CURSOR, false);
setDefault(BOARD_LAYOUT, "raptor.swt.chess.layout.RightOrientedLayout");
setDefault(BOARD_TAKEOVER_INACTIVE_GAMES, true);
setDefault(BOARD_PIECE_JAIL_SHADOW_ALPHA, 30);
setDefault(BOARD_PIECE_SHADOW_ALPHA, 40);
setDefault(BOARD_COORDINATES_SIZE_PERCENTAGE, 26);
setDefault(BOARD_ANNOUNCE_CHECK_WHEN_OPPONENT_CHECKS_ME, false);
setDefault(BOARD_ANNOUNCE_CHECK_WHEN_I_CHECK_OPPONENT, false);
setDefault(BOARD_SPEAK_MOVES_OPP_MAKES, false);
setDefault(BOARD_SPEAK_MOVES_I_MAKE, false);
setDefault(BOARD_SPEAK_WHEN_OBSERVING, false);
setDefault(BOARD_SPEAK_RESULTS, false);
setDefault(BOARD_IGNORE_OBSERVED_GAMES_IF_PLAYING, false);
setDefault(BOARD_MOVE_LIST_CLASS,
"raptor.swt.chess.movelist.TextAreaMoveList");
setDefault(BOARD_IS_USING_SOLID_BACKGROUND_COLORS, false);
PreferenceConverter.setDefault(this, BOARD_BACKGROUND_COLOR, new RGB(0,
0, 0));
PreferenceConverter.setDefault(this, BOARD_COORDINATES_COLOR, new RGB(
0, 0, 0));
PreferenceConverter.setDefault(this, BOARD_ACTIVE_CLOCK_COLOR, new RGB(
0, 255, 0));
PreferenceConverter.setDefault(this, BOARD_INACTIVE_CLOCK_COLOR,
new RGB(128, 128, 128));
PreferenceConverter.setDefault(this, BOARD_CONTROL_COLOR, new RGB(128,
128, 128));
PreferenceConverter.setDefault(this, BOARD_LAG_OVER_20_SEC_COLOR,
new RGB(255, 0, 0));
PreferenceConverter.setDefault(this, BOARD_PIECE_JAIL_LABEL_COLOR,
new RGB(0, 255, 0));
PreferenceConverter.setDefault(this, BOARD_PIECE_JAIL_BACKGROUND_COLOR,
new RGB(0, 0, 0));
PreferenceConverter.setDefault(this,
BOARD_LIGHT_SQUARE_SOLID_BACKGROUND_COLOR, new RGB(0, 153,
197));
PreferenceConverter.setDefault(this,
BOARD_DARK_SQUARE_SOLID_BACKGROUND_COLOR, new RGB(0, 0, 0));
PreferenceConverter.setDefault(this, BOARD_COORDINATES_FONT,
new FontData[] { new FontData(defaultFontName,
defaultMediumFontSize, 0) });
PreferenceConverter
.setDefault(this, BOARD_CLOCK_FONT,
new FontData[] { new FontData(
defaultMonospacedFontName, 24, 0) });
PreferenceConverter.setDefault(this, BOARD_LAG_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_PLAYER_NAME_FONT,
new FontData[] { new FontData(defaultFontName,
defaultLargeFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_PIECE_JAIL_FONT,
new FontData[] { new FontData(defaultFontName,
defaultMediumFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_OPENING_DESC_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_STATUS_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_GAME_DESCRIPTION_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
PreferenceConverter.setDefault(this, BOARD_PREMOVES_FONT,
new FontData[] { new FontData(defaultFontName,
defaultTinyFontSize, 0) });
//Controller button preferences.
setDefault(PLAYING_CONTROLLER + LEFT_MOUSE_BUTTON_ACTION,
PlayingMouseAction.None.toString());
setDefault(PLAYING_CONTROLLER + RIGHT_MOUSE_BUTTON_ACTION,
PlayingMouseAction.PopupMenu.toString());
setDefault(PLAYING_CONTROLLER + MIDDLE_MOUSE_BUTTON_ACTION,
PlayingMouseAction.SmartMove.toString());
setDefault(PLAYING_CONTROLLER + MISC1_MOUSE_BUTTON_ACTION,
PlayingMouseAction.None.toString());
setDefault(PLAYING_CONTROLLER + MISC2_MOUSE_BUTTON_ACTION,
PlayingMouseAction.None.toString());
setDefault(PLAYING_CONTROLLER + LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION,
PlayingMouseAction.None.toString());
setDefault(OBSERVING_CONTROLLER + LEFT_MOUSE_BUTTON_ACTION,
ObservingMouseAction.MakePrimaryGame.toString());
setDefault(OBSERVING_CONTROLLER + RIGHT_MOUSE_BUTTON_ACTION,
ObservingMouseAction.AddGameChatTab.toString());
setDefault(OBSERVING_CONTROLLER + MIDDLE_MOUSE_BUTTON_ACTION,
ObservingMouseAction.MatchWinner.toString());
setDefault(OBSERVING_CONTROLLER + MISC1_MOUSE_BUTTON_ACTION,
ObservingMouseAction.None.toString());
setDefault(OBSERVING_CONTROLLER + MISC2_MOUSE_BUTTON_ACTION,
ObservingMouseAction.None.toString());
setDefault(
OBSERVING_CONTROLLER + LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION,
ObservingMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + LEFT_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + RIGHT_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + MIDDLE_MOUSE_BUTTON_ACTION,
InactiveMouseAction.Rematch.toString());
setDefault(INACTIVE_CONTROLLER + MISC1_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + MISC2_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
setDefault(INACTIVE_CONTROLLER + LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION,
InactiveMouseAction.None.toString());
// BugArena
setDefault(BUG_ARENA_PARTNERS_INDEX, 0);
setDefault(BUG_ARENA_MAX_PARTNERS_INDEX,
BugPartners.getRatings().length - 1);
setDefault(BUG_ARENA_TEAMS_INDEX, 0);
setDefault(BUG_ARENA_TEAMS_IS_RATED, true);
setDefault(BUG_ARENA_SELECTED_TAB, 0);
// SeekTable
setDefault(SEEK_TABLE_RATINGS_INDEX, 0);
setDefault(SEEK_TABLE_MAX_RATINGS_INDEX, SeekTableWindowItem
.getRatings().length - 1);
setDefault(SEEK_TABLE_RATED_INDEX, 0);
setDefault(SEEK_TABLE_SHOW_COMPUTERS, true);
setDefault(SEEK_TABLE_SHOW_LIGHTNING, true);
setDefault(SEEK_TABLE_SHOW_BLITZ, true);
setDefault(SEEK_TABLE_SHOW_STANDARD, true);
setDefault(SEEK_TABLE_SHOW_CRAZYHOUSE, true);
setDefault(SEEK_TABLE_SHOW_FR, true);
setDefault(SEEK_TABLE_SHOW_WILD, true);
setDefault(SEEK_TABLE_SHOW_ATOMIC, true);
setDefault(SEEK_TABLE_SHOW_SUICIDE, true);
setDefault(SEEK_TABLE_SHOW_LOSERS, true);
setDefault(SEEK_TABLE_SHOW_UNTIMED, true);
setDefault(SEEK_TABLE_SELECTED_TAB, 2);
// Games table
setDefault(GAMES_TABLE_SELECTED_TAB, 1);
setDefault(GAMES_TABLE_RATINGS_INDEX, 0);
setDefault(GAMES_TABLE_MAX_RATINGS_INDEX,
GamesWindowItem.getRatings().length - 1);
setDefault(GAMES_TABLE_RATED_INDEX, 0);
setDefault(GAMES_TABLE_SHOW_BUGHOUSE, true);
setDefault(GAMES_TABLE_SHOW_LIGHTNING, true);
setDefault(GAMES_TABLE_SHOW_BLITZ, true);
setDefault(GAMES_TABLE_SHOW_STANDARD, true);
setDefault(GAMES_TABLE_SHOW_CRAZYHOUSE, true);
setDefault(GAMES_TABLE_SHOW_EXAMINED, true);
setDefault(GAMES_TABLE_SHOW_WILD, true);
setDefault(GAMES_TABLE_SHOW_ATOMIC, true);
setDefault(GAMES_TABLE_SHOW_SUICIDE, true);
setDefault(GAMES_TABLE_SHOW_LOSERS, true);
setDefault(GAMES_TABLE_SHOW_UNTIMED, true);
setDefault(GAMES_TABLE_SHOW_NONSTANDARD, true);
setDefault(GAMES_TABLE_SHOW_PRIVATE, true);
// Arrows
PreferenceConverter.setDefault(this, ARROW_OBS_OPP_COLOR, new RGB(255,
0, 255));
PreferenceConverter
.setDefault(this, ARROW_MY_COLOR, new RGB(0, 0, 255));
PreferenceConverter.setDefault(this, ARROW_PREMOVE_COLOR, new RGB(0, 0,
255));
PreferenceConverter.setDefault(this, ARROW_OBS_COLOR,
new RGB(0, 0, 255));
setDefault(ARROW_SHOW_ON_OBS_AND_OPP_MOVES, true);
setDefault(ARROW_SHOW_ON_MOVE_LIST_MOVES, true);
setDefault(ARROW_SHOW_ON_MY_PREMOVES, true);
setDefault(ARROW_SHOW_ON_MY_MOVES, false);
setDefault(ARROW_ANIMATION_DELAY, 200L);
setDefault(ARROW_FADE_AWAY_MODE, true);
setDefault(ARROW_WIDTH_PERCENTAGE, 15);
// Highlights
PreferenceConverter.setDefault(this, HIGHLIGHT_OBS_OPP_COLOR, new RGB(
255, 0, 255));
PreferenceConverter.setDefault(this, HIGHLIGHT_MY_COLOR, new RGB(0, 0,
255));
PreferenceConverter.setDefault(this, HIGHLIGHT_PREMOVE_COLOR, new RGB(
0, 0, 255));
PreferenceConverter.setDefault(this, HIGHLIGHT_OBS_COLOR, new RGB(0, 0,
255));
setDefault(HIGHLIGHT_SHOW_ON_OBS_AND_OPP_MOVES, true);
setDefault(HIGHLIGHT_SHOW_ON_MOVE_LIST_MOVES, true);
setDefault(HIGHLIGHT_SHOW_ON_MY_PREMOVES, true);
setDefault(HIGHLIGHT_SHOW_ON_MY_MOVES, false);
setDefault(HIGHLIGHT_FADE_AWAY_MODE, false);
setDefault(HIGHLIGHT_ANIMATION_DELAY, 200L);
setDefault(HIGHLIGHT_WIDTH_PERCENTAGE, 3);
// Game Results
PreferenceConverter.setDefault(this, RESULTS_COLOR, new RGB(255, 0, 0));
PreferenceConverter.setDefault(this, RESULTS_FONT,
new FontData[] { new FontData(defaultMonospacedFontName, 40,
SWT.BOLD) });
setDefault(RESULTS_IS_SHOWING, true);
setDefault(RESULTS_FADE_AWAY_MODE, true);
setDefault(RESULTS_ANIMATION_DELAY, 400L);
setDefault(RESULTS_WIDTH_PERCENTAGE, 80);
// Chat
setDefault(CHAT_MAX_CONSOLE_CHARS, 100000);
setDefault(CHAT_TIMESTAMP_CONSOLE, false);
setDefault(CHAT_TIMESTAMP_CONSOLE_FORMAT, "'['hh:mma']'");
setDefault(CHAT_IS_PLAYING_CHAT_ON_PTELL, true);
setDefault(CHAT_IS_PLAYING_CHAT_ON_PERSON_TELL, true);
setDefault(CHAT_IS_SMART_SCROLL_ENABLED, true);
setDefault(CHAT_OPEN_CHANNEL_TAB_ON_CHANNEL_TELLS, false);
setDefault(CHAT_OPEN_PERSON_TAB_ON_PERSON_TELLS, false);
setDefault(CHAT_OPEN_PARTNER_TAB_ON_PTELLS, false);
setDefault(CHAT_REMOVE_SUB_TAB_MESSAGES_FROM_MAIN_TAB, true);
setDefault(CHAT_UNDERLINE_URLS, true);
setDefault(CHAT_UNDERLINE_QUOTED_TEXT, true);
setDefault(CHAT_UNDERLINE_SINGLE_QUOTES, false);
setDefault(CHAT_PLAY_NOTIFICATION_SOUND_ON_ARRIVALS, true);
setDefault(CHAT_PLAY_NOTIFICATION_SOUND_ON_DEPARTURES, false);
setDefault(CHAT_UNDERLINE_COMMANDS, true);
setDefault(CHAT_COMMAND_LINE_SPELL_CHECK, true);
PreferenceConverter.setDefault(this, CHAT_INPUT_FONT,
new FontData[] { new FontData(defaultMonospacedFontName,
defaultLargeFontSize, 0) });
PreferenceConverter.setDefault(this, CHAT_OUTPUT_FONT,
new FontData[] { new FontData(defaultMonospacedFontName,
defaultMediumFontSize, 0) });
PreferenceConverter.setDefault(this, CHAT_INPUT_BACKGROUND_COLOR,
new RGB(0, 0, 0));
PreferenceConverter.setDefault(this, CHAT_CONSOLE_BACKGROUND_COLOR,
new RGB(0, 0, 0));
PreferenceConverter.setDefault(this, CHAT_INPUT_DEFAULT_TEXT_COLOR,
new RGB(128, 128, 128));
PreferenceConverter.setDefault(this, CHAT_OUTPUT_BACKGROUND_COLOR,
new RGB(255, 255, 255));
PreferenceConverter.setDefault(this, CHAT_OUTPUT_TEXT_COLOR, new RGB(0,
0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHALLENGE
+ "-color", new RGB(100, 149, 237));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CSHOUT
+ "-color", new RGB(221, 160, 221));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.SHOUT
+ "-color", new RGB(221, 160, 221));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.KIBITZ
+ "-color", new RGB(100, 149, 237));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.WHISPER
+ "-color", new RGB(100, 149, 237));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.OUTBOUND
+ "-color", new RGB(128, 128, 128));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.PARTNER_TELL
+ "-color", new RGB(255, 0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.DRAW_REQUEST
+ "-color", new RGB(255, 0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.ABORT_REQUEST
+ "-color", new RGB(255, 0, 0));
PreferenceConverter
.setDefault(this, CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO
+ ChatType.TELL + "-color", new RGB(255, 0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL
+ "-" + 1 + "-color", new RGB(255, 200, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL
+ "-" + 4 + "-color", new RGB(0, 255, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL
+ "-" + 50 + "-color", new RGB(255, 175, 175));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.CHANNEL_TELL
+ "-" + 53 + "-color", new RGB(255, 0, 255));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.INTERNAL
+ "-color", new RGB(255, 0, 0));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO
+ ChatType.PLAYING_STATISTICS + "-color", new RGB(100,
149, 237));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.QTELL
+ "-color", new RGB(128, 128, 128));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.FINGER
+ "-color", new RGB(128, 128, 128));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.HISTORY
+ "-color", new RGB(128, 128, 128));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.GAMES
+ "-color", new RGB(128, 128, 128));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO + ChatType.BUGWHO_ALL
+ "-color", new RGB(128, 128, 128));
PreferenceConverter.setDefault(this,
CHAT_CHAT_EVENT_TYPE_COLOR_APPEND_TO
+ ChatType.NOTIFICATION_ARRIVAL + "-color", new RGB(
255, 0, 0));
PreferenceConverter.setDefault(this, CHAT_PROMPT_COLOR, new RGB(128,
128, 128));
PreferenceConverter.setDefault(this, CHAT_QUOTE_UNDERLINE_COLOR,
new RGB(0, 255, 0));
PreferenceConverter.setDefault(this, CHAT_LINK_UNDERLINE_COLOR,
new RGB(11, 133, 238));
// Bug house buttons settings.
PreferenceConverter.setDefault(this, BUG_BUTTONS_FONT,
new FontData[] { new FontData(defaultFontName,
defaultSmallFontSize, SWT.BOLD) });
// Bug house
setDefault(BUGHOUSE_PLAYING_OPEN_PARTNER_BOARD, true);
setDefault(BUGHOUSE_OBSERVING_OPEN_PARTNER_BOARD, true);
setDefault(BUGHOUSE_SPEAK_COUNTDOWN_ON_PARTNER_BOARD, true);
setDefault(BUGHOUSE_SPEAK_PARTNER_TELLS, true);
setDefault(BUGHOUSE_IS_PLAYING_PARTNERSHIP_OFFERED_SOUND, true);
// Fics
setDefault(FICS_KEEP_ALIVE, false);
setDefault(FICS_AUTO_CONNECT, false);
setDefault(FICS_LOGIN_SCRIPT, "set seek 0\nset autoflag 1\n");
setDefault(FICS_AUTO_CONNECT, false);
setDefault(FICS_PROFILE, "Primary");
setDefault(FICS_CLOSE_TABS_ON_DISCONNECT, false);
setDefault(FICS_SHOW_BUGBUTTONS_ON_PARTNERSHIP, true);
setDefault(FICS_NO_WRAP_ENABLED, true);
setDefault(FICS_CHANNEL_COMMANDS,
"+channel $channel,-channel $channel,in $channel");
setDefault(
FICS_PERSON_COMMANDS,
"finger $person,follow $person,history $person,joural $person,partner $person,"
+ "observe $person,oldpstat $userName $person,pstat $userName $person,"
+ "stored $person,variables $person,separator,"
+ "+censor $person,-censor $person,+gnotify $person,-gnotify $person,+noplay $person,-noplay $person,+notify $person,-notify $person,separator,"
+ "match $person 1 0,match $person 3 0,match $person 5 0,match $person 15 0");
setDefault(FICS_GAME_COMMANDS,
"observe $gameId,allobservers $gameId,moves $gameId");
setDefault(
FICS_REGULAR_EXPRESSIONS_TO_BLOCK,
"defprompt set\\.,gameinfo set\\.,ms set\\.,startpos set\\.,"
+ "pendinfo set\\.,nowrap set\\.,smartmove set\\.,premove set\\.,"
+ "Style 12 set\\.,Your prompt will now not show the time\\.,"
+ "You will not see seek ads\\.,You will not see seek ads.\\.,"
+ "Auto-flagging enabled\\.,lock set\\.,set seek 0,set autoflag 1,"
+ "allresults set\\.,Bell off\\.,set interface Raptor .*,"
+ "You are not examining or setting up a game\\.");
setDefault(FICS_SEEK_GAME_TYPE, "");
setDefault(FICS_SEEK_MINUTES, "5");
setDefault(FICS_SEEK_INC, "0");
setDefault(FICS_SEEK_MIN_RATING, "Any");
setDefault(FICS_SEEK_MAX_RATING, "Any");
setDefault(FICS_SEEK_MANUAL, false);
setDefault(FICS_SEEK_FORMULA, true);
setDefault(FICS_SEEK_RATED, true);
setDefault(FICS_SEEK_COLOR, "");
setDefault(FICS_KEEP_ALIVE_COMMAND,
"set busy is away from the keyboard.");
// Fics Primary
setDefault(FICS_PRIMARY_USER_NAME, "");
setDefault(FICS_PRIMARY_PASSWORD, "");
setDefault(FICS_PRIMARY_IS_NAMED_GUEST, false);
setDefault(FICS_PRIMARY_IS_ANON_GUEST, false);
setDefault(FICS_PRIMARY_SERVER_URL, "freechess.org");
setDefault(FICS_PRIMARY_PORT, 5000);
setDefault(FICS_PRIMARY_TIMESEAL_ENABLED, true);
// Fics Secondary
setDefault(FICS_SECONDARY_USER_NAME, "");
setDefault(FICS_SECONDARY_PASSWORD, "");
setDefault(FICS_SECONDARY_IS_NAMED_GUEST, false);
setDefault(FICS_SECONDARY_IS_ANON_GUEST, false);
setDefault(FICS_SECONDARY_SERVER_URL, "freechess.org");
setDefault(FICS_SECONDARY_PORT, 5000);
setDefault(FICS_SECONDARY_TIMESEAL_ENABLED, true);
// Fics Tertiary
setDefault(FICS_TERTIARY_USER_NAME, "");
setDefault(FICS_TERTIARY_PASSWORD, "");
setDefault(FICS_TERTIARY_IS_NAMED_GUEST, false);
setDefault(FICS_TERTIARY_IS_ANON_GUEST, false);
setDefault(FICS_TERTIARY_SERVER_URL, "freechess.org");
setDefault(FICS_TERTIARY_PORT, 5000);
setDefault(FICS_TERTIARY_TIMESEAL_ENABLED, true);
// Bics
setDefault(BICS_KEEP_ALIVE, false);
setDefault(BICS_AUTO_CONNECT, false);
setDefault(BICS_LOGIN_SCRIPT, "set autoflag 1\n\n");
setDefault(BICS_AUTO_CONNECT, false);
setDefault(BICS_PROFILE, "Primary");
setDefault(BICS_CLOSE_TABS_ON_DISCONNECT, false);
setDefault(BICS_SHOW_BUGBUTTONS_ON_PARTNERSHIP, true);
setDefault(BICS_KEEP_ALIVE_COMMAND,
"set busy is away from the keyboard.");
setDefault(BICS_CHANNEL_COMMANDS,
"+channel $channel,-channel $channel,in $channel");
setDefault(
BICS_PERSON_COMMANDS,
"finger $person,follow $person,history $person,joural $person,partner $person,"
+ "observe $person,oldpstat $userName $person,pstat $userName $person,"
+ "stored $person,variables $person,separator,"
+ "+censor $person,-censor $person,+gnotify $person,-gnotify $person,+noplay $person,-noplay $person,+notify $person,-notify $person,separator,"
+ "match $person 1 0 zh,match $person 3 0 zh,match $person 1 0 zh fr,match $person 3 0 zh fr,match $person 2 0 bughouse,"
+ "match $person 2 0 bughouse fr, match $person 2 0 bughouse w5");
setDefault(BICS_GAME_COMMANDS,
"observe $gameId,allobservers $gameId,moves $gameId");
setDefault(
BICS_REGULAR_EXPRESSIONS_TO_BLOCK,
"defprompt set\\.,gameinfo set\\.,ms set\\.,startpos set\\.,"
+ "pendinfo set\\.,nowrap set\\.,smartmove set\\.,premove set\\.,"
+ "Style 12 set\\.,Your prompt will now not show the time\\.,"
+ "You will not see seek ads\\.,You will not see seek ads.\\.,"
+ "Auto-flagging enabled\\.,lock set\\.");
// Bics Primary
setDefault(BICS_PRIMARY_USER_NAME, "");
setDefault(BICS_PRIMARY_PASSWORD, "");
setDefault(BICS_PRIMARY_IS_NAMED_GUEST, false);
setDefault(BICS_PRIMARY_IS_ANON_GUEST, false);
setDefault(BICS_PRIMARY_SERVER_URL, "chess.sipay.ru");
setDefault(BICS_PRIMARY_PORT, 5000);
setDefault(BICS_PRIMARY_TIMESEAL_ENABLED, true);
// Bics Secondary
setDefault(BICS_SECONDARY_USER_NAME, "");
setDefault(BICS_SECONDARY_PASSWORD, "");
setDefault(BICS_SECONDARY_IS_NAMED_GUEST, false);
setDefault(BICS_SECONDARY_IS_ANON_GUEST, false);
setDefault(BICS_SECONDARY_SERVER_URL, "chess.sipay.ru");
setDefault(BICS_SECONDARY_PORT, 5000);
setDefault(BICS_SECONDARY_TIMESEAL_ENABLED, true);
// Bics Tertiary
setDefault(BICS_TERTIARY_USER_NAME, "");
setDefault(BICS_TERTIARY_PASSWORD, "");
setDefault(BICS_TERTIARY_IS_NAMED_GUEST, false);
setDefault(BICS_TERTIARY_IS_ANON_GUEST, false);
setDefault(BICS_TERTIARY_SERVER_URL, "chess.sipay.ru");
setDefault(BICS_TERTIARY_PORT, 5000);
setDefault(BICS_TERTIARY_TIMESEAL_ENABLED, true);
// Quadrant settings.
setDefault("fics-" + MAIN_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + CHANNEL_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + PERSON_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + REGEX_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + BUG_WHO_QUADRANT, Quadrant.VIII);
setDefault("fics-" + SEEK_TABLE_QUADRANT, Quadrant.VIII);
setDefault("fics-" + BUG_BUTTONS_QUADRANT, Quadrant.IX);
setDefault("fics-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VI);
setDefault("fics-" + GAMES_TAB_QUADRANT, Quadrant.VIII);
setDefault("fics-" + GAME_BOT_QUADRANT, Quadrant.VIII);
setDefault("fics2-" + MAIN_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + CHANNEL_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + PERSON_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + REGEX_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + BUG_WHO_QUADRANT, Quadrant.VIII);
setDefault("fics2-" + SEEK_TABLE_QUADRANT, Quadrant.VIII);
setDefault("fics2-" + BUG_BUTTONS_QUADRANT, Quadrant.IX);
setDefault("fics2-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VII);
setDefault("fics2-" + GAMES_TAB_QUADRANT, Quadrant.VIII);
setDefault("fics2-" + GAME_BOT_QUADRANT, Quadrant.VIII);
setDefault("bics-" + MAIN_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + CHANNEL_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + PERSON_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + REGEX_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + BUG_WHO_QUADRANT, Quadrant.VIII);
setDefault("bics-" + SEEK_TABLE_QUADRANT, Quadrant.VIII);
setDefault("bics-" + BUG_BUTTONS_QUADRANT, Quadrant.IX);
setDefault("bics-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VI);
setDefault("bics-" + GAMES_TAB_QUADRANT, Quadrant.VIII);
setDefault("bics2-" + MAIN_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + CHANNEL_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + PERSON_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + REGEX_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + PARTNER_TELL_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + BUG_WHO_QUADRANT, Quadrant.VIII);
setDefault("bics2-" + SEEK_TABLE_QUADRANT, Quadrant.VIII);
setDefault("bics2-" + BUG_BUTTONS_QUADRANT, Quadrant.IX);
setDefault("bics2-" + GAME_CHAT_TAB_QUADRANT, Quadrant.VII);
setDefault("bics2-" + GAMES_TAB_QUADRANT, Quadrant.VIII);
// Timeseal 1 connect string
// setDefault(TIMESEAL_INIT_STRING, "TIMESTAMP|iv|OpenSeal|");
setDefault(TIMESEAL_INIT_STRING, "TIMESEAL2|raptorUser|OpenSeal|");
LOG.info("Loaded defaults " + PREFERENCE_PROPERTIES_FILE);
}
@Override
public void save() {
FileOutputStream fileOut = null;
try {
save(fileOut = new FileOutputStream(RAPTOR_PROPERTIES),
"Last saved on " + new Date());
fileOut.flush();
} catch (IOException ioe) {
LOG.error("Error saving raptor preferences:", ioe);
throw new RuntimeException(ioe);
} finally {
try {
fileOut.close();
} catch (Throwable t) {
}
}
}
public void setDefault(String key, Font font) {
PreferenceConverter.setValue(this, key, font.getFontData());
}
public void setDefault(String key, FontData[] fontData) {
PreferenceConverter.setValue(this, key, fontData);
}
public void setDefault(String key, int[] values) {
setDefault(key, RaptorStringUtils.toString(values));
}
public void setDefault(String key, Point point) {
PreferenceConverter.setValue(this, key, point);
}
public void setDefault(String key, Quadrant quadrant) {
setDefault(key, quadrant.name());
}
public void setDefault(String key, Rectangle rectangle) {
PreferenceConverter.setDefault(this, key, rectangle);
}
public void setDefault(String key, RGB rgb) {
PreferenceConverter.setValue(this, key, rgb);
}
public void setDefault(String key, String[] values) {
setDefault(key, RaptorStringUtils.toString(values));
}
public void setValue(String key, Font font) {
PreferenceConverter.setValue(this, key, font.getFontData());
}
public void setValue(String key, FontData[] fontData) {
PreferenceConverter.setValue(this, key, fontData);
}
public void setValue(String key, int[] values) {
setValue(key, RaptorStringUtils.toString(values));
}
public void setValue(String key, Point point) {
PreferenceConverter.setValue(this, key, point);
}
public void setValue(String key, Quadrant quadrant) {
setValue(key, quadrant.name());
}
public void setValue(String key, Rectangle rectangle) {
PreferenceConverter.setValue(this, key, rectangle);
}
public void setValue(String key, RGB rgb) {
PreferenceConverter.setValue(this, key, rgb);
}
public void setValue(String key, String[] values) {
setValue(key, RaptorStringUtils.toString(values));
}
protected void setDefaultMonitorBasedSizes() {
Rectangle fullViewBounds = Display.getCurrent().getPrimaryMonitor()
.getBounds();
int toolbarPieceSize = 12;
String iconSize = "tiny";
defaultLargeFontSize = 12;
defaultMediumFontSize = 10;
defaultSmallFontSize = 8;
defaultTinyFontSize = 6;
if (fullViewBounds.height >= 1200) {
iconSize = "large";
toolbarPieceSize = 24;
defaultLargeFontSize = 18;
defaultMediumFontSize = 16;
defaultSmallFontSize = 14;
defaultTinyFontSize = 12;
} else if (fullViewBounds.height >= 1024) {
iconSize = "medium";
toolbarPieceSize = 20;
defaultLargeFontSize = 16;
defaultMediumFontSize = 14;
defaultSmallFontSize = 12;
defaultTinyFontSize = 10;
} else if (fullViewBounds.height >= 670) {
iconSize = "small";
toolbarPieceSize = 16;
defaultLargeFontSize = 14;
defaultMediumFontSize = 12;
defaultSmallFontSize = 10;
defaultTinyFontSize = 8;
}
getDefauultMonospacedFont();
setDefault(PreferenceKeys.APP_ICON_SIZE, iconSize);
setDefault(PreferenceKeys.APP_TOOLBAR_PIECE_SIZE, toolbarPieceSize);
}
}
|
package com.akiban.qp.persistitadapter;
import com.akiban.ais.model.Column;
import com.akiban.ais.model.GroupIndex;
import com.akiban.ais.model.Index;
import com.akiban.ais.model.IndexColumn;
import com.akiban.ais.model.JoinColumn;
import com.akiban.ais.model.TableIndex;
import com.akiban.ais.model.UserTable;
import com.akiban.qp.expression.IndexBound;
import com.akiban.qp.expression.IndexKeyRange;
import com.akiban.qp.expression.RowBasedUnboundExpressions;
import com.akiban.qp.expression.UnboundExpressions;
import com.akiban.qp.operator.API;
import com.akiban.qp.operator.ArrayBindings;
import com.akiban.qp.operator.Bindings;
import com.akiban.qp.operator.Cursor;
import com.akiban.qp.operator.Operator;
import com.akiban.qp.operator.StoreAdapter;
import com.akiban.qp.row.Row;
import com.akiban.qp.rowtype.IndexRowType;
import com.akiban.qp.rowtype.RowType;
import com.akiban.qp.rowtype.Schema;
import com.akiban.qp.rowtype.UserTableRowType;
import com.akiban.server.api.dml.ConstantColumnSelector;
import com.akiban.server.expression.Expression;
import com.akiban.server.expression.std.VariableExpression;
import com.akiban.server.rowdata.FieldDef;
import com.akiban.server.rowdata.RowData;
import com.akiban.server.rowdata.RowDataValueSource;
import com.akiban.server.types.ToObjectValueTarget;
import com.akiban.server.types.conversion.Converters;
import java.util.*;
final class OperatorStoreMaintenance {
public void run(OperatorStoreGIHandler.Action action, PersistitHKey hKey, RowData forRow, StoreAdapter adapter, OperatorStoreGIHandler handler) {
Operator planOperator = rootOperator(action);
if (planOperator == null)
return;
Bindings bindings = new ArrayBindings(1);
final List<Column> lookupCols;
UserTable userTable = rowType.userTable();
if (usePKs(action)) {
// use PKs
lookupCols = userTable.getPrimaryKey().getColumns();
}
else {
// use FKs
lookupCols = new ArrayList<Column>();
for (JoinColumn joinColumn : userTable.getParentJoin().getJoinColumns()) {
lookupCols.add(joinColumn.getChild());
}
}
bindings.set(OperatorStoreMaintenance.HKEY_BINDING_POSITION, hKey);
// Copy the values into the array bindings
ToObjectValueTarget target = new ToObjectValueTarget();
RowDataValueSource source = new RowDataValueSource();
for (int i=0; i < lookupCols.size(); ++i) {
int bindingsIndex = i+1;
Column col = lookupCols.get(i);
source.bind((FieldDef)col.getFieldDef(), forRow);
target.expectType(col.getType().akType());
bindings.set(bindingsIndex, Converters.convert(source, target).lastConvertedValue());
}
Cursor cursor = API.cursor(planOperator, adapter);
cursor.open(bindings);
try {
Row row;
while ((row = cursor.next()) != null) {
if (row.rowType().equals(planOperator.rowType())) {
handler.handleRow(groupIndex, row, action);
}
}
} finally {
cursor.close();
}
}
private Operator rootOperator(OperatorStoreGIHandler.Action action) {
switch (action) {
case STORE:
return storePlan;
case DELETE:
return deletePlan;
default: throw new AssertionError(action.name());
}
}
private boolean usePKs(OperatorStoreGIHandler.Action action) {
switch (action) {
case STORE:
return usePksStore;
case DELETE:
return usePksDelete;
default: throw new AssertionError(action.name());
}
}
public OperatorStoreMaintenance(BranchTables branchTables,
GroupIndex groupIndex,
UserTableRowType rowType)
{
PlanCreationStruct storePlan = createGroupIndexMaintenancePlan(branchTables, groupIndex, rowType, true);
this.storePlan = storePlan.rootOperator;
this.usePksStore = storePlan.usePKs;
PlanCreationStruct deletePlan = createGroupIndexMaintenancePlan(branchTables, groupIndex, rowType, false);
this.deletePlan = deletePlan.rootOperator;
this.usePksDelete = deletePlan.usePKs;
this.rowType = rowType;
this.groupIndex = groupIndex;
}
private final Operator storePlan;
private final Operator deletePlan;
private final GroupIndex groupIndex;
private final boolean usePksStore;
private final boolean usePksDelete;
private final UserTableRowType rowType;
enum Relationship {
PARENT,
SELF, CHILD
}
// for use in this class
/**
* <p>Creates a struct that describes how GI maintenance works for a row of a given type. This struct contains
* two elements: a parameterized SELECT plan, and a boolean that specifies whether those parameters come from
* the row's PK or its grouping FK.</p>
*
* <p>Any action has three steps: GI cleanup, action, and GI (re)write. For instance, in an INSERT of an order when
* there's a C-O left join GI, we would have to:
* <ol>
* <li><b>cleanup:</b> if this is the first order under this customer, delete the GI entry with NULL'ed out
* order info</li>
* <li><b>action:</b> do the insert, including maintenance of any table indexes</li>
* <li><b>(re)write:</b> write the new GI entry</li>
* </ol>
* </p>
*
* <p>In a perfect world, we would only clean up those entries which we knew would be removed by the end, and we
* would only write those entries which we knew didn't exist before. Instead, we'll be deleting some rows that
* we'll soon need to re-write (which is why that third step isn't just called "write"). The level to which we can
* cut down on superfluous deletes and stores will have performance repercussions and is a potential point
* of optimization.</p>
*
* <p>For now, here's how it works. We start a scan from some table+index (more on this below), then do a deep
* branch lookup to the group table, then flatten all of the rows. The table we start from is either the incoming
* row's table, its parent or its child.
*
* <ul>
* <li>if incoming row is <strong>below the GI</strong>, ignore this event</sup></li>
* <li>if incoming row is <strong>above the GI (is an ancestor of the GI's rootmost table),</strong> always
* look childward</li>
* <li>if the incoming row is <strong>within the GI</strong>
* <ul>
* <li>in a <strong>LEFT JOIN</strong>, look parentward, capped at the GI's rootmost table</li>
* <li>in a <strong>RIGHT JOIN</strong>, look childward, capped at the GI's leafmost table</li>
* </ul>
* </li>
* </ul>
* </p>
*
* <p>Motivating reasons:</p>
*
* <p>First, it's worth calling out everything an action may do to a GI. The actions apply only to INSERT and
* DELETE actions; UPDATE is treated as DELETE+INSERT.
* <ul>
* <li>add an entry</li>
* <li>... and possibly remove an outer GI entry in the process (an outer entry is one that represents the result
* of an outer join that would not have been present in an inner join -- that is, a GI for which one of the rows
* doesn't actually exist)</li>
* <li>remove an entry</li>
* <li>... and possibly create an outer GI entry in the process</li>
* <li>update 1 or more rows' HKey segments (via adoption or orphaning)</li>
* </ul>
* </p>
*
* <p>With that in mind, here's an informal look at the motivation behind each of the above scenarios.</p>
*
* <h3>Incoming row is below the GI</h3>
*
* <p>Such a row can't affect the GI's HKey, since adoption and orphaning can only happen childward of a given row.
* It also can't add or remove an entry, since entries are agnostic to tables outside of the GI segment (other
* than for hkey maintenance). So this is a no-op in all situations.</p>
*
* <h3>Incoming row is above the GI</h3>
*
* <p>Such an action can only affect HKey maintenance. For an insert's cleanup, we have to start the scan at the
* incoming row's child, since the incoming row itself doesn't exist (if the child doesn't exist either, there's no
* HKey maintenance to do that will trickle up to the GI). For a delete's (re)write, we also have to start the
* scan at the newly-deleted row's child, since that row doesn't exist anymore. For the other two situations
* (insert's (re)write phase or delete's cleanup), we could start on the incoming row's table if we want, but
* because of RIGHT JOIN semantics there's no harm in starting on the child. In fact, it's a bit more selective
* and thus efficient.
*
* <h4>Incoming row is within the GI</h4>
*
* <p>Such an action can:<ul>
* <li>insert a GI entry, possibly removing an outer GI entry</li>
* <li>remove a GI entry, possibly inserting an outer GI entry</li>
* </ul>
* </p>
*
* <p>For <strong>LEFT JOIN GIs</strong>, we need to start at the incoming row's parent to clean up or insert any
* outer GIs (as part of an insert's cleanup or remove's (re)write, respectivley). On the other hand, if the
* incoming row is the rootmost table in the GI, then going to its parent isn't necessary for outer GI maintenance
* (there's nothing to do, since there can't be an outer GI), and it's wrong for regular GI maintenance, since it
* means that if hat parent row doesn't exist, we won't get any GI entries even though we should have at least one.
* Note that this problem doesn't hold true for tables further down the GI branch: if their parent doesn't exist,
* then there's nothing to do because of LEFT JOIN semantics, and starting the scan at the parent is fine (the scan
* will correctly return no rows). So we have the following situations:</p>
*
* <p>Putting all that together, we want to go to the incoming row's parent, unless the incoming row is of the
* rootmost table in the GI, in which we want to stay on that table. So, we want to go parentward but capped at
* the GI border.</p>
*
* <p>For </strong>RIGHT JOIN GIs</strong>, the situation is similar but reversed. Outer GI entries come from the
* child, so we need to look childward in order to maintain them. On the other hand, we can't look past the GI
* border, because if we did we'd be missing rows in the case of the leafmost table of a GI not having any children.
* So, we should be scanning starting from the child, but again capped at the GI.</p>
*
* @param branchTables
* @param groupIndex
* @param rowType
* @param forStoring
* @return
*/
private static PlanCreationStruct createGroupIndexMaintenancePlan(
BranchTables branchTables,
GroupIndex groupIndex,
UserTableRowType rowType,
boolean forStoring)
{
if (branchTables.isEmpty()) {
throw new RuntimeException("group index has empty branch: " + groupIndex);
}
if (!branchTables.fromRoot().contains(rowType)) {
throw new RuntimeException(rowType + " not in branch for " + groupIndex + ": " + branchTables);
}
PlanCreationStruct result = new PlanCreationStruct();
// compute if this is a no-op
if (!forStoring && rowType.userTable().getDepth() == 0 && rowType != branchTables.rootMost()) {
return result;
}
Schema schema = rowType.schema();
final Relationship scanFrom;
// this is a cleanup scan
int index = branchTables.fromRootMost().indexOf(rowType);
if (index < 0) {
// incoming row is above the GI, so look downward
scanFrom = Relationship.CHILD;
}
else if (groupIndex.getJoinType() == Index.JoinType.LEFT) {
int indexWithinGI = branchTables.fromRootMost().indexOf(rowType) - 1;
scanFrom = indexWithinGI < 0
? Relationship.SELF
: Relationship.PARENT;
}
else if (groupIndex.getJoinType() == Index.JoinType.RIGHT) {
int indexWithinGI = branchTables.fromRootMost().indexOf(rowType) + 1;
scanFrom = indexWithinGI < branchTables.fromRootMost().size()
? Relationship.CHILD
: Relationship.SELF;
}
else {
throw new AssertionError(groupIndex + " has join " + groupIndex.getJoinType());
}
final UserTableRowType startFromRowType;
TableIndex startFromIndex;
final boolean usePKs;
switch (scanFrom) {
case PARENT:
usePKs = false;
startFromRowType = schema.userTableRowType(rowType.userTable().parentTable());
startFromIndex = startFromRowType.userTable().getPrimaryKey().getIndex();
break;
case SELF:
usePKs = true;
startFromRowType = rowType;
startFromIndex = startFromRowType.userTable().getPrimaryKey().getIndex();
break;
case CHILD:
usePKs = true;
int idIndex = branchTables.fromRoot().indexOf(rowType);
startFromRowType = branchTables.fromRoot().get(idIndex+1);
startFromIndex = fkIndex(startFromRowType.userTable(), rowType.userTable());
break;
default:
throw new AssertionError(scanFrom.name());
}
result.usePKs = usePKs;
UserTable startFrom = startFromRowType.userTable();
List<Expression> pkExpressions = new ArrayList<Expression>(startFromIndex.getColumns().size());
for (int i=0; i < startFrom.getPrimaryKey().getColumns().size(); ++i) {
int fieldPos = i + 1; // position 0 is already claimed in OperatorStore
Column col = startFrom.getPrimaryKey().getColumns().get(i);
Expression pkField = new VariableExpression(col.getType().akType(), fieldPos);
pkExpressions.add(pkField);
}
UnboundExpressions unboundExpressions = new RowBasedUnboundExpressions(startFromRowType, pkExpressions);
IndexBound bound = new IndexBound(unboundExpressions, ConstantColumnSelector.ALL_ON);
IndexKeyRange range = new IndexKeyRange(bound, true, bound, true);
// the scan, main table and flattens
Operator plan;
IndexRowType pkRowType = schema.indexRowType(startFromIndex);
plan = API.indexScan_Default(pkRowType, false, range);
plan = API.branchLookup_Default(
plan,
startFrom.getGroup().getGroupTable(),
pkRowType,
branchTables.allTablesForBranch.get(0),
API.LookupOption.DISCARD_INPUT
);
// RIGHT JOIN until the GI, and then the GI's join types
RowType parentRowType = null;
API.JoinType joinType = API.JoinType.RIGHT_JOIN;
int branchStartDepth = branchTables.rootMost().userTable().getDepth() - 1;
boolean withinBranch = branchStartDepth == -1;
API.JoinType withinBranchJoin = operatorJoinType(groupIndex);
for (UserTableRowType branchRowType : branchTables.fromRoot()) {
if (parentRowType == null) {
parentRowType = branchRowType;
}
else {
plan = API.flatten_HKeyOrdered(plan, parentRowType, branchRowType, joinType);
parentRowType = plan.rowType();
}
if (branchRowType.userTable().getDepth() == branchStartDepth) {
withinBranch = true;
} else if (withinBranch) {
joinType = withinBranchJoin;
}
}
result.rootOperator = plan;
return result;
}
private static API.JoinType operatorJoinType(Index index) {
switch (index.getJoinType()) {
case LEFT:
return API.JoinType.LEFT_JOIN;
case RIGHT:
return API.JoinType.RIGHT_JOIN;
default:
throw new AssertionError(index.getJoinType().name());
}
}
/**
* Given a table with a FK column and a table with a PK column, gets the index from the FK table that
* connects to the PK table.
* @param fkTable the child table
* @param pkTable the
* @return the fkTable's FK index
*/
private static TableIndex fkIndex(UserTable fkTable, UserTable pkTable) {
if (fkTable.getParentJoin() == null || fkTable.getParentJoin().getParent() != pkTable)
throw new IllegalArgumentException(pkTable + " is not a parent of " + fkTable);
List<Column> fkIndexCols = new ArrayList<Column>();
for(JoinColumn joinColumn : fkTable.getParentJoin().getJoinColumns()) {
fkIndexCols.add(joinColumn.getChild());
}
List<Column> candidateIndexColumns = new ArrayList<Column>();
for (TableIndex index : fkTable.getIndexes()) {
for (IndexColumn indexCol : index.getColumns()) {
candidateIndexColumns.add(indexCol.getColumn());
}
if (candidateIndexColumns.equals(fkIndexCols)) {
return index;
}
candidateIndexColumns.clear();
}
throw new AssertionError("no index found for columns: " + fkIndexCols);
}
// package consts
private static final int HKEY_BINDING_POSITION = 0;
// nested classes
static class BranchTables {
// BranchTables interface
public List<UserTableRowType> fromRoot() {
return allTablesForBranch;
}
public List<UserTableRowType> fromRootMost() {
return onlyBranch;
}
public boolean isEmpty() {
return fromRootMost().isEmpty();
}
public UserTableRowType rootMost() {
return onlyBranch.get(0);
}
public BranchTables(Schema schema, GroupIndex groupIndex) {
List<UserTableRowType> localTables = new ArrayList<UserTableRowType>();
UserTable rootmost = groupIndex.rootMostTable();
int branchRootmostIndex = -1;
for (UserTable table = groupIndex.leafMostTable(); table != null; table = table.parentTable()) {
if (table.equals(rootmost)) {
assert branchRootmostIndex == -1 : branchRootmostIndex;
branchRootmostIndex = table.getDepth();
}
localTables.add(schema.userTableRowType(table));
}
if (branchRootmostIndex < 0) {
throw new RuntimeException("branch root not found! " + rootmost + " within " + localTables);
}
Collections.reverse(localTables);
this.allTablesForBranch = Collections.unmodifiableList(localTables);
this.onlyBranch = branchRootmostIndex == 0
? allTablesForBranch
: allTablesForBranch.subList(branchRootmostIndex, allTablesForBranch.size());
}
// object state
private final List<UserTableRowType> allTablesForBranch;
private final List<UserTableRowType> onlyBranch;
}
static class PlanCreationStruct {
public Operator rootOperator;
public boolean usePKs;
}
}
|
package com.codingchili.core.Configuration;
/**
* @author Robin Duda
*
* Represents a basic configurable that is saveable.
*/
public class WritableConfigurable implements Configurable {
private String path;
@Override
public String getPath() {
return path;
}
@Override
public void setPath(String path) {
this.path = path;
}
}
|
package com.danielflower.apprunner.router.web.v1;
import com.danielflower.apprunner.router.mgmt.Cluster;
import com.danielflower.apprunner.router.mgmt.MapManager;
import com.danielflower.apprunner.router.mgmt.Runner;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Optional;
import static org.apache.commons.lang3.StringUtils.isBlank;
@Path("/runners")
public class RunnerResource {
public static final Logger log = LoggerFactory.getLogger(RunnerResource.class);
private final Cluster cluster;
private final MapManager mapManager;
public RunnerResource(Cluster cluster, MapManager mapManager) {
this.cluster = cluster;
this.mapManager = mapManager;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public String all(@Context UriInfo uriInfo) {
return cluster.toJSON().toString(4);
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getRunner(@Context UriInfo uriInfo, @PathParam("id") String id) {
Optional<Runner> app = cluster.runner(id);
if (app.isPresent()) {
return Response.ok(app.get().toJSON().toString(4)).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@GET
@Path("/{id}/apps")
@Produces(MediaType.APPLICATION_JSON)
public Response getRunnerApps(@Context HttpServletRequest clientRequest, @PathParam("id") String id) {
Optional<Runner> app = cluster.runner(id);
if (!app.isPresent()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
try {
JSONObject appsJSON = mapManager.loadRunner(clientRequest, app.get());
return Response.ok(appsJSON.toString(4)).build();
} catch (Exception e) {
log.error("Error while getting apps for " + id, e);
return Response.serverError().entity(e.getMessage()).build();
}
}
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response create(@Context HttpServletRequest clientRequest,
@Context UriInfo uriInfo,
@FormParam("id") String id,
@FormParam("url") String url,
@FormParam("maxApps") int maxApps) {
if (isBlank(id)) {
return Response.status(400).entity("No runner ID was specified").build();
}
if (isBlank(url)) {
return Response.status(400).entity("No runner URL was specified").build();
}
if (maxApps < 0) {
return Response.status(400).entity("The max apps value must be at least 0").build();
}
try {
String resourceLocation = uriInfo.getRequestUri() + "/" + urlEncode(id);
if (cluster.runner(id).isPresent()) {
return Response
.status(409)
.header("Location", resourceLocation)
.entity("A runner with the ID " + id + " already exists. To update this runner, instead make a PUT request to " + resourceLocation).build();
}
Runner runner = new Runner(id, URI.create(url), maxApps);
log.info("Creating " + runner.toJSON().toString());
cluster.addRunner(clientRequest, runner);
return Response.status(201)
.header("Location", resourceLocation)
.entity(runner.toJSON().toString(4))
.build();
} catch (Exception e) {
log.error("Error while adding app runner instance", e);
return Response.serverError().entity("Error while adding app runner instance: " + e.getMessage()).build();
}
}
@PUT
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response update(@Context HttpServletRequest clientRequest,
@Context UriInfo uriInfo,
@PathParam("id") String id,
@FormParam("url") String url,
@FormParam("maxApps") int maxApps) {
if (isBlank(url)) {
return Response.status(400).entity("No runner URL was specified").build();
}
if (maxApps < 0) {
return Response.status(400).entity("The max apps value must be at least 0").build();
}
try {
String resourceLocation = uriInfo.getRequestUri().toString();
if (!cluster.runner(id).isPresent()) {
return Response
.status(404)
.entity("No runner with the ID " + id + " exists").build();
}
Runner runner = new Runner(id, URI.create(url), maxApps);
log.info("Updating " + runner.toJSON().toString());
cluster.deleteRunner(runner);
cluster.addRunner(clientRequest, runner);
return Response.status(200)
.header("Location", resourceLocation)
.entity(runner.toJSON().toString(4))
.build();
} catch (Exception e) {
log.error("Error while updating app runner instance", e);
return Response.serverError().entity("Error while updating app runner instance: " + e.getMessage()).build();
}
}
public static String urlEncode(String value) {
try {
return URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported Encoding for " + value, e);
}
}
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}")
public Response delete(@Context UriInfo uriInfo, @PathParam("id") String id) throws IOException {
Optional<Runner> existing = cluster.runner(id);
if (existing.isPresent()) {
Runner runner = existing.get();
cluster.deleteRunner(runner);
return Response.ok(runner.toJSON().toString(4)).build();
} else {
return Response.status(400).entity("Could not find runner with name " + id).build();
}
}
}
|
package com.extrahardmode.features.monsters.skeletors;
import com.extrahardmode.ExtraHardMode;
import com.extrahardmode.config.RootConfig;
import com.extrahardmode.config.RootNode;
import com.extrahardmode.events.EhmSkeletonDeflectEvent;
import com.extrahardmode.events.EhmSkeletonKnockbackEvent;
import com.extrahardmode.events.EhmSkeletonShootSilverfishEvent;
import com.extrahardmode.module.EntityHelper;
import com.extrahardmode.service.ListenerModule;
import com.extrahardmode.service.OurRandom;
import com.extrahardmode.task.SlowKillTask;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
import java.util.*;
/**
* Changes to Skeletons include:
* <p/>
* Immunity to arrows
*/
public class Skeletors extends ListenerModule
{
/**
* Plugin
*/
private final ExtraHardMode plugin;
/**
* Configuration
*/
private final RootConfig CFG;
/**
* All our custom Skeletons, 0 is the default skeleton. all other skeletons are identified by the id of their PotionEffectType
*/
private Map<String, List<CustomSkeleton>> customSkeletonsTypes = new HashMap<String, List<CustomSkeleton>>();
/**
* A constructor
*
* @param plugin owning plugin
*/
public Skeletors(ExtraHardMode plugin)
{
super(plugin);
this.plugin = plugin;
CFG = plugin.getModuleForClass(RootConfig.class);
//Initlizes all CustomSkeletons for all the worlds that we are activated in.
for (String world : CFG.getEnabledWorlds())
initForWorld(world);
}
/**
* Arrows pass through skeletons
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onSkeletonHitByArrow(EntityDamageByEntityEvent event)
{
// FEATURE: arrows pass through skeletons
if (event.getEntity() instanceof Skeleton &&! getSkelisForWorld(event.getEntity().getWorld().getName()).isEmpty())
{
Skeleton skeli = (Skeleton) event.getEntity();
World world = skeli.getWorld();
//final int deflect = CFG.getInt(RootNode.SKELI_RED_DEFLECT_ARROWS, world.getName());
//final int knockBackPercent = CFG.getInt(RootNode.SKELI_GREY_KNOCK_BACK_PERCENT, world.getName());
Entity damageSource = event.getDamager();
CustomSkeleton type = CustomSkeleton.getCustom(skeli, plugin, getSkelisForWorld(world.getName()));
// only arrows
if (damageSource instanceof Arrow)
{
if (type.getArrowsReflectPerc() > 0)
{
Arrow arrow = (Arrow) damageSource;
Player player = arrow.getShooter() instanceof Player ? (Player) arrow.getShooter() : null;
if (player != null)
{
EhmSkeletonDeflectEvent skeliEvent = new EhmSkeletonDeflectEvent(player, skeli, type.getArrowsReflectPerc(), type, !type.isArrowsPassThrough());
plugin.getServer().getPluginManager().callEvent(skeliEvent);
// percent chance
if (!skeliEvent.isCancelled())
{
// cancel the damage
event.setCancelled(true);
// teleport the arrow a single block farther along its flight path
// note that .6 and 12 were the unexplained recommended values for speed and spread, reflectively, in the bukkit wiki
arrow.remove();
world.spawnArrow(arrow.getLocation().add((arrow.getVelocity().normalize()).multiply(2)), arrow.getVelocity(), 0.6f, 12.0f);
}
}
}
}
}
}
/**
* Skeletons sometimes hoot knockback arrows
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerHitByArrow(EntityDamageByEntityEvent event)
{
//Knockback player to some percentage
if (event.getDamager() instanceof Arrow && event.getEntity() instanceof Player &&! getSkelisForWorld(event.getEntity().getWorld().getName()).isEmpty())
{
Arrow arrow = (Arrow) event.getDamager();
if (arrow.getShooter() instanceof Skeleton)
{
CustomSkeleton type = CustomSkeleton.getCustom(arrow.getShooter(), plugin, getSkelisForWorld(arrow.getWorld().getName()));
// FEATURE: skeletons can knock back
if (type.getKnockbackPercent() > 0)
{
if (plugin.random(type.getKnockbackPercent()))
{
// Knockback is enough, reduce dmg
event.setDamage(event.getDamage() / 2.0);
// knock back target with half the arrow's velocity
Vector knockback = arrow.getVelocity().multiply(0.5D);
EhmSkeletonKnockbackEvent knockbackEvent = new EhmSkeletonKnockbackEvent(event.getEntity(), (Skeleton) arrow.getShooter(), knockback, type.getKnockbackPercent());
if (!knockbackEvent.isCancelled())
knockbackEvent.getEntity().setVelocity(knockbackEvent.getVelocity());
}
}
}
}
}
/**
* Some Minions can apply PotionEffects to the player when they attack
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerHurtByMinion(EntityDamageByEntityEvent event)
{
// Apply effect when player hurt by minion
if (event.getDamager() instanceof LivingEntity && Minion.isMinion((LivingEntity) event.getDamager()) && event.getEntity() instanceof Player)
{
Player player = (Player) event.getEntity();
Minion matched = null;
//Search for the Skeli that spawns this type of Minion
for (CustomSkeleton skeli : getSkelisForWorld(event.getEntity().getWorld().getName()))
{
if (skeli.getMinionType().getMinionType() == event.getDamager().getType())
matched = skeli.getMinionType();
}
if (matched != null)
{
switch (matched.getDamagePlayer())
{
case SLOW:
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, matched.getEffectDuration(), 4));
break;
case BLIND:
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, matched.getEffectDuration(), 4));
break;
case NOTHING:
case EXPLODE:
break;
default:
throw new EnumConstantNotPresentException(OnDamage.class, "You added a new Action in OnDamage but didn't implement it!");
}
}
}
}
/**
* Minions can't be damaged by their summoners
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onMinionDamageBySummoner(EntityDamageByEntityEvent event)
{
//Block Summoners from damaging their minions
if (event.getEntity() instanceof LivingEntity && Minion.isMinion((LivingEntity) event.getEntity()) && event.getDamager() instanceof Arrow && ((Arrow) event.getDamager()).getShooter() instanceof Skeleton)
{
event.setCancelled(true);
Arrow arrow = (Arrow) event.getDamager();
arrow.remove();
Location loc = event.getDamager().getLocation();
loc.getWorld().spawnArrow(arrow.getLocation().add((arrow.getVelocity().normalize()).multiply(4)), event.getDamager().getVelocity(), 2.0F, 0.0F);
}
}
/**
* when an entity shoots a bow...
* <p/>
* skeletons may summon minions
*
* @param event - Event that occurred.
*/
@EventHandler
public void onShootProjectile(ProjectileLaunchEvent event)
{
Location location = event.getEntity().getLocation();
World world = location.getWorld();
EntityType entityType = event.getEntityType();
// FEATURE: skeletons sometimes release silverfish to attack their targets
if (event.getEntity() != null && event.getEntity() instanceof Arrow &&! getSkelisForWorld(world.getName()).isEmpty())
{
Arrow arrow = (Arrow) event.getEntity();
LivingEntity shooter = arrow.getShooter();
if (shooter instanceof Skeleton)
{
Skeleton skeleton = (Skeleton) shooter;
CustomSkeleton customSkeleton = CustomSkeleton.getCustom(skeleton, plugin, getSkelisForWorld(world.getName()));
int currentSpawnLimit = customSkeleton.getMinionType().getCurrentSpawnLimit(),
totalSpawnLimit = customSkeleton.getMinionType().getTotalSpawnLimit();
if (skeleton.getTarget() instanceof Player && OurRandom.percentChance(customSkeleton.getReleaseMinionPercent())
&& (currentSpawnLimit < 0 || currentSpawnLimit > CustomSkeleton.getSpawnedMinions(skeleton, plugin).size()) //Prevent tons of Minions
&& (totalSpawnLimit < 0 || totalSpawnLimit > CustomSkeleton.getTotalSummoned(skeleton, plugin)))
{
// Cancel and replace arrow with a summoned minion
event.setCancelled(true);
final Player player = (Player) skeleton.getTarget();
// replace with silverfish, quarter velocity of arrow, wants to attack same target as skeleton
LivingEntity minion = (LivingEntity) skeleton.getWorld().spawnEntity(skeleton.getLocation().add(0.0, 1.5, 0.0), customSkeleton.getMinionType().getMinionType());
minion.setVelocity(arrow.getVelocity().multiply(0.25));
if (minion instanceof Creature)
((Creature) minion).setTarget(skeleton.getTarget());
if (minion instanceof Slime) //Magmacubes extend Slime
((Slime) minion).setSize(2);
if (minion instanceof MagmaCube) //ignore so they dont explode
EntityHelper.flagIgnore(plugin, minion);
EntityHelper.markLootLess(plugin, minion); // the minion doesn't drop loot
Minion.setMinion(plugin, minion);
Minion.setParent(skeleton, minion, plugin);
CustomSkeleton.addMinion(skeleton, minion, plugin);
EhmSkeletonShootSilverfishEvent shootSilverfishEvent = new EhmSkeletonShootSilverfishEvent(player, skeleton, minion, customSkeleton.getReleaseMinionPercent(), customSkeleton);
plugin.getServer().getPluginManager().callEvent(shootSilverfishEvent);
if (shootSilverfishEvent.isCancelled()) //Undo
{
event.setCancelled(false);
minion.remove();
}
}
}
}
}
/**
* Remove minions if set when a skeleton dies
*
* @param event event that occured
*/
@EventHandler
public void onSkeletonDeath(EntityDeathEvent event)
{
LivingEntity entity = event.getEntity();
if (entity instanceof Skeleton && !customSkeletonsTypes.isEmpty() &&! getSkelisForWorld(entity.getWorld().getName()).isEmpty())
{
CustomSkeleton customSkeleton = CustomSkeleton.getCustom(entity, plugin, getSkelisForWorld(entity.getWorld().getName()));
if (customSkeleton.willRemoveMinions())
{
List<UUID> minionIds = CustomSkeleton.getSpawnedMinions(entity, plugin);
//Only look for the type of minion we spawned, e.g. only Silverfish
for (Entity worldEntity : entity.getWorld().getEntitiesByClass(customSkeleton.getMinionType().getMinionType().getEntityClass()))
for (UUID id : minionIds)
if (worldEntity.getUniqueId() == id)
{
((LivingEntity) worldEntity).addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 1));
worldEntity.setFireTicks(Integer.MAX_VALUE);
new SlowKillTask((LivingEntity) worldEntity, plugin);
}
}
}
}
@EventHandler
public void onMinionDeath(EntityDeathEvent event)
{
LivingEntity entity = event.getEntity();
if (Minion.isMinion(entity))
{
UUID parent = Minion.getParent(entity, plugin);
//Try to find the parent by id
for (LivingEntity worldEntity : entity.getWorld().getLivingEntities())
{
if (worldEntity.getUniqueId() == parent)
CustomSkeleton.removeMinion(entity.getUniqueId(), worldEntity);
}
}
}
/**
* Block slimes that are minions from splitting into small slimes as those don't damage you
*
* @param event event that occured
*/
@EventHandler
public void onSlimeSplit(SlimeSplitEvent event)
{
if (Minion.isMinion(event.getEntity()))
event.setCancelled(true);
}
@EventHandler
public void onSkeletonSpawn(CreatureSpawnEvent event)
{
World world = event.getLocation().getWorld();
if (event.getEntity() instanceof Skeleton &&! getSkelisForWorld(event.getEntity().getWorld().getName()).isEmpty() && world != null)
{
List<Integer> weights = new ArrayList<Integer>();
for (CustomSkeleton skeli : getSkelisForWorld(world.getName()))
weights.add(skeli.getSpawnWeight());
if (CFG.getBoolean(RootNode.SKELI_SWORDGUY_ENABLE, world.getName()))
weights.add(CFG.getInt(RootNode.SKELI_SWORDGUY_WEIGHT, world.getName()));
int type = OurRandom.weightedRandom(weights.toArray(new Integer[weights.size()]));
//Last index is our sword skeli
if (type + 1 == weights.size())
event.getEntity().getEquipment().setItemInHand(new ItemStack(Material.STONE_HOE));
else
CustomSkeleton.setCustom(event.getEntity(), plugin, getSkelisForWorld(world.getName()).get(type));
}
}
@EventHandler
public void onSilverfishSpawn(CreatureSpawnEvent event)
{
final boolean tempFix = CFG.getBoolean(RootNode.SILVERFISH_TEMP_POTION_EFFECT_FIX, event.getLocation().getWorld().getName());
if (event.getEntityType() == EntityType.SILVERFISH && tempFix)
event.getEntity().addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, Integer.MAX_VALUE, 1, false));
}
/**
* Get the CustomSkeleton types that can be spawned in a particular world
*
* @param world get skeletons for this world
*
* @return List of Skeletons or an empty List if no skeletons are enabled in the world
*/
private List<CustomSkeleton> getSkelisForWorld(String world)
{
List<CustomSkeleton> skelis = Collections.emptyList();
if (CFG.isEnabledForAll() && !customSkeletonsTypes.containsKey(world))
skelis = customSkeletonsTypes.get(CFG.getAllWorldString());
else if (customSkeletonsTypes.containsKey(world))
skelis = customSkeletonsTypes.get(world);
return skelis;
}
/**
* Initializes the CustomSkeletons for a given world
*/
private void initForWorld(String world)
{
List<CustomSkeleton> skeletons = new ArrayList<CustomSkeleton>(3);
//It's important that all customskelis have the same format for the ENUM otherwise you be getting an Enum not found error
{
boolean enabled = CFG.getBoolean(RootNode.SKELI_GREY_ENABLE, world);
if (enabled)
{
int spawnWeight = CFG.getInt(RootNode.SKELI_GREY_WEIGHT, world);
int knockbackPercent = CFG.getInt(RootNode.SKELI_GREY_KNOCK_BACK_PERCENT, world);
int deflectPercent = CFG.getInt(RootNode.SKELI_GREY_DEFLECT_ARROWS, world);
int minionReleasePercent = CFG.getInt(RootNode.SKELI_GREY_RELEASE_PERCENT, world);
int minionLimit = CFG.getInt(RootNode.SKELI_GREY_MINION_LIMIT, world);
int minionTotalLimit = CFG.getInt(RootNode.SKELI_GREY_MINION_TOTAL_LIMIT, world);
boolean minionDieWith = CFG.getBoolean(RootNode.SKELI_GREY_MINION_KILL_WITH, world);
int minionLootPercentage = CFG.getInt(RootNode.SKELI_GREY_MINION_LOOT_PERCENTAGE, world);
Minion myMinion = new Minion(OnDamage.NOTHING, EntityType.SILVERFISH, 0, minionLimit, minionTotalLimit, minionLootPercentage);
CustomSkeleton skeleton = new CustomSkeleton("ehm-skeli-grey", null, myMinion, minionReleasePercent, minionDieWith, deflectPercent, knockbackPercent, spawnWeight);
skeletons.add(skeleton);
}
}
{
boolean enabled = CFG.getBoolean(RootNode.SKELI_GREEN_ENABLE, world);
if (enabled)
{
int spawnWeight = CFG.getInt(RootNode.SKELI_GREEN_WEIGHT, world);
int knockbackPercent = CFG.getInt(RootNode.SKELI_GREEN_KNOCK_BACK_PERCENT, world);
int deflectPercent = CFG.getInt(RootNode.SKELI_GREEN_DEFLECT_ARROWS, world);
int minionReleasePercent = CFG.getInt(RootNode.SKELI_GREEN_RELEASE_PERCENT, world);
int minionLimit = CFG.getInt(RootNode.SKELI_GREEN_MINION_LIMIT, world);
int minionTotalLimit = CFG.getInt(RootNode.SKELI_GREEN_MINION_TOTAL_LIMIT, world);
boolean minionDieWith = CFG.getBoolean(RootNode.SKELI_GREEN_MINION_KILL_WITH, world);
int minionLootPercentage = CFG.getInt(RootNode.SKELI_GREEN_MINION_LOOT_PERCENTAGE, world);
Minion myMinion = new Minion(OnDamage.SLOW, EntityType.SLIME, 40, minionLimit, minionTotalLimit, minionLootPercentage);
CustomSkeleton skeleton = new CustomSkeleton("ehm-skeli-green", null, myMinion, minionReleasePercent, minionDieWith, deflectPercent, knockbackPercent, spawnWeight);
skeletons.add(skeleton);
}
}
{
boolean enabled = CFG.getBoolean(RootNode.SKELI_RED_ENABLE, world);
if (enabled)
{
int spawnWeight = CFG.getInt(RootNode.SKELI_RED_WEIGHT, world);
int knockbackPercent = CFG.getInt(RootNode.SKELI_RED_KNOCK_BACK_PERCENT, world);
int deflectPercent = CFG.getInt(RootNode.SKELI_RED_DEFLECT_ARROWS, world);
int minionReleasePercent = CFG.getInt(RootNode.SKELI_RED_RELEASE_PERCENT, world);
int minionLimit = CFG.getInt(RootNode.SKELI_RED_MINION_LIMIT, world);
int minionTotalLimit = CFG.getInt(RootNode.SKELI_RED_MINION_TOTAL_LIMIT, world);
boolean minionDieWith = CFG.getBoolean(RootNode.SKELI_RED_MINION_KILL_WITH, world);
int minionLootPercentage = CFG.getInt(RootNode.SKELI_RED_MINION_LOOT_PERCENTAGE, world);
Minion myMinion = new Minion(OnDamage.BLIND, EntityType.MAGMA_CUBE, 40, minionLimit, minionTotalLimit, minionLootPercentage);
CustomSkeleton skeleton = new CustomSkeleton("ehm-skeli-red", null, myMinion, minionReleasePercent, minionDieWith, deflectPercent, knockbackPercent, spawnWeight);
skeletons.add(skeleton);
}
}
customSkeletonsTypes.put(world, skeletons);
}
}
|
package com.github.bingoohuang.springrediscache;
import com.github.bingoohuang.utils.codec.Json;
import com.github.bingoohuang.utils.redis.Redis;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.io.Files;
import com.google.common.primitives.Primitives;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import static com.github.bingoohuang.springrediscache.RedisCacheConnector.THREADLOCAL;
import static com.github.bingoohuang.springrediscache.RedisFor.StoreValue;
import static org.springframework.util.StringUtils.capitalize;
public class RedisCacheUtils {
public static long getExpirationSeconds(InvocationRuntime rt) {
Object value = rt.getValue();
if (value == null) return -1;
long seconds = -1;
if (value instanceof RedisCacheExpirationAware)
seconds = ((RedisCacheExpirationAware) value).expirationSeconds();
if (seconds <= 0) seconds = tryRedisCacheExpirationTag(value);
if (seconds <= 0) seconds = rt.expirationSeconds();
if (seconds > 0) return Math.min(seconds, Consts.DaySeconds);
return seconds;
}
private static long tryRedisCacheExpirationTag(Object value) {
Method method = findRedisCacheExpirationAwareTagMethod(value.getClass());
if (method == null) return -1;
try {
Number result = (Number) method.invoke(value);
return result.longValue();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static LoadingCache<Class<?>, Optional<Method>> redisCacheExpirationAwareTagMethodCache
= CacheBuilder.newBuilder().build(new CacheLoader<Class<?>, Optional<Method>>() {
@Override
public Optional<Method> load(Class<?> aClass) throws Exception {
return searchRedisCacheExpirationAwareTagMethod(aClass);
}
});
static Method findRedisCacheExpirationAwareTagMethod(Class<?> aClass) {
return redisCacheExpirationAwareTagMethodCache.getUnchecked(aClass).orNull();
}
private static Optional<Method> searchRedisCacheExpirationAwareTagMethod(Class<?> aClass) {
Logger log = LoggerFactory.getLogger(aClass);
for (Method method : aClass.getMethods()) {
RedisCacheExpirationAwareTag awareTag = method.getAnnotation(RedisCacheExpirationAwareTag.class);
if (awareTag == null) continue;
if (method.getParameterTypes().length != 0) {
log.warn("@RedisCacheExpirationAwareTag method should be non arguments");
continue;
}
Class<?> returnType = method.getReturnType();
if (returnType.isPrimitive())
returnType = Primitives.wrap(returnType);
if (!Number.class.isAssignableFrom(returnType)) {
log.warn("@RedisCacheExpirationAwareTag method should be return Number type");
continue;
}
return Optional.of(method);
}
return Optional.absent();
}
public static long redisExpirationSeconds(String key, ApplicationContext appContext) {
Redis redis = tryGetBean(appContext, Redis.class);
String expirationStr = redis != null ? redis.get(key) : cwdFileRefreshSeconds(key);
long expirationSeconds = Consts.MaxSeconds;
if (expirationStr == null) return expirationSeconds;
if (expirationStr.matches("\\d+")) return Long.parseLong(expirationStr);
return Consts.MinSeconds + expirationStr.hashCode();
}
public static long trySaveExpireSeconds(String key, ApplicationContext appContext, InvocationRuntime rt) {
long realExpireSeconds = getExpirationSeconds(rt);
if (realExpireSeconds < 0)
return redisExpirationSeconds(key, appContext);
Redis redis = tryGetBean(appContext, Redis.class);
if (redis != null) {
redis.set(key, "" + realExpireSeconds);
} else {
writeCwdFileRefreshSeconds(key, realExpireSeconds);
}
return realExpireSeconds;
}
private static void writeCwdFileRefreshSeconds(String key, long realExpirationSeconds) {
File file = new File("." + key.replace(':', '.'));
try {
Files.write("" + realExpirationSeconds, file, Charsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("try to write cwdFileRefreshSeconds for key " + key + " failed", e);
}
}
private static String cwdFileRefreshSeconds(String key) {
File file = new File("." + key.replace(':', '.'));
if (!file.exists() || !file.isFile()) return null;
try {
return Files.toString(file, Charsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("try to read cwdFileRefreshSeconds for key " + key + " failed", e);
}
}
public static <T> T createObject(Class<T> clazz) {
try {
return clazz.newInstance();
} catch (Exception e) {
return null;
}
}
public static <T> T getBean(ApplicationContext appContext, Class<T> beanClass) {
try {
return appContext.getBean(beanClass);
} catch (BeansException e) {
return RedisCacheUtils.createObject(beanClass);
}
}
static Object invokeMethod(MethodInvocation invocation, ApplicationContext appContext) {
Method method = invocation.getMethod();
Class<?> declaringClass = method.getDeclaringClass();
RedisCacheTargetMock redisCacheTargetMock = declaringClass.getAnnotation(RedisCacheTargetMock.class);
if (redisCacheTargetMock == null) return invokeMethod(invocation);
String className = redisCacheTargetMock.value();
try {
Class clazz = Class.forName(className);
Object bean = appContext.getBean(clazz);
Method mockMethod = clazz.getMethod(method.getName(), method.getParameterTypes());
return mockMethod.invoke(bean, invocation.getArguments());
} catch (Exception e) {
return invokeMethod(invocation);
}
}
private static Object invokeMethod(MethodInvocation invocation) {
try {
Optional<Object> threadLocalValue = THREADLOCAL.get();
if (threadLocalValue != null) {
Object obj = threadLocalValue.orNull();
return obj == RedisCacheConnector.CLEARTAG ? null : obj;
}
return invocation.proceed();
} catch (Throwable throwable) {
throw Throwables.propagate(throwable);
}
}
public static String joinArguments(MethodInvocation invocation) {
StringBuilder sb = new StringBuilder();
for (Object arg : invocation.getArguments()) {
sb.append(convert(arg)).append(':');
}
if (sb.length() > 0) sb.setLength(sb.length() - 1);
else sb.append("NoArgs");
return sb.toString();
}
private static String convert(Object arg) {
if (arg == null) return null;
if (arg.getClass().isPrimitive()) return arg.toString();
if (Primitives.isWrapperType(arg.getClass())) return arg.toString();
if (arg instanceof Enum) return arg.toString();
if (arg instanceof CharSequence) return arg.toString();
return Json.json(arg);
}
public static void sleep(int millis) {
try {
TimeUnit.MILLISECONDS.sleep(millis);
} catch (InterruptedException e) {
// ignore
}
}
static ValueSerializable createValueSerializer(ApplicationContext appContext,
RedisCacheEnabled redisCacheAnn,
Method method, Logger logger) {
if (redisCacheAnn.redisFor() != StoreValue) return null;
Class<?> returnType = method.getReturnType();
if (redisCacheAnn.valueSerializer() == AutoSelectValueSerializer.class) {
if (returnType == String.class)
return new StringValueSerializable();
if (returnType.isPrimitive() || Primitives.isWrapperType(returnType))
return new PrimitiveValueSerializable(returnType);
if (returnType.isEnum())
return new EnumValueSerializable(returnType);
return new JSONValueSerializer(returnType, logger);
}
try {
return appContext.getBean(redisCacheAnn.valueSerializer());
} catch (BeansException e) {
logger.warn("unable to get spring bean by " + redisCacheAnn.valueSerializer());
}
ValueSerializable serializable = RedisCacheUtils.createObject(redisCacheAnn.valueSerializer());
if (serializable == null) {
logger.warn("unable to create instance for " + redisCacheAnn.valueSerializer()
+ ", use " + JSONValueSerializer.class + " for instead");
serializable = new JSONValueSerializer(returnType, logger);
}
return serializable;
}
static String generateValueKey(MethodInvocation invocation,
RedisCacheEnabled redisCacheAnn,
ApplicationContext appContext,
Logger logger) {
Class<? extends RedisCacheNameGenerator> naming = redisCacheAnn.naming();
if (naming != NoopRedisCacheNameGenerator.class) {
RedisCacheNameGenerator bean = getBean(appContext, naming);
if (bean != null) return bean.generateCacheName(invocation);
logger.warn("fail to get/create instance for {}", naming);
}
String arguments = joinArguments(invocation);
return "Cache:" + getNamePrefix(invocation) + ":" + arguments;
}
private static String getNamePrefix(MethodInvocation invocation) {
Method method = invocation.getMethod();
String methodName = method.getName();
String simpleName = method.getDeclaringClass().getSimpleName() + ":";
if (methodName.startsWith("get")) methodName = methodName.substring(3);
return simpleName + capitalize(methodName);
}
public static <T> T tryGetBean(ApplicationContext appContext, Class<T> clazz) {
try {
return appContext.getBean(clazz);
} catch (NoSuchBeanDefinitionException e) {
return null;
}
}
}
|
package com.github.bot.curiosone.core.nlp.base;
public enum PartOfSpeechType {
/**
* Adjective Phrase.
*/
AP,
/**
* Adjective preposition phrase.
*/
APP,
/**
* Adjective.
*/
ADJ,
/**
* Adverb.
*/
ADV,
/**
* Conjunction.
*/
CONJ,
/**
* Determiner.
*/
DET,
/**
* Interjections.
* (bye, goodbye, hello, farewell, hi, so long excuse me, thanks, thank you,
* thanks a lot, sorry, pardon)
*/
INTERJ,
/**
* Noun.
*/
N,
/**
* Negation.
*/
NEG,
/**
* Nominal part.
*/
NP,
/**
* Noun preposition phrase.
*/
NPP,
/**
* Number.
*/
NUMB,
/**
* Preposition.
*/
PREP,
/**
* Pronoun.
*/
PRON,
/**
* Sentence.
*/
S,
/**
* Unknown.
*/
UNKN,
/**
* Verb.
*/
V,
/**
* Verbal part.
*/
VP,
/**
* Verb preposition phrase.
*/
VPP
}
|
package com.github.mkopylec.sessioncouchbase.data;
import com.couchbase.client.java.document.json.JsonArray;
import com.couchbase.client.java.error.DocumentDoesNotExistException;
import com.couchbase.client.java.query.N1qlQueryResult;
import com.couchbase.client.java.query.N1qlQueryRow;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.data.couchbase.core.CouchbaseQueryExecutionException;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.retry.support.RetryTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static com.couchbase.client.java.document.json.JsonArray.from;
import static com.couchbase.client.java.query.N1qlParams.build;
import static com.couchbase.client.java.query.N1qlQuery.parameterized;
import static com.couchbase.client.java.query.N1qlQuery.simple;
import static com.couchbase.client.java.query.consistency.ScanConsistency.REQUEST_PLUS;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.util.Assert.isTrue;
public class PersistentDao implements SessionDao {
private static final Logger log = getLogger(PersistentDao.class);
protected final String bucket;
protected final CouchbaseTemplate couchbaseTemplate;
protected final RetryTemplate retryTemplate;
public PersistentDao(CouchbaseProperties couchbase, CouchbaseTemplate couchbaseTemplate, RetryTemplate retryTemplate) {
bucket = couchbase.getBucket().getName();
this.couchbaseTemplate = couchbaseTemplate;
this.retryTemplate = retryTemplate;
}
@Override
public void insertNamespace(String namespace, String id) {
printAllDocs();
String statement = "UPDATE " + bucket + " USE KEYS $1 SET data.`" + namespace + "` = {}";
executeQuery(statement, from(id, namespace));
}
@Override
public void updateSession(Map<String, Object> attributesToUpdate, Set<String> attributesToRemove, String namespace, String id) {
printAllDocs();
StringBuilder statement = new StringBuilder("UPDATE ").append(bucket).append(" USE KEYS $1");
List<Object> parameters = new ArrayList<>(attributesToUpdate.size() + attributesToRemove.size() + 1);
parameters.add(id);
int parameterIndex = 2;
if (MapUtils.isNotEmpty(attributesToUpdate)) {
statement.append(" SET ");
for (Entry<String, Object> attribute : attributesToUpdate.entrySet()) {
parameters.add(attribute.getValue());
statement.append("data.`").append(namespace).append("`.`").append(attribute.getKey()).append("` = $").append(parameterIndex++).append(",");
}
deleteLastCharacter(statement);
}
if (CollectionUtils.isNotEmpty(attributesToRemove)) {
statement.append(" UNSET ");
attributesToRemove.forEach(name -> statement.append("data.`").append(namespace).append("`.`").append(name).append("`,"));
deleteLastCharacter(statement);
}
executeQuery(statement.toString(), from(parameters));
}
@Override
public void updatePutPrincipalSession(String principal, String sessionId) {
printAllDocs();
String statement = "UPDATE " + bucket + " USE KEYS $1 SET sessionIds = ARRAY_PUT(sessionIds, $2)";
executeQuery(statement, from(principal, sessionId));
}
@Override
public void updateRemovePrincipalSession(String principal, String sessionId) {
printAllDocs();
String statement = "UPDATE " + bucket + " USE KEYS $1 SET sessionIds = ARRAY_REMOVE(sessionIds, $2)";
executeQuery(statement, from(principal, sessionId));
}
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> findSessionAttributes(String id, String namespace) {
printAllDocs();
String statement = "SELECT * FROM " + bucket + ".data.`" + namespace + "` USE KEYS $1";
N1qlQueryResult result = executeQuery(statement, from(id));
List<N1qlQueryRow> attributes = result.allRows();
isTrue(attributes.size() < 2, "Invalid HTTP session state. Multiple namespaces '" + namespace + "' for session ID '" + id + "'");
if (attributes.isEmpty()) {
return null;
}
return (Map<String, Object>) attributes.get(0).value().toMap().get(namespace);
}
@Override
public SessionDocument findById(String id) {
printAllDocs();
return couchbaseTemplate.findById(id, SessionDocument.class);
}
@Override
public PrincipalSessionsDocument findByPrincipal(String principal) {
printAllDocs();
return couchbaseTemplate.findById(principal, PrincipalSessionsDocument.class);
}
@Override
public void updateExpirationTime(String id, int expiry) {
printAllDocs();
couchbaseTemplate.getCouchbaseBucket().touch(id, expiry);
}
@Override
public void save(SessionDocument document) {
printAllDocs();
couchbaseTemplate.save(document);
}
@Override
public void save(PrincipalSessionsDocument document) {
printAllDocs();
couchbaseTemplate.save(document);
}
@Override
public boolean exists(String documentId) {
printAllDocs();
return couchbaseTemplate.exists(documentId);
}
@Override
public void delete(String id) {
printAllDocs();
try {
couchbaseTemplate.remove(id);
} catch (DataRetrievalFailureException ex) {
if (!(ex.getCause() instanceof DocumentDoesNotExistException)) {
throw ex;
}
//Do nothing
}
}
@Override
public void deleteAll() {
printAllDocs();
String statement = "DELETE FROM " + bucket + " d RETURNING d";
N1qlQueryResult arg = executeQuery(statement, from());
log.info("### Delete all. {} | {} | {} | {}", arg.errors(), arg.finalSuccess(), arg.status(), arg.allRows());
}
protected void printAllDocs() {
N1qlQueryResult rows = couchbaseTemplate.queryN1QL(simple("SELECT * FROM " + bucket, build().consistency(REQUEST_PLUS)));
log.info("### all docs: {}", rows.allRows());
}
protected N1qlQueryResult executeQuery(String statement, JsonArray parameters) {
return retryTemplate.execute(context -> {
N1qlQueryResult result = couchbaseTemplate.queryN1QL(parameterized(statement, parameters, build().consistency(REQUEST_PLUS)));
if (isQueryFailed(result)) {
throw new CouchbaseQueryExecutionException("Error executing N1QL statement '" + statement + "'. " + result.errors());
}
return result;
});
}
protected boolean isQueryFailed(N1qlQueryResult result) {
return !result.finalSuccess() || CollectionUtils.isNotEmpty(result.errors());
}
protected void deleteLastCharacter(StringBuilder statement) {
statement.deleteCharAt(statement.length() - 1);
}
}
|
package com.gmail.woodyc40.commons.reflection.asm;
import com.gmail.woodyc40.commons.reflection.asm.sun.ClassFileAssembler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Creates dynamic classes for unsafe cast
*
* @author AgentTroll
* @version 1.0
*/
public class ClassBytecode {
private ClassBytecode() {}
// Class schema:
// Magic header - 0xCAFEBABE int
// Major version - 51 short
// Minor version - 0 short
// Constant pool - amount (short), all data types (tag (short), value (type write))
// Access - short
// Class - short
// Superclass - short
// Interfaces - short
// Interface val - short
// Fields - short
// Field val - Access (short), Name (short index at constant pool),
// Descriptor (short index at constant pool), 0 (short attr)
// Methods - short
// Method val - Access (short), Name (short index at constant pool),
// Descriptor (short index at constant pool), 0 (short attr)
// Attributes - short
// Atribute val - short name, short data amount, byte data array loop
/**
* The assembly utility from the <code>sun.reflect package</code>
*/
private final ClassFileAssembler asm = new ClassFileAssembler();
/**
* The bytecoded constant pool used to reference vars from bytecode
*/
private final Pool constantPool = new Pool();
/**
* The fields of this <code>class</code>
*/
private final List<BytecodeField> fields = new ArrayList<>();
/**
* The methods of this <code>class</code>
*/
private final List<BytecodeMethod> methods = new ArrayList<>();
/**
* The declared name of the <code>class</code>
*/
private String className;
/**
* The superclass of this <code>class</code>
*/
private Class<?> superclass;
/**
* The interfaces <code>implemented</code> by this <code>class</code>
*/
private Class[] interfaces;
/**
* Whether or not this <code>class</code> is an <code>interface</code>
*/
private boolean isInterface;
/**
* Creates a new instance of the bytecode builder
*
* @param className the name of the <code>class</code>
* @param superclass the concrete <code>class</code> that will be <code>extend</code>ed
* by this <code>class</code>. {@link java.lang.Object}.<code>class</code> if none
* @param interfaces the concrete <code>inteface</code>s that will be <code>implemented</code>
* by this <code>class</code>, an empty <code>class</code> array if none
* @param isInterface whether or not this <code>class</code> is an interface
*/
public ClassBytecode(String className, Class<?> superclass, Class[] interfaces,
boolean isInterface) {
asm.emitMagicAndVersion(); // Magic + version header
this.className = className;
this.superclass = superclass;
this.interfaces = interfaces;
this.isInterface = isInterface;
}
/**
* Gets the assembler used to emit bytecode to the builder
*
* @return the {@link com.gmail.woodyc40.commons.reflection.asm.sun.ClassFileAssembler}
* associated with this builder
*/
public ClassFileAssembler getAssembler() {
return this.asm;
}
/**
* Gets the constant listings in the pool used to hold local vars
*
* @return the constant pool associated with the builder
*/
public Pool getConstantPool() {
return this.constantPool;
}
/**
* Returns a <code>byte</code> array representing the built class
*
* <p>
* Array based in order to ensure compatibility
*
* @return the <code>byte</code>s representing the bytecode of the built <code>class</code>
*/
public byte[] writeClassCode() {
try {
constantPool.writeData(asm);
} catch (IOException e) {
e.printStackTrace();
}
if (isInterface)
asm.emitShort((short) (Modifiers.ACC_PUBLIC | Modifiers.ACC_INTERFACE | Modifiers.ACC_ABSTRACT));
else asm.emitShort((short) (Modifiers.ACC_PUBLIC | Modifiers.ACC_SUPER)); // Access
asm.emitShort((short) constantPool.newClassInfo(className)); // Class name
asm.emitShort((short) constantPool.newClassInfo(superclass.getName())); // Superclass name
asm.emitShort((short) interfaces.length); // Interfaces
for (Class<?> face : interfaces)
asm.emitShort((short) constantPool.newClassInfo(face.getName()));
asm.emitShort((short) methods.size()); // Fields
for (BytecodeField field : fields)
field.add(this);
asm.emitShort((short) methods.size()); // Methods
for (BytecodeMethod method : methods)
method.add(this);
asm.emitShort((short) 1); // Attributes
String fnlName = "";
int index = className.lastIndexOf('.');
if (index >= 0)
fnlName = className.substring(index + 1) + ".java";
Pool.Attr attr = new Pool.SourceAttr(constantPool, fnlName);
attr.toData(asm);
return asm.getData().getData();
}
/**
* Adds a field to the builder, uses params of the constructor of the representing field
*
* <p>
* See {@link com.gmail.woodyc40.commons.reflection.asm.BytecodeField} for more details
*
* @param fieldName the declared name of the field
* @param access the access flags to declare the field as
* @param type the type of field the declaration will hold
*/
public void addField(String fieldName, int access, Class<?> type) {
fields.add(new BytecodeField(fieldName, access, type));
}
public void addMethod(BytecodeMethod method) {
methods.add(method);
}
}
|
package com.hea3ven.buildingbricks.core.tileentity;
import java.util.Collection;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.property.ExtendedBlockState;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import com.hea3ven.buildingbricks.core.blocks.base.BlockBuildingBricks;
import com.hea3ven.buildingbricks.core.blocks.properties.PropertyMaterial;
import com.hea3ven.buildingbricks.core.materials.*;
import com.hea3ven.buildingbricks.core.materials.mapping.MaterialIdMapping;
public class TileMaterial extends TileEntity {
public static final PropertyMaterial MATERIAL = new PropertyMaterial();
public static boolean blocksInCreative = true;
private Material material;
private String materialId;
public Material getMaterial() {
if (material != null)
return material;
else
return null;
}
public void setMaterial(Material material) {
if(material != null)
materialId = material.getMaterialId();
this.material = material;
}
public static IExtendedBlockState setStateMaterial(IExtendedBlockState state, Material mat) {
return state.withProperty(MATERIAL, mat);
}
public static TileMaterial getTile(IBlockAccess world, BlockPos pos) {
TileMaterial tile;
TileEntity te = world.getTileEntity(pos);
if (!(te instanceof TileMaterial))
return null;
tile = (TileMaterial) te;
return tile;
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setString("material", materialId);
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
if (nbt.hasKey("material")) {
String matId = nbt.getString("material");
if (!matId.contains(":"))
matId = "buildingbrickscompatvanilla:" + matId;
materialId = matId;
setMaterial(MaterialRegistry.get(matId));
} else {
Material mat = MaterialIdMapping.get().getMaterialById(nbt.getShort("m"));
materialId = mat.getMaterialId();
setMaterial(mat);
}
}
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate) {
return oldState.getBlock() != newSate.getBlock();
}
@Override
public Packet getDescriptionPacket() {
NBTTagCompound nbt = new NBTTagCompound();
writeToNBT(nbt);
return new S35PacketUpdateTileEntity(pos, 1, nbt);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
readFromNBT(pkt.getNbtCompound());
}
public static BlockState createBlockState(BlockState superState) {
Collection props = superState.getProperties();
return new ExtendedBlockState(superState.getBlock(),
(IProperty[]) props.toArray(new IProperty[props.size()]),
new IUnlistedProperty[] {TileMaterial.MATERIAL});
}
public static IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) {
TileMaterial tile = getTile(world, pos);
if (tile == null || tile.getMaterial() == null)
return state;
return TileMaterial.setStateMaterial((IExtendedBlockState) state, tile.getMaterial());
}
public static void onBlockPlacedBy(Block block, World world, BlockPos pos, IBlockState state,
EntityLivingBase placer, ItemStack stack) {
TileMaterial.getTile(world, pos).setMaterial(MaterialStack.get(stack));
}
public static ItemStack getPickBlock(Block block, MovingObjectPosition target, World world,
BlockPos pos) {
ItemStack stack = new ItemStack(block, 1);
MaterialStack.set(stack, TileMaterial.getTile(world, pos).getMaterial());
return stack;
}
public static void getSubBlocks(Block block, Item item, CreativeTabs tab, List<ItemStack> list) {
if (blocksInCreative) {
for (Material mat : MaterialBlockRegistry.instance.getBlockMaterials(block)) {
ItemStack stack = new ItemStack(item);
MaterialStack.set(stack, mat);
list.add(stack);
}
}
}
public static ItemStack getHarvestBlock(World world, BlockPos pos, EntityPlayer player) {
Block block = world.getBlockState(pos).getBlock();
if (!(block instanceof BlockBuildingBricks))
return null;
MaterialBlockType blockType = ((BlockBuildingBricks) block).getBlockLogic().getBlockType();
TileMaterial te = TileMaterial.getTile(world, pos);
if (te == null)
return null;
Material mat = te.getMaterial();
if (mat == null)
return null;
boolean silk = mat.getSilkHarvestMaterial() != null && EnchantmentHelper.getSilkTouchModifier(player);
String harvestMatId = silk ? mat.getSilkHarvestMaterial() : mat.getNormalHarvestMaterial();
if (harvestMatId == null)
return null;
Material itemMat = MaterialRegistry.get(harvestMatId);
if (itemMat == null)
return null;
return itemMat.getBlock(blockType).getStack().copy();
}
}
|
package com.imcode.imcms.controller.core;
import com.imcode.imcms.api.DocumentLanguageDisabledException;
import com.imcode.imcms.domain.exception.DocumentNotExistException;
import com.imcode.imcms.domain.service.AccessService;
import com.imcode.imcms.domain.service.CommonContentService;
import com.imcode.imcms.domain.service.VersionService;
import com.imcode.imcms.mapping.DocumentMapper;
import com.imcode.imcms.model.CommonContent;
import com.imcode.imcms.persistence.entity.Version;
import imcode.server.Imcms;
import imcode.server.ImcmsConstants;
import imcode.server.LanguageMapper;
import imcode.server.document.textdocument.TextDocumentDomainObject;
import imcode.server.user.UserDomainObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.imcode.imcms.mapping.DocumentMeta.DisabledLanguageShowMode.SHOW_IN_DEFAULT_LANGUAGE;
import static imcode.server.ImcmsConstants.REQUEST_PARAM__WORKING_PREVIEW;
@Controller
@RequestMapping("/viewDoc")
public class ViewDocumentController {
private final DocumentMapper documentMapper;
private final VersionService versionService;
private final CommonContentService commonContentService;
private final AccessService accessService;
private final String imagesPath;
private final String version;
private final boolean isVersioningAllowed;
ViewDocumentController(DocumentMapper documentMapper,
VersionService versionService,
CommonContentService commonContentService,
AccessService accessService,
@Value("${ImagePath}") String imagesPath,
@Value("${imcms.version}") String version,
@Value("${document.versioning:true}") boolean isVersioningAllowed) {
this.documentMapper = documentMapper;
this.versionService = versionService;
this.commonContentService = commonContentService;
this.accessService = accessService;
this.imagesPath = imagesPath;
this.version = version;
this.isVersioningAllowed = isVersioningAllowed;
}
@RequestMapping({"", "/"})
public ModelAndView goToStartPage(HttpServletRequest request, ModelAndView mav) {
final String docId = String.valueOf(ImcmsConstants.DEFAULT_START_DOC_ID);
final TextDocumentDomainObject textDocument = getTextDocument(docId, getLanguageCode(), request);
return processDocView(textDocument, request, mav);
}
@RequestMapping("/{docIdentifier}")
public ModelAndView getDocument(@PathVariable("docIdentifier") String docIdentifier,
HttpServletRequest request,
ModelAndView mav) {
final TextDocumentDomainObject textDocument = getTextDocument(docIdentifier, getLanguageCode(), request);
return processDocView(textDocument, request, mav);
}
private ModelAndView processDocView(TextDocumentDomainObject textDocument, HttpServletRequest request,
ModelAndView mav) {
final String isEditModeStr = Objects.toString(request.getAttribute("isEditMode"), "false");
final boolean isEditMode = Boolean.parseBoolean(isEditModeStr);
final boolean isPreviewMode = isVersioningAllowed
&& Boolean.parseBoolean(request.getParameter(REQUEST_PARAM__WORKING_PREVIEW));
final String viewName = textDocument.getTemplateName();
final int docId = textDocument.getId();
final String docLangCode = textDocument.getLanguage().getCode();
final Version latestDocVersion = versionService.getLatestVersion(docId);
final List<CommonContent> enabledCommonContents =
commonContentService.getCommonContents(docId, latestDocVersion.getNo())
.stream()
.filter(CommonContent::isEnabled)
.collect(Collectors.toList());
if (enabledCommonContents.size() == 0) {
throw new DocumentLanguageDisabledException(textDocument, textDocument.getLanguage());
}
final Optional<CommonContent> optionalCommonContent = enabledCommonContents.stream()
.filter(commonContent -> commonContent.getLanguage().getCode().equals(docLangCode))
.findFirst();
final String language;
final UserDomainObject user = Imcms.getUser();
if (!optionalCommonContent.isPresent()) {
if (textDocument.getDisabledLanguageShowMode().equals(SHOW_IN_DEFAULT_LANGUAGE)) {
language = LanguageMapper.convert639_2to639_1(user.getLanguageIso639_2());
} else {
throw new DocumentLanguageDisabledException(textDocument, textDocument.getLanguage());
}
} else {
language = docLangCode;
}
mav.setViewName(viewName);
mav.addObject("userLanguage", user.getLanguage());
mav.addObject("currentDocument", textDocument);
mav.addObject("language", language);
mav.addObject("isAdmin", user.isAdmin());
mav.addObject("isEditMode", isEditMode);
mav.addObject("contextPath", request.getContextPath());
mav.addObject("imagesPath", imagesPath);
mav.addObject("isVersioningAllowed", isVersioningAllowed);
mav.addObject("isPreviewMode", isPreviewMode);
mav.addObject("hasNewerVersion", versionService.hasNewerVersion(docId));
mav.addObject("version", version);
mav.addObject("editOptions", accessService.getEditPermission(user.getId(), docId));
return mav;
}
private TextDocumentDomainObject getTextDocument(String docId, String languageCode, HttpServletRequest request) {
return Optional.ofNullable(documentMapper.<TextDocumentDomainObject>getVersionedDocument(docId, languageCode, request))
.orElseThrow(() -> new DocumentNotExistException(docId));
}
private String getLanguageCode() {
return Imcms.getLanguage().getCode();
}
}
|
package com.mercury.chat.server.protocol.group;
import static com.mercury.chat.common.constant.Constant.userInfo;
import static com.mercury.chat.common.util.Channels.get;
import static com.mercury.chat.common.util.Channels.has;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.EventExecutor;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.mercury.chat.user.entity.User;
public class ChatChannelGroup extends DefaultChannelGroup {
private RemovalListener<String,Channel> removalListener = new RemovalListener<String,Channel>(){
@Override
public void onRemoval(RemovalNotification<String, Channel> notification) {
//TODO add logic to handler removing the channel
}
};
private Cache<String,Channel> cache = CacheBuilder
.newBuilder()
.concurrencyLevel(4)
.initialCapacity(8)
.maximumSize(10000)
.removalListener(removalListener)
.recordStats()
.build();
public Cache<String,Channel> getCache(){
return cache;
}
public ChatChannelGroup(EventExecutor executor) {
super(executor);
}
public ChatChannelGroup(String name, EventExecutor executor) {
super(name, executor);
}
@Override
public boolean add(Channel channel) {
boolean added = super.add(channel);
if(has(channel,userInfo)){
User user = get(channel,userInfo);
cache.put(user.getUserId(), channel);
}
return added;
}
@Override
public boolean remove(Object o) {
Channel channel = null;
if (o instanceof ChannelId) {
ChannelId id = (ChannelId) o;
channel = find(id);
}else if(o instanceof Channel){
channel = (Channel) o;
}
if(has(channel,userInfo)){
User user = get(channel,userInfo);
cache.invalidate(user.getUserId());
}
boolean removed = super.remove(o);
return removed;
}
@Override
public ChannelGroupFuture writeAndFlush(Object message, ChannelMatcher matcher) {
return super.writeAndFlush(message, matcher);
}
}
|
package com.nongfenqi.nexus.plugin.rundeck;
import com.google.common.base.Supplier;
import org.apache.http.client.utils.DateUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.sonatype.goodies.common.ComponentSupport;
import org.sonatype.nexus.blobstore.api.Blob;
import org.sonatype.nexus.repository.Repository;
import org.sonatype.nexus.repository.manager.RepositoryManager;
import org.sonatype.nexus.repository.search.SearchService;
import org.sonatype.nexus.repository.storage.Asset;
import org.sonatype.nexus.repository.storage.Bucket;
import org.sonatype.nexus.repository.storage.StorageFacet;
import org.sonatype.nexus.repository.storage.StorageTx;
import org.sonatype.nexus.rest.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.sonatype.nexus.common.text.Strings2.isBlank;
@Named
@Singleton
@Path("/rundeck/maven/options")
public class RundeckMavenResource
extends ComponentSupport
implements Resource {
private final SearchService searchService;
private final RepositoryManager repositoryManager;
private static final Response NOT_FOUND = Response.status(404).build();
@Inject
public RundeckMavenResource(
SearchService searchService,
RepositoryManager repositoryManager
) {
this.searchService = checkNotNull(searchService);
this.repositoryManager = checkNotNull(repositoryManager);
}
@GET
@Path("content")
public Response content(
@QueryParam("r") String repositoryName,
@QueryParam("g") String groupId,
@QueryParam("a") String artifactId,
@QueryParam("v") String version,
@QueryParam("c") String classifier,
@QueryParam("p") @DefaultValue("jar") String extension
) {
// default version
if ("LATEST".equals(version)) {
version = null;
}
version = Optional.ofNullable(version).orElse(latestVersion(
repositoryName, groupId, artifactId, classifier, extension
));
// valid params
if (isBlank(repositoryName) || isBlank(groupId) || isBlank(artifactId) || isBlank(version)) {
return NOT_FOUND;
}
Repository repository = repositoryManager.get(repositoryName);
if (null == repository || !repository.getFormat().getValue().equals("maven2")) {
return NOT_FOUND;
}
StorageFacet facet = repository.facet(StorageFacet.class);
Supplier<StorageTx> storageTxSupplier = facet.txSupplier();
log.debug("rundeck download repository: {}", repository);
final StorageTx tx = storageTxSupplier.get();
tx.begin();
Bucket bucket = tx.findBucket(repository);
log.debug("rundeck download bucket: {}", bucket);
if (null == bucket) {
return commitAndReturn(NOT_FOUND, tx);
}
String folderVersion = version.replaceAll("-\\d{8}\\.\\d{6}\\-\\d+", "-SNAPSHOT");
String fileName = artifactId + "-" + version + (isBlank(classifier) ? "" : ("-" + classifier)) + "." + extension;
String path = groupId.replace(".", "/") +
"/" + artifactId +
"/" + folderVersion +
"/" + fileName;
Asset asset = tx.findAssetWithProperty("name", path, bucket);
log.debug("rundeck download asset: {}", asset);
if (null == asset) {
return commitAndReturn(NOT_FOUND, tx);
}
asset.markAsDownloaded();
tx.saveAsset(asset);
Blob blob = tx.requireBlob(asset.requireBlobRef());
Response.ResponseBuilder ok = Response.ok(blob.getInputStream());
ok.header("Content-Type", blob.getHeaders().get("BlobStore.content-type"));
ok.header("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
return commitAndReturn(ok.build(), tx);
}
@GET
@Path("version")
@Produces(APPLICATION_JSON)
public List<RundeckXO> version(
@DefaultValue("10") @QueryParam("l") int limit,
@QueryParam("r") String repository,
@QueryParam("g") String groupId,
@QueryParam("a") String artifactId,
@QueryParam("c") String classifier,
@QueryParam("p") String extension
) {
log.debug("param value, repository: {}, limit: {}, groupId: {}, artifactId: {}, classifier: {}, extension: {}", repository, limit, groupId, artifactId, classifier, extension);
BoolQueryBuilder query = boolQuery();
query.filter(termQuery("format", "maven2"));
if (!isBlank(repository)) {
query.filter(termQuery("repository_name", repository));
}
if (!isBlank(groupId)) {
query.filter(termQuery("attributes.maven2.groupId", groupId));
}
if (!isBlank(artifactId)) {
query.filter(termQuery("attributes.maven2.artifactId", artifactId));
}
if (!isBlank(classifier)) {
query.filter(termQuery("assets.attributes.maven2.classifier", classifier));
}
if (!isBlank(extension)) {
query.filter(termQuery("assets.attributes.maven2.extension", extension));
}
log.debug("rundeck maven version query: {}", query);
SearchResponse result = searchService.searchUnrestricted(
query,
Collections.singletonList(new FieldSortBuilder("assets.attributes.content.last_modified").order(SortOrder.DESC)),
0,
limit
);
return Arrays.stream(result.getHits().hits())
.map(this::his2RundeckXO)
.collect(Collectors.toList());
}
private String latestVersion(String repositoryName, String groupId, String artifactId, String classifier, String extension) {
List<RundeckXO> latestVersion = version(1, repositoryName, groupId, artifactId, classifier, extension);
if (!latestVersion.isEmpty()) {
return latestVersion.get(0).getValue();
}
return null;
}
private RundeckXO his2RundeckXO(SearchHit hit) {
String version = (String) hit.getSource().get("version");
List<Map<String, Object>> assets = (List<Map<String, Object>>) hit.getSource().get("assets");
Map<String, Object> attributes = (Map<String, Object>) assets.get(0).get("attributes");
Map<String, Object> content = (Map<String, Object>) attributes.get("content");
String lastModifiedTime = "null";
if (content != null && content.containsKey("last_modified")) {
Long lastModified = (Long) content.get("last_modified");
lastModifiedTime = DateUtils.formatDate(new Date(lastModified), "yyyy-MM-dd HH:mm:ss");
}
return RundeckXO.builder().name(version + " (" + lastModifiedTime + ")").value(version).build();
}
private Response commitAndReturn(Response response, StorageTx tx) {
if (tx.isActive()) {
tx.commit();
}
return response;
}
}
|
package com.skelril.skree.system.registry.item;
import com.skelril.nitro.registry.Craftable;
import com.skelril.nitro.registry.item.CookedItem;
import com.skelril.nitro.registry.item.ICustomItem;
import com.skelril.nitro.selector.EventAwareContent;
import com.skelril.skree.SkreePlugin;
import com.skelril.skree.content.registry.item.CustomItemTypes;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.ItemModelMesher;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.GameRegistry;
import org.spongepowered.api.Sponge;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class CustomItemSystem {
public void preInit() {
try {
iterate(CustomItemSystem.class.getDeclaredMethod("register", Object.class));
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
}
public void associate() {
try {
iterate(CustomItemSystem.class.getDeclaredMethod("registerAssociates", Object.class));
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
}
public void init() {
try {
iterate(CustomItemSystem.class.getDeclaredMethod("render", Object.class));
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
}
private void iterate(Method method) {
method.setAccessible(true);
for (Field field : CustomItemTypes.class.getFields()) {
try {
Object result = field.get(null);
method.invoke(this, result);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// Invoked via reflection
@SuppressWarnings("unused")
private void register(Object item) {
if (item instanceof Item && item instanceof ICustomItem) {
((Item) item).setUnlocalizedName("skree_" + ((ICustomItem) item).__getID());
((Item) item).setRegistryName("skree:" + ((ICustomItem) item).__getID());
GameRegistry.register((Item) item);
// Add selective hooks
if (item instanceof EventAwareContent) {
Sponge.getEventManager().registerListeners(SkreePlugin.inst(), item);
}
} else {
throw new IllegalArgumentException("Invalid custom item!");
}
}
@SuppressWarnings("unused")
private void registerAssociates(Object item) {
if (item instanceof Item && item instanceof ICustomItem) {
// Add selective hooks
if (item instanceof Craftable) {
((Craftable) item).registerRecipes();
}
if (item instanceof CookedItem) {
((CookedItem) item).registerIngredients();
}
} else {
throw new IllegalArgumentException("Invalid custom item!");
}
}
// Invoked via reflection
@SuppressWarnings("unused")
private void render(Object item) {
if (item instanceof Item && item instanceof ICustomItem) {
if (Sponge.getPlatform().getExecutionType().isClient()) {
RenderItem renderItem = Minecraft.getMinecraft().getRenderItem();
ItemModelMesher mesher = renderItem.getItemModelMesher();
Optional<ItemMeshDefinition> optMeshDefinition = ((ICustomItem) item).__getCustomMeshDefinition();
if (optMeshDefinition.isPresent()) {
mesher.register((Item) item, optMeshDefinition.get());
}
List<String> variants = ((ICustomItem) item).__getMeshDefinitions();
List<ResourceLocation> modelResources = new ArrayList<>();
for (int i = 0; i < variants.size(); ++i) {
ModelResourceLocation resourceLocation = new ModelResourceLocation(
"skree:" + variants.get(i),
"inventory"
);
if (!optMeshDefinition.isPresent()) {
mesher.register((Item) item, i, resourceLocation);
}
modelResources.add(resourceLocation);
}
ModelBakery.registerItemVariants(
(Item) item,
modelResources.toArray(new ResourceLocation[modelResources.size()])
);
}
} else {
throw new IllegalArgumentException("Invalid custom item!");
}
}
}
|
package rhogenwizard;
import java.util.concurrent.Callable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
public class ConsoleHelper
{
public interface Stream
{
void print(String message);
void println();
void println(String message);
}
public interface Console
{
void show();
void showOnNextMessage();
void clear();
void disable();
Stream getStream();
Stream getOutputStream();
Stream getErrorStream();
}
public static Stream nullStream = new Stream()
{
@Override
public void println(String message)
{
}
@Override
public void println()
{
}
@Override
public void print(String message)
{
}
};
public static Console nullConsole = new Console()
{
@Override
public void show()
{
}
@Override
public void showOnNextMessage()
{
}
@Override
public void clear()
{
}
@Override
public void disable()
{
}
@Override
public Stream getStream()
{
return nullStream;
}
@Override
public Stream getOutputStream()
{
return nullStream;
}
@Override
public Stream getErrorStream()
{
return nullStream;
}
};
private interface Callback
{
void call();
}
private static class StreamImpl implements Stream
{
private boolean m_enabled;
private Callable<Object> m_callback;
private MessageConsoleStream m_stream;
public StreamImpl(MessageConsole console, Callable<Object> callback, int swtColorId)
{
m_enabled = true;
m_callback = callback;
m_stream = console.newMessageStream();
setColor(m_stream, swtColorId);
}
public void disable()
{
m_enabled = false;
}
@Override
public void print(String message)
{
if (m_enabled)
{
try
{
m_callback.call();
m_stream.print(message);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
@Override
public void println()
{
if (m_enabled)
{
try
{
m_callback.call();
m_stream.println();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
@Override
public void println(String message)
{
if (m_enabled)
{
try
{
m_callback.call();
m_stream.println(message);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private static void setColor(final MessageConsoleStream stream, final int swtColorId)
{
Display display1 = Display.getCurrent();
if (display1 != null)
{
stream.setColor(display1.getSystemColor(swtColorId));
return;
}
final Display display2 = Display.getDefault();
if (display2 != null)
{
display2.asyncExec(new Runnable()
{
@Override
public void run()
{
stream.setColor(display2.getSystemColor(swtColorId));
}
});
}
}
}
private static class ConsoleImpl implements Console
{
private final MessageConsole m_console;
private final StreamImpl m_stream;
private final StreamImpl m_outputStream;
private final StreamImpl m_errorStream;
private boolean m_enabled;
private boolean m_showOnNextMessage;
public ConsoleImpl(String name)
{
Callable<Object> callback = new Callable<Object>()
{
@Override
public Object call()
{
if (m_showOnNextMessage)
{
show();
m_showOnNextMessage = false;
}
return null;
}
};
m_console = findConsole(name);
m_stream = new StreamImpl(m_console, callback, SWT.COLOR_BLACK);
m_outputStream = new StreamImpl(m_console, callback, SWT.COLOR_DARK_BLUE);
m_errorStream = new StreamImpl(m_console, callback, SWT.COLOR_DARK_RED);
m_enabled = true;
m_showOnNextMessage = false;
}
@Override
public void clear()
{
if (m_enabled)
{
m_console.clearConsole();
}
}
@Override
public void show()
{
if (m_enabled)
{
IConsoleManager conMan = ConsolePlugin.getDefault().getConsoleManager();
conMan.showConsoleView(m_console);
conMan.refresh(m_console);
}
}
@Override
public void showOnNextMessage()
{
if (m_enabled)
{
m_showOnNextMessage = true;
}
}
@Override
public Stream getStream()
{
return m_stream;
}
@Override
public Stream getOutputStream()
{
return m_outputStream;
}
@Override
public Stream getErrorStream()
{
return m_errorStream;
}
public void disable()
{
m_enabled = false;
m_stream.disable();
m_outputStream.disable();
m_errorStream.disable();
}
private static MessageConsole findConsole(String name)
{
ConsolePlugin plugin = ConsolePlugin.getDefault();
if (plugin == null)
return null;
IConsoleManager conMan = plugin.getConsoleManager();
if (conMan == null)
return null;
IConsole[] existing = conMan.getConsoles();
for (int i = 0; i < existing.length; i++)
{
if (name.equals(existing[i].getName()))
{
return (MessageConsole) existing[i];
}
}
// no console found, so create a new one
MessageConsole myConsole = new MessageConsole(name, null);
conMan.addConsoles(new IConsole[] { myConsole });
return myConsole;
}
}
private static Console appConsole = null;
private static Console buildConsole = null;
public static void initialize()
{
if (appConsole == null)
{
appConsole = new ConsoleImpl("Rhomobile application console");
}
if (buildConsole == null)
{
buildConsole = new ConsoleImpl("Rhomobile build console");
}
}
public static void setupNullConsoles()
{
appConsole = nullConsole;
buildConsole = nullConsole;
}
public static void disableConsoles()
{
initialize();
appConsole.disable();
buildConsole.disable();
}
public static Console getAppConsole()
{
initialize();
return appConsole;
}
public static Console getBuildConsole()
{
initialize();
return buildConsole;
}
}
|
package com.teamwizardry.refraction.client.render;
import com.teamwizardry.refraction.api.ConfigValues;
import com.teamwizardry.refraction.client.core.RenderLaserUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.GlStateManager.DestFactor;
import net.minecraft.client.renderer.GlStateManager.SourceFactor;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import org.lwjgl.opengl.GL11;
import java.awt.Color;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class LaserRenderer {
public static final LaserRenderer INSTANCE = new LaserRenderer();
protected Map<LaserRenderInfo, Integer> lasers = new ConcurrentHashMap<>();
private LaserRenderer() {
MinecraftForge.EVENT_BUS.register(this);
}
public static void add(Vec3d start, Vec3d end, Color color) {
INSTANCE.lasers.put(new LaserRenderInfo(start, end, color), ConfigValues.BEAM_PARTICLE_LIFE);
}
@SubscribeEvent
public void unload(WorldEvent.Unload event) {
lasers.clear();
}
@SubscribeEvent
public void load(WorldEvent.Load event) {
lasers.clear();
}
@SubscribeEvent
public void renderWorldLast(RenderWorldLastEvent event) {
EntityPlayer rootPlayer = Minecraft.getMinecraft().player;
double x = rootPlayer.lastTickPosX + (rootPlayer.posX - rootPlayer.lastTickPosX) * event.getPartialTicks();
double y = rootPlayer.lastTickPosY + (rootPlayer.posY - rootPlayer.lastTickPosY) * event.getPartialTicks();
double z = rootPlayer.lastTickPosZ + (rootPlayer.posZ - rootPlayer.lastTickPosZ) * event.getPartialTicks();
GlStateManager.disableCull();
GlStateManager.depthMask(false);
GlStateManager.enableBlend();
GlStateManager.enableAlpha();
GlStateManager.alphaFunc(GL11.GL_GEQUAL, 1f / 255f);
if (ConfigValues.ADDITIVE_BLENDING) {
GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE);
}
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bb = tessellator.getBuffer();
bb.setTranslation(-x, -y, -z);
bb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
// vvv actual rendering stuff vvv
for (LaserRenderInfo info : lasers.keySet())
RenderLaserUtil.renderLaser(info.color, info.start, info.end, bb);
tessellator.draw();
bb.setTranslation(0, 0, 0);
if (ConfigValues.ADDITIVE_BLENDING) {
GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA);
}
GlStateManager.enableCull();
GlStateManager.disableBlend();
GlStateManager.depthMask(true);
}
@SubscribeEvent
public void tick(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.START) {
// update();
}
}
public void update() {
lasers.entrySet().removeIf((e) -> {
if (e.getValue() <= 0) return true;
else {
e.setValue(e.getValue() - 1);
return false;
}
});
}
public static class LaserRenderInfo {
public Vec3d start, end;
public Color color;
public LaserRenderInfo(Vec3d start, Vec3d end, Color color) {
this.start = start;
this.end = end;
this.color = color == null ? Color.WHITE : color;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LaserRenderInfo that = (LaserRenderInfo) o;
if (!start.equals(that.start)) return false;
if (!end.equals(that.end)) return false;
return color.equals(that.color);
}
@Override
public int hashCode() {
int result = start.hashCode();
result = 31 * result + end.hashCode();
result = 31 * result + color.hashCode();
return result;
}
}
}
|
package de.interseroh.report.services;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.interseroh.report.exception.BirtSystemException;
import de.interseroh.report.model.ReportReference;
@Service
public class BirtFileReaderServiceBean implements BirtFileReaderService {
private static final String REPORT_FILESUFFIX = ".rptdesign";
public static final int REPORT_FILESUFFIX_LENGTH = REPORT_FILESUFFIX.length();
private static final Logger logger = LoggerFactory
.getLogger(BirtFileReaderServiceBean.class);
@Autowired
private SecurityService securityControl;
/**
* deliver all file names (report names) in specified directory.
*
* @return names of all files in this directory (only reports)
*/
@Override
public List<ReportReference> getReportReferences() {
final File directory = securityControl.getTmpDirectory();
logger.debug("call to get role of current user in directory {}",
directory);
if (directory == null) {
return Collections.emptyList();
}
List<ReportReference> reportReferences = new ArrayList<>();
List<String> stripRoleNames = securityControl.getStripRoleNames();
try {
if (directory.exists() && directory.canRead()
&& directory.isDirectory()) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".rptdesign");
}
};
File[] files = directory.listFiles(filter);
if (files != null) {
for (File file : files) {
String fileName = file.getName().substring(0,
(file.getName().length() - REPORT_FILESUFFIX_LENGTH));
for (String role : stripRoleNames) {
if (role.equalsIgnoreCase(fileName)) {
reportReferences.add(new ReportReference(
fileName, "reports..."));
}
}
}
}
}
} catch (Exception e) {
throw new BirtSystemException(String.format(
"Error during to fill report list in directory: %s",
directory), e.getCause());
}
return reportReferences;
}
}
|
package dk.statsbiblioteket.nrtmosaic.service;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import dk.statsbiblioteket.nrtmosaic.service.exception.InternalServiceException;
import dk.statsbiblioteket.nrtmosaic.service.exception.InvalidArgumentServiceException;
import dk.statsbiblioteket.nrtmosaic.service.exception.ServiceException;
@Path("/")
public class NrtmosaicResource {
private static Log log = LogFactory.getLog(NrtmosaicResource.class);
@GET
@Path("/image")
@Produces("image/jpeg")
public Response getImage(@QueryParam("source") String arcFilePath, @QueryParam("x") double x, @QueryParam("y") double y, @QueryParam("z") double z)
throws ServiceException {
try {
//Do somethign with source, x, y, z parameters and then delete renderSampleImage method
BufferedImage image = renderSampleImage();
ResponseBuilder response = Response.ok((Object) image);
return response.build();
} catch (Exception e) {
throw handleServiceExceptions(e);
}
}
private static BufferedImage renderSampleImage() {
System.setProperty("java.awt.headless", "true");
final int size = 100;
BufferedImage img = new BufferedImage(size, size,
BufferedImage.TYPE_BYTE_GRAY);
Graphics2D gfx = img.createGraphics();
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
gfx.setStroke(new BasicStroke(size / 40f, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
gfx.setColor(Color.BLACK);
gfx.setBackground(Color.WHITE);
gfx.clearRect(0, 0, size, size);
int b = size / 30;
gfx.drawOval(b, b, size - 1 - 2 * b, size - 1 - 2 * b);
int esz = size / 7;
int ex = (int) (0.27f * size);
gfx.drawOval(ex, ex, esz, esz);
gfx.drawOval(size - 1 - esz - ex, ex, esz, esz);
b = size / 5;
gfx.drawArc(b, b, size - 1 - 2 * b, size - 1 - 2 * b, 200, 140);
return img;
}
private ServiceException handleServiceExceptions(Exception e) {
if (e instanceof ServiceException) {
log.info("Handling serviceException:" + e.getMessage());
return (ServiceException) e; // Do nothing, exception already correct
} else if (e instanceof IllegalArgumentException) {
log.error("ServiceException(HTTP 400) in Service:", e);
return new InvalidArgumentServiceException(e.getMessage());
} else {// SQL and other unforseen exceptions.... should not happen.
log.error("ServiceException(HTTP 500) in Service:", e);
return new InternalServiceException(e.getMessage());
}
}
}
|
package giraudsa.marshall.serialisation.binary;
import giraudsa.marshall.annotations.TypeRelation;
import giraudsa.marshall.exception.MarshallExeption;
import giraudsa.marshall.exception.NotImplementedSerializeException;
import giraudsa.marshall.serialisation.Marshaller;
import giraudsa.marshall.serialisation.binary.actions.ActionBinaryCollectionType;
import giraudsa.marshall.serialisation.binary.actions.ActionBinaryDate;
import giraudsa.marshall.serialisation.binary.actions.ActionBinaryDictionaryType;
import giraudsa.marshall.serialisation.binary.actions.ActionBinaryEnum;
import giraudsa.marshall.serialisation.binary.actions.ActionBinaryObject;
import giraudsa.marshall.serialisation.binary.actions.ActionBinaryString;
import giraudsa.marshall.serialisation.binary.actions.ActionBinaryUUID;
import giraudsa.marshall.serialisation.binary.actions.simple.ActionBinaryBoolean;
import giraudsa.marshall.serialisation.binary.actions.simple.ActionBinaryByte;
import giraudsa.marshall.serialisation.binary.actions.simple.ActionBinaryChar;
import giraudsa.marshall.serialisation.binary.actions.simple.ActionBinaryDouble;
import giraudsa.marshall.serialisation.binary.actions.simple.ActionBinaryFloat;
import giraudsa.marshall.serialisation.binary.actions.simple.ActionBinaryInteger;
import giraudsa.marshall.serialisation.binary.actions.simple.ActionBinaryLong;
import giraudsa.marshall.serialisation.binary.actions.simple.ActionBinaryShort;
import giraudsa.marshall.serialisation.binary.actions.simple.ActionBinaryVoid;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import utils.Constants;
import utils.champ.FakeChamp;
public class BinaryMarshaller extends Marshaller{
private static final Logger LOGGER = LoggerFactory.getLogger(BinaryMarshaller.class);
private DataOutputStream output;
private Map<Object, Integer> smallIds = new HashMap<>();
private Map<Class<?>, Integer> dejaVuType = new HashMap<>();
private int compteur = 0;
private int compteurType = 1;
private BinaryMarshaller(DataOutputStream output, boolean isCompleteSerialisation) throws IOException {
super(isCompleteSerialisation);
this.output = output;
output.writeBoolean(isCompleteSerialisation);
}
/////METHODES STATICS PUBLICS
public static <U> void toBinary(U obj, OutputStream output) throws MarshallExeption{
try(DataOutputStream stream = new DataOutputStream(output)){
BinaryMarshaller v = new BinaryMarshaller(stream, false);
v.marshall(obj);
stream.flush();
} catch (IOException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | NotImplementedSerializeException e) {
LOGGER.error("Problème lors de la sérialisation binaire", e);
throw new MarshallExeption(e);
}
}
public static <U> void toCompleteBinary(U obj, OutputStream output) throws MarshallExeption{
try(DataOutputStream stream = new DataOutputStream(output)){
BinaryMarshaller v = new BinaryMarshaller(stream,true);
v.marshall(obj);
stream.flush();
} catch (IOException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | NotImplementedSerializeException e) {
LOGGER.error("Problème lors de la sérialisation binaire complète", e);
throw new MarshallExeption(e);
}
}
/////METHODES
private <T> void marshall(T obj) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException, NotImplementedSerializeException, MarshallExeption{
FakeChamp fieldsInfo = new FakeChamp(null, Object.class, TypeRelation.COMPOSITION);
marshallSpecialise(obj, fieldsInfo);
while(!aFaire.isEmpty()){
deserialisePile();
}
}
private static byte getTypeOfSmallId(int smallId) {
if( ((int)((byte)smallId) & 0x000000FF) == smallId)
return Constants.SmallIdType.NEXT_IS_SMALL_ID_BYTE;
if( ((int)((short)smallId) & 0x0000FFFF) == smallId)
return Constants.SmallIdType.NEXT_IS_SMALL_ID_SHORT;
return Constants.SmallIdType.NEXT_IS_SMALL_ID_INT;
}
private static byte getTypeOfSmallIdTypeObj(int smallId) {
if( ((int)((byte)smallId) & 0x000000FF) == smallId)
return Constants.Type.CODAGE_BYTE;
if( ((int)((short)smallId) & 0x0000FFFF) == smallId)
return Constants.Type.CODAGE_SHORT;
return Constants.Type.CODAGE_INT;
}
private int getSmallIdAndStockObj(Object obj){
if(!smallIds.containsKey(obj)){
smallIds.put(obj, compteur++);
}
return smallIds.get(obj);
}
private int getSmallIdTypeAndStockType(Class<?> typeObj) {
if(!isDejaVuType(typeObj)){
dejaVuType.put(typeObj, compteurType++);
}
return dejaVuType.get(typeObj);
}
@Override protected void initialiseDico() {
dicoTypeToAction.put(void.class, new ActionBinaryVoid(this));
dicoTypeToAction.put(Boolean.class, new ActionBinaryBoolean(this));
dicoTypeToAction.put(Integer.class, new ActionBinaryInteger(this));
dicoTypeToAction.put(Byte.class, new ActionBinaryByte(this));
dicoTypeToAction.put(Float.class, new ActionBinaryFloat(this));
dicoTypeToAction.put(Double.class, new ActionBinaryDouble(this));
dicoTypeToAction.put(Long.class, new ActionBinaryLong(this));
dicoTypeToAction.put(Short.class, new ActionBinaryShort(this));
dicoTypeToAction.put(Character.class, new ActionBinaryChar(this));
dicoTypeToAction.put(UUID.class, new ActionBinaryUUID(this));
dicoTypeToAction.put(String.class, new ActionBinaryString(this));
dicoTypeToAction.put(Date.class, new ActionBinaryDate(this));
dicoTypeToAction.put(Enum.class, new ActionBinaryEnum(this));
dicoTypeToAction.put(Collection.class, new ActionBinaryCollectionType(this));
dicoTypeToAction.put(Map.class, new ActionBinaryDictionaryType(this));
dicoTypeToAction.put(Object.class, new ActionBinaryObject(this));
}
protected byte[] calculHeader(Object o, byte debutHeader, boolean estDejaVu) throws IOException, MarshallExeption{
Class<?> typeObj = o.getClass();
byte debut = debutHeader;
boolean isTypeAutre = debutHeader == Constants.Type.AUTRE || debutHeader== Constants.Type.DEVINABLE;
boolean typeDevinable = debutHeader== Constants.Type.DEVINABLE;
int smallId = getSmallIdAndStockObj(o);
byte typeOfSmallId = getTypeOfSmallId(smallId);
debut |= typeOfSmallId;
boolean isDejaVuTypeObj = true;
int smallIdTypeObj = 0;
byte typeOfSmallIdTypeObj = 0;
if(isTypeAutre && !estDejaVu){
typeObj = problemeHibernate(typeObj);
isDejaVuTypeObj = isDejaVuType(typeObj);
smallIdTypeObj = getSmallIdTypeAndStockType(typeObj);
typeOfSmallIdTypeObj = getTypeOfSmallIdTypeObj(smallIdTypeObj);
debut |= typeOfSmallIdTypeObj;
}
try(ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(byteOut)){
dataOut.writeByte(debut);
writeSmallId(smallId, typeOfSmallId, dataOut);
if(!estDejaVu)
ecritTypeSiNecessaire(typeObj, isTypeAutre, typeDevinable, isDejaVuTypeObj, smallIdTypeObj,
typeOfSmallIdTypeObj, dataOut);
return byteOut.toByteArray();
}
}
private Class<?> problemeHibernate(Class<?> typeObj) {
Class<?> ret = typeObj;
if(typeObj.getName().toLowerCase().indexOf("org.hibernate.collection.PersistentBag") != -1)
ret = ArrayList.class;
if(typeObj.getName().toLowerCase().indexOf("org.hibernate.collection.PersistentSet") != -1)
ret = HashSet.class;
if(typeObj.getName().toLowerCase().indexOf("org.hibernate.collection.PersistentMap") != -1)
ret = HashMap.class;
if(typeObj.getName().toLowerCase().indexOf("org.hibernate.collection.PersistentSortedSet") != -1)
ret = TreeSet.class;
if(typeObj.getName().toLowerCase().indexOf("org.hibernate.collection.PersistentSortedMap") != -1)
ret = TreeMap.class;
return ret;
}
private static void writeSmallId(int smallId, byte typeOfSmallId, DataOutputStream dataOut)
throws IOException, MarshallExeption {
switch (typeOfSmallId) {
case Constants.SmallIdType.NEXT_IS_SMALL_ID_BYTE:
dataOut.writeByte((byte)smallId);
break;
case Constants.SmallIdType.NEXT_IS_SMALL_ID_SHORT:
dataOut.writeShort((short)smallId);
break;
case Constants.SmallIdType.NEXT_IS_SMALL_ID_INT:
dataOut.writeInt(smallId);
break;
default :
throw new MarshallExeption("trop d'objets");
}
}
private static void ecritTypeSiNecessaire(Class<?> typeObj, boolean isTypeAutre, boolean typeDevinable,
boolean isDejaVuTypeObj, int smallIdTypeObj, byte typeOfSmallIdTypeObj, DataOutputStream dataOut)
throws IOException, MarshallExeption {
if(isTypeAutre && !typeDevinable){
writeSmallIdType(smallIdTypeObj, typeOfSmallIdTypeObj, dataOut);
if(!isDejaVuTypeObj){
dataOut.writeUTF(typeObj.getName());
}
}
}
private static void writeSmallIdType(int smallIdTypeObj, byte typeOfSmallIdTypeObj, DataOutputStream dataOut)
throws IOException, MarshallExeption {
switch (typeOfSmallIdTypeObj) {
case Constants.Type.CODAGE_BYTE:
dataOut.writeByte((byte)smallIdTypeObj);
break;
case Constants.Type.CODAGE_SHORT:
dataOut.writeShort((short)smallIdTypeObj);
break;
case Constants.Type.CODAGE_INT:
dataOut.writeInt(smallIdTypeObj);
break;
default :
throw new MarshallExeption("trop de type");
}
}
protected boolean isDejaVuType(Class<?> typeObj) {
return dejaVuType.containsKey(typeObj);
}
protected boolean writeBoolean(boolean v) throws IOException {
output.writeBoolean(v);
return v;
}
protected void writeByte(byte v) throws IOException {
output.writeByte((int)v);
}
protected void writeByteArray(byte[] v) throws IOException{
output.write(v);
}
protected void writeShort(short v) throws IOException {
output.writeShort((int)v);
}
protected void writeChar(char v) throws IOException {
output.writeChar((int)v);
}
protected void writeInt(int v) throws IOException {
output.writeInt(v);
}
protected void writeLong(long v) throws IOException {
output.writeLong(v);
}
protected void writeFloat(float v) throws IOException {
output.writeFloat(v);
}
protected void writeDouble(double v) throws IOException {
output.writeDouble(v);
}
protected void writeUTF(String s) throws IOException {
output.writeUTF(s);
}
}
|
package io.github.lukehutch.fastclasspathscanner.utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class JarUtils {
private static final List<String> JRE_PATHS = new ArrayList<>();
private static String RT_JAR_PATH = null;
private static String getProperty(final String propName) {
try {
return System.getProperty(propName);
} catch (final SecurityException e) {
return null;
}
}
private static void addJREPath(final File dir, final Set<String> jrePathsSet) {
if (ClasspathUtils.canRead(dir) && dir.isDirectory()) {
String path = dir.getPath();
if (!path.endsWith(File.separator)) {
path += File.separator;
}
final String jrePath = FastPathResolver.resolve("", path);
if (!jrePath.isEmpty()) {
jrePathsSet.add(jrePath);
}
try {
String canonicalPath = dir.getCanonicalPath();
if (!canonicalPath.endsWith(File.separator)) {
canonicalPath += File.separator;
}
final String jreCanonicalPath = FastPathResolver.resolve("", canonicalPath);
if (!jreCanonicalPath.equals(jrePath) && !jreCanonicalPath.isEmpty()) {
jrePathsSet.add(jreCanonicalPath);
}
} catch (IOException | SecurityException e) {
}
}
}
// Find JRE jar dirs.
// TODO: Update for JDK9.
static {
final Set<String> jrePathsSet = new HashSet<>();
final String javaHome = getProperty("java.home");
if (javaHome != null && !javaHome.isEmpty()) {
final File javaHomeFile = new File(javaHome);
addJREPath(javaHomeFile, jrePathsSet);
final File libFile = new File(javaHomeFile, "lib");
addJREPath(libFile, jrePathsSet);
final File extFile = new File(libFile, "ext");
addJREPath(extFile, jrePathsSet);
final File rtJarFile = new File(libFile, "rt.jar");
if (ClasspathUtils.canRead(rtJarFile)) {
RT_JAR_PATH = rtJarFile.getPath();
}
if (javaHomeFile.getName().equals("jre")) {
// Handle jre/../lib/tools.jar
final File parent = javaHomeFile.getParentFile();
if (parent != null) {
final File parentLibFile = new File(parent, "lib");
addJREPath(parentLibFile, jrePathsSet);
}
}
}
final String javaExtDirs = getProperty("java.ext.dirs");
if (javaExtDirs != null) {
for (final String javaExtDir : javaExtDirs.split(File.pathSeparator)) {
if (!javaExtDir.isEmpty()) {
final File javaExtDirFile = new File(javaExtDir);
addJREPath(javaExtDirFile, jrePathsSet);
}
}
}
// Add special-case path for Mac OS X, this is not always picked up
// from java.home or java.ext.dirs
addJREPath(new File("/System/Library/Java"), jrePathsSet);
JRE_PATHS.addAll(jrePathsSet);
Collections.sort(JRE_PATHS);
}
/** Get the path of rt.jar */
public static String getRtJarPath() {
return RT_JAR_PATH;
}
/** Log the Java version and the JRE paths that were found. */
public static void logJavaInfo(final LogNode log) {
if (log != null) {
log.log("Operating system: " + getProperty("os.name") + " " + getProperty("os.version") + " "
+ getProperty("os.arch"));
log.log("Java version: " + getProperty("java.version") + " (" + getProperty("java.vendor") + ")");
final LogNode javaLog = log.log("JRE paths:");
for (final String jrePath : JRE_PATHS) {
javaLog.log(jrePath);
}
if (RT_JAR_PATH != null) {
javaLog.log(RT_JAR_PATH);
}
}
}
/** Determine whether a given jarfile is in a JRE system directory (jre, jre/lib, jre/lib/ext, etc.). */
public static boolean isJREJar(final String filePath, final LogNode log) {
for (final String jrePathPrefix : JRE_PATHS) {
if (filePath.startsWith(jrePathPrefix)) {
return true;
}
}
return false;
}
/** Returns true if the path ends with a jarfile extension, ignoring case. */
public static boolean isJar(final String path) {
final int len = path.length();
return path.regionMatches(true, len - 4, ".jar", 0, 4)
|| path.regionMatches(true, len - 4, ".zip", 0, 4)
|| path.regionMatches(true, len - 4, ".war", 0, 4)
|| path.regionMatches(true, len - 4, ".car", 0, 4)
|| path.regionMatches(true, len - 6, ".wsjar", 0, 6);
}
/** Returns the leafname of a path. */
public static String leafName(final String path) {
final int lastSlashIdx = File.separatorChar == '/' ? path.lastIndexOf('/')
: Math.max(path.lastIndexOf('/'), path.lastIndexOf(File.separatorChar));
// In case of temp files (for jars extracted from within jars), remove the temp filename prefix
// -- see NestedJarHandler.unzipToTempFile()
int sepIdx = path.indexOf(NestedJarHandler.TEMP_FILENAME_LEAF_SEPARATOR);
if (sepIdx >= 0) {
sepIdx += NestedJarHandler.TEMP_FILENAME_LEAF_SEPARATOR.length() - 1;
}
final int maxIdx = Math.max(lastSlashIdx, sepIdx);
return maxIdx < 0 ? path : path.substring(maxIdx + 1);
}
}
|
package com.redhat.ceylon.compiler.java;
import java.util.Arrays;
import ceylon.language.ArraySequence;
import ceylon.language.AssertionError;
import ceylon.language.Callable;
import ceylon.language.Finished;
import ceylon.language.Integer;
import ceylon.language.Iterable;
import ceylon.language.Iterator;
import ceylon.language.Ranged;
import ceylon.language.Sequential;
import ceylon.language.empty_;
import ceylon.language.finished_;
import com.redhat.ceylon.cmr.api.ArtifactResult;
import com.redhat.ceylon.compiler.java.language.ArrayIterable;
import com.redhat.ceylon.compiler.java.language.SequenceBuilder;
import com.redhat.ceylon.compiler.java.metadata.Class;
import com.redhat.ceylon.compiler.java.metadata.Name;
import com.redhat.ceylon.compiler.java.metadata.TypeInfo;
import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;
public class Util {
static {
// Make sure the rethrow class is loaded if ever we need to rethrow
// errors such as StackOverflowError, otherwise if we have to rethrow it
// we will not be able to load that class since we've ran out of stack
ceylon.language.impl.rethrow_.class.toString();
}
private static final int INIT_ARRAY_SIZE = 10;
public static String declClassName(String name) {
return name.replace("::", ".");
}
public static void loadModule(String name, String version,
ArtifactResult result, ClassLoader classLoader){
Metamodel.loadModule(name, version, result, classLoader);
}
public static boolean isReified(java.lang.Object o, TypeDescriptor type){
return Metamodel.isReified(o, type);
}
/**
* Returns true if the given object satisfies ceylon.language.Identifiable
*/
public static boolean isIdentifiable(java.lang.Object o){
if(o == null)
return false;
Class classAnnotation = getClassAnnotationForIdentifiableOrBasic(o);
// unless marked as NOT identifiable, every instance is Identifiable
return classAnnotation != null ? classAnnotation.identifiable() : true;
}
private static Class getClassAnnotationForIdentifiableOrBasic(Object o) {
java.lang.Class<? extends Object> klass = o.getClass();
while(klass != null && klass != java.lang.Object.class){
Class classAnnotation = klass.getAnnotation(Class.class);
if(classAnnotation != null){
return classAnnotation;
}
// else keep looking up
klass = klass.getSuperclass();
}
// no annotation found
return null;
}
/**
* Returns true if the given object extends ceylon.language.Basic
*/
public static boolean isBasic(java.lang.Object o){
if(o == null)
return false;
Class classAnnotation = getClassAnnotationForIdentifiableOrBasic(o);
// unless marked as NOT identifiable, every instance is Basic
return classAnnotation != null ? classAnnotation.basic() : true;
}
// Java variadic conversions
/** Return the size of the given iterable if we know it can be computed
* efficiently (typcially without iterating the iterable)
*/
private static <T> int fastIterableSize(Iterable<? extends T, ?> iterable) {
if (iterable instanceof Sequential
|| iterable instanceof ArrayIterable) {
return (int)iterable.getSize();
}
String[] o = null;
Object[] i;
i = o;
return -1;
}
private static <T> void fillArray(T[] array, int offset, Iterable<? extends T, ?> iterable) {
Iterator<?> iterator = iterable.iterator();
Object o;
int index = offset;
while((o = iterator.next()) != finished_.get_()){
array[index] = (T)o;
index++;
}
}
/**
* Base class for a family of builders for Java native arrays.
*
* Encapsulation has been sacraficed for efficiency.
*
* @param <A> an array type such as int[]
*/
public static abstract class ArrayBuilder<A> {
private static final int MIN_CAPACITY = 5;
private static final int MAX_CAPACITY = java.lang.Integer.MAX_VALUE;
/** The number of elements in {@link #array}. This is always <= {@link #capacity} */
protected int size;
/** The length of {@link #array} */
protected int capacity;
/** The array */
protected A array;
ArrayBuilder(int initialSize) {
capacity = Math.max(initialSize, MIN_CAPACITY);
array = allocate(capacity);
size = 0;
}
/** Append all the elements in the given array */
final void appendArray(A elements) {
int increment = size(elements);
int newsize = this.size + increment;
ensure(newsize);
System.arraycopy(elements, 0, array, this.size, increment);
this.size = newsize;
}
/** Ensure the {@link #array} is as big, or bigger than the given capacity */
protected final void ensure(int requestedCapacity) {
if (this.capacity >= requestedCapacity) {
return;
}
int newcapacity = requestedCapacity+(requestedCapacity>>1);
if (newcapacity < MIN_CAPACITY) {
newcapacity = MIN_CAPACITY;
} else if (newcapacity > MAX_CAPACITY) {
newcapacity = requestedCapacity;
if (newcapacity > MAX_CAPACITY) {
throw new AssertionError("can't allocate array bigger than " + MAX_CAPACITY);
}
}
A newArray = allocate(newcapacity);
System.arraycopy(this.array, 0, newArray, 0, this.size);
this.capacity = newcapacity;
this.array = newArray;
}
/**
* Allocate and return an array of the given size
*/
protected abstract A allocate(int size);
/**
* The size of the given array
*/
protected abstract int size(A array);
/**
* Returns an array of exactly the right size to contain all the
* appended elements.
*/
A build() {
if (this.capacity == this.size) {
return array;
}
A result = allocate(this.size);
System.arraycopy(this.array, 0, result, 0, this.size);
return result;
}
}
/**
* An array builder whose result is an {@code Object[]}.
* @see ReflectingObjectArrayBuilder
*/
static final class ObjectArrayBuilder extends ArrayBuilder<Object[]> {
ObjectArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected Object[] allocate(int size) {
return new Object[size];
}
@Override
protected int size(Object[] array) {
return array.length;
}
void appendRef(Object t) {
ensure(size+1);
array[size] = t;
size++;
}
}
/**
* An array builder whose result is an array of a given component type, that is, {@code T[]}.
* The intermediate arrays are {@code Object[]}.
* @see ObjectArrayBuilder
*/
public static final class ReflectingObjectArrayBuilder<T> extends ArrayBuilder<T[]> {
private final java.lang.Class<T> klass;
public ReflectingObjectArrayBuilder(int initialSize, java.lang.Class<T> klass) {
super(initialSize);
this.klass = klass;
}
@SuppressWarnings("unchecked")
@Override
protected T[] allocate(int size) {
return (T[])new Object[size];
}
@Override
protected int size(T[] array) {
return array.length;
}
public void appendRef(T t) {
ensure(size+1);
array[size] = t;
size++;
}
public T[] build() {
T[] result = (T[])java.lang.reflect.Array.newInstance(klass, this.size);
System.arraycopy(this.array, 0, result, 0, this.size);
return result;
}
}
/**
* An array builder whose result is a {@code int[]}.
*/
static final class IntArrayBuilder extends ArrayBuilder<int[]> {
IntArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected int[] allocate(int size) {
return new int[size];
}
@Override
protected int size(int[] array) {
return array.length;
}
void appendInt(int i) {
ensure(size+1);
array[size] = i;
size++;
}
void appendLong(long i) {
appendInt((int)i);
}
}
/**
* An array builder whose result is a {@code long[]}.
*/
static final class LongArrayBuilder extends ArrayBuilder<long[]> {
LongArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected long[] allocate(int size) {
return new long[size];
}
@Override
protected int size(long[] array) {
return array.length;
}
void appendLong(long i) {
ensure(size+1);
array[size] = i;
size++;
}
}
/**
* An array builder whose result is a {@ocde boolean[]}.
*/
static final class BooleanArrayBuilder extends ArrayBuilder<boolean[]> {
BooleanArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected boolean[] allocate(int size) {
return new boolean[size];
}
@Override
protected int size(boolean[] array) {
return array.length;
}
void appendBoolean(boolean b) {
ensure(size+1);
array[size] = b;
size++;
}
}
/**
* An array builder whose result is a {@code byte[]}.
*/
static final class ByteArrayBuilder extends ArrayBuilder<byte[]> {
ByteArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected byte[] allocate(int size) {
return new byte[size];
}
@Override
protected int size(byte[] array) {
return array.length;
}
void appendByte(byte b) {
ensure(size+1);
array[size] = b;
size++;
}
void appendLong(long b) {
appendByte((byte)b);
}
}
/**
* An array builder whose result is a {@code short[]}.
*/
static final class ShortArrayBuilder extends ArrayBuilder<short[]> {
ShortArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected short[] allocate(int size) {
return new short[size];
}
@Override
protected int size(short[] array) {
return array.length;
}
void appendShort(short b) {
ensure(size+1);
array[size] = b;
size++;
}
void appendLong(long b) {
appendShort((short)b);
}
}
/**
* An array builder whose result is a {@code double[]}.
*/
static final class DoubleArrayBuilder extends ArrayBuilder<double[]> {
DoubleArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected double[] allocate(int size) {
return new double[size];
}
@Override
protected int size(double[] array) {
return array.length;
}
void appendDouble(double i) {
ensure(size+1);
array[size] = i;
size++;
}
}
/**
* An array builder whose result is a {@code float[]}.
*/
static final class FloatArrayBuilder extends ArrayBuilder<float[]> {
FloatArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected float[] allocate(int size) {
return new float[size];
}
@Override
protected int size(float[] array) {
return array.length;
}
void appendFloat(float i) {
ensure(size+1);
array[size] = i;
size++;
}
void appendDouble(double d) {
appendFloat((float)d);
}
}
/**
* An array builder whose result is a {@code char[]}.
*/
static final class CharArrayBuilder extends ArrayBuilder<char[]> {
CharArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected char[] allocate(int size) {
return new char[size];
}
@Override
protected int size(char[] array) {
return array.length;
}
void appendChar(char b) {
ensure(size+1);
array[size] = b;
size++;
}
void appendCodepoint(int codepoint) {
if (Character.charCount(codepoint) == 1) {
appendChar((char)codepoint);
} else {
appendChar(Character.highSurrogate(codepoint));
appendChar(Character.lowSurrogate(codepoint));
}
}
}
/**
* An array builder whose result is a {@code java.lang.String[]}.
*/
static final class StringArrayBuilder extends ArrayBuilder<java.lang.String[]> {
StringArrayBuilder(int initialSize) {
super(initialSize);
}
@Override
protected java.lang.String[] allocate(int size) {
return new java.lang.String[size];
}
@Override
protected int size(java.lang.String[] array) {
return array.length;
}
void appendString(java.lang.String b) {
ensure(size+1);
array[size] = b;
size++;
}
void appendCeylonString(ceylon.language.String javaString) {
appendString(javaString.value);
}
}
@SuppressWarnings("unchecked")
public static boolean[]
toBooleanArray(ceylon.language.Iterable<? extends ceylon.language.Boolean, ?> sequence,
boolean... initialElements){
if(sequence instanceof ceylon.language.List)
return toBooleanArray((ceylon.language.List<? extends ceylon.language.Boolean>)sequence,
initialElements);
BooleanArrayBuilder builder = new BooleanArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
builder.appendArray(initialElements);
Iterator<? extends ceylon.language.Boolean> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendBoolean(((ceylon.language.Boolean)o).booleanValue());
}
return builder.build();
}
public static boolean[]
toBooleanArray(ceylon.language.List<? extends ceylon.language.Boolean> list,
boolean... initialElements){
if(list == null)
return initialElements;
int i=initialElements.length;
boolean[] ret = new boolean[(int) list.getSize() + i];
System.arraycopy(initialElements, 0, ret, 0, i);
Iterator<? extends ceylon.language.Boolean> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = ((ceylon.language.Boolean)o).booleanValue();
}
return ret;
}
@SuppressWarnings("unchecked")
public static byte[]
toByteArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toByteArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence,
initialElements);
ByteArrayBuilder builder = new ByteArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
int i=0;
for(;i<initialElements.length;i++){
builder.appendLong(initialElements[i]);
}
Iterator<? extends ceylon.language.Integer> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendLong(((ceylon.language.Integer)o).longValue());
}
return builder.build();
}
public static byte[]
toByteArray(ceylon.language.List<? extends ceylon.language.Integer> list,
long... initialElements){
byte[] ret = new byte[(list == null ? 0 : (int) list.getSize()) + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (byte) initialElements[i];
}
if(list != null){
Iterator<? extends ceylon.language.Integer> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = (byte)((ceylon.language.Integer)o).longValue();
}
}
return ret;
}
@SuppressWarnings("unchecked")
public static short[]
toShortArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toShortArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence,
initialElements);
ShortArrayBuilder builder = new ShortArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
int i=0;
for(;i<initialElements.length;i++){
builder.appendLong(initialElements[i]);
}
Iterator<? extends ceylon.language.Integer> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendLong(((ceylon.language.Integer)o).longValue());
}
return builder.build();
}
public static short[]
toShortArray(ceylon.language.List<? extends ceylon.language.Integer> list,
long... initialElements){
short[] ret = new short[(list == null ? 0 : (int) list.getSize()) + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (short) initialElements[i];
}
if(list != null){
Iterator<? extends ceylon.language.Integer> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = (short)((ceylon.language.Integer)o).longValue();
}
}
return ret;
}
@SuppressWarnings("unchecked")
public static int[]
toIntArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toIntArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence,
initialElements);
IntArrayBuilder builder = new IntArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
int i=0;
for(;i<initialElements.length;i++){
builder.appendLong(initialElements[i]);
}
Iterator<? extends ceylon.language.Integer> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendLong(((ceylon.language.Integer)o).longValue());
}
return builder.build();
}
public static int[]
toIntArray(ceylon.language.List<? extends ceylon.language.Integer> list,
long... initialElements){
int[] ret = new int[(list == null ? 0 : (int) list.getSize()) + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (int) initialElements[i];
}
if(list != null){
Iterator<? extends ceylon.language.Integer> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = (int)((ceylon.language.Integer)o).longValue();
}
}
return ret;
}
@SuppressWarnings("unchecked")
public static long[]
toLongArray(ceylon.language.Iterable<? extends ceylon.language.Integer, ?> sequence,
long... initialElements){
if(sequence instanceof ceylon.language.List)
return toLongArray((ceylon.language.List<? extends ceylon.language.Integer>)sequence,
initialElements);
LongArrayBuilder builder = new LongArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
builder.appendArray(initialElements);
Iterator<? extends ceylon.language.Integer> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendLong(((ceylon.language.Integer)o).longValue());
}
return builder.build();
}
public static long[]
toLongArray(ceylon.language.List<? extends ceylon.language.Integer> list,
long... initialElements){
if(list == null)
return initialElements;
int i=initialElements.length;
long[] ret = new long[(int) list.getSize() + i];
System.arraycopy(initialElements, 0, ret, 0, i);
Iterator<? extends ceylon.language.Integer> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = ((ceylon.language.Integer)o).longValue();
}
return ret;
}
@SuppressWarnings("unchecked")
public static float[]
toFloatArray(ceylon.language.Iterable<? extends ceylon.language.Float, ?> sequence,
double... initialElements){
if(sequence instanceof ceylon.language.List)
return toFloatArray((ceylon.language.List<? extends ceylon.language.Float>)sequence,
initialElements);
FloatArrayBuilder builder = new FloatArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
int i=0;
for(;i<initialElements.length;i++){
builder.appendDouble(initialElements[i]);
}
Iterator<? extends ceylon.language.Float> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendDouble(((ceylon.language.Float)o).doubleValue());
}
return builder.build();
}
public static float[]
toFloatArray(ceylon.language.List<? extends ceylon.language.Float> list,
double... initialElements){
float[] ret = new float[(list == null ? 0 : (int) list.getSize()) + initialElements.length];
int i=0;
for(;i<initialElements.length;i++){
ret[i] = (float) initialElements[i];
}
if(list != null){
Iterator<? extends ceylon.language.Float> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = (float)((ceylon.language.Float)o).doubleValue();
}
}
return ret;
}
@SuppressWarnings("unchecked")
public static double[]
toDoubleArray(ceylon.language.Iterable<? extends ceylon.language.Float, ?> sequence,
double... initialElements){
if(sequence instanceof ceylon.language.List)
return toDoubleArray((ceylon.language.List<? extends ceylon.language.Float>)sequence,
initialElements);
DoubleArrayBuilder builder = new DoubleArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
builder.appendArray(initialElements);
Iterator<? extends ceylon.language.Float> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendDouble(((ceylon.language.Float)o).doubleValue());
}
return builder.build();
}
public static double[]
toDoubleArray(ceylon.language.List<? extends ceylon.language.Float> list,
double... initialElements){
if(list == null)
return initialElements;
int i=initialElements.length;
double[] ret = new double[(int) list.getSize() + i];
System.arraycopy(initialElements, 0, ret, 0, i);
Iterator<? extends ceylon.language.Float> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = ((ceylon.language.Float)o).doubleValue();
}
return ret;
}
public static char[]
toCharArray(ceylon.language.Iterable<? extends ceylon.language.Character, ?> sequence,
int... initialElements){
// Note the List optimization doesn't work because the number of codepoints in the sequence
// doesn't equal the size of the result array.
CharArrayBuilder builder = new CharArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
int i=0;
for(;i<initialElements.length;i++){
builder.appendCodepoint((char) initialElements[i]);
}
Iterator<? extends ceylon.language.Character> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendCodepoint(((ceylon.language.Character)o).codePoint);
}
return builder.build();
}
public static char[]
toCharArray(ceylon.language.List<? extends ceylon.language.Character> sequence,
int... initialElements){
return toCharArray((ceylon.language.Iterable<? extends ceylon.language.Character, ?>)sequence, initialElements);
}
@SuppressWarnings("unchecked")
public static int[]
toCodepointArray(ceylon.language.Iterable<? extends ceylon.language.Character, ?> sequence,
int... initialElements){
if(sequence instanceof ceylon.language.List)
return toCodepointArray((ceylon.language.List<? extends ceylon.language.Character>)sequence,
initialElements);
IntArrayBuilder builder = new IntArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
builder.appendArray(initialElements);
Iterator<? extends ceylon.language.Character> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendInt(((ceylon.language.Character)o).codePoint);
}
return builder.build();
}
public static int[]
toCodepointArray(ceylon.language.List<? extends ceylon.language.Character> list,
int... initialElements){
if(list == null)
return initialElements;
int i=initialElements.length;
int[] ret = new int[(int) list.getSize() + i];
System.arraycopy(initialElements, 0, ret, 0, i);
Iterator<? extends ceylon.language.Character> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = ((ceylon.language.Character)o).intValue();
}
return ret;
}
@SuppressWarnings("unchecked")
public static java.lang.String[]
toJavaStringArray(ceylon.language.Iterable<? extends ceylon.language.String, ?> sequence,
java.lang.String... initialElements){
if(sequence instanceof ceylon.language.List)
return toJavaStringArray((ceylon.language.List<? extends ceylon.language.String>)sequence,
initialElements);
StringArrayBuilder builder = new StringArrayBuilder(initialElements.length+INIT_ARRAY_SIZE);
builder.appendArray(initialElements);
Iterator<? extends ceylon.language.String> iterator = sequence.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendString(((ceylon.language.String)o).value);
}
return builder.build();
}
public static java.lang.String[]
toJavaStringArray(ceylon.language.List<? extends ceylon.language.String> list,
java.lang.String... initialElements){
if(list == null)
return initialElements;
int i=initialElements.length;
java.lang.String[] ret = new java.lang.String[(int) list.getSize() + i];
System.arraycopy(initialElements, 0, ret, 0, i);
Iterator<? extends ceylon.language.String> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = ((ceylon.language.String)o).toString();
}
return ret;
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(ceylon.language.List<? extends T> sequence,
T[] ret, T... initialElements){
if(sequence == null)
return initialElements;
int i=initialElements.length;
System.arraycopy(initialElements, 0, ret, 0, i);
Iterator<? extends T> iterator = sequence.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = (T)o;
}
return ret;
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(ceylon.language.Iterable<? extends T, ?> iterable,
java.lang.Class<T> klass, T... initialElements){
if (iterable == null) {
return initialElements;
}
T[] ret;
int size = fastIterableSize(iterable);
if (size != -1) {
ret = (T[]) java.lang.reflect.Array.newInstance(klass,
size + initialElements.length);
if(initialElements.length != 0){
// fast copy of list
System.arraycopy(initialElements, 0, ret, 0, initialElements.length);
}
fillArray(ret, initialElements.length, iterable);
} else {
ReflectingObjectArrayBuilder<T> builder = new ReflectingObjectArrayBuilder<T>(initialElements.length+INIT_ARRAY_SIZE, klass);
builder.appendArray(initialElements);
Iterator<? extends T> iterator = iterable.iterator();
Object o;
while (!((o = iterator.next()) instanceof Finished)) {
builder.appendRef((T)o);
}
ret = builder.build();
}
return ret;
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(ceylon.language.List<? extends T> list,
java.lang.Class<T> klass, T... initialElements){
if(list == null)
return initialElements;
int i=initialElements.length;
T[] ret = (T[]) java.lang.reflect.Array.newInstance(klass,
(int)list.getSize() + i);
System.arraycopy(initialElements, 0, ret, 0, i);
Iterator<? extends T> iterator = list.iterator();
Object o;
while((o = iterator.next()) != finished_.get_()){
ret[i++] = (T)o;
}
return ret;
}
public static <T> T checkNull(T t) {
if(t == null)
throw new AssertionError("null value returned from native call not assignable to Object");
return t;
}
/**
* Return {@link empty_#getEmpty$ empty} or an {@link ArraySequence}
* wrapping the given elements, depending on whether the given array is
* empty
* @param elements The elements
* @return A Sequential
*/
@SuppressWarnings({"unchecked","rawtypes"})
public static <T> Sequential<T>
sequentialInstance(TypeDescriptor $reifiedT, T[] elements) {
if (elements.length == 0) {
return (Sequential)empty_.get_();
}
// Annoyingly this implies an extra copy
return ArraySequence.<T>instance($reifiedT, elements);
}
/**
* Return {@link empty_#getEmpty$ empty} or an {@link ArraySequence}
* wrapping the given elements, depending on whether the given array is
* empty, but only considering the given number of elements
* @param elements The elements
* @return A Sequential
*/
@SuppressWarnings({"unchecked","rawtypes"})
public static <T> Sequential<T>
sequentialInstance(TypeDescriptor $reifiedT, T[] elements, int length) {
if (length == 0) {
return (Sequential)empty_.get_();
}
// Annoyingly this implies an extra copy
return ArraySequence.<T>instance($reifiedT, elements, length);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.String>
sequentialInstanceBoxed(java.lang.String[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(java.lang.String element : elements){
newArray[i++] = ceylon.language.String.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.String.$TypeDescriptor$,
newArray);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.Integer>
sequentialInstanceBoxed(long[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(long element : elements){
newArray[i++] = ceylon.language.Integer.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Integer.$TypeDescriptor$,
newArray);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.Character>
sequentialInstanceBoxed(int[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(int element : elements){
newArray[i++] = ceylon.language.Character.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Character.$TypeDescriptor$,
newArray);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.Boolean>
sequentialInstanceBoxed(boolean[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(boolean element : elements){
newArray[i++] = ceylon.language.Boolean.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Boolean.$TypeDescriptor$,
newArray);
}
@SuppressWarnings({"unchecked","rawtypes"})
public static Sequential<? extends ceylon.language.Float>
sequentialInstanceBoxed(double[] elements) {
if (elements.length == 0){
return (Sequential)empty_.get_();
}
int total = elements.length;
java.lang.Object[] newArray = new java.lang.Object[total];
int i = 0;
for(double element : elements){
newArray[i++] = ceylon.language.Float.instance(element);
}
// TODO Annoyingly this results in an extra copy
return ArraySequence.instance(ceylon.language.Float.$TypeDescriptor$,
newArray);
}
/**
* Return {@link empty_#getEmpty$ empty} or an {@link ArraySequence}
* wrapping the given elements, depending on whether the given array
* and varargs are empty
* @param rest The elements at the end of the sequence
* @param elements the elements at the start of the sequence
* @return A Sequential
*/
@SuppressWarnings({"unchecked"})
public static <T> Sequential<? extends T>
sequentialInstance(TypeDescriptor $reifiedT, Sequential<? extends T> rest,
T... elements) {
return sequentialInstance($reifiedT, 0,
elements.length, elements, true, rest);
}
/**
* Returns a Sequential made by concatenating the {@code length} elements
* of {@code elements} starting from {@code state} with the elements of
* {@code rest}: <code> {*elements[start:length], *rest}</code>.
*
* <strong>This method does not copy {@code elements} unless it has to</strong>
*/
@SuppressWarnings("unchecked")
public static <T> Sequential<? extends T> sequentialInstance(
TypeDescriptor $reifiedT,
int start, int length, T[] elements, boolean copy,
Sequential<? extends T> rest) {
if (length == 0){
if(rest.getEmpty()) {
return (Sequential<T>)empty_.get_();
}
return rest;
}
// elements is not empty
if(rest.getEmpty()) {
return new ArraySequence<T>($reifiedT, elements,
start, length, copy);
}
// we have both, let's find the total size
int total = (int) (rest.getSize() + length);
java.lang.Object[] newArray = new java.lang.Object[total];
System.arraycopy(elements, start, newArray, 0, length);
Iterator<? extends T> iterator = rest.iterator();
int i = length;
for(Object elem; (elem = iterator.next()) != finished_.get_(); i++){
newArray[i] = elem;
}
return ArraySequence.<T>instance($reifiedT, newArray);
}
/**
* Method for instantiating a Range (or Empty) from a Tree.SpreadOp,
* {@code start:length}.
* @param start The start
* @param length The size of the Range to create
* @return A range
*/
@SuppressWarnings({"unchecked","rawtypes"})
public static <T extends ceylon.language.Ordinal<? extends T>> Sequential<T>
spreadOp(TypeDescriptor $reifiedT, T start, long length) {
if (length <= 0) {
return (Sequential)empty_.get_();
}
if (start instanceof ceylon.language.Integer) {
ceylon.language.Integer startInt = (ceylon.language.Integer)start;
return new ceylon.language.Range($reifiedT, startInt,
ceylon.language.Integer.instance(startInt.longValue() + (length - 1)));
} else if (start instanceof ceylon.language.Character) {
ceylon.language.Character startChar = (ceylon.language.Character)start;
return new ceylon.language.Range($reifiedT, startChar,
ceylon.language.Character.instance((int)(startChar.intValue() + length - 1)));
} else {
T end = start;
long ii = 0L;
while (++ii < length) {
end = end.getSuccessor();
}
return new ceylon.language.Range($reifiedT, start, end);
}
}
/**
* Converts an Iterable to a Sequential without calling
* Iterable.getSequence(). This is used for spread arguments in
* tuple literals: {@code [*foo]}
* a
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Sequential sequentialInstance(Iterable iterable) {
if (iterable instanceof Sequential) {
// since it's immutable
return (Sequential)iterable;
}
Iterator iterator = iterable.iterator();
Object e = iterator.next();
if (e instanceof Finished) {
return empty_.get_();
} else {
SequenceBuilder sb = new SequenceBuilder(Metamodel.getTypeDescriptor(iterable));
sb.append(e);
e = iterator.next();
while (!(e instanceof Finished)) {
sb.append(e);
e = iterator.next();
}
return sb.getSequence();
}
}
/**
* Returns a runtime exception. To be used by implementors
* of mixin methods used to access super-interfaces $impl fields
* for final classes that don't and will never need them
*/
public static RuntimeException makeUnimplementedMixinAccessException() {
return new RuntimeException("Internal error: should never be called");
}
/**
* Specialised version of Tuple.spanFrom for when the
* typechecker determines that it can do better than the
* generic one that returns a Sequential. Here we return
* a Tuple, although our type signature hides this.
*/
public static Sequential<?> tuple_spanFrom(Ranged tuple,
ceylon.language.Integer index){
Sequential<?> seq = (Sequential<?>)tuple;
long i = index.longValue();
while(i
seq = seq.getRest();
}
return seq;
}
public static boolean[] fillArray(boolean[] array, boolean val){
Arrays.fill(array, val);
return array;
}
public static byte[] fillArray(byte[] array, byte val){
Arrays.fill(array, val);
return array;
}
public static short[] fillArray(short[] array, short val){
Arrays.fill(array, val);
return array;
}
public static int[] fillArray(int[] array, int val){
Arrays.fill(array, val);
return array;
}
public static long[] fillArray(long[] array, long val){
Arrays.fill(array, val);
return array;
}
public static float[] fillArray(float[] array, float val){
Arrays.fill(array, val);
return array;
}
public static double[] fillArray(double[] array, double val){
Arrays.fill(array, val);
return array;
}
public static char[] fillArray(char[] array, char val){
Arrays.fill(array, val);
return array;
}
public static <T> T[] fillArray(T[] array, T val){
Arrays.fill(array, val);
return array;
}
@SuppressWarnings("unchecked")
public static <T> T[] makeArray(TypeDescriptor $reifiedElement, int size){
return (T[]) java.lang.reflect.Array.newInstance($reifiedElement.getArrayElementClass(), size);
}
@SuppressWarnings("unchecked")
public static <T> T[] makeArray(TypeDescriptor $reifiedElement, int... dimensions){
return (T[]) java.lang.reflect.Array.newInstance($reifiedElement.getArrayElementClass(), dimensions);
}
/**
* Returns a runtime exception. To be used by implementors
* of Java array methods used to make sure they are never
* called
*/
public static RuntimeException makeJavaArrayWrapperException() {
return new RuntimeException("Internal error: should never be called");
}
/**
* Throws an exception without having to declare it. This
* uses a Ceylon helper that does this because Ceylon does
* not have checked exceptions. This is merely to avoid a
* javac check wrt. checked exceptions.
* Stef tried using Unsafe.throwException() but
* Unsafe.getUnsafe() throws if we have a ClassLoader, and
* the only other way is using reflection to get to it,
* which starts to smell real bad when we can just use a
* Ceylon helper.
*/
public static void rethrow(final Throwable t){
ceylon.language.impl.rethrow_.rethrow(t);
}
/**
* Null-safe equals.
*/
public static boolean eq(Object a, Object b) {
if(a == null)
return b == null;
if(b == null)
return false;
return a.equals(b);
}
/**
* Applies the given function to the given arguments. The
* argument types are assumed to be correct and will not
* be checked. This method will properly deal with variadic
* functions. The arguments are expected to be spread in the
* given sequential, even in the case of variadic functions,
* which means that there will be no spreading of any
* Sequential instance in the given arguments. On the
* contrary, a portion of the given arguments may be packaged
* into a Sequential if the given function is variadic.
*
* @param function the function to apply
* @param arguments the argument values to pass to the function
* @return the function's return value
*/
public static <Return> Return
apply(Callable<? extends Return> function,
Sequential<? extends Object> arguments){
int variadicParameterIndex = function.$getVariadicParameterIndex$();
switch ((int) arguments.getSize()) {
case 0:
// even if the function is variadic it will overload $call so we're good
return function.$call$();
case 1:
// if the first param is variadic, just pass the sequence along
if(variadicParameterIndex == 0)
return function.$callvariadic$(arguments);
return function.$call$(arguments.get(Integer.instance(0)));
case 2:
switch(variadicParameterIndex){
// pass the sequence along
case 0: return function.$callvariadic$(arguments);
// extract the first, pass the rest
case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)),
(Sequential<?>)arguments.spanFrom(Integer.instance(1)));
// no variadic param, or after we run out of elements to pass
default:
return function.$call$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)));
}
case 3:
switch(variadicParameterIndex){
// pass the sequence along
case 0: return function.$callvariadic$(arguments);
// extract the first, pass the rest
case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)),
(Sequential<?>)arguments.spanFrom(Integer.instance(1)));
// extract the first and second, pass the rest
case 2: return function.$callvariadic$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
(Sequential<?>)arguments.spanFrom(Integer.instance(2)));
// no variadic param, or after we run out of elements to pass
default:
return function.$call$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
arguments.get(Integer.instance(2)));
}
default:
switch(variadicParameterIndex){
// pass the sequence along
case 0: return function.$callvariadic$(arguments);
// extract the first, pass the rest
case 1: return function.$callvariadic$(arguments.get(Integer.instance(0)),
(Sequential<?>)arguments.spanFrom(Integer.instance(1)));
// extract the first and second, pass the rest
case 2: return function.$callvariadic$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
(Sequential<?>)arguments.spanFrom(Integer.instance(2)));
case 3: return function.$callvariadic$(arguments.get(Integer.instance(0)),
arguments.get(Integer.instance(1)),
arguments.get(Integer.instance(2)),
(Sequential<?>)arguments.spanFrom(Integer.instance(3)));
// no variadic param
case -1:
java.lang.Object[] args = Util.toArray(arguments,
new java.lang.Object[(int) arguments.getSize()]);
return function.$call$(args);
// we have a variadic param in there bothering us
default:
// we stuff everything before the variadic into an array
int beforeVariadic = (int)Math.min(arguments.getSize(),
variadicParameterIndex);
boolean needsVariadic = beforeVariadic < arguments.getSize();
args = new java.lang.Object[beforeVariadic + (needsVariadic ? 1 : 0)];
Iterator<?> iterator = arguments.iterator();
java.lang.Object it;
int i=0;
while(i < beforeVariadic &&
(it = iterator.next()) != finished_.get_()){
args[i++] = it;
}
// add the remainder as a variadic arg if required
if(needsVariadic){
args[i] = arguments.spanFrom(Integer.instance(beforeVariadic));
return function.$callvariadic$(args);
}
return function.$call$(args);
}
}
}
@SuppressWarnings("unchecked")
public static <T> java.lang.Class<T>
getJavaClassForDescriptor(TypeDescriptor descriptor) {
if(descriptor == TypeDescriptor.NothingType
|| descriptor == ceylon.language.Object.$TypeDescriptor$
|| descriptor == ceylon.language.Anything.$TypeDescriptor$
|| descriptor == ceylon.language.Basic.$TypeDescriptor$
|| descriptor == ceylon.language.Null.$TypeDescriptor$
|| descriptor == ceylon.language.Identifiable.$TypeDescriptor$)
return (java.lang.Class<T>) Object.class;
if(descriptor instanceof TypeDescriptor.Class)
return (java.lang.Class<T>) ((TypeDescriptor.Class) descriptor).getKlass();
if(descriptor instanceof TypeDescriptor.Member)
return getJavaClassForDescriptor(((TypeDescriptor.Member) descriptor).getMember());
if(descriptor instanceof TypeDescriptor.Intersection)
return (java.lang.Class<T>) Object.class;
if(descriptor instanceof TypeDescriptor.Union){
TypeDescriptor.Union union = (TypeDescriptor.Union) descriptor;
TypeDescriptor[] members = union.getMembers();
// special case for optional types
if(members.length == 2){
if(members[0] == ceylon.language.Null.$TypeDescriptor$)
return getJavaClassForDescriptor(members[1]);
if(members[1] == ceylon.language.Null.$TypeDescriptor$)
return getJavaClassForDescriptor(members[0]);
}
return (java.lang.Class<T>) Object.class;
}
return (java.lang.Class<T>) Object.class;
}
public static int arrayLength(Object o) {
if (o instanceof Object[])
return ((Object[])o).length;
else if (o instanceof boolean[])
return ((boolean[])o).length;
else if (o instanceof float[])
return ((float[])o).length;
else if (o instanceof double[])
return ((double[])o).length;
else if (o instanceof char[])
return ((char[])o).length;
else if (o instanceof byte[])
return ((byte[])o).length;
else if (o instanceof short[])
return ((short[])o).length;
else if (o instanceof int[])
return ((int[])o).length;
else if (o instanceof long[])
return ((long[])o).length;
throw new ClassCastException(notArrayType(o));
}
/**
* Used by the JVM backend to get unboxed items from an Array<Integer> backing array
*/
public static long getIntegerArray(Object o, int index) {
if (o instanceof byte[])
return ((byte[])o)[index];
else if (o instanceof short[])
return ((short[])o)[index];
else if (o instanceof int[])
return ((int[])o)[index];
else if (o instanceof long[])
return ((long[])o)[index];
throw new ClassCastException(notArrayType(o));
}
/**
* Used by the JVM backend to get unboxed items from an Array<Float> backing array
*/
public static double getFloatArray(Object o, int index) {
if (o instanceof float[])
return ((float[])o)[index];
else if (o instanceof double[])
return ((double[])o)[index];
throw new ClassCastException(notArrayType(o));
}
/**
* Used by the JVM backend to get unboxed items from an Array<Character> backing array
*/
public static int getCharacterArray(Object o, int index) {
if (o instanceof int[])
return ((int[])o)[index];
throw new ClassCastException(notArrayType(o));
}
/**
* Used by the JVM backend to get unboxed items from an Array<Boolean> backing array
*/
public static boolean getBooleanArray(Object o, int index) {
if (o instanceof boolean[])
return ((boolean[])o)[index];
throw new ClassCastException(notArrayType(o));
}
/**
* Used by the JVM backend to get items from an ArraySequence object. Beware: do not use that
* for Array<Object> as there's too much magic in there.
*/
public static Object getObjectArray(Object o, int index) {
if (o instanceof Object[])
return ((Object[])o)[index];
else if (o instanceof boolean[])
return ceylon.language.Boolean.instance(((boolean[])o)[index]);
else if (o instanceof float[])
return ceylon.language.Float.instance(((float[])o)[index]);
else if (o instanceof double[])
return ceylon.language.Float.instance(((double[])o)[index]);
else if (o instanceof char[])
return ceylon.language.Character.instance(((char[])o)[index]);
else if (o instanceof byte[])
return ceylon.language.Integer.instance(((byte[])o)[index]);
else if (o instanceof short[])
return ceylon.language.Integer.instance(((short[])o)[index]);
else if (o instanceof int[])
return ceylon.language.Integer.instance(((int[])o)[index]);
else if (o instanceof long[])
return ceylon.language.Integer.instance(((long[])o)[index]);
throw new ClassCastException(notArrayType(o));
}
private static String notArrayType(Object o) {
return (o == null ? "null" : o.getClass().getName()) + " is not an array type";
}
public static ceylon.language.Sequential<? extends java.lang.Throwable> suppressedExceptions(
@Name("exception")
@TypeInfo("ceylon.language::Exception")
final java.lang.Throwable exception) {
java.lang.Throwable[] sup = exception.getSuppressed();
if (sup.length > 0) {
return new ArraySequence(TypeDescriptor.klass(java.lang.Throwable.class), sup, 0, sup.length, false);
} else {
return (ceylon.language.Sequential)empty_.get_();
}
}
public static <T> ceylon.language.Sequence<T> asSequence(ceylon.language.Sequential<T> sequential) {
if (sequential instanceof ceylon.language.Sequence) {
return (ceylon.language.Sequence)sequential;
} else {
throw new AssertionError("Assertion failed");
}
}
}
|
package main.feedthecreepertweaks.handlers;
import java.util.Formatter;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import main.feedthecreepertweaks.ConfigHandler;
import main.feedthecreepertweaks.FeedTheCreeperTweaks;
import main.feedthecreepertweaks.ModInformation;
import main.feedthecreepertweaks.util.TextHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentText;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
public class DeathPositionHandler
{
private static final String configSection = "DeathPosition";
private boolean alertPlayer = true;
public void preInit(FMLPreInitializationEvent event)
{
alertPlayer = ConfigHandler.config.getBoolean("alertPlayer",configSection, alertPlayer, "Alert Player of position in chat");
ConfigHandler.config.save();
}
public void init(FMLInitializationEvent event)
{
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void playerDeath(LivingDeathEvent event)
{
if(!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayer)
{
String coords = String.format("%d,%d,%d Dimension: %d",
Math.round(event.entity.posX),
Math.round(event.entity.posY),
Math.round(event.entity.posZ),
event.entity.dimension);
String msg = String.format("%s %s %s",
((EntityPlayer)event.entity).getCommandSenderName(),
TextHelper.localize("info." + ModInformation.ID + ".console.load.deathMessageDied"),
coords);
FeedTheCreeperTweaks.logger.info(msg);
if(alertPlayer)
{
msg = TextHelper.localize("info." + ModInformation.ID + ".chat.deathMessage") + " " + coords;
((EntityPlayer)event.entity).addChatComponentMessage(new ChatComponentText(msg));
}
}
}
}
|
package net.minecraftforge.srg2source.rangeapplier;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import net.minecraftforge.srg2source.rangeapplier.RangeMap.RangeEntry;
import net.minecraftforge.srg2source.util.Util;
import net.minecraftforge.srg2source.util.io.ConfLogger;
import net.minecraftforge.srg2source.util.io.FolderSupplier;
import net.minecraftforge.srg2source.util.io.InputSupplier;
import net.minecraftforge.srg2source.util.io.OutputSupplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
public class RangeApplier extends ConfLogger<RangeApplier>
{
@SuppressWarnings({ "unchecked", "resource" })
public static void main(String[] args) throws IOException
{
// configure parser
OptionParser parser = new OptionParser();
{
parser.acceptsAll(Arrays.asList("h", "help")).isForHelp();
parser.accepts("srcRoot", "Source root directory to rename").withRequiredArg().ofType(File.class).isRequired(); // var=srcRoot
parser.accepts("srcRangeMap", "Source range map generated by srg2source").withRequiredArg().ofType(File.class).isRequired(); // var=srcRangeMap
parser.accepts("srgFiles", "Symbol map file(s), separated by ' '").withRequiredArg().ofType(File.class).isRequired(); // var=srgFiles
parser.accepts("git", "Command to invoke git"); // var=git default="git"
parser.accepts("lvRangeMap", "Original source range map generated by srg2source, for renaming local variables"); // var=lvRangeMap) CSV instead?
parser.accepts("mcpConfDir", "MCP configuration directory, for renaming parameters").withRequiredArg().ofType(File.class); // var=mcpConfDir
parser.accepts("excFiles", "Parameter map file(s), separated by ' '").withRequiredArg().ofType(File.class); // var=excFiles
//parser.accepts("no-dumpRenameMap", "Disable dumping symbol rename map before renaming"); // var="dumpRenameMap", default=True
parser.accepts("dumpRangeMap", "Enable dumping the ordered range map and quit"); // var=dumpRangeMap, default=False
parser.accepts("outDir", "The output folder for editted classes.").withRequiredArg().ofType(File.class); // default null
}
OptionSet options = parser.parse(args);
if (options.has("help"))
{
parser.printHelpOn(System.out);
System.exit(0);
}
//boolean dumpRenameMap = !options.has("no-dumpRenameMap");
boolean dumpRangeMap = options.has("dumpRangeMap");
// read range map, spit, and return
if (dumpRangeMap)
{
RangeMap ranges = new RangeMap().read((File) options.valueOf("srcRangeMap"));
for (String key : ranges.keySet())
{
for (RangeEntry info : ranges.get(key))
{
System.out.println(info);
}
}
return;
}
// setup RangeApplier.
RangeApplier app = new RangeApplier().readSrg((List<File>) options.valuesOf("srgFiles"));
// read parameter remaps
if (options.has("mcpConfDir") && options.hasArgument("mcpConfDir"))
{
File conf = (File) options.valueOf("mcpConfDir");
File primary = new File(conf, "joined.exc");
List<File> excs = new LinkedList<File>();
if (!primary.exists())
primary = new File(conf, "packaged.exc");
excs.add(primary);
if (options.has("excFiles") && options.hasArgument("excFiles"))
excs.addAll((List<File>) options.valuesOf("excFiles"));
app.readParamMap(excs);
}
// read local varaible map
if (options.has("lvRangeMap") && options.hasArgument("lvRangeMap"))
{
app.readLvRangeMap((File) options.valueOf("lvRangeMap"));
}
//options.valuesOf("srgFiles");
FolderSupplier srcRoot = new FolderSupplier((File) options.valueOf("srcRoot"));
// output supplier..
OutputSupplier outDir = (OutputSupplier) srcRoot;
if (options.has("outDir"))
outDir = new FolderSupplier((File) options.valueOf("outDir"));
app.remapSources(srcRoot, outDir, (File) options.valueOf("srcRangeMap"), false);
srcRoot.close();
outDir.close();
System.out.println("FINISHED!");
}
private SrgContainer srg = new SrgContainer();
private final RenameMap map = new RenameMap();
// SRG stuff
public RangeApplier readSrg(File srg)
{
this.srg.readSrg(srg);
map.readSrg(this.srg);
return this;
}
public RangeApplier readSrg(Iterable<File> srgs)
{
srg.readSrgs(srgs);
map.readSrg(this.srg);
return this;
}
public RangeApplier readSrg(SrgContainer srgCont)
{
this.srg = srgCont;
map.readSrg(this.srg);
return this;
}
// excptors
public RangeApplier readParamMap(Iterable<File> exceptors)
{
ExceptorFile exc = new ExceptorFile().read(exceptors);
map.readParamMap(srg, exc);
return this;
}
// LV map
public RangeApplier readLvRangeMap(File lvRangeMap)
{
try
{
map.readLocalVariableMap(new LocalVarFile().read(lvRangeMap), srg);
}
catch (IOException e)
{
Throwables.propagate(e);
}
return this;
}
/**
* Outputs the contents of the rename map.
* Spits everything to the outLogger.
*/
public void dumpRenameMap()
{
List<Entry<String, String>> entries = new ArrayList<Entry<String, String>>(map.maps.entrySet());
Collections.sort(entries, new Comparator<Entry<String, String>>()
{
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2)
{
return o1.getKey().compareTo(o2.getKey());
}
});
for (Entry<String, String> e : entries)
{
log("RENAME MAP: " + e.getKey() + " -> " + e.getValue());
}
}
/**
* Actually remaps stuff.
* @param inSupp
* @param outSupp
* @param rangeMap
* @param annotate Marks all renamed symbols with a comment and the old name.
* @throws IOException
*/
public void remapSources(InputSupplier inSupp, OutputSupplier outSupp, File rangeMap, boolean annotate) throws IOException
{
RangeMap range = new RangeMap().read(rangeMap);
List<String> paths = new ArrayList<String>(range.keySet());
Collections.sort(paths);
for (String filePath : paths)
{
log("Start Processing: " + filePath);
InputStream stream = inSupp.getInput(filePath);
//no stream? what?
if (stream == null)
{
// yeah.. nope.
log("Data not found: " + filePath);
continue;
}
String data = new String(ByteStreams.toByteArray(stream), Charset.forName("UTF-8"));
stream.close();
if (data.contains("\r"))
{
// to ensure that the offsets are not off by 1.
log("Warning: " + filePath + " has CRLF line endings; consider switching to LF");
data = data.replace("\r", "");
}
// process
List<String> out = processJavaSourceFile(filePath, data, range.get(filePath), annotate);
filePath = out.get(0);
data = out.get(1);
// write.
OutputStream outStream = outSupp.getOutput(filePath);
outStream.write(data.getBytes(Charset.forName("UTF-8")));
outStream.close();
log("End Processing: " + filePath);
log("");
}
}
/**
* Rename symbols in source code
* @return
* @throws IOException
*/
private ImmutableList<String> processJavaSourceFile(String fileName, String data, Collection<RangeEntry> rangeList, boolean shouldAnnotate) throws IOException
{
StringBuilder outData = new StringBuilder();
outData.append(data);
Set<String> importsToAdd = new TreeSet<String>();
int shift = 0;
// Existing package/class name (with package, internal) derived from filename
String oldTopLevelClassFullName = Util.getTopLevelClassForFilename(fileName);
String oldTopLevelClassPackage = Util.splitPackageName(oldTopLevelClassFullName);
String oldTopLevelClassName = Util.splitBaseName(oldTopLevelClassFullName);
// New package/class name through mapping
String newTopLevelClassPackage = Util.sourceName2Internal(map.maps.get("package " + oldTopLevelClassPackage));
String newTopLevelClassName = map.maps.get("class " + oldTopLevelClassFullName);
if (newTopLevelClassPackage != null && newTopLevelClassName == null)
throw new RuntimeException("filename " + fileName + " found package " + oldTopLevelClassPackage + "->" + newTopLevelClassPackage + " but no class map for " + newTopLevelClassName);
if (newTopLevelClassPackage == null && newTopLevelClassName != null)
throw new RuntimeException("filename " + fileName + " found class map " + oldTopLevelClassName + "->" + newTopLevelClassName + " but no package map for " + oldTopLevelClassPackage);
// start,end,expectedOldText,key
for (RangeEntry info : rangeList)
{
int end = info.end;
String expectedOldText = info.expectedOldText;
if (map.maps.containsKey(info.key) && map.maps.get(info.key).isEmpty()) // has an empty key.
{
// Replacing a symbol with no text = removing a symbol
if (!info.key.startsWith("package "))
throw new RuntimeException("unable to remove non-package symbol " + info.key);
// Remove that pesky extra period after qualified package names
end++;
expectedOldText += ".";
}
String oldName = outData.substring(info.start + shift, end + shift);
if (!oldName.equals(expectedOldText))
throw new RuntimeException("Rename sanity check failed: expected '" + expectedOldText + "' at [" + info.start + "," + end + "] (shifted " + shift + " to [" + (shift + info.start) + "," + (shift + end) + "]) in " + fileName + ", but found '" + oldName + "'\nRegenerate symbol map on latest sources or start with fresh source and try again");
String newName = getNewName(info.key, oldName, map.maps, shouldAnnotate);
if (newName == null)
{
if (info.key.split(" ")[1].contains("net/minecraft"))
log("No rename for " + info.key);
continue;
}
log("Rename " + info.key + "[" + (info.start + shift) + "," + (end + shift) + "]" + "::" + oldName + "->" + newName);
// do importing.
String key = info.key;
if (newName.indexOf('.') > 0) // contains a .
{
// split as many times as its qualified.
for (int i = 0; i < Util.countChar(newName, '.'); i++)
key = Util.splitPackageName(key);
}
if (map.imports.containsKey(key))
{
// This rename requires adding an import, if it crosses packages
String importPackage = Util.splitPackageName(Util.sourceName2Internal(map.imports.get(info.key)));
if (!importPackage.equals(newTopLevelClassPackage))
importsToAdd.add(map.imports.get(key));
}
// Rename algorithm:
// 1. textually replace text at specified range with new text
// 2. shift future ranges by difference in text length
//data = data.substring(0, info.start + shift) + newName + data.substring(end + shift);
outData.replace(info.start + shift, end + shift, newName);
shift += (newName.length() - oldName.length());
}
// Lastly, update imports - this == separate from symbol range manipulation above
String outString = updateImports(outData, importsToAdd, map.imports);
// rename?
if (newTopLevelClassPackage != null) // rename if package changed
{
String newFileName = (newTopLevelClassPackage + "/" + newTopLevelClassName + ".java").replace('\\', '/');
log("Rename file " + fileName + " -> " + newFileName);
fileName = newFileName;
}
return ImmutableList.of(fileName, outString);
}
/**
* Add new import statements to source
*/
private String updateImports(StringBuilder data, Set<String> newImports, Map<String, String> importMap)
{
//String[] lines = data.split("\n");
int lastIndex = 0;
int nextIndex = data.indexOf("\n");
// Parse the existing imports and find out where to add ours
// This doesn't use Psi.. but the syntax is easy enough to parse here
boolean addedNewImports = false;
boolean sawImports = false;
String line;
while (nextIndex > -1)
{
line = data.substring(lastIndex, nextIndex);
while (line.startsWith("\n"))
{
lastIndex++;
line = data.substring(lastIndex, nextIndex);
}
if (line.startsWith("import "))
{
sawImports = true;
// remove stuff thats already added by a wildcard
if (line.indexOf('*') > 0)
{
LinkedList<String> remove = new LinkedList<String>();
String starter = line.replace("import ", "").replace(".*;", "");
for (String imp : newImports)
{
String impStart = imp.substring(0, imp.lastIndexOf('.'));
if (impStart.equals(starter))
remove.add(imp);
}
newImports.removeAll(remove);
}
if (line.startsWith("import net.minecraft."))
{
// If no import map, *remove* NMS imports (OBC rewritten with fully-qualified names)
if (importMap.isEmpty())
{
// next line.
lastIndex = nextIndex + 1; // +1 to skip the \n at the end of the line there
nextIndex = data.indexOf("\n", lastIndex + 1); // another +1 because otherwise it would just return lastIndex
continue;
}
// Rewrite NMS imports
String oldClass = line.replace("import ", "").replace(";", "");
log("Import: " + oldClass);
String newClass = oldClass;
if (oldClass.equals("net.minecraft.server.*"))
{
// wildcard NMS imports (CraftWorld, CraftEntity, CraftPlayer).. bad idea
// next line. Duplicated from the bottom of the loop.
lastIndex = nextIndex + 1; // +1 to skip the \n at the end of the line there
nextIndex = data.indexOf("\n", lastIndex + 1); // another +1 because otherwise it would just return lastIndex
continue;
}
else if (importMap.containsKey("class " + Util.sourceName2Internal(oldClass)))
newClass = importMap.get("class " + Util.sourceName2Internal(oldClass));
if (newImports.contains(newClass)) // if not already added & its changed
{
if (oldClass.equals(newClass))
{
newImports.remove(newClass);
}
else
{
// otherwise remove from the file... it will be added again later.
data.delete(lastIndex, nextIndex + 1); // the newLine too
nextIndex = data.indexOf("\n", lastIndex); // get from here to the end of the line.
continue;
}
}
else
{
int change = "import ".length();
data.replace(lastIndex, nextIndex, "import ");
data.insert(lastIndex + change, newClass);
change += newClass.length();
data.insert(lastIndex + change, ";");
nextIndex = lastIndex + change + 1; // +1 for the semicolon
}
}
}
else if (sawImports && !addedNewImports)
{
// Add our new imports right after the last import
log("Adding " + newImports.size() + " imports");
CharSequence sub = data.subSequence(lastIndex, data.length()); // grab the rest of the string.
data.setLength(lastIndex); // cut off the build there
for (String imp : newImports)
data.append("import ").append(imp).append(";\n");
int change = data.length() - lastIndex; // get changed size
lastIndex = data.length(); // reset the end to the actual end..
nextIndex += change; // shift nextIndex accordingly..
data.append(sub); // add on the rest if the string again
addedNewImports = true;
}
// next line.
lastIndex = nextIndex + 1; // +1 to skip the \n at the end of the line there
nextIndex = data.indexOf("\n", lastIndex + 1); // another +1 because otherwise it would just return lastIndex
}
// got through the whole file without seeing or adding any imports???
if (!addedNewImports)
{
// insert imports after the second line.
int index = data.indexOf("\n") + 1;
index = data.indexOf("\n", index) + 1; // search again from the second point, for 2 lines. +1 for after the \n
CharSequence sub = data.subSequence(index, data.length()); // grab the rest of the string.
data.setLength(index); // cut off the build there
for (String imp : newImports)
data.append("import ").append(imp).append(";\n");
data.append(sub); // add on the rest if the string again
}
String newData = data.toString();
// Warning: ugly hack ahead
// The symbol range map extractor is supposed to emit package reference ranges, which we can
// update with the correct new package names. However, it has a bug where the package ranges
// are not always emitted on fully-qualified names. For example: (net.minecraft.server.X)Y - a
// cast - will fail to recognize the net.minecraft.server package, so it won't be processed by us.
// This leads to some qualified names in the original source to becoming "overqualified", that is,
// net.minecraft.server.net.minecraft.X; the NMS class is replaced with its fully-qualified name
// (in non-NMS source, where we want it to always be fully-qualified): original package name isn't replaced.
// Occurs in OBC source which uses fully-qualified NMS names already, and NMS source which (unnecessarily)
// uses fully-qualified NMS names, too. Attempted to fix this problem for longer than I should..
// maybe someone smarter can figure it out -- but until then, in the interest of expediency, I present
// this ugly workaround, replacing the overqualified names after-the-fact.
// Fortunately, this pattern is easy enough to reliably detect and replace textually!
newData = newData.replace("net.minecraft.server.net.minecraft", "net.minecraft"); // OBC overqualified symbols
newData = newData.replace("net.minecraft.server.Block", "Block"); // NMS overqualified symbols
// ..and qualified inner classes, only one.... last ugly hack, I promise :P
newData = newData.replace("net.minecraft.block.BlockSapling/*was:BlockSapling*/.net.minecraft.block.BlockSapling.TreeGenerator", "net.minecraft.block.BlockSapling.TreeGenerator");
newData = newData.replace("net.minecraft.block.BlockSapling.net.minecraft.block.BlockSapling.TreeGenerator", "net.minecraft.block.BlockSapling.TreeGenerator");
return newData;
}
private String getNewName(String key, String oldName, Map<String, String> renameMap, boolean shouldAnnotate)
{
String newName;
if (!renameMap.containsKey(key))
{
String constructorClassName = getConstructor(key);
if (constructorClassName != null)
{
// Constructors are not in the method map (from .srg, and can't be derived
// exclusively from the class map since we don't know all the parameters).. so we
// have to synthesize a rename from the class map here. Ugh..but, it works.
log("FOUND CONSTR " + key + " " + constructorClassName);
if (renameMap.containsKey("class " + constructorClassName))
// Rename constructor to new class name
newName = Util.splitBaseName(renameMap.get("class " + constructorClassName));
else
return null;
}
else
// Not renaming this
return null;
}
else
newName = renameMap.get(key);
newName = Util.splitBaseName(newName, Util.countChar(oldName, '.'));
if (shouldAnnotate)
newName += "/* was " + oldName + "*/";
return newName;
}
/**
* Check whether a unique identifier method key is a constructor, if so return full class name for remapping, else null
*/
private String getConstructor(String key)
{
String[] tokens = key.split(" ", 3); // TODO: switch to non-conflicting separator..types can have spaces :(
if (!tokens[0].equals("method"))
return null;
log(Arrays.toString(tokens));
//kind, fullMethodName, methodSig = tokens
if (tokens[2].charAt(tokens[2].length() - 1) != 'V') // constructors marked with 'V' return type signature in ApplySrg2Source and MCP
return null;
String fullClassName = Util.splitPackageName(tokens[1]);
String methodName = Util.splitBaseName(tokens[1]);
String className = Util.splitBaseName(fullClassName);
if (className.equals(methodName)) // constructor has same name as class
return fullClassName;
else
return null;
}
}
|
package net.sf.jabref.model.search.rules;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.Keyword;
import net.sf.jabref.search.SearchBaseVisitor;
import net.sf.jabref.search.SearchLexer;
import net.sf.jabref.search.SearchParser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.ParseTree;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* The search query must be specified in an expression that is acceptable by the Search.g4 grammar.
*/
public class GrammarBasedSearchRule implements SearchRule {
private static final Log LOGGER = LogFactory.getLog(GrammarBasedSearchRule.class);
private final boolean caseSensitiveSearch;
private final boolean regExpSearch;
private ParseTree tree;
private String query;
public static class ThrowingErrorListener extends BaseErrorListener {
public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener();
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
int line, int charPositionInLine, String msg, RecognitionException e)
throws ParseCancellationException {
throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + msg);
}
}
public GrammarBasedSearchRule(boolean caseSensitiveSearch, boolean regExpSearch) throws RecognitionException {
this.caseSensitiveSearch = caseSensitiveSearch;
this.regExpSearch = regExpSearch;
}
public static boolean isValid(boolean caseSensitive, boolean regExp, String query) {
return new GrammarBasedSearchRule(caseSensitive, regExp).validateSearchStrings(query);
}
public boolean isCaseSensitiveSearch() {
return this.caseSensitiveSearch;
}
public boolean isRegExpSearch() {
return this.regExpSearch;
}
public ParseTree getTree() {
return this.tree;
}
public String getQuery() {
return this.query;
}
private void init(String query) throws ParseCancellationException {
if (Objects.equals(this.query, query)) {
return;
}
SearchLexer lexer = new SearchLexer(new ANTLRInputStream(query));
lexer.removeErrorListeners(); // no infos on file system
lexer.addErrorListener(ThrowingErrorListener.INSTANCE);
SearchParser parser = new SearchParser(new CommonTokenStream(lexer));
parser.removeErrorListeners(); // no infos on file system
parser.addErrorListener(ThrowingErrorListener.INSTANCE);
parser.setErrorHandler(new BailErrorStrategy()); // ParseCancelationException on parse errors
tree = parser.start();
this.query = query;
}
@Override
public boolean applyRule(String query, BibEntry bibEntry) {
try {
return new BibtexSearchVisitor(caseSensitiveSearch, regExpSearch, bibEntry).visit(tree);
} catch (Exception e) {
LOGGER.debug("Search failed", e);
return false;
}
}
@Override
public boolean validateSearchStrings(String query) {
try {
init(query);
return true;
} catch (ParseCancellationException e) {
LOGGER.debug("Search query invalid", e);
return false;
}
}
public enum ComparisonOperator {
EXACT, CONTAINS, DOES_NOT_CONTAIN;
public static ComparisonOperator build(String value) {
if ("CONTAINS".equalsIgnoreCase(value) || "=".equals(value)) {
return CONTAINS;
} else if ("MATCHES".equalsIgnoreCase(value) || "==".equals(value)) {
return EXACT;
} else {
return DOES_NOT_CONTAIN;
}
}
}
public static class Comparator {
private final ComparisonOperator operator;
private final Pattern fieldPattern;
private final Pattern valuePattern;
public Comparator(String field, String value, ComparisonOperator operator, boolean caseSensitive, boolean regex) {
this.operator = operator;
int option = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
this.fieldPattern = Pattern.compile(regex ? field : "\\Q" + field + "\\E", option);
this.valuePattern = Pattern.compile(regex ? value : "\\Q" + value + "\\E", option);
}
public boolean compare(BibEntry entry) {
// special case for searching for entrytype=phdthesis
if (fieldPattern.matcher(BibEntry.TYPE_HEADER).matches()) {
return matchFieldValue(entry.getType());
}
// special case for searching a single keyword
if (fieldPattern.matcher("anykeyword").matches()) {
return entry.getKeywords(',').stream().map(Keyword::toString).anyMatch(this::matchFieldValue);
}
// specification of fieldsKeys to search is done in the search expression itself
Set<String> fieldsKeys = entry.getFieldNames();
// special case for searching allfields=cat and title=dog
if (!fieldPattern.matcher("anyfield").matches()) {
// Filter out the requested fields
fieldsKeys = fieldsKeys.stream().filter(matchFieldKey()).collect(Collectors.toSet());
}
for (String field : fieldsKeys) {
Optional<String> fieldValue = entry.getLatexFreeField(field);
if (fieldValue.isPresent()) {
if (matchFieldValue(fieldValue.get())) {
return true;
}
}
}
// special case of asdf!=whatever and entry does not contain asdf
return fieldsKeys.isEmpty() && (operator == ComparisonOperator.DOES_NOT_CONTAIN);
}
private Predicate<String> matchFieldKey() {
return s -> fieldPattern.matcher(s).matches();
}
public boolean matchFieldValue(String content) {
Matcher matcher = valuePattern.matcher(content);
if (operator == ComparisonOperator.CONTAINS) {
return matcher.find();
} else if (operator == ComparisonOperator.EXACT) {
return matcher.matches();
} else if (operator == ComparisonOperator.DOES_NOT_CONTAIN) {
return !matcher.find();
} else {
throw new IllegalStateException("MUST NOT HAPPEN");
}
}
}
/**
* Search results in boolean. It may be later on converted to an int.
*/
static class BibtexSearchVisitor extends SearchBaseVisitor<Boolean> {
private final boolean caseSensitive;
private final boolean regex;
private final BibEntry entry;
public BibtexSearchVisitor(boolean caseSensitive, boolean regex, BibEntry bibEntry) {
this.caseSensitive = caseSensitive;
this.regex = regex;
this.entry = bibEntry;
}
public boolean comparison(String field, ComparisonOperator operator, String value) {
return new Comparator(field, value, operator, caseSensitive, regex).compare(entry);
}
@Override
public Boolean visitStart(SearchParser.StartContext ctx) {
return visit(ctx.expression());
}
@Override
public Boolean visitComparison(SearchParser.ComparisonContext context) {
// remove possible enclosing " symbols
String right = context.right.getText();
if(right.startsWith("\"") && right.endsWith("\"")) {
right = right.substring(1, right.length() - 1);
}
Optional<SearchParser.NameContext> fieldDescriptor = Optional.ofNullable(context.left);
if (fieldDescriptor.isPresent()) {
return comparison(fieldDescriptor.get().getText(), ComparisonOperator.build(context.operator.getText()), right);
} else {
return new ContainBasedSearchRule(caseSensitive).applyRule(right, entry);
}
}
@Override
public Boolean visitUnaryExpression(SearchParser.UnaryExpressionContext ctx) {
return !visit(ctx.expression()); // negate
}
@Override
public Boolean visitParenExpression(SearchParser.ParenExpressionContext ctx) {
return visit(ctx.expression()); // ignore parenthesis
}
@Override
public Boolean visitBinaryExpression(SearchParser.BinaryExpressionContext ctx) {
if ("AND".equalsIgnoreCase(ctx.operator.getText())) {
return visit(ctx.left) && visit(ctx.right); // and
} else {
return visit(ctx.left) || visit(ctx.right);
}
}
}
}
|
package net.sf.kerner.utils.collections.list.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import net.sf.kerner.utils.collections.Filter;
import net.sf.kerner.utils.collections.list.ListFilter;
import net.sf.kerner.utils.collections.list.ListView;
public class ArrayListView<T> implements ListView<T>, List<T> {
protected final List<T> collection;
public ArrayListView(List<? extends T> collection, ListFilter<T> filter) {
this.collection = new ArrayList<T>();
for (int i = 0; i < collection.size(); i++) {
final T t = collection.get(i);
if (filter.visit(t, i)) {
this.collection.add(t);
}
}
}
public ArrayListView(Collection<? extends T> collection, Filter<T> filter) {
this.collection = new ArrayList<T>();
for (T t : collection) {
if (filter.visit(t)) {
this.collection.add(t);
}
}
}
public ArrayListView(Collection<? extends T> collection) {
this.collection = new ArrayList<T>(collection);
}
public ListView<T> getView(final Filter<T> filter) {
return new ArrayListView<T>(collection, filter);
}
public ListView<T> getView(final ListFilter<T> filter) {
return new ArrayListView<T>(collection, filter);
}
@Override
public String toString() {
return collection.toString();
}
public int size() {
return collection.size();
}
public boolean isEmpty() {
return collection.isEmpty();
}
public boolean contains(Object o) {
return collection.contains(o);
}
public Iterator<T> iterator() {
return collection.iterator();
}
public Object[] toArray() {
return collection.toArray();
}
public <T> T[] toArray(T[] a) {
return collection.toArray(a);
}
public boolean add(T e) {
return collection.add(e);
}
public boolean remove(Object o) {
return collection.remove(o);
}
public boolean containsAll(Collection<?> c) {
return collection.containsAll(c);
}
public boolean addAll(Collection<? extends T> c) {
return collection.addAll(c);
}
public boolean addAll(int index, Collection<? extends T> c) {
return collection.addAll(index, c);
}
public boolean removeAll(Collection<?> c) {
return collection.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
return collection.retainAll(c);
}
public void clear() {
collection.clear();
}
public boolean equals(Object o) {
return collection.equals(o);
}
public int hashCode() {
return collection.hashCode();
}
public T get(int index) {
return collection.get(index);
}
public T set(int index, T element) {
return collection.set(index, element);
}
public void add(int index, T element) {
collection.add(index, element);
}
public T remove(int index) {
return collection.remove(index);
}
public int indexOf(Object o) {
return collection.indexOf(o);
}
public int lastIndexOf(Object o) {
return collection.lastIndexOf(o);
}
public ListIterator<T> listIterator() {
return collection.listIterator();
}
public ListIterator<T> listIterator(int index) {
return collection.listIterator(index);
}
public List<T> subList(int fromIndex, int toIndex) {
return collection.subList(fromIndex, toIndex);
}
}
|
package net.smoofyuniverse.common.util.io;
import java.nio.file.CopyOption;
import java.nio.file.Path;
public class StringCopyFileVisitor extends AbstractCopyFileVisitor {
protected final Path source, target;
protected final int sourceLength;
public StringCopyFileVisitor(Path source, Path target, CopyOption... options) {
super(options);
this.source = source;
this.target = target;
String sep = source.getFileSystem().getSeparator();
String str = source.toString();
this.sourceLength = str.endsWith(sep) ? str.length() : (str.length() + sep.length());
}
@Override
protected Path getDestination(Path path) {
String str = path.toString();
return str.length() > this.sourceLength ? this.target.resolve(str.substring(this.sourceLength)) : this.target;
}
}
|
package org.jenkinsci.plugins.graniteclient;
import com.cloudbees.jenkins.plugins.sshcredentials.SSHUser;
import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserPrivateKey;
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.common.UsernameCredentials;
import jenkins.model.Jenkins;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Pojo for capturing the group of configuration values for a single Granite Client connection
*/
public final class GraniteClientConfig implements Serializable {
private static final long serialVersionUID = 2713710297119924270L;
private final String baseUrl;
private final String credentialsId;
private final long requestTimeout;
private final long serviceTimeout;
private final long waitDelay;
private final Credentials credentials;
public GraniteClientConfig(String baseUrl, String credentialsId) {
this(baseUrl, credentialsId, 0L, 0L, 0L);
}
public GraniteClientConfig(String baseUrl, String credentialsId, long requestTimeout, long serviceTimeout) {
this(baseUrl, credentialsId, requestTimeout, serviceTimeout, 0L);
}
public GraniteClientConfig(String baseUrl, String credentialsId, long requestTimeout, long serviceTimeout, long waitDelay) {
this.credentialsId = credentialsId;
this.requestTimeout = requestTimeout > 0L ? requestTimeout : -1L;
this.serviceTimeout = serviceTimeout > 0L ? serviceTimeout : -1L;
this.waitDelay = waitDelay > 0L ? waitDelay : -1L;
String _baseUrl = sanitizeUrl(baseUrl);
Credentials _credentials = GraniteNamedIdCredentials.getCredentialsById(credentialsId);
if (_credentials == null) {
_credentials = GraniteAHCFactory.getFactoryInstance().getDefaultCredentials();
}
try {
URI baseUri = new URI(_baseUrl);
if (baseUri.getUserInfo() != null) {
_credentials = GraniteNamedIdCredentials
.getCredentialsFromURIUserInfo(baseUri.getUserInfo(), _credentials);
URI changed = new URI(
baseUri.getScheme(),
null,
baseUri.getHost(),
baseUri.getPort(),
baseUri.getPath(),
baseUri.getQuery(),
baseUri.getFragment());
_baseUrl = changed.toString();
}
} catch (URISyntaxException e) {
// do nothing at the moment;
}
this.baseUrl = _baseUrl;
this.credentials = _credentials;
}
public String getBaseUrl() {
return baseUrl;
}
public String getCredentialsId() {
return credentialsId;
}
public boolean isSignatureLogin() {
return credentials instanceof SSHUserPrivateKey;
}
public String getUsername() {
if (this.credentials instanceof SSHUser) {
return ((SSHUser) this.credentials).getUsername();
} else if (this.credentials instanceof UsernameCredentials) {
return ((UsernameCredentials) this.credentials).getUsername();
} else {
return "admin";
}
}
public long getRequestTimeout() {
return requestTimeout;
}
public long getServiceTimeout() {
return serviceTimeout;
}
public long getWaitDelay() {
return waitDelay;
}
public Credentials getCredentials() {
return credentials;
}
private static final Pattern HTTP_URL_PATTERN = Pattern.compile("(https?:
public static String sanitizeUrl(final String url) {
// remove tokens with extreme prejudice
String _url = url.replaceAll("\\$\\{\\w*\\}?", "");
// identify http/s URLs, since that's really all we support
Matcher urlMatcher = HTTP_URL_PATTERN.matcher(_url);
if (urlMatcher.find()) {
StringBuilder sb = new StringBuilder(urlMatcher.group(1));
final String authority = urlMatcher.group(2);
int lastAt = authority.lastIndexOf('@');
if (lastAt >= 0) {
final String host = authority.substring(lastAt);
final String rawUserInfo = authority.substring(0, lastAt);
final int firstColon = rawUserInfo.indexOf(':');
if (firstColon >= 0) {
String rawUsername = rawUserInfo.substring(0, firstColon);
String rawPassword = rawUserInfo.substring(firstColon + 1);
sb.append(urlEscape(rawUsername)).append(":").append(urlEscape(rawPassword));
} else {
sb.append(urlEscape(rawUserInfo));
}
sb.append(host);
} else {
sb.append(authority);
}
_url = sb.append(urlMatcher.group(3)).toString();
}
return _url;
}
private static String urlEscape(final String raw) {
return raw.replaceAll("%(?![A-Fa-f0-9]{2})", "%25")
.replace(" ", "%20")
.replace("!", "%21")
.replace("
.replace("$", "%24")
.replace("&", "%26")
.replace("'", "%27")
.replace("(", "%28")
.replace(")", "%29")
.replace("*", "%2A")
.replace("+", "%2B")
.replace(",", "%2C")
.replace("/", "%2F")
.replace(":", "%3A")
.replace(";", "%3B")
.replace("=", "%3D")
.replace("?", "%3F")
.replace("@", "%40")
.replace("[", "%5B")
.replace("]", "%5D");
}
}
|
package org.letustakearest.presentation.resources;
import com.google.code.siren4j.Siren4J;
import com.google.code.siren4j.component.Entity;
import org.letustakearest.application.service.HotelService;
import org.letustakearest.domain.EntityNotFoundException;
import org.letustakearest.domain.Hotel;
import org.letustakearest.presentation.representations.HotelRepresentationBuilder;
import org.letustakearest.presentation.representations.HotelWithPlacesRepresentationBuilder;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.*;
import java.util.List;
/**
* @author volodymyr.tsukur
*/
public class HotelResource {
private Long id;
private HotelService hotelService;
public HotelResource(final Long id, final HotelService hotelService) {
this.id = id;
this.hotelService = hotelService;
}
@GET
@Produces({ Siren4J.JSON_MEDIATYPE })
public Entity read(@Context final UriInfo uriInfo) {
final Hotel hotel = findHotel();
return new HotelRepresentationBuilder(hotel, uriInfo).build();
}
@GET
@Produces({ "application/vnd.siren.hotel.v2+json" })
public Entity readWithPlaces(@Context final UriInfo uriInfo) {
return prepareHotelAsPlaceRepresentation(uriInfo);
}
@GET
@Path("/runtime-content-negotiation")
public Response readViaRuntimeContentNegotiation(
@Context final UriInfo uriInfo,
@Context final Request request) {
final List<Variant> variants = Variant.mediaTypes(
MediaType.valueOf(Siren4J.JSON_MEDIATYPE),
MediaType.valueOf("application/vnd.siren.hotel.v2+json")
).build();
final Variant variant = request.selectVariant(variants);
if (variant == null) {
return Response.notAcceptable(variants).build();
}
else {
final Hotel hotel = findHotel();
if (variant.getMediaType().equals(MediaType.valueOf("application/vnd.siren.hotel.v2+json"))) {
return Response.ok(prepareHotelAsPlaceRepresentation(uriInfo), variant).build();
}
else {
return Response.ok(new HotelRepresentationBuilder(hotel, uriInfo).build(), variant).build();
}
}
}
@GET
@Produces({ Siren4J.JSON_MEDIATYPE })
@Path("/versioning-by-header")
public Response readViaRuntimeContentNegotiation(
@Context final UriInfo uriInfo,
@Context final HttpHeaders httpHeaders) {
final Hotel hotel = findHotel();
if ("2".equals(httpHeaders.getHeaderString("X-Version"))) {
return Response.ok(prepareHotelAsPlaceRepresentation(uriInfo)).build();
}
else {
return Response.ok(new HotelRepresentationBuilder(hotel, uriInfo).build()).build();
}
}
@GET
@Path("/as-place")
@Produces({ Siren4J.JSON_MEDIATYPE })
public Entity readWithPlacesViaURI(@Context final UriInfo uriInfo) {
return prepareHotelAsPlaceRepresentation(uriInfo);
}
private Entity prepareHotelAsPlaceRepresentation(UriInfo uriInfo) {
final Hotel hotel = findHotel();
return new HotelWithPlacesRepresentationBuilder(hotel, uriInfo).build();
}
private Hotel findHotel() throws WebApplicationException {
try {
return hotelService.findById(id);
}
catch (final EntityNotFoundException e) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
}
|
package org.spacehq.mc.protocol.data.game.values.world;
public enum Particle {
EXPLOSION_NORMAL,
EXPLOSION_LARGE,
EXPLOSION_HUGE,
FIREWORKS_SPARK,
WATER_BUBBLE,
WATER_SPLASH,
WATER_WAKE,
SUSPENDED,
SUSPENDED_DEPTH,
CRIT,
CRIT_MAGIC,
SMOKE_NORMAL,
SMOKE_LARGE,
SPELL,
SPELL_INSTANT,
SPELL_MOB,
SPELL_MOB_AMBIENT,
SPELL_WITCH,
DRIP_WATER,
DRIP_LAVA,
VILLAGER_ANGRY,
VILLAGER_HAPPY,
TOWN_AURA,
NOTE,
PORTAL,
ENCHANTMENT_TABLE,
FLAME,
LAVA,
FOOTSTEP,
CLOUD,
REDSTONE,
SNOWBALL,
SNOW_SHOVEL,
SLIME,
HEART,
BARRIER,
ICON_CRACK(2),
BLOCK_CRACK(1),
BLOCK_DUST(1),
WATER_DROP,
ITEM_TAKE,
MOB_APPEARANCE;
private int dataLength;
private Particle() {
this(0);
}
private Particle(int dataLength) {
this.dataLength = dataLength;
}
public int getDataLength() {
return this.dataLength;
}
}
|
package org.spongepowered.asm.mixin.injection.struct;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.transformer.MixinData;
/**
* <p>Information bundle about a member (method or field) parsed from a String token in another annotation, this is used where target members need to
* be specified as Strings in order to parse the String representation to something useful.</p>
*
* <p>Some examples: <blockquote><pre>
* // references a method or field called func_1234_a, if there are multiple members with the same signature, matches the first occurrence
* func_1234_a
*
* // references a method or field called func_1234_a, if there are multiple members with the same signature, matches all occurrences
* func_1234_a*
*
* // references a method called func_1234_a which takes 3 ints and returns a bool
* func_1234_a(III)Z
*
* // references a field called field_5678_z which is a String
* field_5678_z:Ljava/lang/String;
*
* // references a ctor which takes a single String argument
* <init>(Ljava/lang/String;)V
*
* // references a method called func_1234_a in class foo.bar.Baz
* Lfoo/bar/Baz;func_1234_a
*
* // references a field called field_5678_z in class com.example.Dave
* Lcom/example/Dave;field_5678_z
*
* // references a method called func_1234_a in class foo.bar.Baz which takes 3 doubles and returns void
* Lfoo/bar/Baz;func_1234_a(DDD)V
*
* // alternate syntax for the same
* foo.bar.Baz.func_1234_a(DDD)V</pre></blockquote>
* </p>
*/
public class MemberInfo {
/**
* Member owner in internal form but without L;, can be null
*/
public final String owner;
/**
* Member name, can be null to match any member
*/
public final String name;
/**
* Member descriptor, can be null
*/
public final String desc;
/**
* True to match all matching members, not just the first
*/
public final boolean matchAll;
/**
* @param name Member name, must not be null
*/
public MemberInfo(String name, boolean matchAll) {
this(name, null, null, matchAll);
}
/**
* @param name Member name, must not be null
* @param owner Member owner, can be null otherwise must be in internal form without L;
*/
public MemberInfo(String name, String owner, boolean matchAll) {
this(name, owner, null, matchAll);
}
/**
* @param name Member name, must not be null
* @param owner Member owner, can be null otherwise must be in internal form without L;
* @param desc Member descriptor, can be null
* @param matchAll True to match all matching members, not just the first
*/
public MemberInfo(String name, String owner, String desc, boolean matchAll) {
if (owner != null && owner.contains(".")) {
throw new IllegalArgumentException("Attempt to instance a MemberInfo with an invalid owner format");
}
this.owner = owner;
this.name = name;
this.desc = desc;
this.matchAll = matchAll;
}
/**
* Initialise a MemberInfo using the supplied insn which must be an instance of MethodInsnNode or FieldInsnNode
*/
public MemberInfo(AbstractInsnNode insn) {
this.matchAll = false;
if (insn instanceof MethodInsnNode) {
MethodInsnNode methodNode = (MethodInsnNode) insn;
this.owner = methodNode.owner;
this.name = methodNode.name;
this.desc = methodNode.desc;
} else if (insn instanceof FieldInsnNode) {
FieldInsnNode fieldNode = (FieldInsnNode) insn;
this.owner = fieldNode.owner;
this.name = fieldNode.name;
this.desc = fieldNode.desc;
} else {
throw new IllegalArgumentException("insn must be an instance of MethodInsnNode or FieldInsnNode");
}
}
/**
* Initialise a MemberInfo using the supplied MethodData object
*/
public MemberInfo(MethodData methodData) {
int slashPos = methodData.name.lastIndexOf('/');
this.owner = methodData.name.substring(0, slashPos);
this.name = methodData.name.substring(slashPos + 1);
this.desc = methodData.sig;
this.matchAll = false;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String owner = this.owner != null ? "L" + this.owner + ";" : "";
String name = this.name != null ? this.name : "";
String qualifier = this.matchAll ? "*" : "";
String desc = this.desc != null ? this.desc : "";
String separator = desc.startsWith("(") ? "" : (this.desc != null ? ":" : "");
return owner + name + qualifier + separator + desc;
}
/**
* Return this MemberInfo as an SRG mapping
*/
public String toSrg() {
if (!this.isFullyQualified()) {
throw new RuntimeException("Cannot convert unqalified reference to SRG mapping");
}
if (this.desc.startsWith("(")) {
return this.owner + "/" + this.name + " " + this.desc;
}
return this.owner + "/" + this.name;
}
public MethodData asMethodData() {
if (!this.isFullyQualified()) {
throw new RuntimeException("Cannot convert unqalified reference to MethodData");
}
if (this.isField()) {
throw new RuntimeException("Cannot convert a non-method reference to MethodData");
}
return new MethodData(this.owner + "/" + this.name, this.desc);
}
/**
* Get whether this reference is fully qualified
*/
public boolean isFullyQualified() {
return this.owner != null && this.name != null && this.desc != null;
}
/**
* Get whether this MemberInfo is definitely a field, the output of this method is undefined if {@link #isFullyQualified} returns false
*/
public boolean isField() {
return this.desc != null && !this.desc.startsWith("(");
}
/**
* Test whether this MemberInfo matches the supplied values. Null values are ignored.
*/
public boolean matches(String owner, String name, String desc) {
return this.matches(owner, name, desc, 0);
}
/**
* Test whether this MemberInfo matches the supplied values at the specified ordinal. Null values are ignored.
*/
public boolean matches(String owner, String name, String desc, int ordinal) {
if (this.desc != null && desc != null && !this.desc.equals(desc)) {
return false;
}
if (this.name != null && name != null && !this.name.equals(name)) {
return false;
}
if (this.owner != null && owner != null && !this.owner.equals(owner)) {
return false;
}
return ordinal == 0 || this.matchAll;
}
/**
* Test whether this MemberInfo matches the supplied values. Null values are ignored.
*/
public boolean matches(String name, String desc) {
return this.matches(name, desc, 0);
}
/**
* Test whether this MemberInfo matches the supplied values at the specified ordinal. Null values are ignored.
*/
public boolean matches(String name, String desc, int ordinal) {
return (this.name == null || this.name.equals(name))
&& (this.desc == null || (desc != null && desc.equals(this.desc)))
&& (ordinal == 0 || this.matchAll);
}
/**
* Parse a MemberInfo from a string
*/
public static MemberInfo parse(String name) {
return MemberInfo.parse(name, null, null);
}
/**
* Parse a MemberInfo from a string
*/
public static MemberInfo parse(String name, MixinData mixin) {
return MemberInfo.parse(name, mixin.getReferenceMapper(), mixin.getClassRef());
}
/**
* Parse a MemberInfo from a string
*/
public static MemberInfo parse(String name, ReferenceMapper refMapper, String mixinClass) {
String desc = null;
String owner = null;
if (refMapper != null) {
name = refMapper.remap(mixinClass, name);
}
int lastDotPos = name.lastIndexOf('.');
int semiColonPos = name.indexOf(';');
if (lastDotPos > -1) {
owner = name.substring(0, lastDotPos).replace('.', '/');
name = name.substring(lastDotPos + 1);
} else if (semiColonPos > -1 && name.startsWith("L")) {
owner = name.substring(1, semiColonPos).replace('.', '/');
name = name.substring(semiColonPos + 1);
}
int parenPos = name.indexOf('(');
int colonPos = name.indexOf(':');
if (parenPos > -1) {
desc = name.substring(parenPos);
name = name.substring(0, parenPos);
} else if (colonPos > -1) {
desc = name.substring(colonPos + 1);
name = name.substring(0, colonPos);
}
boolean matchAll = name.endsWith("*");
if (matchAll) {
name = name.substring(0, name.length() - 1);
}
if (name.isEmpty()) {
name = null;
}
return new MemberInfo(name, owner, desc, matchAll);
}
public static MemberInfo fromSrgField(String srgName, String desc) {
int slashPos = srgName.lastIndexOf('/');
String owner = srgName.substring(0, slashPos);
String name = srgName.substring(slashPos + 1);
return new MemberInfo(name, owner, desc, false);
}
public static MemberInfo fromSrgMethod(MethodData methodData) {
return new MemberInfo(methodData);
}
}
|
package net.littlebigisland.droidibus.activity.preferences;
import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.DatePicker;
public class DatePreference extends DialogPreference{
private DatePicker mDatePicker = null;
private String mCurrentDate = "";
public DatePreference(Context ctxt) {
this(ctxt, null);
}
public DatePreference(Context ctxt, AttributeSet attrs) {
this(ctxt, attrs, 0);
}
public DatePreference(Context ctxt, AttributeSet attrs, int defStyle) {
super(ctxt, attrs, defStyle);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
@Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
mDatePicker.updateDate(2014, 07, 25);
}
@Override
protected View onCreateDialogView() {
mDatePicker = new DatePicker(getContext());
return(mDatePicker);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
mCurrentDate = String.format(
"%s %s %s",
mDatePicker.getDayOfMonth(),
mDatePicker.getMonth() + 1,
mDatePicker.getYear() - 2000 // BEWARE POTENTIAL BUGS
);
if (callChangeListener(mCurrentDate)) {
persistString(mCurrentDate);
}
}
}
}
|
package org.TexasTorque.TexasTorque2013.subsystem.manipulator;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.TexasTorque.TexasTorque2013.constants.Constants;
import org.TexasTorque.TexasTorque2013.io.DriverInput;
import org.TexasTorque.TexasTorque2013.io.RobotOutput;
import org.TexasTorque.TexasTorque2013.io.SensorInput;
import org.TexasTorque.TexasTorque2013.subsystem.drivebase.Drivebase;
import org.TexasTorque.TorqueLib.util.DashboardManager;
import org.TexasTorque.TorqueLib.util.Parameters;
import org.TexasTorque.TorqueLib.util.TorqueLogging;
public class Manipulator
{
private static Manipulator instance;
private DashboardManager dashboardManager;
private RobotOutput robotOutput;
private SensorInput sensorInput;
private DriverInput driverInput;
private TorqueLogging logging;
private Parameters params;
private Shooter shooter;
private Elevator elevator;
private Intake intake;
private Magazine magazine;
public static Manipulator getInstance()
{
return (instance == null) ? instance = new Manipulator() : instance;
}
public Manipulator()
{
dashboardManager = DashboardManager.getInstance();
robotOutput = RobotOutput.getInstance();
sensorInput = SensorInput.getInstance();
driverInput = DriverInput.getInstance();
logging = TorqueLogging.getInstance();
params = Parameters.getInstance();
shooter = Shooter.getInstance();
elevator = Elevator.getInstance();
intake = Intake.getInstance();
magazine = Magazine.getInstance();
}
public void run()
{
if(!driverInput.override())
{
if(driverInput.reverseIntake())
{
calcReverseIntake();
}
else if(driverInput.runIntake())
{
calcIntake();
}
else if(driverInput.shootVisionHigh())
{
shootHighWithVision();
}
else
{
restoreDefaultPositions();
}
shooter.run();
elevator.run();
intake.run();
magazine.run();
}
else
{
calcOverrides();
}
}
public synchronized void logData()
{
logging.logValue("InOverrideState", driverInput.override());
intake.logData();
shooter.logData();
elevator.logData();
}
public void calcOverrides()
{
if(driverInput.intakeOverride())
{
robotOutput.setIntakeMotor(params.getAsDouble("I_IntakeSpeed", 1.0));
}
else if(driverInput.outtakeOverride())
{
robotOutput.setIntakeMotor(params.getAsDouble("I_OuttakeSpeed", -1.0));
}
else
{
robotOutput.setIntakeMotor(Constants.MOTOR_STOPPED);
}
if(driverInput.elevatorTopOverride())
{
double speed = params.getAsDouble("E_ElevatorOverrideSpeed", 0.5);
robotOutput.setElevatorMotors(speed);
}
else if(driverInput.elevatorBottomOverride())
{
double speed = -1 * params.getAsDouble("E_ElevatorOverrideSpeed", 0.5) * 0.8; // Accounts for gravity
robotOutput.setElevatorMotors(speed);
}
else
{
robotOutput.setElevatorMotors(Constants.MOTOR_STOPPED);
}
if(driverInput.tiltUpOverride())
{
double speed = params.getAsDouble("S_TiltOverrideSpeed", 0.5);
robotOutput.setShooterTiltMotor(speed);
}
else if(driverInput.tiltDownOverride())
{
double speed = -1 * params.getAsDouble("S_TiltOverrideSpeed", 0.5);
robotOutput.setShooterTiltMotor(speed);
}
else
{
robotOutput.setShooterTiltMotor(Constants.MOTOR_STOPPED);
}
if(driverInput.shooterOverride())
{
double frontSpeed = params.getAsDouble("S_FrontShooterOverrideSpeed", 0.7);
double rearSpeed = params.getAsDouble("S_RearShooterOverrideSpeed", 0.5);
robotOutput.setShooterMotors(frontSpeed, rearSpeed);
}
else
{
robotOutput.setShooterMotors(Constants.MOTOR_STOPPED, Constants.MOTOR_STOPPED);
}
if(driverInput.magazineShootOverride())
{
robotOutput.setLoaderSolenoid(false);
}
else if(driverInput.intakeOverride())
{
robotOutput.setFrisbeeLifter(false);
}
else
{
robotOutput.setFrisbeeLifter(true);
robotOutput.setLoaderSolenoid(true);
}
}
public void calcReverseIntake()
{
shooter.setTiltAngle(Constants.TILT_PARALLEL_POSITION);
shooter.setShooterRates(Constants.SHOOTER_STOPPED_RATE, Constants.SHOOTER_STOPPED_RATE);
magazine.setDesiredState(Constants.MAGAZINE_READY_STATE);
if(shooter.isParallel())
{
elevator.setDesiredPosition(params.getAsInt("E_ElevatorBottomPosition", Constants.DEFAULT_ELEVATOR_BOTTOM_POSITION));
if(elevator.elevatorAtBottom())
{
intake.setIntakeSpeed(params.getAsDouble("I_OuttakeSpeed", -1.0));
}
}
}
public void calcIntake()
{
shooter.setTiltAngle(Constants.TILT_PARALLEL_POSITION);
shooter.setShooterRates(Constants.SHOOTER_STOPPED_RATE, Constants.SHOOTER_STOPPED_RATE);
magazine.setDesiredState(Constants.MAGAZINE_LOADING_STATE);
if(shooter.isParallel())
{
elevator.setDesiredPosition(params.getAsInt("E_ElevatorBottomPosition", Constants.DEFAULT_ELEVATOR_BOTTOM_POSITION));
if(elevator.elevatorAtBottom())
{
intake.setIntakeSpeed(params.getAsDouble("I_IntakeSpeed", Constants.MOTOR_STOPPED));
}
}
}
public void shootHighWithVision()
{
elevator.setDesiredPosition(params.getAsInt("E_ElevatorTopPosition", Constants.DEFAULT_ELEVATOR_TOP_POSITION));
intake.setIntakeSpeed(Constants.MOTOR_STOPPED);
magazine.setDesiredState(Constants.MAGAZINE_READY_STATE);
if(elevator.elevatorAtTop() && SmartDashboard.getBoolean("found", false))
{
double frontRate = params.getAsDouble("S_FrontShooterRate", Constants.DEFAULT_FRONT_SHOOTER_RATE);
double rearRate = params.getAsDouble("S_RearShooterRate", Constants.DEFAULT_REAR_SHOOTER_RATE);
shooter.setShooterRates(frontRate, rearRate);
double elevation = SmartDashboard.getNumber("elevation", Constants.TILT_PARALLEL_POSITION);
shooter.setTiltAngle(elevation);
if((driverInput.fireFrisbee() || dashboardManager.getDS().isAutonomous()) && shooter.isReadyToFire() && Drivebase.getInstance().isHorizontallyLocked())
{
magazine.setDesiredState(Constants.MAGAZINE_SHOOTING_STATE);
}
}
}
public void restoreDefaultPositions()
{
shooter.setShooterRates(Constants.SHOOTER_STOPPED_RATE, Constants.SHOOTER_STOPPED_RATE);
shooter.setTiltAngle(Constants.TILT_PARALLEL_POSITION);
intake.setIntakeSpeed(Constants.MOTOR_STOPPED);
magazine.setDesiredState(Constants.MAGAZINE_READY_STATE);
if(shooter.isParallel())
{
elevator.setDesiredPosition(params.getAsInt("E_ElevatorBottomPosition", Constants.DEFAULT_ELEVATOR_BOTTOM_POSITION));
}
}
public void pullNewPIDGains()
{
shooter.loadFrontShooterPID();
shooter.loadRearShooterPID();
shooter.loadTiltPID();
elevator.loadElevatorPID();
}
}
|
package org.ensembl.healthcheck.configuration;
import uk.co.flamingpenguin.jewel.cli.Option;
public interface ConfigurationUserParameters
extends
ConfigureHost,
ConfigureDatabases,
ConfigureTestGroups,
ConfigureConfiguration,
ConfigureTestRunner,
ConfigureHealthcheckDatabase,
ConfigureCompareSchema,
ConfigureMiscProperties {
@Option(helpRequest = true, description = "display help", shortName = "h")
boolean getHelp();
}
|
package org.objectweb.proactive.core.group.spmd;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
/**
* @author Laurent Baduel
*/
public class ProActiveSPMDGroupManager implements java.io.Serializable {
/**
* The spmd group he object belongs to
*/
private Object spmdGroup = null;
/**
* The current 'active' barrriers.
* The requests tagged with at least one of those barriers
* will be ignored until the barrier will be released.
*/
private HashMap currentBarriers = new HashMap(4); // initial capacity is 4.
/**
* The tags joint to the requests.
* The requests tagged with those barriers
* will be ignored until all those barriers will be released.
*/
private LinkedList barrierTags = new LinkedList();
/**
* Set the SPMD group for the active object.
* @param o - the new SPMD group
*/
public void setSPMDGroup(Object o) {
this.spmdGroup = o;
}
/**
* Returns the SPMD group of the active object.
* @return the SPMD group of the active object
*/
public Object getSPMDGroup() {
return this.spmdGroup;
}
/**
* Adds the barrier ID into the list of barrier ID used to tag messages.
* @param barrierID the barrier name
*/
public void addToBarrierTags(String barrierID) {
if (!this.barrierTags.contains(barrierID)) {
this.barrierTags.add(barrierID);
}
}
/**
* Return a BarrierState object representing the current state of a barrier.
* @param barrierName the name of the barrier
* @return the state of the specified barrier
*/
public BarrierState getBarrierStateFor(String barrierName) {
return (BarrierState) this.currentBarriers.get(barrierName);
}
/**
* Set the number of awaited barrier calls to release the specified barrier
* @param barrierName the name of the barrier
* @param nbCalls the number of awaited calls
*/
public void setAwaitedBarrierCalls(String barrierName, int nbCalls) {
BarrierState bs = (BarrierState) this.currentBarriers.get(barrierName);
if (bs == null) {
// System.out.println("First barrier \"" + this.getIDName() + "\" encountered !");
// build and add infos about new barrier
bs = new BarrierState();
this.addToCurrentBarriers(barrierName, bs);
}
bs.setAwaitedCalls(nbCalls);
}
/**
* Set a BarrierState for the specified barrier
* @param barrierName the name of the barrier
* @param bs a state for the barrier
*/
public void addToCurrentBarriers(String barrierName, BarrierState bs) {
this.currentBarriers.put(barrierName, bs);
}
/**
* Remove the informations (BarrierState and tag) of the specified barrier
* (invoked when the barrier is over).
* @param barreirName the name of the barrier
*/
public void remove(String barrierName) {
// stop tagging the outgoing message
this.barrierTags.remove(barrierName);
// remove the barrier from the current active barriers list
this.currentBarriers.remove(barrierName);
}
/**
* Check if the list of barrier tags is empty
* @return true if the the list is empty, false if it is not
*/
public boolean isTagsListEmpty() {
return (this.barrierTags.size() == 0);
}
/**
* Return the list of barrier tags
* @return a LinkedList containing the barrier tags
*/
public LinkedList getBarrierTags() {
return this.barrierTags;
}
/**
* Check if the tags given in parameter contains none
* of the tags of the current barriers
* @param barrierTags a list of Tag
* @return true if barrierTags contains no tags of the current barriers, false if barrierTags contains at least one tag of the current barriers
*/
public boolean checkExecution(LinkedList barrierTags) {
if (barrierTags == null) {
return true;
}
Iterator it = barrierTags.iterator();
while (it.hasNext()) {
if (this.currentBarriers.get((String) it.next()) != null) {
return false;
}
}
return true;
}
/**
* Check if there is active barriers
* @return true if there is no active barrier, false if there is at least one active barrier
*/
public boolean isCurrentBarriersEmpty() {
return (this.currentBarriers.size() == 0);
}
}
|
package org.pentaho.di.trans.steps.scriptvalues_mod;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.TreeEditor;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.ScriptOrFnNode;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.tools.ToolErrorReporter;
import org.pentaho.di.compatibility.Value;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.RowSet;
import org.pentaho.di.core.dialog.ErrorDialog;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.widget.ColumnInfo;
import org.pentaho.di.core.widget.StyledTextComp;
import org.pentaho.di.core.widget.TableView;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepDialog;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.RowListener;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMetaInterface;
public class ScriptValuesModDialog extends BaseStepDialog implements StepDialogInterface
{
private ModifyListener lsMod;
private SashForm wSash;
private FormData fdSash;
private Composite wTop, wBottom;
private FormData fdTop, fdBottom;
private Label wlScript;
private FormData fdlScript, fdScript;
private Label wSeparator;
private FormData fdSeparator;
private Label wlFields;
private TableView wFields;
private FormData fdlFields, fdFields;
private Label wlPosition;
private FormData fdlPosition;
private Text wlHelpLabel;
private Button wVars, wTest;
private Listener lsVars, lsTest;
// private Button wHelp;
private Label wlScriptFunctions;
private FormData fdlScriptFunctions;
private Tree wTree;
private TreeItem wTreeScriptsItem;
private TreeItem wTreeClassesitem;
private FormData fdlTree;
private Listener lsTree;
// private Listener lsHelp;
private FormData fdHelpLabel;
private Image imageActiveScript=null;
private Image imageInactiveScript=null;
private Image imageActiveStartScript=null;
private Image imageActiveEndScript=null;
private CTabFolder folder;
private Menu cMenu;
private Menu tMenu;
// Suport for Rename Tree
private TreeItem [] lastItem;
private TreeEditor editor;
private static final int DELETE_ITEM = 0;
private static final int ADD_ITEM = 1;
private static final int RENAME_ITEM = 2;
private static final int SET_ACTIVE_ITEM = 3;
private static final int ADD_COPY = 2;
private static final int ADD_BLANK = 1;
private static final int ADD_DEFAULT = 0;
private String strActiveScript;
private String strActiveStartScript;
private String strActiveEndScript;
private static String[] jsFunctionList = ScriptValuesAddedFunctions.jsFunctionList;
public final static int SKIP_TRANSFORMATION = 1;
private final static int ABORT_TRANSFORMATION = -1;
private final static int ERROR_TRANSFORMATION = -2;
private final static int CONTINUE_TRANSFORMATION = 0;
private ScriptValuesMetaMod input;
private ScriptValuesHelp scVHelp;
private ScriptValuesHighlight lineStyler = new ScriptValuesHighlight();
private Button wCompatible;
/**
* Dummy class used for test().
*/
public class ScriptValuesModDummy implements StepInterface
{
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
return false;
}
public void addRowListener(RowListener rowListener) {
}
public void dispose(StepMetaInterface sii, StepDataInterface sdi) {
}
public long getErrors() {
return 0;
}
public List<RowSet> getInputRowSets() {
return null;
}
public long getLinesInput() {
return 0;
}
public long getLinesOutput() {
return 0;
}
public long getLinesRead() {
return 0;
}
public long getLinesUpdated() {
return 0;
}
public long getLinesWritten() {
return 0;
}
public List<RowSet> getOutputRowSets() {
return null;
}
public String getPartitionID() {
return null;
}
public Object[] getRow() throws KettleException {
return null;
}
public List<RowListener> getRowListeners() {
return null;
}
public String getStepID() {
return null;
}
public String getStepname() {
return null;
}
public boolean init(StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface) {
return false;
}
public boolean isAlive() {
return false;
}
public boolean isPartitioned() {
return false;
}
public boolean isStopped() {
return false;
}
public void markStart() {
}
public void markStop() {
}
public void putRow(RowMetaInterface rowMeta, Object[] row) throws KettleException {
}
public void removeRowListener(RowListener rowListener) {
}
public void run() {
}
public void setErrors(long errors) {
}
public void setOutputDone() {
}
public void setPartitionID(String partitionID) {
}
public void start() {
}
public void stopAll() {
}
public void stopRunning(StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface) throws KettleException {
}
}
public ScriptValuesModDialog(Shell parent, Object in, TransMeta transMeta, String sname){
super(parent, (BaseStepMeta)in, transMeta, sname);
input=(ScriptValuesMetaMod)in;
try{
ImageLoader xl = new ImageLoader();
imageActiveScript = new Image(parent.getDisplay(),xl.load(this.getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"faScript.png"))[0]);
imageInactiveScript = new Image(parent.getDisplay(),xl.load(this.getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"fScript.png"))[0]);
imageActiveStartScript = new Image(parent.getDisplay(),xl.load(this.getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"sScript.png"))[0]);
imageActiveEndScript = new Image(parent.getDisplay(),xl.load(this.getClass().getResourceAsStream(Const.IMAGE_DIRECTORY+"eScript.png"))[0]);
}catch(Exception e){
imageActiveScript = new Image(parent.getDisplay(), 16, 16);
imageInactiveScript = new Image(parent.getDisplay(), 16, 16);
imageActiveStartScript = new Image(parent.getDisplay(), 16, 16);
imageActiveEndScript = new Image(parent.getDisplay(), 16, 16);
}
try
{
scVHelp = new ScriptValuesHelp("/be/ibridge/kettle/trans/step/scriptvalues_mod/jsFunctionHelp.xml");
}
catch (Exception e)
{
new ErrorDialog(shell, "Unexpected error", "There was an unexpected error reading the javascript functions help", e);
}
}
public String open(){
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
setShellImage(shell, input);
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("ScriptValuesDialogMod.Shell.Title")); //$NON-NLS-1$
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Filename line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(Messages.getString("ScriptValuesDialogMod.Stepname.Label")); //$NON-NLS-1$
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right= new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wSash = new SashForm(shell, SWT.VERTICAL );
props.setLook(wSash);
// Top sash form
wTop = new Composite(wSash, SWT.NONE);
props.setLook(wTop);
FormLayout topLayout = new FormLayout ();
topLayout.marginWidth = Const.FORM_MARGIN;
topLayout.marginHeight = Const.FORM_MARGIN;
wTop.setLayout(topLayout);
// Script line
wlScriptFunctions=new Label(wTop, SWT.NONE);
wlScriptFunctions.setText(Messages.getString("ScriptValuesDialogMod.JavascriptFunctions.Label")); //$NON-NLS-1$
props.setLook(wlScriptFunctions);
fdlScriptFunctions=new FormData();
fdlScriptFunctions.left = new FormAttachment(0, 0);
fdlScriptFunctions.top = new FormAttachment(0, 0);
wlScriptFunctions.setLayoutData(fdlScriptFunctions);
// Tree View Test
wTree = new Tree(wTop, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
props.setLook(wTree);
fdlTree=new FormData();
fdlTree.left = new FormAttachment(0, 0);
fdlTree.top = new FormAttachment(wlScriptFunctions, margin);
fdlTree.right = new FormAttachment(20, 0);
fdlTree.bottom = new FormAttachment(100, -margin);
wTree.setLayoutData(fdlTree);
// Script line
wlScript=new Label(wTop, SWT.NONE);
wlScript.setText(Messages.getString("ScriptValuesDialogMod.Javascript.Label")); //$NON-NLS-1$
props.setLook(wlScript);
fdlScript=new FormData();
fdlScript.left = new FormAttachment(wTree, margin);
fdlScript.top = new FormAttachment(0, 0);
wlScript.setLayoutData(fdlScript);
folder = new CTabFolder(wTop, SWT.BORDER | SWT.RESIZE);
folder.setSimple(false);
folder.setUnselectedImageVisible(true);
folder.setUnselectedCloseVisible(true);
fdScript=new FormData();
fdScript.left = new FormAttachment(wTree, margin);
fdScript.top = new FormAttachment(wlScript, margin);
fdScript.right = new FormAttachment(100, -5);
fdScript.bottom = new FormAttachment(100, -50);
folder.setLayoutData(fdScript);
wlPosition=new Label(wTop, SWT.NONE);
wlPosition.setText(Messages.getString("ScriptValuesDialogMod.Position.Label")); //$NON-NLS-1$
props.setLook(wlPosition);
fdlPosition=new FormData();
fdlPosition.left = new FormAttachment(wTree, margin);
fdlPosition.right = new FormAttachment(30, 0);
fdlPosition.top = new FormAttachment(folder, margin);
wlPosition.setLayoutData(fdlPosition);
Label wlCompatible = new Label(wTop, SWT.NONE);
wlCompatible.setText(Messages.getString("ScriptValuesDialogMod.Compatible.Label")); //$NON-NLS-1$
props.setLook(wlCompatible);
FormData fdlCompatible = new FormData();
fdlCompatible.left = new FormAttachment(wTree, margin);
fdlCompatible.right = new FormAttachment(middle, 0);
fdlCompatible.top = new FormAttachment(wlPosition, margin);
wlCompatible.setLayoutData(fdlCompatible);
wCompatible = new Button(wTop, SWT.CHECK);
props.setLook(wCompatible);
FormData fdCompatible = new FormData();
fdCompatible.left = new FormAttachment(wlCompatible, margin);
fdCompatible.top = new FormAttachment(wlPosition, margin);
wCompatible.setLayoutData(fdCompatible);
wlHelpLabel = new Text(wTop, SWT.V_SCROLL | SWT.LEFT);
wlHelpLabel.setEditable(false);
wlHelpLabel.setText("Hallo");
props.setLook(wlHelpLabel);
fdHelpLabel = new FormData();
fdHelpLabel.left = new FormAttachment(wlPosition, margin);
fdHelpLabel.top = new FormAttachment(folder, margin);
fdHelpLabel.right = new FormAttachment(100, -5);
fdHelpLabel.bottom = new FormAttachment(100,0);
wlHelpLabel.setLayoutData(fdHelpLabel);
wlHelpLabel.setVisible(false);
fdTop=new FormData();
fdTop.left = new FormAttachment(0, 0);
fdTop.top = new FormAttachment(0, 0);
fdTop.right = new FormAttachment(100, 0);
fdTop.bottom= new FormAttachment(100, 0);
wTop.setLayoutData(fdTop);
wBottom = new Composite(wSash, SWT.NONE);
props.setLook(wBottom);
FormLayout bottomLayout = new FormLayout ();
bottomLayout.marginWidth = Const.FORM_MARGIN;
bottomLayout.marginHeight = Const.FORM_MARGIN;
wBottom.setLayout(bottomLayout);
wSeparator = new Label(wBottom, SWT.SEPARATOR | SWT.HORIZONTAL);
fdSeparator= new FormData();
fdSeparator.left = new FormAttachment(0, 0);
fdSeparator.right = new FormAttachment(100, 0);
fdSeparator.top = new FormAttachment(0, -margin+2);
wSeparator.setLayoutData(fdSeparator);
wlFields=new Label(wBottom, SWT.NONE);
wlFields.setText(Messages.getString("ScriptValuesDialogMod.Fields.Label")); //$NON-NLS-1$
props.setLook(wlFields);
fdlFields=new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wSeparator, 0);
wlFields.setLayoutData(fdlFields);
final int FieldsRows=input.getName().length;
ColumnInfo[] colinf=new ColumnInfo[]
{
new ColumnInfo(Messages.getString("ScriptValuesDialogMod.ColumnInfo.Filename"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("ScriptValuesDialogMod.ColumnInfo.RenameTo"), ColumnInfo.COLUMN_TYPE_TEXT, false ), //$NON-NLS-1$
new ColumnInfo(Messages.getString("ScriptValuesDialogMod.ColumnInfo.Type"), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes() ), //$NON-NLS-1$
new ColumnInfo(Messages.getString("ScriptValuesDialogMod.ColumnInfo.Length"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("ScriptValuesDialogMod.ColumnInfo.Precision"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
};
wFields=new TableView(transMeta, wBottom,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(wlFields, margin);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom = new FormAttachment(100, 0);
wFields.setLayoutData(fdFields);
fdBottom=new FormData();
fdBottom.left = new FormAttachment(0, 0);
fdBottom.top = new FormAttachment(0, 0);
fdBottom.right = new FormAttachment(100, 0);
fdBottom.bottom= new FormAttachment(100, 0);
wBottom.setLayoutData(fdBottom);
fdSash = new FormData();
fdSash.left = new FormAttachment(0, 0);
fdSash.top = new FormAttachment(wStepname, 0);
fdSash.right = new FormAttachment(100, 0);
fdSash.bottom= new FormAttachment(100, -50);
wSash.setLayoutData(fdSash);
wSash.setWeights(new int[] {75,25});
wOK=new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK")); //$NON-NLS-1$
wVars=new Button(shell, SWT.PUSH);
wVars.setText(Messages.getString("ScriptValuesDialogMod.GetVariables.Button")); //$NON-NLS-1$
wTest=new Button(shell, SWT.PUSH);
wTest.setText(Messages.getString("ScriptValuesDialogMod.TestScript.Button")); //$NON-NLS-1$
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel")); //$NON-NLS-1$
setButtonPositions(new Button[] { wOK, wVars, wTest, wCancel }, margin, null);
// Add listeners
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
//lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsTest = new Listener() { public void handleEvent(Event e) { test(false, true); } };
lsVars = new Listener() { public void handleEvent(Event e) { test(true, true); } };
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsTree = new Listener() { public void handleEvent(Event e) { treeDblClick(e); } };
// lsHelp = new Listener(){public void handleEvent(Event e){ wlHelpLabel.setVisible(true); }};
wCancel.addListener(SWT.Selection, lsCancel);
//wGet.addListener (SWT.Selection, lsGet );
wTest.addListener (SWT.Selection, lsTest );
wVars.addListener (SWT.Selection, lsVars );
wOK.addListener (SWT.Selection, lsOK );
wTree.addListener(SWT.MouseDoubleClick, lsTree);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
folder.addCTabFolder2Listener(new CTabFolder2Adapter() {
public void close(CTabFolderEvent event) {
CTabItem cItem = (CTabItem)event.item;
event.doit=false;
if(cItem!=null && folder.getItemCount()>1){
MessageBox messageBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.NO | SWT.YES);
messageBox.setText("Delete Item");
messageBox.setMessage("Do you really want to delete "+cItem.getText() + "?");
switch(messageBox.open()){
case SWT.YES:
modifyScriptTree(cItem,DELETE_ITEM);
event.doit=true;
break;
}
}
}
});
cMenu = new Menu(shell, SWT.POP_UP);
buildingFolderMenu();
tMenu = new Menu(shell, SWT.POP_UP);
buildingTreeMenu();
// Adding the Default Transform Scripts Item to the Tree
wTreeScriptsItem = new TreeItem(wTree, SWT.NULL);
wTreeScriptsItem.setText("Transform Scripts");
// Set the shell size, based upon previous time...
setSize();
getData();
// Adding the Rest (Functions, InputItems, etc.) to the Tree
buildSpecialFunctionsTree();
buildInputFieldsTree();
buildOutputFieldsTree();
buildAddClassesListTree();
addRenameTowTreeScriptItems();
input.setChanged(changed);
// Create the drag source on the tree
DragSource ds = new DragSource(wTree, DND.DROP_MOVE);
ds.setTransfer(new Transfer[] { TextTransfer.getInstance() });
ds.addDragListener(new DragSourceAdapter() {
public void dragStart(DragSourceEvent event) {
TreeItem item = wTree.getSelection()[0];
// Qualifikation where the Drag Request Comes from
if(item !=null && item.getParentItem()!=null){
if(item.getParentItem().equals(wTreeScriptsItem)){
event.doit=false;
}else if(!item.getData().equals("Function")){
String strInsert =(String)item.getData();
if(strInsert.equals("jsFunction")) event.doit=true;
else event.doit=false;
}else{
event.doit=false;
}
}else{
event.doit=false;
}
}
public void dragSetData(DragSourceEvent event) {
// Set the data to be the first selected item's text
event.data = wTree.getSelection()[0].getText();
}
});
shell.open();
while (!shell.isDisposed()){
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
private void setActiveCtab(String strName){
if(strName.length()==0){
folder.setSelection(0);
}
else folder.setSelection(getCTabPosition(strName));
}
private void addCtab(String cScriptName, String strScript, int iType){
CTabItem item = new CTabItem(folder, SWT.CLOSE);
switch(iType){
case ADD_DEFAULT: item.setText(cScriptName);
break;
default:
item.setText(getNextName(cScriptName));
break;
}
StyledTextComp wScript=new StyledTextComp(item.getParent(), SWT.MULTI | SWT.LEFT | SWT.H_SCROLL | SWT.V_SCROLL, item.getText());
if(strScript.length()>0) wScript.setText(strScript);
else wScript.setText("//Script here");
item.setImage(imageInactiveScript);
props.setLook(wScript, Props.WIDGET_STYLE_FIXED);
wScript.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e) { setPosition(); }
public void keyReleased(KeyEvent e) { setPosition(); }
}
);
wScript.addFocusListener(new FocusAdapter(){
public void focusGained(FocusEvent e) { setPosition(); }
public void focusLost(FocusEvent e) { setPosition(); }
}
);
wScript.addMouseListener(new MouseAdapter(){
public void mouseDoubleClick(MouseEvent e) { setPosition(); }
public void mouseDown(MouseEvent e) { setPosition(); }
public void mouseUp(MouseEvent e) { setPosition(); }
}
);
wScript.addModifyListener(lsMod);
// Text Higlighting
lineStyler = new ScriptValuesHighlight(ScriptValuesAddedFunctions.jsFunctionList);
wScript.addLineStyleListener(lineStyler);
item.setControl(wScript);
// Adding new Item to Tree
modifyScriptTree(item, ADD_ITEM );
}
private void modifyScriptTree(CTabItem ctabitem, int iModType){
switch(iModType){
case DELETE_ITEM :
TreeItem dItem = getTreeItemByName(ctabitem.getText());
if(dItem!=null){
dItem.dispose();
input.setChanged();
}
break;
case ADD_ITEM :
TreeItem item = new TreeItem(wTreeScriptsItem, SWT.NULL);
item.setText(ctabitem.getText());
input.setChanged();
break;
case RENAME_ITEM :
input.setChanged();
break;
case SET_ACTIVE_ITEM :
input.setChanged();
break;
}
}
private TreeItem getTreeItemByName(String strTabName){
TreeItem[] tItems = wTreeScriptsItem.getItems();
for(int i=0;i<tItems.length;i++){
if(tItems[i].getText().equals(strTabName)) return tItems[i];
}
return null;
}
private int getCTabPosition(String strTabName){
CTabItem[] cItems = folder.getItems();
for(int i=0;i<cItems.length;i++){
if(cItems[i].getText().equals(strTabName)) return i;
}
return -1;
}
private CTabItem getCTabItemByName(String strTabName){
CTabItem[] cItems = folder.getItems();
for(int i=0;i<cItems.length;i++){
if(cItems[i].getText().equals(strTabName)) return cItems[i];
}
return null;
}
private void modifyCTabItem(TreeItem tItem, int iModType, String strOption){
switch(iModType){
case DELETE_ITEM :
CTabItem dItem = folder.getItem(getCTabPosition(tItem.getText()));
if(dItem!=null){
dItem.dispose();
input.setChanged();
}
break;
case RENAME_ITEM :
CTabItem rItem = folder.getItem(getCTabPosition(tItem.getText()));
if(rItem!=null){
rItem.setText(strOption);
input.setChanged();
if(rItem.getImage().equals(imageActiveScript)) strActiveScript = strOption;
else if(rItem.getImage().equals(imageActiveStartScript)) strActiveStartScript = strOption;
else if(rItem.getImage().equals(imageActiveEndScript)) strActiveEndScript = strOption;
}
break;
case SET_ACTIVE_ITEM :
CTabItem aItem = folder.getItem(getCTabPosition(tItem.getText()));
if(aItem!=null){
input.setChanged();
strActiveScript = tItem.getText();
for(int i=0;i<folder.getItemCount();i++){
if(folder.getItem(i).equals(aItem))aItem.setImage(imageActiveScript);
else folder.getItem(i).setImage(imageInactiveScript);
}
}
break;
}
}
private StyledTextComp getStyledTextComp(){
CTabItem item = folder.getSelection();
if(item.getControl().isDisposed()) return null;
else return (StyledTextComp)item.getControl();
}
private StyledTextComp getStyledTextComp(CTabItem item){
return (StyledTextComp)item.getControl();
}
/*
private void setStyledTextComp(String strText){
CTabItem item = folder.getSelection();
((StyledTextComp)item.getControl()).setText(strText);
}
private void setStyledTextComp(String strText, CTabItem item){
((StyledTextComp)item.getControl()).setText(strText);
}
*/
private String getNextName(String strActualName){
String strRC = "";
if(strActualName.length()==0){
strActualName = "Item";
}
int i=0;
strRC = strActualName + "_" + i;
while(getCTabItemByName(strRC)!=null){
i++;
strRC = strActualName + "_" + i;
}
return strRC;
}
public void setPosition(){
StyledTextComp wScript = getStyledTextComp();
String scr = wScript.getText();
int linenr = wScript.getLineAtOffset(wScript.getCaretOffset())+1;
int posnr = wScript.getCaretOffset();
// Go back from position to last CR: how many positions?
int colnr=0;
while (posnr>0 && scr.charAt(posnr-1)!='\n' && scr.charAt(posnr-1)!='\r')
{
posnr
colnr++;
}
wlPosition.setText(Messages.getString("ScriptValuesDialogMod.Position.Label2")+linenr+", "+colnr); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
wCompatible.setSelection(input.isCompatible());
for (int i=0;i<input.getName().length;i++)
{
if (input.getName()[i]!=null && input.getName()[i].length()>0)
{
TableItem item = wFields.table.getItem(i);
item.setText(1, input.getName()[i]);
if (input.getRename()[i]!=null && !input.getName()[i].equals(input.getRename()[i]))
item.setText(2, input.getRename()[i]);
item.setText(3, ValueMeta.getTypeDesc(input.getType()[i]));
if (input.getLength()[i]>=0) item.setText(4, ""+input.getLength()[i]); //$NON-NLS-1$
if (input.getPrecision()[i]>=0) item.setText(5, ""+input.getPrecision()[i]); //$NON-NLS-1$
}
}
ScriptValuesScript[] jsScripts = input.getJSScripts();
if(jsScripts.length>0){
for(int i=0;i<jsScripts.length;i++){
if(jsScripts[i].isTransformScript()) strActiveScript =jsScripts[i].getScriptName();
else if(jsScripts[i].isStartScript()) strActiveStartScript =jsScripts[i].getScriptName();
else if(jsScripts[i].isEndScript()) strActiveEndScript =jsScripts[i].getScriptName();
addCtab(jsScripts[i].getScriptName(), jsScripts[i].getScript(), ADD_DEFAULT);
}
}else{
addCtab("", "", ADD_DEFAULT);
}
setActiveCtab(strActiveScript);
refresh();
wFields.setRowNums();
wFields.optWidth(true);
wStepname.selectAll();
}
// Setting default active Script
private void refresh(){
//CTabItem item = getCTabItemByName(strActiveScript);
for(int i=0;i<folder.getItemCount();i++){
CTabItem item = folder.getItem(i);
if(item.getText().equals(strActiveScript))item.setImage(imageActiveScript);
else if(item.getText().equals(strActiveStartScript))item.setImage(imageActiveStartScript);
else if(item.getText().equals(strActiveEndScript))item.setImage(imageActiveEndScript);
else item.setImage(imageInactiveScript);
}
//modifyScriptTree(null, SET_ACTIVE_ITEM);
}
private void refreshScripts(){
CTabItem[] cTabs = folder.getItems();
for(int i =0;i<cTabs.length;i++){
if(cTabs[i].getImage().equals(imageActiveStartScript)) strActiveStartScript = cTabs[i].getText();
else if(cTabs[i].getImage().equals(imageActiveEndScript)) strActiveEndScript = cTabs[i].getText();
}
}
private void cancel(){
stepname=null;
input.setChanged(changed);
dispose();
}
private void ok()
{
stepname = wStepname.getText(); // return value
boolean bInputOK = false;
// Check if Active Script has set, otherwise Ask
if(getCTabItemByName(strActiveScript)==null){
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.CANCEL | SWT.ICON_ERROR );
mb.setMessage("No active Script has been set! Should the first tab set as acitve Script?");
mb.setText("ERROR"); //$NON-NLS-1$
switch(mb.open()){
case SWT.OK:
strActiveScript = folder.getItem(0).getText();
refresh();
bInputOK = true;
break;
case SWT.CANCEL: bInputOK = false;
break;
}
}else{
bInputOK = true;
}
if(bInputOK){
//StyledTextComp wScript = getStyledTextComp();
input.setCompatible( wCompatible.getSelection() );
int nrfields = wFields.nrNonEmpty();
input.allocate(nrfields);
for (int i=0;i<nrfields;i++){
TableItem item = wFields.getNonEmpty(i);
input.getName() [i] = item.getText(1);
input.getRename()[i] = item.getText(2);
if (input.getRename()[i]==null ||
input.getRename()[i].length()==0 ||
input.getRename()[i].equalsIgnoreCase(input.getName()[i])
)
{
input.getRename()[i] = input.getName()[i];
}
input.getType() [i] = ValueMeta.getType(item.getText(3));
String slen = item.getText(4);
String sprc = item.getText(5);
input.getLength() [i]=Const.toInt(slen, -1);
input.getPrecision()[i]=Const.toInt(sprc, -1);
}
//input.setActiveJSScript(strActiveScript);
CTabItem[] cTabs = folder.getItems();
if(cTabs.length>0){
ScriptValuesScript[] jsScripts = new ScriptValuesScript[cTabs.length];
for(int i=0;i<cTabs.length;i++){
ScriptValuesScript jsScript = new ScriptValuesScript(
ScriptValuesScript.NORMAL_SCRIPT,
cTabs[i].getText(),
getStyledTextComp(cTabs[i]).getText()
);
if(cTabs[i].getImage().equals(imageActiveScript)) jsScript.setScriptType(ScriptValuesScript.TRANSFORM_SCRIPT);
else if(cTabs[i].getImage().equals(imageActiveStartScript)) jsScript.setScriptType(ScriptValuesScript.START_SCRIPT);
else if(cTabs[i].getImage().equals(imageActiveEndScript)) jsScript.setScriptType(ScriptValuesScript.END_SCRIPT);
jsScripts[i] = jsScript;
}
input.setJSScripts(jsScripts);
}
dispose();
}
}
public boolean test()
{
return test(false, false);
}
private boolean test(boolean getvars, boolean popup)
{
boolean retval=true;
StyledTextComp wScript = getStyledTextComp();
String scr = wScript.getText();
String errorMessage = ""; //$NON-NLS-1$
Context jscx;
Scriptable jsscope;
// Script jsscript;
// Making Refresh to get Active Script State
refreshScripts();
jscx = Context.enter();
jscx.setOptimizationLevel(-1);
jsscope = jscx.initStandardObjects(null);
// Adding the existing Scripts to the Context
for(int i=0;i<folder.getItemCount();i++){
StyledTextComp sItem = getStyledTextComp(folder.getItem(i));
Scriptable jsR = Context.toObject(sItem.getText(), jsscope);
jsscope.put(folder.getItem(i).getText(), jsscope, jsR); //$NON-NLS-1$
}
// Adding the Name of the Transformation to the Context
jsscope.put("_TransformationName_", jsscope, new String(this.stepname));
ScriptValuesModDummy dummyStep = new ScriptValuesModDummy();
Scriptable jsvalue = Context.toObject(dummyStep, jsscope);
jsscope.put("_step_", jsscope, jsvalue); //$NON-NLS-1$
try{
RowMetaInterface row = transMeta.getPrevStepFields(stepname);
if (row!=null){
// Modification for Additional Script parsing
try{
if (input.getAddClasses()!=null)
{
for(int i=0;i<input.getAddClasses().length;i++){
Object jsOut = Context.javaToJS(input.getAddClasses()[i].getAddObject(), jsscope);
ScriptableObject.putProperty(jsscope, input.getAddClasses()[i].getJSName(), jsOut);
}
}
}catch(Exception e){
errorMessage="Couldn't add JavaClasses to Context! Error:"+Const.CR+e.toString(); //$NON-NLS-1$
retval = false;
}
// Adding some default JavaScriptFunctions to the System
try {
Context.javaToJS(ScriptValuesAddedFunctions.class, jsscope);
((ScriptableObject)jsscope).defineFunctionProperties(jsFunctionList, ScriptValuesAddedFunctions.class, ScriptableObject.DONTENUM);
} catch (Exception ex) {
errorMessage="Couldn't add Default Functions! Error:"+Const.CR+ex.toString(); //$NON-NLS-1$
retval = false;
};
// Adding some Constants to the JavaScript
try {
jsscope.put("SKIP_TRANSFORMATION", jsscope, new Integer(SKIP_TRANSFORMATION));
jsscope.put("ABORT_TRANSFORMATION", jsscope, new Integer(ABORT_TRANSFORMATION));
jsscope.put("ERROR_TRANSFORMATION", jsscope, new Integer(ERROR_TRANSFORMATION));
jsscope.put("CONTINUE_TRANSFORMATION", jsscope, new Integer(CONTINUE_TRANSFORMATION));
} catch (Exception ex) {
errorMessage="Couldn't add Transformation Constants! Error:"+Const.CR+ex.toString(); //$NON-NLS-1$
retval = false;
};
try{
Scriptable jsrow = Context.toObject(row, jsscope);
jsscope.put("row", jsscope, jsrow); //$NON-NLS-1$
for (int i=0;i<row.size();i++)
{
ValueMetaInterface valueMeta = row.getValueMeta(i);
Object valueData = null;
// Set date and string values to something to simulate real thing
if (valueMeta.isDate()) valueData = new Date();
if (valueMeta.isString()) valueData = "test value test value test value test value test value test value test value test value test value test value"; //$NON-NLS-1$
if (valueMeta.isInteger()) valueData = new Long(0L);
if (valueMeta.isNumber()) valueData = new Double(0.0);
if (valueMeta.isBigNumber()) valueData = new BigDecimal(0.0);
if (valueMeta.isBoolean()) valueData = new Boolean(true);
if (valueMeta.isBinary()) valueData = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, };
if (wCompatible.getSelection()) {
Value value = valueMeta.createOriginalValue(valueData);
Scriptable jsarg = Context.toObject(value, jsscope);
jsscope.put(valueMeta.getName(), jsscope, jsarg);
}
else {
Scriptable jsarg = Context.toObject(valueData, jsscope);
jsscope.put(valueMeta.getName(), jsscope, jsarg);
}
}
// Add support for Value class (new Value())
Scriptable jsval = Context.toObject(Value.class, jsscope);
jsscope.put("Value", jsscope, jsval); //$NON-NLS-1$
}catch(Exception ev){
errorMessage="Couldn't add Input fields to Script! Error:"+Const.CR+ev.toString(); //$NON-NLS-1$
retval = false;
}
try{
// Checking for StartScript
if(strActiveStartScript != null && !folder.getSelection().getText().equals(strActiveStartScript) && strActiveStartScript.length()>0){
String strStartScript = getStyledTextComp(folder.getItem(getCTabPosition(strActiveStartScript))).getText();
/* Object startScript = */ jscx.evaluateString(jsscope, strStartScript, "trans_Start", 1, null);
}
}catch(Exception e){
errorMessage="Couldn't process Start Script! Error:"+Const.CR+e.toString(); //$NON-NLS-1$
retval = false;
};
try{
Script evalScript = jscx.compileString(scr, "script", 1, null);
evalScript.exec(jscx, jsscope);
//Object tranScript = jscx.evaluateString(jsscope, scr, "script", 1, null);
if (getvars){
ScriptOrFnNode tree = parseVariables(jscx, jsscope, scr, "script", 1, null);
for (int i=0;i<tree.getParamAndVarCount();i++){
String varname = tree.getParamOrVarName(i);
if (!varname.equalsIgnoreCase("row") && !varname.equalsIgnoreCase("trans_Status") && row.indexOfValue(varname)<0){
int type=ValueMetaInterface.TYPE_STRING;
int length=-1, precision=-1;
Object result = jsscope.get(varname, jsscope);
if (result!=null){
String classname = result.getClass().getName();
if (classname.equalsIgnoreCase("java.lang.Byte")){
// MAX = 127
type=ValueMetaInterface.TYPE_INTEGER;
length=3;
precision=0;
}else if (classname.equalsIgnoreCase("java.lang.Integer")){
// MAX = 2147483647
type=ValueMetaInterface.TYPE_INTEGER;
length=9;
precision=0;
}else if (classname.equalsIgnoreCase("java.lang.Long")){
// MAX = 9223372036854775807
type=ValueMetaInterface.TYPE_INTEGER;
length=18;
precision=0;
}else if (classname.equalsIgnoreCase("java.lang.Double")){
type=ValueMetaInterface.TYPE_NUMBER;
length=16;
precision=2;
}else if (classname.equalsIgnoreCase("org.mozilla.javascript.NativeDate") || classname.equalsIgnoreCase("java.util.Date")){
type=ValueMetaInterface.TYPE_DATE;
}else if (classname.equalsIgnoreCase("java.lang.Boolean")){
type=ValueMetaInterface.TYPE_BOOLEAN;
}
}
TableItem ti = new TableItem(wFields.table, SWT.NONE);
ti.setText(1, varname);
ti.setText(2, varname);
ti.setText(3, ValueMeta.getTypeDesc(type));
ti.setText(4, ""+length); //$NON-NLS-1$
ti.setText(5, ""+precision); //$NON-NLS-1$
}
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth(true);
}
// End Script!
}
catch(JavaScriptException jse){
errorMessage=Messages.getString("ScriptValuesDialogMod.Exception.CouldNotExecuteScript")+Const.CR+jse.toString(); //$NON-NLS-1$
retval=false;
}
catch(Exception e){
errorMessage=Messages.getString("ScriptValuesDialogMod.Exception.CouldNotExecuteScript2")+Const.CR+e.toString(); //$NON-NLS-1$
retval=false;
}
}else{
errorMessage = Messages.getString("ScriptValuesDialogMod.Exception.CouldNotGetFields"); //$NON-NLS-1$
retval=false;
}
if (popup){
if (retval){
if (!getvars){
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage("This script compiled without problems."+Const.CR); //$NON-NLS-1$
mb.setText("OK"); //$NON-NLS-1$
mb.open();
}
}else{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(errorMessage);
mb.setText("ERROR"); //$NON-NLS-1$
mb.open();
}
}
}catch(KettleException ke){
retval=false;
new ErrorDialog(shell, Messages.getString("ScriptValuesDialogMod.TestFailed.DialogTitle"), Messages.getString("ScriptValuesDialogMod.TestFailed.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}finally{
if (jscx!=null) Context.exit();
}
return retval;
}
public String toString(){
return this.getClass().getName();
}
private void buildSpecialFunctionsTree(){
TreeItem item = new TreeItem(wTree, SWT.NULL);
item.setText("Transform Constants");
TreeItem itemT = new TreeItem(item, SWT.NULL);
itemT.setText("SKIP_TRANSFORMATION");
itemT.setData("SKIP_TRANSFORMATION");
//itemT = new TreeItem(item, SWT.NULL);
//itemT.setText("ABORT_TRANSFORMATION");
//itemT.setData("ABORT_TRANSFORMATION");
itemT = new TreeItem(item, SWT.NULL);
itemT.setText("ERROR_TRANSFORMATION");
itemT.setData("ERROR_TRANSFORMATION");
itemT = new TreeItem(item, SWT.NULL);
itemT.setText("CONTINUE_TRANSFORMATION");
itemT.setData("CONTINUE_TRANSFORMATION");
item = new TreeItem(wTree, SWT.NULL);
item.setText("Transform Functions");
String strData = "";
// Adding the Grouping Items to the Tree
TreeItem itemStringFunctionsGroup = new TreeItem(item, SWT.NULL);
itemStringFunctionsGroup.setText("String Functions");
itemStringFunctionsGroup.setData("Function");
TreeItem itemNumericFunctionsGroup = new TreeItem(item, SWT.NULL);
itemNumericFunctionsGroup.setText("Numeric Functions");
itemNumericFunctionsGroup.setData("Function");
TreeItem itemDateFunctionsGroup = new TreeItem(item, SWT.NULL);
itemDateFunctionsGroup.setText("Date Functions");
itemDateFunctionsGroup.setData("Function");
TreeItem itemLogicFunctionsGroup = new TreeItem(item, SWT.NULL);
itemLogicFunctionsGroup.setText("Logic Functions");
itemLogicFunctionsGroup.setData("Function");
TreeItem itemSpecialFunctionsGroup = new TreeItem(item, SWT.NULL);
itemSpecialFunctionsGroup.setText("Special Functions");
itemSpecialFunctionsGroup.setData("Function");
// Loading the Default delivered JScript Functions
//Method[] methods = ScriptValuesAddedFunctions.class.getMethods();
//String strClassType = ScriptValuesAddedFunctions.class.toString();
Hashtable<String, String> hatFunctions =scVHelp.getFunctionList();
Vector<String> v = new Vector<String>(hatFunctions.keySet());
Collections.sort(v);
for (String strFunction : v) {
String strFunctionType =(String)hatFunctions.get(strFunction);
int iFunctionType = Integer.valueOf(strFunctionType).intValue();
TreeItem itemFunction=null;
switch(iFunctionType){
case ScriptValuesAddedFunctions.STRING_FUNCTION: itemFunction = new TreeItem(itemStringFunctionsGroup,SWT.NULL); break;
case ScriptValuesAddedFunctions.NUMERIC_FUNCTION:itemFunction = new TreeItem(itemNumericFunctionsGroup,SWT.NULL); break;
case ScriptValuesAddedFunctions.DATE_FUNCTION:itemFunction = new TreeItem(itemDateFunctionsGroup,SWT.NULL); break;
case ScriptValuesAddedFunctions.LOGIC_FUNCTION:itemFunction = new TreeItem(itemLogicFunctionsGroup,SWT.NULL); break;
case ScriptValuesAddedFunctions.SPECIAL_FUNCTION:itemFunction = new TreeItem(itemSpecialFunctionsGroup,SWT.NULL); break;
}
if(itemFunction !=null){
itemFunction.setText(strFunction);
strData = "jsFunction";
itemFunction.setData(strData);
}
}
}
public boolean TreeItemExist(TreeItem itemToCheck, String strItemName){
boolean bRC=false;
if(itemToCheck.getItemCount()>0){
TreeItem[] items = itemToCheck.getItems();
for(int i=0;i<items.length;i++){
if(items[i].getText().equals(strItemName)) return true;
}
}
return bRC;
}
private void buildOutputFieldsTree(){
try{
RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if (r!=null){
TreeItem item = new TreeItem(wTree, SWT.NULL);
item.setText("Output Fields");
String strItemToAdd="";
for (int i=0;i<r.size();i++){
ValueMetaInterface v = r.getValueMeta(i);
switch(v.getType()){
case ValueMetaInterface.TYPE_STRING :
case ValueMetaInterface.TYPE_NUMBER :
case ValueMetaInterface.TYPE_INTEGER:
case ValueMetaInterface.TYPE_DATE :
case ValueMetaInterface.TYPE_BOOLEAN:
strItemToAdd=v.getName()+".setValue(var)"; break; //$NON-NLS-1$
default: strItemToAdd=v.getName(); break;
}
TreeItem itemInputFields = new TreeItem(item, SWT.NULL);
itemInputFields.setText(strItemToAdd);
itemInputFields.setData(strItemToAdd);
}
}
}catch(KettleException ke){
new ErrorDialog(shell, Messages.getString("ScriptValuesDialogMod.FailedToGetFields.DialogTitle"), Messages.getString("ScriptValuesDialogMod.FailedToGetFields.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void buildInputFieldsTree(){
try{
RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if (r!=null){
TreeItem item = new TreeItem(wTree, SWT.NULL);
item.setText("Input Fields");
String strItemToAdd="";
for (int i=0;i<r.size();i++){
ValueMetaInterface v = r.getValueMeta(i);
switch(v.getType()){
case ValueMetaInterface.TYPE_STRING : strItemToAdd=v.getName()+".getString()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_NUMBER : strItemToAdd=v.getName()+".getNumber()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_INTEGER: strItemToAdd=v.getName()+".getInteger()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_DATE : strItemToAdd=v.getName()+".getDate()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_BOOLEAN: strItemToAdd=v.getName()+".getBoolean()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_BIGNUMBER: strItemToAdd=v.getName()+".getBigNumber()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_BINARY: strItemToAdd=v.getName()+".getBytes()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_SERIALIZABLE: strItemToAdd=v.getName()+".getSerializable()"; break; //$NON-NLS-1$
default: strItemToAdd=v.getName(); break;
}
TreeItem itemInputFields = new TreeItem(item, SWT.NULL);
itemInputFields.setText(strItemToAdd);
itemInputFields.setData(strItemToAdd);
}
}
}catch(KettleException ke){
new ErrorDialog(shell, Messages.getString("ScriptValuesDialogMod.FailedToGetFields.DialogTitle"), Messages.getString("ScriptValuesDialogMod.FailedToGetFields.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Adds the Current item to the current Position
private void treeDblClick(Event event){
StyledTextComp wScript = getStyledTextComp();
Point point = new Point(event.x, event.y);
TreeItem item = wTree.getItem(point);
// Qualifikation where the Click comes from
if(item !=null && item.getParentItem()!=null){
if(item.getParentItem().equals(wTreeScriptsItem)){
setActiveCtab(item.getText());
}else if(!item.getData().equals("Function")){
int iStart = wScript.getCaretOffset();
String strInsert =(String)item.getData();
if(strInsert.equals("jsFunction")) strInsert = (String)item.getText();
wScript.insert(strInsert);
wScript.setSelection(iStart,iStart+strInsert.length());
}
}
/*
if (item != null && item.getParentItem()!=null && !item.getData().equals("Function")) {
int iStart = wScript.getCaretOffset();
String strInsert =(String)item.getData();
if(strInsert.equals("jsFunction")) strInsert = (String)item.getText();
wScript.insert(strInsert);
wScript.setSelection(iStart,iStart+strInsert.length());
}*/
}
// Building the Tree for Additional Classes
private void buildAddClassesListTree(){
if(wTreeClassesitem!=null){
wTreeClassesitem.dispose();
}
if (input.getAddClasses()!=null)
{
for(int i=0;i<input.getAddClasses().length;i++){
//System.out.println(input.getAddClasses().length);
try{
Method[] methods = input.getAddClasses()[i].getAddClass().getMethods();
String strClassType = input.getAddClasses()[i].getAddClass().toString();
String strParams;
wTreeClassesitem = new TreeItem(wTree, SWT.NULL);
wTreeClassesitem.setText(input.getAddClasses()[i].getJSName());
for (int j=0; j<methods.length; j++){
String strDeclaringClass = methods[j].getDeclaringClass().toString();
if(strClassType.equals(strDeclaringClass)){
TreeItem item2 = new TreeItem(wTreeClassesitem, SWT.NULL);
strParams = buildAddClassFunctionName(methods[j]);
item2.setText(methods[j].getName() + "("+ strParams +")");
String strData = input.getAddClasses()[i].getJSName() + "." +methods[j].getName() + "("+strParams+")";
item2.setData(strData);
}
}
}
catch(Exception e){
}
}
}
}
private String buildAddClassFunctionName(Method metForParams){
StringBuffer sbRC = new StringBuffer();
String strRC = "";
Class<?>[] clsParamType = metForParams.getParameterTypes();
String strParam;
for(int x=0;x<clsParamType.length;x++){
strParam = clsParamType[x].getName();
if(strParam.toLowerCase().indexOf("javascript")>0){
}else if(strParam.toLowerCase().indexOf("object")>0){
sbRC.append("var");
sbRC.append(", ");
}else if(strParam.equals("java.lang.String")){
sbRC.append("String");
sbRC.append(", ");
}else{
sbRC.append(strParam);
sbRC.append(", ");
}
}
strRC = sbRC.toString();
if(strRC.length()>0) strRC = strRC.substring(0,sbRC.length()-2);
return strRC;
}
private void buildingFolderMenu(){
//styledTextPopupmenu = new Menu(, SWT.POP_UP);
MenuItem addNewItem = new MenuItem(cMenu, SWT.PUSH);
addNewItem.setText("Add New");
addNewItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
addCtab("","", ADD_BLANK);
}
});
MenuItem copyItem = new MenuItem(cMenu, SWT.PUSH);
copyItem.setText("Add Copy");
copyItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
StyledTextComp st = (StyledTextComp)item.getControl();
addCtab(item.getText(),st.getText(), ADD_COPY);
}
});
new MenuItem(cMenu, SWT.SEPARATOR);
MenuItem setActiveScriptItem = new MenuItem(cMenu, SWT.PUSH);
setActiveScriptItem.setText("Set Transform Script");
setActiveScriptItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
for(int i=0;i<folder.getItemCount();i++){
if(folder.getItem(i).equals(item)){
if(item.getImage().equals(imageActiveScript)) strActiveScript="";
else if(item.getImage().equals(imageActiveStartScript)) strActiveStartScript="";
else if(item.getImage().equals(imageActiveEndScript)) strActiveEndScript="";
item.setImage(imageActiveScript);
strActiveScript = item.getText();
}
else if(folder.getItem(i).getImage().equals(imageActiveScript)){
folder.getItem(i).setImage(imageInactiveScript);
}
}
modifyScriptTree(item, SET_ACTIVE_ITEM);
}
});
MenuItem setStartScriptItem = new MenuItem(cMenu, SWT.PUSH);
setStartScriptItem.setText("Set Start Script");
setStartScriptItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
for(int i=0;i<folder.getItemCount();i++){
if(folder.getItem(i).equals(item)){
if(item.getImage().equals(imageActiveScript)) strActiveScript="";
else if(item.getImage().equals(imageActiveStartScript)) strActiveStartScript="";
else if(item.getImage().equals(imageActiveEndScript)) strActiveEndScript="";
item.setImage(imageActiveStartScript);
strActiveStartScript = item.getText();
}
else if(folder.getItem(i).getImage().equals(imageActiveStartScript)){
folder.getItem(i).setImage(imageInactiveScript);
}
}
modifyScriptTree(item, SET_ACTIVE_ITEM);
}
});
MenuItem setEndScriptItem = new MenuItem(cMenu, SWT.PUSH);
setEndScriptItem.setText("Set End Script");
setEndScriptItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
for(int i=0;i<folder.getItemCount();i++){
if(folder.getItem(i).equals(item)){
if(item.getImage().equals(imageActiveScript)) strActiveScript="";
else if(item.getImage().equals(imageActiveStartScript)) strActiveStartScript="";
else if(item.getImage().equals(imageActiveEndScript)) strActiveEndScript="";
item.setImage(imageActiveEndScript);
strActiveEndScript = item.getText();
}
else if(folder.getItem(i).getImage().equals(imageActiveEndScript)){
folder.getItem(i).setImage(imageInactiveScript);
}
}
modifyScriptTree(item, SET_ACTIVE_ITEM);
}
});
new MenuItem(cMenu, SWT.SEPARATOR);
MenuItem setRemoveScriptItem = new MenuItem(cMenu, SWT.PUSH);
setRemoveScriptItem.setText("Remove Script Type");
setRemoveScriptItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
input.setChanged(true);
if(item.getImage().equals(imageActiveScript)) strActiveScript="";
else if(item.getImage().equals(imageActiveStartScript)) strActiveStartScript="";
else if(item.getImage().equals(imageActiveEndScript)) strActiveEndScript="";
item.setImage(imageInactiveScript);
}
});
folder.setMenu(cMenu);
}
private void buildingTreeMenu(){
//styledTextPopupmenu = new Menu(, SWT.POP_UP);
MenuItem addDeleteItem = new MenuItem(tMenu, SWT.PUSH);
addDeleteItem.setText("Delete");
addDeleteItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
TreeItem tItem = wTree.getSelection()[0];
if(tItem!=null){
MessageBox messageBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.NO | SWT.YES);
messageBox.setText("Delete Item");
messageBox.setMessage("Do you really want to delete "+tItem.getText() + "?");
switch(messageBox.open()){
case SWT.YES:
modifyCTabItem(tItem,DELETE_ITEM,"");
tItem.dispose();
input.setChanged();
break;
}
}
}
});
MenuItem renItem = new MenuItem(tMenu, SWT.PUSH);
renItem.setText("Rename");
renItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
renameFunction(wTree.getSelection()[0]);
}
});
new MenuItem(tMenu, SWT.SEPARATOR);
MenuItem helpItem = new MenuItem(tMenu, SWT.PUSH);
helpItem.setText("Sample");
helpItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
String strFunctionName = wTree.getSelection()[0].getText();
String strFunctionNameWithArgs = strFunctionName;
strFunctionName = strFunctionName.substring(0,strFunctionName.indexOf('('));
String strHelpTabName = strFunctionName + "_Sample";
if(getCTabPosition(strHelpTabName)==-1)
addCtab(strHelpTabName, scVHelp.getSample(strFunctionName,strFunctionNameWithArgs), 0);
if(getCTabPosition(strHelpTabName)!=-1)
setActiveCtab(strHelpTabName);
}
});
wTree.addListener(SWT.MouseDown, new Listener(){
public void handleEvent(Event e){
TreeItem tItem = wTree.getSelection()[0];
if(tItem != null){
TreeItem pItem = tItem.getParentItem();
if(pItem !=null && pItem.equals(wTreeScriptsItem)){
if(folder.getItemCount()>1) tMenu.getItem(0).setEnabled(true);
else tMenu.getItem(0).setEnabled(false);
tMenu.getItem(1).setEnabled(true);
tMenu.getItem(3).setEnabled(false);
}else if(tItem.equals(wTreeClassesitem)){
tMenu.getItem(0).setEnabled(false);
tMenu.getItem(1).setEnabled(false);
tMenu.getItem(3).setEnabled(false);
}else if(tItem.getData() != null && tItem.getData().equals("jsFunction")){
tMenu.getItem(0).setEnabled(false);
tMenu.getItem(1).setEnabled(false);
tMenu.getItem(3).setEnabled(true);
}else{
tMenu.getItem(0).setEnabled(false);
tMenu.getItem(1).setEnabled(false);
tMenu.getItem(3).setEnabled(false);
}
}
}
});
wTree.setMenu(tMenu);
}
private void addRenameTowTreeScriptItems(){
lastItem = new TreeItem [1];
editor = new TreeEditor (wTree);
wTree.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event event) {
final TreeItem item = (TreeItem)event.item;
renameFunction(item);
}
});
}
// This function is for a Windows Like renaming inside the tree
private void renameFunction(TreeItem tItem){
final TreeItem item = tItem;
if(item.getParentItem()!=null && item.getParentItem().equals(wTreeScriptsItem)){
if (item != null && item == lastItem [0]) {
boolean isCarbon = SWT.getPlatform ().equals ("carbon");
final Composite composite = new Composite (wTree, SWT.NONE);
if (!isCarbon) composite.setBackground(shell.getDisplay().getSystemColor (SWT.COLOR_BLACK));
final Text text = new Text (composite, SWT.NONE);
final int inset = isCarbon ? 0 : 1;
composite.addListener (SWT.Resize, new Listener () {
public void handleEvent (Event e) {
Rectangle rect = composite.getClientArea ();
text.setBounds (rect.x + inset, rect.y + inset, rect.width - inset * 2, rect.height - inset * 2);
}
});
Listener textListener = new Listener () {
public void handleEvent (final Event e) {
switch (e.type) {
case SWT.FocusOut:
if(text.getText().length()>0){
// Check if the name Exists
if(getCTabItemByName(text.getText())==null){
modifyCTabItem(item,RENAME_ITEM, text.getText());
item.setText (text.getText ());
}
}
composite.dispose ();
break;
case SWT.Verify:
String newText = text.getText ();
String leftText = newText.substring (0, e.start);
String rightText = newText.substring (e.end, newText.length ());
GC gc = new GC (text);
Point size = gc.textExtent (leftText + e.text + rightText);
gc.dispose ();
size = text.computeSize (size.x, SWT.DEFAULT);
editor.horizontalAlignment = SWT.LEFT;
Rectangle itemRect = item.getBounds (), rect = wTree.getClientArea ();
editor.minimumWidth = Math.max (size.x, itemRect.width) + inset * 2;
int left = itemRect.x, right = rect.x + rect.width;
editor.minimumWidth = Math.min (editor.minimumWidth, right - left);
editor.minimumHeight = size.y + inset * 2;
editor.layout ();
break;
case SWT.Traverse:
switch (e.detail) {
case SWT.TRAVERSE_RETURN:
if(text.getText().length()>0){
// Check if the name Exists
if(getCTabItemByName(text.getText())==null){
modifyCTabItem(item,RENAME_ITEM, text.getText());
item.setText (text.getText ());
}
}
case SWT.TRAVERSE_ESCAPE:
composite.dispose ();
e.doit = false;
}
break;
}
}
};
text.addListener (SWT.FocusOut, textListener);
text.addListener (SWT.Traverse, textListener);
text.addListener (SWT.Verify, textListener);
editor.setEditor (composite, item);
text.setText (item.getText ());
text.selectAll ();
text.setFocus ();
}
}
lastItem [0] = item;
}
// This could be useful for further improvements
public static ScriptOrFnNode parseVariables(Context cx, Scriptable scope, String source, String sourceName, int lineno, Object securityDomain){
// Interpreter compiler = new Interpreter();
CompilerEnvirons evn = new CompilerEnvirons();
evn.setLanguageVersion(Context.VERSION_1_5);
evn.setOptimizationLevel(-1);
evn.setGeneratingSource(true);
evn.setGenerateDebugInfo(true);
ErrorReporter errorReporter = new ToolErrorReporter(false);
Parser p = new Parser(evn, errorReporter);
ScriptOrFnNode tree = p.parse(source, "",0); // IOException
//Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
return tree;
}
}
|
package com.grayben.riskExtractor.htmlScorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.elementScorers.EmphasisElementScorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.elementScorers.SegmentationElementScorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers.TagAndAttributeScorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers.TagEmphasisScorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers.TagSegmentationScorer;
import org.jsoup.nodes.Element;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.HashSet;
import java.util.Set;
import static junit.framework.TestCase.fail;
@RunWith(MockitoJUnitRunner.class)
public class TreeHtmlScorerTest
extends HtmlScorerTest {
TreeHtmlScorer treeHtmlScorerSUT;
@Before
public void setUp() throws Exception {
Set<Scorer<Element>> elementScorers = new HashSet<>();
elementScorers.add(
new EmphasisElementScorer(
new TagEmphasisScorer(TagEmphasisScorer.defaultMap()),
new TagAndAttributeScorer(TagAndAttributeScorer.defaultMap())
)
);
elementScorers.add(
new SegmentationElementScorer(
new TagSegmentationScorer(TagSegmentationScorer.defaultMap())
)
);
ScoringAndFlatteningNodeVisitor nv = new ScoringAndFlatteningNodeVisitor(elementScorers);
//TODO: inject the NodeTraversor into the TreeHtmlScorer constructor
setHtmlScorerSUT(new TreeHtmlScorer(nv));
super.setUp();
}
@After
public void tearDown() throws Exception {
super.tearDown();
this.treeHtmlScorerSUT = null;
}
@Test
public void
test_InitThrowsNullPointerException_WhenNodeVisitorIsNull
() throws Exception {
ScoringAndFlatteningNodeVisitor nv = null;
thrown.expect(NullPointerException.class);
treeHtmlScorerSUT = new TreeHtmlScorer(nv);
}
@Override
@Test
public void
test_ScoreHtmlReturnsExpected_WhenTextInputIsSimple
() throws Exception {
fail("Test not implemented");
}
@Override
@Test
public void
test_ScoreHtmlReturnsExpected_WhenTextInputIsComplicated
() throws Exception {
fail("Test not implemented");
}
}
|
package org.mafagafogigante.dungeon.io;
import org.mafagafogigante.dungeon.schema.JsonRule;
import org.mafagafogigante.dungeon.schema.rules.JsonRuleFactory;
import com.eclipsesource.json.JsonObject;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class AchievementsJsonFileTest extends ResourcesTypeTest {
private static final String ID_FIELD = "id";
private static final String NAME_FIELD = "name";
private static final String INFO_FIELD = "info";
private static final String TEXT_FIELD = "text";
private static final String TYPE_FIELD = "type";
private static final String COUNT_FIELD = "count";
private static final String QUERY_FIELD = "query";
private static final String FOREST_FIELD = "FOREST";
private static final String DESERT_FIELD = "DESERT";
private static final String GRAVEYARD_FIELD = "GRAVEYARD";
private static final String PART_OF_DAY_FIELD = "partOfDay";
private static final String ACHIEVEMENTS_FIELD = "achievements";
private static final String STONE_BRIDGE_FIELD = "STONE_BRIDGE";
private static final String CAUSE_OF_DEATH_FIELD = "causeOfDeath";
private static final String TIMBER_BRIDGE_FIELD = "TIMBER_BRIDGE";
private static final String VISITED_LOCATIONS_FIELD = "visitedLocations";
private static final String BATTLE_REQUIREMENTS_FIELD = "battleRequirements";
private static final String KILLS_BY_LOCATION_ID_FIELD = "killsByLocationID";
private static final String ACHIEVEMENTS_JSON_FILE_NAME = "achievements.json";
private static final String MAXIMUM_NUMBER_OF_VISITS_FIELD = "maximumNumberOfVisits";
private static final String EXPLORATION_REQUIREMENTS_FIELD = "explorationRequirements";
@Test
public void testIsFileHasValidStructure() {
JsonRule caseOfDeathRule = getCauseOfDeathRule();
JsonRule queryRule = getQueryRule(caseOfDeathRule);
JsonRule battleRequirementsRule = getBattleRequirementsRule(queryRule);
JsonRule visitedLocationsRule = getVisitedLocationsRule();
JsonRule maximumNumberOfVisitsRule = getMaximumNumberOfVisitsRule();
JsonRule killsByLocationIdRule = getKillsByLocationIdRule();
Map<String, JsonRule> explorationRequirementsRules = new HashMap<>();
JsonRule optionalKillsByLocationRule = JsonRuleFactory.makeOptionalRule(killsByLocationIdRule);
explorationRequirementsRules.put(KILLS_BY_LOCATION_ID_FIELD, optionalKillsByLocationRule);
JsonRule optionalMaximumNumberRule = JsonRuleFactory.makeOptionalRule(maximumNumberOfVisitsRule);
explorationRequirementsRules.put(MAXIMUM_NUMBER_OF_VISITS_FIELD, optionalMaximumNumberRule);
JsonRule optionalVisitedLocationsRule = JsonRuleFactory.makeOptionalRule(visitedLocationsRule);
explorationRequirementsRules.put(VISITED_LOCATIONS_FIELD, optionalVisitedLocationsRule);
JsonRule explorationRequirementsRule = JsonRuleFactory.makeObjectRule(explorationRequirementsRules);
JsonRule achievementRule = makeAchievementsRule(explorationRequirementsRule, battleRequirementsRule);
JsonRule achievementsFileRule = getAchievementsFileRule(achievementRule);
JsonObject achievementsFileJson = getJsonObjectByJsonFile(ACHIEVEMENTS_JSON_FILE_NAME);
achievementsFileRule.validate(achievementsFileJson);
}
private JsonRule getAchievementsFileRule(JsonRule achievementRule) {
Map<String, JsonRule> achievementsFileRules = new HashMap<>();
achievementsFileRules.put(ACHIEVEMENTS_FIELD, JsonRuleFactory.makeVariableArrayRule(achievementRule));
return JsonRuleFactory.makeObjectRule(achievementsFileRules);
}
private JsonRule makeAchievementsRule(JsonRule explorationRequirementsRule, JsonRule battleRequirementsRule) {
JsonRule jsonStringRule = JsonRuleFactory.makeStringRule();
Map<String, JsonRule> achievementRules = new HashMap<>();
achievementRules.put(ID_FIELD, JsonRuleFactory.makeIdRule());
achievementRules.put(NAME_FIELD, jsonStringRule);
achievementRules.put(INFO_FIELD, jsonStringRule);
achievementRules.put(TEXT_FIELD, jsonStringRule);
JsonRule battleVariableJsonRule = JsonRuleFactory.makeVariableArrayRule(battleRequirementsRule);
achievementRules.put(BATTLE_REQUIREMENTS_FIELD, JsonRuleFactory.makeOptionalRule(battleVariableJsonRule));
JsonRule optionalExplorationRule = JsonRuleFactory.makeOptionalRule(explorationRequirementsRule);
achievementRules.put(EXPLORATION_REQUIREMENTS_FIELD, optionalExplorationRule);
return JsonRuleFactory.makeObjectRule(achievementRules);
}
private JsonRule getBattleRequirementsRule(JsonRule queryRule) {
Map<String, JsonRule> battleRequirementsRules = new HashMap<>();
battleRequirementsRules.put(COUNT_FIELD, JsonRuleFactory.makeIntegerRule());
battleRequirementsRules.put(QUERY_FIELD, queryRule);
return JsonRuleFactory.makeObjectRule(battleRequirementsRules);
}
private JsonRule getQueryRule(JsonRule caseOfDeathRule) {
Map<String, JsonRule> queryRules = new HashMap<>();
JsonRule optionalStringRule = JsonRuleFactory.makeOptionalRule(JsonRuleFactory.makeStringRule());
queryRules.put(ID_FIELD, optionalStringRule);
queryRules.put(TYPE_FIELD, optionalStringRule);
JsonRule uppercaseRule = JsonRuleFactory.makeUppercaseStringRule();
JsonRule optionalUppercaseRule = JsonRuleFactory.makeOptionalRule(uppercaseRule);
queryRules.put(PART_OF_DAY_FIELD, optionalUppercaseRule);
queryRules.put(CAUSE_OF_DEATH_FIELD, JsonRuleFactory.makeOptionalRule(caseOfDeathRule));
return JsonRuleFactory.makeObjectRule(queryRules);
}
private JsonRule getCauseOfDeathRule() {
Map<String, JsonRule> causeOfDeathRules = new HashMap<>();
causeOfDeathRules.put(ID_FIELD, JsonRuleFactory.makeIdRule());
causeOfDeathRules.put(TYPE_FIELD, JsonRuleFactory.makeUppercaseStringRule());
return JsonRuleFactory.makeObjectRule(causeOfDeathRules);
}
private JsonRule getKillsByLocationIdRule() {
Map<String, JsonRule> killsByLocationIdRules = new HashMap<>();
JsonRule optionalIntegerRule = JsonRuleFactory.makeOptionalRule(JsonRuleFactory.makeIntegerRule());
killsByLocationIdRules.put(FOREST_FIELD, optionalIntegerRule);
return JsonRuleFactory.makeObjectRule(killsByLocationIdRules);
}
private JsonRule getMaximumNumberOfVisitsRule() {
Map<String, JsonRule> maximumNumberOfVisitsRules = new HashMap<>();
JsonRule optionalIntegerRule = JsonRuleFactory.makeOptionalRule(JsonRuleFactory.makeIntegerRule());
maximumNumberOfVisitsRules.put(STONE_BRIDGE_FIELD, optionalIntegerRule);
maximumNumberOfVisitsRules.put(TIMBER_BRIDGE_FIELD, optionalIntegerRule);
maximumNumberOfVisitsRules.put(GRAVEYARD_FIELD, optionalIntegerRule);
return JsonRuleFactory.makeObjectRule(maximumNumberOfVisitsRules);
}
private JsonRule getVisitedLocationsRule() {
Map<String, JsonRule> visitedLocationsRules = new HashMap<>();
JsonRule optionalIntegerRule = JsonRuleFactory.makeOptionalRule(JsonRuleFactory.makeIntegerRule());
visitedLocationsRules.put(DESERT_FIELD, optionalIntegerRule);
visitedLocationsRules.put(GRAVEYARD_FIELD, optionalIntegerRule);
return JsonRuleFactory.makeObjectRule(visitedLocationsRules);
}
}
|
package ua.yandex.shad.tempseries;
import static org.junit.Assert.*;
import org.junit.Test;
import java.util.InputMismatchException;
/**
* Test structure
*
* /@Test
* public void test[UnitOfWork_StateUnderTest_ExpectedBehavior]() {
* // Arrange
* ...
* // Act
* ...
* // Assert
* }
*/
public class TemperatureSeriesAnalysisTest {
/**
* Used in double comparison
*/
public static final double EPS = 5e-5;
@Test
public void testDefaultConstructor_size() {
int expectedSize = 0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis();
int actualSize = analysis.getArray().length;
assertEquals(expectedSize, actualSize);
}
@Test
public void testTemperatureSeriesConstructor_size() {
double[] temps = {1.0, -1.0, 2.0};
int expectedSize = 3;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
int actualSize = analysis.getArray().length;
assertEquals(expectedSize, actualSize);
}
@Test
public void testTempsConstructor_array() {
double[] temps = {1.0, -1.0, 2.0};
double[] expectedArray = {1.0, -1.0, 2.0};
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double[] actualArray = analysis.getArray();
assertArrayEquals(expectedArray, actualArray, EPS);
}
@Test
public void testTempsConstructor_modifyTempsArrayAfter() {
double[] temps = {1.0, -1.0, 2.0};
int index = 2;
double newValue = -1.1;
double[] expectedArray = {1.0, -1.0, 2.0};
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
temps[index] = newValue;
double[] actualArray = analysis.getArray();
assertArrayEquals(expectedArray, actualArray, EPS);
}
@Test(expected = InputMismatchException.class)
public void testTempsConstructor_tempOutOfLowerBound() {
double[] temps = {1.0, -274.0, 2.0};
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
}
@Test
public void testTempsConstructor_exactLowerBoundTemp() {
double[] temps = {-273.0, -1.0, 2.0};
double[] expectedArray = {-273.0, -1.0, 2.0};
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double[] actualArray = analysis.getArray();
assertArrayEquals(expectedArray, actualArray, EPS);
}
@Test(expected = IllegalArgumentException.class)
public void testAverage_emptyArray() {
double[] temps = {};
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
analysis.average();
}
@Test
public void testAverage_arrayWithOneTemp() {
double[] temps = {1.0};
double expectedResult = 1.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.average();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testAverage_arrayWithEqualTemps() {
double[] temps = {-7.0, -7.0, -7.0, -7e0};
double expectedResult = -7.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.average();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testAverage_result() {
double[] temps = {1.0, -2.0, 3.0, 0.0};
double expectedResult = 0.5;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.average();
assertEquals(expectedResult, actualResult, EPS);
}
@Test(expected = IllegalArgumentException.class)
public void testDeviation_emptyArray() {
double[] temps = {};
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
analysis.deviation();
}
@Test
public void testDeviation_arrayWithOneTemp() {
double[] temps = {-7.0};
double expectedResult = 0.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.deviation();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testDeviation_arrayWithEqualTemps() {
double[] temps = {-4.0, -4.0, -4.0, -4e0};
double expectedResult = 0.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.deviation();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testDeviation_result() {
double[] temps = {2.0, -2.0, -2.0, 2.0};
double expectedResult = 2.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.deviation();
assertEquals(expectedResult, actualResult, EPS);
}
@Test(expected = IllegalArgumentException.class)
public void testMin_emptyArray() {
double[] temps = {};
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
analysis.min();
}
@Test
public void testMin_arrayWithOneTemp() {
double[] temps = {-7.0};
double expectedResult = -7.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.min();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testMin_arrayWithEqualTemps() {
double[] temps = {-4.0, -4.0, -4.0, -4e0};
double expectedResult = -4.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.min();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testMin_result() {
double[] temps = {2.0, -14.0, -2.0, 100.0};
double expectedResult = -14.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.min();
assertEquals(expectedResult, actualResult, EPS);
}
@Test(expected = IllegalArgumentException.class)
public void testMax_emptyArray() {
double[] temps = {};
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
analysis.max();
}
@Test
public void testMax_arrayWithOneTemp() {
double[] temps = {56.0};
double expectedResult = 56.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.max();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testMax_arrayWithEqualTemps() {
double[] temps = {-4.0, -4.0, -4.0, -4e0};
double expectedResult = -4.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.max();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testMax_result() {
double[] temps = {2.0, -14.0, -2.0, 100.0};
double expectedResult = 100.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.max();
assertEquals(expectedResult, actualResult, EPS);
}
@Test(expected = IllegalArgumentException.class)
public void testFindTempClosestToZero_emptyArray() {
double[] temps = {};
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
analysis.findTempClosestToZero();
}
@Test
public void testFindTempClosestToZero_arrayWithOneTemp() {
double[] temps = {56.0};
double expectedResult = 56.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToZero();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testFindTempClosestToZero_onlyPositiveTemps() {
double[] temps = {2.0, 14.0, 2.0, 100.0};
double expectedResult = 2.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToZero();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testFindTempClosestToZero_arrayWithDifferentTemps() {
double[] temps = {-20.0, 14.0, -2.0, 100.0};
double expectedResult = -2.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToZero();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testFindTempClosestToZero_twoTempsWithEqualDistFirstNegative() {
double[] temps = {-2.0, 14.0, 2.0, 100.0};
double expectedResult = 2.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToZero();
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testFindTempClosestToZero_twoTempsWithEqualDistFirstPositive() {
double[] temps = {2.0, 14.0, -2.0, 100.0};
double expectedResult = 2.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToZero();
assertEquals(expectedResult, actualResult, EPS);
}
@Test(expected = IllegalArgumentException.class)
public void testFindTempClosestToValue_emptyArray() {
double[] temps = {};
double tempValue = 42;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
analysis.findTempClosestToValue(tempValue);
}
@Test
public void testFindTempClosestToValue_arrayWithOneTemp() {
double[] temps = {56.0};
double tempValue = 45.78;
double expectedResult = 56.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToValue(tempValue);
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testFindTempClosestToValue_arrayWithGreaterTemps() {
double[] temps = {40.0, 27.0, 35.0, 30.0};
double tempValue = 25.0;
double expectedResult = 27.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToValue(tempValue);
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testFindTempClosestToValue_arrayWithLowerTemps() {
double[] temps = {40.0, 27.0, 35.0, 30.0};
double tempValue = 60.0;
double expectedResult = 40.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToValue(tempValue);
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testFindTempClosestToValue_arrayWithDifferentTemps() {
double[] temps = {-40.0, 27.0, -35.0, 2.0, 30.0};
double tempValue = 10.0;
double expectedResult = 2.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToValue(tempValue);
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testFindTempClosestToValue_twoTempsWithEqualDistFirstPositive() {
double[] temps = {3.0, 14.0, -1.0, 100.0};
double tempValue = 1.0;
double expectedResult = 3.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToValue(tempValue);
assertEquals(expectedResult, actualResult, EPS);
}
@Test
public void testFindTempClosestToValue_twoTempsWithEqualDistFirstNegative() {
double[] temps = {-1.0, 14.0, 3.0, 100.0};
double tempValue = 1.0;
double expectedResult = 3.0;
TemperatureSeriesAnalysis analysis = new TemperatureSeriesAnalysis(temps);
double actualResult = analysis.findTempClosestToValue(tempValue);
assertEquals(expectedResult, actualResult, EPS);
}
}
|
package uk.org.ownage.dmdirc.plugins.plugins.nickcolours;
import java.awt.Color;
import java.util.Map;
import java.util.Properties;
import uk.org.ownage.dmdirc.Channel;
import uk.org.ownage.dmdirc.ChannelClientProperty;
import uk.org.ownage.dmdirc.Config;
import uk.org.ownage.dmdirc.actions.ActionType;
import uk.org.ownage.dmdirc.actions.CoreActionType;
import uk.org.ownage.dmdirc.parser.ChannelClientInfo;
import uk.org.ownage.dmdirc.parser.ChannelInfo;
import uk.org.ownage.dmdirc.parser.ClientInfo;
import uk.org.ownage.dmdirc.plugins.EventPlugin;
import uk.org.ownage.dmdirc.ui.components.PreferencesInterface;
import uk.org.ownage.dmdirc.ui.components.PreferencesPanel;
import uk.org.ownage.dmdirc.ui.messages.ColourManager;
/**
* Provides various features related to nickname colouring.
* @author chris
*/
public class NickColourPlugin implements EventPlugin, PreferencesInterface {
/** The config domain to use for this plugin. */
private static final String DOMAIN = "plugin-NickColour";
/** Whether this plugin is active or not. */
private boolean isActive;
/** "Random" colours to use to colour nicknames. */
private String[] randColours = new String[] {
"E90E7F", "8E55E9", "B30E0E", "18B33C",
"58ADB3", "9E54B3", "B39875", "3176B3"
};
/** Creates a new instance of NickColourPlugin. */
public NickColourPlugin() {
super();
}
/** {@inheritDoc} */
public void processEvent(final ActionType type, final StringBuffer format,
final Object... arguments) {
if (type.equals(CoreActionType.CHANNEL_GOTNAMES)) {
final ChannelInfo chanInfo = ((Channel) arguments[0]).getChannelInfo();
for (ChannelClientInfo client : chanInfo.getChannelClients()) {
colourClient(client);
}
} else if (type.equals(CoreActionType.CHANNEL_JOIN)) {
colourClient((ChannelClientInfo) arguments[1]);
}
}
/**
* Colours the specified client according to the user's config.
* @param client The client to be coloured
*/
@SuppressWarnings("unchecked")
private void colourClient(final ChannelClientInfo client) {
final Map map = client.getMap();
final ClientInfo myself = client.getClient().getParser().getMyself();
final String nickOption = "colour-" + client.getNickname();
if (Config.getOptionBool(DOMAIN, "useowncolour") && client.getClient().equals(myself)) {
final Color color = ColourManager.parseColour(Config.getOption(DOMAIN, "owncolour"));
map.put(ChannelClientProperty.COLOUR_FOREGROUND, color);
} else if (Config.hasOption(DOMAIN, nickOption)) {
final Color color = ColourManager.parseColour(Config.getOption(DOMAIN, nickOption));
map.put(ChannelClientProperty.COLOUR_FOREGROUND, color);
} else if (Config.getOptionBool(DOMAIN, "userandomcolour")) {
map.put(ChannelClientProperty.COLOUR_FOREGROUND, getColour(client.getNickname()));
}
}
/**
* Retrieves a pseudo-random colour for the specified nickname.
* @param nick The nickname of the client whose colour we're determining
*/
private Color getColour(final String nick) {
int count = 0;
for (int i = 0; i < nick.length(); i++) {
count += nick.charAt(i);
}
count = count % randColours.length;
return ColourManager.parseColour(randColours[count]);
}
/** {@inheritDoc} */
public boolean onLoad() {
return true;
}
/** {@inheritDoc} */
public void onUnload() {
}
/** {@inheritDoc} */
public void onActivate() {
isActive = true;
if (Config.hasOption(DOMAIN, "randomcolours")) {
randColours = Config.getOption(DOMAIN, "randomcolours").split("\n");
}
}
/** {@inheritDoc} */
public boolean isActive() {
return isActive;
}
/** {@inheritDoc} */
public void onDeactivate() {
isActive = false;
}
/** {@inheritDoc} */
public boolean isConfigurable() {
return true;
}
/** {@inheritDoc} */
public void showConfig() {
final PreferencesPanel preferencesPanel = new PreferencesPanel(this, "NickColour Plugin - Config");
preferencesPanel.addCategory("General", "General configuration for NickColour plugin.");
preferencesPanel.addCheckboxOption("General", "showintext",
"Show colours in text area: ", "Colour nicknames in main text area?",
Config.getOptionBool("ui", "shownickcoloursintext"));
preferencesPanel.addCheckboxOption("General", "showinlist",
"Show colours in nick list: ", "Colour nicknames in channel user lists?",
Config.getOptionBool("ui", "shownickcoloursinnicklist"));
preferencesPanel.addCheckboxOption("General", "userandomcolour",
"Enable Random Colour: ", "Use a pseudo-random colour for each person?",
Config.getOptionBool("plugin-NickColour", "userandomcolour"));
preferencesPanel.addCheckboxOption("General", "useowncolour",
"Use colour for own nick: ", "Always use the same colour for own nick?",
Config.getOptionBool("plugin-NickColour", "useowncolour"));
preferencesPanel.addColourOption("General", "owncolour",
"Colour to use for own nick: ", "Colour used for own nick",
Config.getOption("plugin-NickColour", "owncolour", "1"), true, true);
preferencesPanel.display();
}
/**
* Called when the preferences dialog is closed.
*
* @param properties user preferences
*/
public void configClosed(final Properties properties) {
Config.setOption("ui", "shownickcoloursintext", properties.getProperty("showintext"));
Config.setOption("ui", "shownickcoloursinnicklist", properties.getProperty("showinlist"));
Config.setOption(DOMAIN, "userandomcolour", properties.getProperty("userandomcolour"));
Config.setOption(DOMAIN, "useowncolour", properties.getProperty("useowncolour"));
Config.setOption(DOMAIN, "owncolour", properties.getProperty("owncolour"));
}
/** {@inheritDoc} */
public String getVersion() {
return "0.0";
}
/** {@inheritDoc} */
public String getAuthor() {
return "Chris <chris@dmdirc.com>";
}
/** {@inheritDoc} */
public String getDescription() {
return "Provides various nick colouring tools";
}
/** {@inheritDoc} */
public String toString() {
return "Nick Colour Plugin";
}
}
|
package org.eclipse.birt.report.designer.ui.cubebuilder.dialog;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.eclipse.birt.core.format.DateFormatter;
import org.eclipse.birt.report.designer.internal.ui.dialogs.helper.IDialogHelper;
import org.eclipse.birt.report.designer.internal.ui.dialogs.helper.IDialogHelperProvider;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.util.WidgetUtil;
import org.eclipse.birt.report.designer.ui.cubebuilder.nls.Messages;
import org.eclipse.birt.report.designer.ui.cubebuilder.provider.CubeExpressionProvider;
import org.eclipse.birt.report.designer.ui.cubebuilder.util.BuilderConstants;
import org.eclipse.birt.report.designer.ui.cubebuilder.util.OlapUtil;
import org.eclipse.birt.report.designer.ui.util.ExceptionUtil;
import org.eclipse.birt.report.designer.ui.views.ElementAdapterManager;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.model.api.Expression;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.TabularCubeHandle;
import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle;
import org.eclipse.birt.report.model.api.olap.TabularLevelHandle;
import org.eclipse.birt.report.model.elements.interfaces.IHierarchyModel;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
public class DateLevelDialog extends TitleAreaDialog
{
private static final String NONE = Messages.getString( "DateLevelDialog.None" ); //$NON-NLS-1$
private Text nameText;
private Combo typeCombo;
private TabularLevelHandle input;
private TabularCubeHandle cube;
private IDialogHelper helper;
private static HashMap formatMap = new HashMap( );
static
{
Date defaultDate = new Date( );
formatMap.put( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_YEAR,
new String[][]{
{
new DateFormatter( "yyyy" ).format( defaultDate ), //$NON-NLS-1$
"yyyy" //$NON-NLS-1$
},
{
new DateFormatter( "yy" ).format( defaultDate ), //$NON-NLS-1$
"yy" //$NON-NLS-1$
}
} );
formatMap.put( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_MONTH,
new String[][]{
{
new DateFormatter( "MMM" ).format( defaultDate ), //$NON-NLS-1$
"MMM" //$NON-NLS-1$
},
{
new DateFormatter( "MMM yyyy" ).format( defaultDate ), //$NON-NLS-1$
"MMM yyyy" //$NON-NLS-1$
},
{
new DateFormatter( "MMM yy" ).format( defaultDate ), //$NON-NLS-1$
"MMM yy" //$NON-NLS-1$
}
} );
formatMap.put( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_DAY_OF_YEAR,
new String[][]{
{
new DateFormatter( "MMMM dd, yyyy" ).format( defaultDate ), //$NON-NLS-1$
"MMMM dd, yyyy" //$NON-NLS-1$
},
{
new DateFormatter( "MMMM dd, yy" ).format( defaultDate ), //$NON-NLS-1$
"MMMM dd, yy" //$NON-NLS-1$
}
} );
formatMap.put( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_DAY_OF_MONTH,
new String[][]{
{
new DateFormatter( "dd" ).format( defaultDate ), //$NON-NLS-1$
"dd" //$NON-NLS-1$
}
} );
formatMap.put( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_DAY_OF_WEEK,
new String[][]{
{
new DateFormatter( "EEEE" ).format( defaultDate ), //$NON-NLS-1$
"EEEE" //$NON-NLS-1$
}
} );
formatMap.put( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_HOUR,
new String[][]{
{
new DateFormatter( "HH:mm:ss aaa" ).format( defaultDate ), //$NON-NLS-1$
"HH:mm:ss aaa" //$NON-NLS-1$
},
{
new DateFormatter( "HH:mm:ss" ).format( defaultDate ), //$NON-NLS-1$
"HH:mm:ss" //$NON-NLS-1$
},
{
new DateFormatter( "HH:mm" ).format( defaultDate ), //$NON-NLS-1$
"HH:mm" //$NON-NLS-1$
}
} );
formatMap.put( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_MINUTE,
new String[][]{
{
new DateFormatter( "mm" ).format( defaultDate ), //$NON-NLS-1$
"mm" //$NON-NLS-1$
}
} );
formatMap.put( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_SECOND,
new String[][]{
{
new DateFormatter( "ss" ).format( defaultDate ), //$NON-NLS-1$
"ss" //$NON-NLS-1$
}
} );
};
private String[] getFormatDisplayItems( String type )
{
String[][] formatPattern = (String[][]) formatMap.get( type );
if ( formatPattern == null )
return new String[0];
String[] items = new String[formatPattern.length];
for ( int i = 0; i < items.length; i++ )
{
items[i] = formatPattern[i][0];
}
return items;
}
private String[] getFormatPatternItems( String type )
{
String[][] formatPattern = (String[][]) formatMap.get( type );
String[] items = new String[formatPattern.length];
for ( int i = 0; i < items.length; i++ )
{
items[i] = formatPattern[i][1];
}
return items;
}
private String getDateFormatDisplayName( String dateType, String pattern )
{
if ( dateType == null )
return NONE;
String[][] formatPattern = (String[][]) formatMap.get( dateType );
if ( pattern == null )
return NONE;
for ( int i = 0; i < formatPattern.length; i++ )
{
if ( pattern.equals( formatPattern[i][1] ) )
return formatPattern[i][0];
}
return NONE;
}
public DateLevelDialog( )
{
super( UIUtil.getDefaultShell( ) );
setShellStyle( getShellStyle( ) | SWT.RESIZE | SWT.MAX );
}
public void setInput( TabularCubeHandle cube, TabularLevelHandle level )
{
this.input = level;
this.cube = cube;
}
// private Button noneIntervalButton;
// private Button intervalButton;
private Combo formatCombo;
private Text fieldText;
private List getDateTypeNames( IChoice[] choices )
{
List dateTypeList = new ArrayList( );
if ( choices == null )
return dateTypeList;
for ( int i = 0; i < choices.length; i++ )
{
dateTypeList.add( choices[i].getName( ) );
}
return dateTypeList;
}
private String[] getAvailableDateTypeDisplayNames( )
{
List dateTypeList = getAvailableDateTypeNames( );
List dateTypeDisplayList = new ArrayList( );
for ( int i = 0; i < dateTypeList.size( ); i++ )
{
dateTypeDisplayList.add( getDateTypeDisplayName( dateTypeList.get( i )
.toString( ) ) );
}
return (String[]) dateTypeDisplayList.toArray( new String[0] );
}
private IChoice[] getLevelTypesByDateType( )
{
TabularHierarchyHandle hierarchy = (TabularHierarchyHandle) input.getContainer( );
String dataField = input.getColumnName( );
if ( hierarchy == null || dataField == null )
return null;
ResultSetColumnHandle column = OlapUtil.getDataField( OlapUtil.getHierarchyDataset( hierarchy ),
dataField );
if ( column == null )
return OlapUtil.getDateTimeLevelTypeChoices( );
String dataType = column.getDataType( );
if ( dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME ) )
return OlapUtil.getDateTimeLevelTypeChoices( );
else if ( dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATE ) )
return OlapUtil.getDateLevelTypeChoices( );
else
return OlapUtil.getTimeLevelTypeChoices( );
}
private List getAvailableDateTypeNames( )
{
List dateTypeList = new ArrayList( );
dateTypeList.addAll( getDateTypeNames( getLevelTypesByDateType( ) ) );
List levels = input.getContainer( )
.getContents( IHierarchyModel.LEVELS_PROP );
for ( int i = 0; i < levels.size( ); i++ )
{
if ( levels.get( i ) == input )
continue;
dateTypeList.remove( ( (TabularLevelHandle) levels.get( i ) ).getDateTimeLevelType( ) );
}
return dateTypeList;
}
public String getDateTypeDisplayName( String name )
{
if ( name == null )
return ""; //$NON-NLS-1$
return ChoiceSetFactory.getDisplayNameFromChoiceSet( name,
OlapUtil.getDateTimeLevelTypeChoiceSet( ) );
}
protected Control createDialogArea( Composite parent )
{
UIUtil.bindHelp( parent, IHelpContextIds.CUBE_DATE_LEVEL_DIALOG );
setTitle( Messages.getString( "DateLevelDialog.Title" ) ); //$NON-NLS-1$
getShell( ).setText( Messages.getString( "DateLevelDialog.Shell.Title" ) ); //$NON-NLS-1$
setMessage( Messages.getString( "DateLevelDialog.Message" ) ); //$NON-NLS-1$
Composite area = (Composite) super.createDialogArea( parent );
Composite contents = new Composite( area, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.marginWidth = 20;
contents.setLayout( layout );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = convertWidthInCharsToPixels( 80 );
// data.heightHint = 200;
contents.setLayoutData( data );
createContentArea( contents );
WidgetUtil.createGridPlaceholder( contents, 1, true );
initLevelDialog( );
parent.layout( );
return contents;
}
private void initLevelDialog( )
{
nameText.setText( input.getName( ) );
fieldText.setText( input.getColumnName( ) );
typeCombo.setItems( getAvailableDateTypeDisplayNames( ) );
typeCombo.setText( getDateTypeDisplayName( input.getDateTimeLevelType( ) ) );
if ( typeCombo.getSelectionIndex( ) > -1 )
{
formatCombo.setItems( getFormatDisplayItems( getAvailableDateTypeNames( ).get( typeCombo.getSelectionIndex( ) )
.toString( ) ) );
}
formatCombo.add( NONE, 0 );
formatCombo.setText( getDateFormatDisplayName( input.getDateTimeLevelType( ),
input.getDateTimeFormat( ) ) );
}
private void createContentArea( Composite parent )
{
Composite content = new Composite( parent, SWT.NONE );
content.setLayoutData( new GridData( GridData.FILL_BOTH ) );
GridLayout layout = new GridLayout( );
layout.numColumns = 3;
content.setLayout( layout );
new Label( content, SWT.NONE ).setText( Messages.getString( "DateLevelDialog.Name" ) ); //$NON-NLS-1$
nameText = new Text( content, SWT.BORDER );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
nameText.setLayoutData( gd );
nameText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkOkButtonStatus( );
}
} );
new Label( content, SWT.NONE ).setText( Messages.getString("DateLevelDialog.KeyField") ); //$NON-NLS-1$
fieldText = new Text( content, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
fieldText.setLayoutData( gd );
new Label( content, SWT.NONE ).setText( Messages.getString( "DateLevelDialog.Type" ) ); //$NON-NLS-1$
typeCombo = new Combo( content, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
typeCombo.setLayoutData( gd );
typeCombo.setVisibleItemCount( 30 );
typeCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
checkOkButtonStatus( );
formatCombo.setItems( new String[0] );
formatCombo.setItems( getFormatDisplayItems( getAvailableDateTypeNames( ).get( typeCombo.getSelectionIndex( ) )
.toString( ) ) );
formatCombo.add( NONE, 0 );
formatCombo.select( 0 );
}
} );
new Label( content, SWT.NONE ).setText( Messages.getString( "DateLevelDialog.Format" ) ); //$NON-NLS-1$
formatCombo = new Combo( content, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
formatCombo.setLayoutData( gd );
formatCombo.setVisibleItemCount( 30 );
formatCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
checkOkButtonStatus( );
}
} );
createSecurityPart( content );
createHyperLinkPart( content );
}
private IDialogHelper createHyperLinkPart( Composite parent )
{
Object[] helperProviders = ElementAdapterManager.getAdapters( cube,
IDialogHelperProvider.class );
if ( helperProviders != null )
{
for ( int i = 0; i < helperProviders.length; i++ )
{
IDialogHelperProvider helperProvider = (IDialogHelperProvider) helperProviders[i];
if ( helperProvider != null )
{
final IDialogHelper hyperLinkHelper = helperProvider.createHelper( this,
BuilderConstants.HYPERLINK_HELPER_KEY );
if ( hyperLinkHelper != null )
{
hyperLinkHelper.setProperty( BuilderConstants.HYPERLINK_LABEL,
Messages.getString( "DateLevelDialog.Label.LinkTo" ) ); //$NON-NLS-1$
hyperLinkHelper.setProperty( BuilderConstants.HYPERLINK_BUTTON_TEXT,
Messages.getString( "DateLevelDialog.Button.Text.Edit" ) ); //$NON-NLS-1$
hyperLinkHelper.setProperty( BuilderConstants.HYPERLINK_REPORT_ITEM_HANDLE,
input );
hyperLinkHelper.createContent( parent );
hyperLinkHelper.addListener( SWT.Modify,
new Listener( ) {
public void handleEvent( Event event )
{
hyperLinkHelper.update( false );
}
} );
hyperLinkHelper.update( true );
return hyperLinkHelper;
}
}
}
}
return null;
}
private void createSecurityPart( Composite parent )
{
Object[] helperProviders = ElementAdapterManager.getAdapters( cube,
IDialogHelperProvider.class );
if ( helperProviders != null )
{
for ( int i = 0; i < helperProviders.length; i++ )
{
IDialogHelperProvider helperProvider = (IDialogHelperProvider) helperProviders[i];
if ( helperProvider != null && helper == null )
{
helper = helperProvider.createHelper( this,
BuilderConstants.SECURITY_HELPER_KEY );
if ( helper != null )
{
helper.setProperty( BuilderConstants.SECURITY_EXPRESSION_LABEL,
Messages.getString( "DateLevelDialog.Access.Control.List.Expression" ) ); //$NON-NLS-1$
helper.setProperty( BuilderConstants.SECURITY_EXPRESSION_CONTEXT,
cube );
helper.setProperty( BuilderConstants.SECURITY_EXPRESSION_PROVIDER,
new CubeExpressionProvider( cube ) );
helper.setProperty( BuilderConstants.SECURITY_EXPRESSION_PROPERTY,
input.getACLExpression( ) );
helper.createContent( parent );
helper.addListener( SWT.Modify, new Listener( ) {
public void handleEvent( Event event )
{
helper.update( false );
}
} );
helper.update( true );
}
}
}
}
}
protected void createButtonsForButtonBar( Composite parent )
{
super.createButtonsForButtonBar( parent );
checkOkButtonStatus( );
}
protected void checkOkButtonStatus( )
{
if ( nameText.getText( ) == null
|| nameText.getText( ).trim( ).equals( "" ) //$NON-NLS-1$
|| typeCombo.getSelectionIndex( ) == -1
|| formatCombo.getSelectionIndex( ) == -1 )
{
if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( false );
setMessage( null );
setErrorMessage( Messages.getString( "DateLevelDialog.Message.BlankName" ) ); //$NON-NLS-1$
}
else if ( !UIUtil.validateDimensionName( nameText.getText( ) ) )
{
if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( false );
setMessage( null );
setErrorMessage( Messages.getString( "LevelPropertyDialog.Message.NumericName" ) ); //$NON-NLS-1$
}
else
{
if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( true );
setErrorMessage( null );
setMessage( Messages.getString( "DateLevelDialog.Message" ) ); //$NON-NLS-1$
}
}
protected void okPressed( )
{
try
{
if ( nameText.getText( ) != null
&& !nameText.getText( ).trim( ).equals( "" ) ) //$NON-NLS-1$
{
input.setName( nameText.getText( ) );
}
if ( typeCombo.getText( ) != null )
{
input.setDateTimeLevelType( getAvailableDateTypeNames( ).get( typeCombo.getSelectionIndex( ) )
.toString( ) );
}
if ( formatCombo.getText( ) != null )
{
if ( formatCombo.getText( ).equals( NONE ) )
input.setDateTimeFormat( null );
else
input.setDateTimeFormat( getFormatPatternItems( getAvailableDateTypeNames( ).get( typeCombo.getSelectionIndex( ) )
.toString( ) )[formatCombo.getSelectionIndex( ) - 1] );
}
if ( helper != null )
{
input.setExpressionProperty( LevelHandle.ACL_EXPRESSION_PROP,
(Expression) helper.getProperty( BuilderConstants.SECURITY_EXPRESSION_PROPERTY ) );
}
}
catch ( Exception e )
{
ExceptionUtil.handle( e );
return;
}
super.okPressed( );
}
}
|
package org.eclipse.birt.report.designer.internal.ui.resourcelocator;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.model.api.IResourceLocator;
import org.eclipse.birt.report.model.api.LibraryHandle;
import org.eclipse.birt.report.model.api.css.CssStyleSheetHandle;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;
/**
* FragmentResourceEntry
*/
public class FragmentResourceEntry extends BaseResourceEntity
{
public static final String TEMPLATE_ROOT = "templates"; //$NON-NLS-1$
public static final String RESOURCE_ROOT = "resources"; //$NON-NLS-1$
protected Bundle bundle;
protected String name;
protected String displayName;
private FragmentResourceEntry parent;
private String path;
private List children = new ArrayList( );
private LibraryHandle library;
private CssStyleSheetHandle cssStyleHandle;
protected boolean isRoot;
private boolean isFile;
/** The entries been parsed, saves them to avoid to parsed repeatly. */
private final Collection<URL> parsedEntries = new HashSet<URL>( );
private FileFilter filter;
public FragmentResourceEntry( )
{
this( null );
}
public FragmentResourceEntry( final String[] filePattern, String name,
String displayName, String path )
{
this( filePattern,
name,
displayName,
path,
Platform.getBundle( IResourceLocator.FRAGMENT_RESOURCE_HOST ) );
}
public FragmentResourceEntry( final String[] filePattern, String name,
String displayName, String path, Bundle bundle )
{
this( name, displayName, path, null, false, true ); //$NON-NLS-1$//$NON-NLS-2$
if ( filePattern != null )
filter = new FileFilter( filePattern );
this.bundle = bundle;
if ( bundle != null )
{
Enumeration<URL> enumeration = findEntries( path );
parseResourceEntry( this, enumeration );
parsedEntries.clear( );
}
}
public FragmentResourceEntry( String[] filePattern )
{
this( filePattern,
Messages.getString( "FragmentResourceEntry.RootName" ), Messages.getString( "FragmentResourceEntry.RootDisplayName" ), RESOURCE_ROOT ); //$NON-NLS-1$//$NON-NLS-2$
}
private void parseResourceEntry( FragmentResourceEntry parent,
Enumeration<URL> enumeration )
{
while ( enumeration != null && enumeration.hasMoreElements( ) )
{
URL element = enumeration.nextElement( );
String path = element.getPath( );
File file = null;
try
{
file = new File( FileLocator.toFileURL( element ).getPath( ) );
}
catch ( IOException e )
{
continue;
}
FragmentResourceEntry entry = new FragmentResourceEntry( file.getName( ),
path,
parent,
file.isFile( ) );
entry.bundle = Platform.getBundle( IResourceLocator.FRAGMENT_RESOURCE_HOST );
// Saves the element, avoid to be parsed repeatedly.
parsedEntries.add( element );
Enumeration<URL> children = findEntries( path );
if ( children != null )
{
parseResourceEntry( entry, children );
}
}
}
protected FragmentResourceEntry( String name, String displayName,
String path, FragmentResourceEntry parent, boolean isFile,
boolean isRoot )
{
this( name, path, parent, isFile );
this.isRoot = isRoot;
this.displayName = displayName; //$NON-NLS-1$
}
protected FragmentResourceEntry( String name, String path,
FragmentResourceEntry parent, boolean isFile )
{
this.name = name;
this.path = path;
this.parent = parent;
if ( parent != null )
parent.addChild( this );
this.isFile = isFile;
}
private void addChild( FragmentResourceEntry entry )
{
this.children.add( entry );
}
private FragmentResourceEntry getChild( String name )
{
for ( Iterator iter = this.children.iterator( ); iter.hasNext( ); )
{
FragmentResourceEntry entry = (FragmentResourceEntry) iter.next( );
if ( entry.getName( ).equals( name ) )
return entry;
}
return null;
}
public boolean hasChildren( )
{
return children.size( ) > 0;
}
public ResourceEntry[] getChildren( )
{
return (ResourceEntry[]) this.children.toArray( new ResourceEntry[this.children.size( )] );
}
public String getName( )
{
return this.name;
}
public String getDisplayName( )
{
return this.displayName;
}
public Image getImage( )
{
if ( this.isRoot || !isFile( ) )
return PlatformUI.getWorkbench( )
.getSharedImages( )
.getImage( ISharedImages.IMG_OBJ_FOLDER );
return super.getImage( );
}
public ResourceEntry getParent( )
{
return this.parent;
}
public URL getURL( )
{
if ( bundle != null )
return bundle.getResource( this.path );
return null;
}
public boolean isFile( )
{
return this.isFile;
}
public boolean isRoot( )
{
return this.isRoot;
}
public void dispose( )
{
if ( this.library != null )
{
this.library.close( );
this.library = null;
}
if ( this.cssStyleHandle != null )
{
// according to Xingjie, GUI needn't close() it.
this.cssStyleHandle = null;
}
ResourceEntry[] children = getChildren( );
for ( int i = 0; i < children.length; i++ )
{
children[i].dispose( );
}
}
public Object getAdapter( Class adapter )
{
if ( adapter == LibraryHandle.class
&& getURL( ).toString( ).toLowerCase( ).endsWith( "library" ) )
{
if ( !hasChildren( ) && this.library == null ) //$NON-NLS-1$
{
try
{
this.library = SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.openLibrary( FileLocator.toFileURL( getURL( ) )
.toString( ) );
}
catch ( Exception e )
{
}
}
return library;
}
else if ( adapter == CssStyleSheetHandle.class )
{
if ( this.cssStyleHandle == null
&& getURL( ).toString( ).toLowerCase( ).endsWith( ".css" ) ) //$NON-NLS-1$
{
try
{
cssStyleHandle = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.openCssStyleSheet( FileLocator.toFileURL( getURL( ) )
.toString( ) );
}
catch ( Exception e )
{
}
}
return cssStyleHandle;
}
return super.getAdapter( adapter );
}
@Override
public boolean equals( Object object )
{
if ( object == null )
return false;
if ( !( object instanceof FragmentResourceEntry || object instanceof String ) )
return false;
if ( object == this )
return true;
else
{
if ( object instanceof FragmentResourceEntry )
{
FragmentResourceEntry temp = (FragmentResourceEntry) object;
if ( temp.path.equals( this.path ) )
{
return true;
}
}
else if ( object instanceof String )
{
if ( object.equals( this.path ) )
{
return true;
}
}
}
return false;
}
public int hashCode( )
{
return this.path.hashCode( );
}
/**
* Returns an enumeration of URL objects for each matching entry.
*
* @param path
* The path name in which to look.
* @param patterns
* The file name pattern for selecting entries in the specified
* path.
* @return an enumeration of URL objects for each matching entry.
*/
private Enumeration<URL> findEntries( String path )
{
Set<URL> entries = new HashSet<URL>( );
Enumeration<URL> children = bundle.findEntries( path, null, false );
while ( children != null && children.hasMoreElements( ) )
{
URL url = children.nextElement( );
if ( filter == null || ( filter != null && filter.accept( url ) ) )
entries.add( url );
}
children = bundle.findEntries( path, null, false );
while ( children != null && children.hasMoreElements( ) )
{
URL child = children.nextElement( );
if ( !isParsed( child ) && hasChildren( child ) )
{
entries.add( child );
}
}
return new Vector<URL>( entries ).elements( );
}
/**
* Tests whether the specified URL contains children.
*
* @param url
* the URL to test.
* @return <code>true</code> if the specified URL contains children,
* <code>false</code> otherwise.
*/
private boolean hasChildren( URL url )
{
Enumeration<URL> children = bundle.findEntries( url.getPath( ),
null,
false );
return children != null && children.hasMoreElements( );
}
/**
* Tests whether the specified URL has been parsed.
*
* @param url
* the URL to test.
* @return <code>true</code> if the specified URL has been parsed,
* <code>false</code> otherwise.
*/
private boolean isParsed( URL url )
{
return parsedEntries.contains( url );
}
class FileFilter
{
private String[] filePattern;
public FileFilter( String[] filePattern )
{
this.filePattern = filePattern;
}
public boolean accept( URL path )
{
for ( int i = 0; i < filePattern.length; i++ )
{
String[] regs = filePattern[i].split( ";" ); //$NON-NLS-1$
for ( int j = 0; j < regs.length; j++ )
{
// need use decoded String ???
if ( URLDecoder.decode( path.toString( ) )
.toLowerCase( )
.endsWith( regs[j].toLowerCase( ).substring( 1 ) ) )
return true;
}
}
return false;
}
};
}
|
package org.csstudio.opibuilder.adl2boy.translator;
import java.util.Map;
import junit.framework.TestCase;
import org.csstudio.opibuilder.util.MacrosInput;
import org.csstudio.opibuilder.widgetActions.OpenDisplayAction;
import org.csstudio.utility.adlparser.fileParser.ADLWidget;
import org.csstudio.utility.adlparser.fileParser.WrongADLFormatException;
import org.csstudio.utility.adlparser.fileParser.widgetParts.ADLTestObjects;
import org.csstudio.utility.adlparser.fileParser.widgetParts.RelatedDisplayItem;
import org.eclipse.core.runtime.Path;
/**
* @author hammonds
*
*/
public class RelatedDisplay2ModelTest extends TestCase {
RelatedDisplay2Model converter = null;
/**
* @throws java.lang.Exception
*/
protected void setUp() throws Exception {
converter = new RelatedDisplay2Model(ADLTestObjects.makeColorMap());
// converter.setColorMap(makeColorMap());
}
/**
* @throws java.lang.Exception
*/
protected void tearDown() throws Exception {
converter.cleanup();
converter = null;
}
/**
* Test method for {@link org.csstudio.opibuilder.adl2boy.translator.RelatedDisplay2Model#RelatedDisplay2Model(org.csstudio.utility.adlparser.fileParser.ADLWidget, org.eclipse.swt.graphics.RGB[], org.csstudio.opibuilder.model.AbstractContainerModel)}.
*/
public void testRelatedDisplay2Model() {
}
public void testCreateOpenDisplayAction(){
// Standard test
{
OpenDisplayAction od = converter.createOpenDisplayAction(ADLTestObjects.makeRelatedDisplay1());
Path path = (Path)od.getPropertyValue(OpenDisplayAction.PROP_PATH);
assertTrue("FilePath " + path, path.toString().equals("myfile.opi"));
Boolean replace = (Boolean)od.getPropertyValue(OpenDisplayAction.PROP_REPLACE);
assertTrue("Replace display " + replace, replace.equals(true));
String label = od.getDescription();
assertTrue(" TestLabel " + label, "myLabel".equals(label));
}
//test where there is no policy defined
{
OpenDisplayAction od = converter.createOpenDisplayAction(ADLTestObjects.makeRelatedDisplayNoPolicy());
Path path = (Path)od.getPropertyValue(OpenDisplayAction.PROP_PATH);
assertTrue("FilePath " + path, path.toString().equals("myfile.opi"));
Boolean replace = (Boolean)od.getPropertyValue(OpenDisplayAction.PROP_REPLACE);
assertTrue("Replace display " + replace, replace.equals(false));
String label = (String)od.getPropertyValue(OpenDisplayAction.PROP_DESCRIPTION);
assertTrue(" TestLabel " + label, "myLabel".equals(label));
}
//test where there are mixed set of arguments (from parent and not)
{
OpenDisplayAction od = converter.createOpenDisplayAction(ADLTestObjects.makeRelatedDisplayMixedArgs());
Path path = (Path)od.getPropertyValue(OpenDisplayAction.PROP_PATH);
assertTrue("FilePath " + path, path.toString().equals("path/myfile.opi"));
Boolean replace = (Boolean)od.getPropertyValue(OpenDisplayAction.PROP_REPLACE);
assertTrue("Replace display " + replace, replace.equals(false));
String label = (String)od.getPropertyValue(OpenDisplayAction.PROP_DESCRIPTION);
assertTrue(" TestLabel " + label, "my label".equals(label));
}
}
public void testAddMacrosToOpenDisplayAction() {
// Explicite definition
RelatedDisplayItem[] rds = makeRelatedDisplays(ADLTestObjects.setupRelDispNoPolicy());
OpenDisplayAction odAction = new OpenDisplayAction();
converter.addMacrosToOpenDisplayAction(rds[0], odAction);
Map<String,String> map = ((MacrosInput)(odAction.getPropertyValue(OpenDisplayAction.PROP_MACROS))).getMacrosMap();
assertEquals("Map size for P=iocT1:,M=m1:, " + map, 2, map.size());
// Definition using parent macros
rds = makeRelatedDisplays(ADLTestObjects.setupRelDisp());
odAction = new OpenDisplayAction();
converter.addMacrosToOpenDisplayAction(rds[0], odAction);
map = ((MacrosInput)(odAction.getPropertyValue(OpenDisplayAction.PROP_MACROS))).getMacrosMap();
assertEquals("Map size for P=$(P),M=$(M):, " + map, 0 , map.size());
// Definition using parent macros
rds = makeRelatedDisplays(ADLTestObjects.setupRelDispMixedArgs());
odAction = new OpenDisplayAction();
converter.addMacrosToOpenDisplayAction(rds[0], odAction);
map = ((MacrosInput)(odAction.getPropertyValue(OpenDisplayAction.PROP_MACROS))).getMacrosMap();
assertEquals("Map size for P=$(P),M=$(M),T=temp:,PREC=3", 2, map.size());
}
private RelatedDisplayItem[] makeRelatedDisplays(ADLWidget adl) {
RelatedDisplayItem[] rds = new RelatedDisplayItem[1];
try {
rds[0] = new RelatedDisplayItem(adl);
} catch (WrongADLFormatException e) {
fail("This should work since test items are known");
e.printStackTrace();
}
return rds;
}
/**
* Test the makeMacros function
*/
public void testMakeMacros(){
// Explicite definition
MacrosInput mi = converter.makeMacros("P=iocT1:,M=m1:");
Map<String,String> map = mi.getMacrosMap();
assertEquals("Map size for P=iocT1:,M=m1:, " + map, 2, map.size());
// Definition with straight macros
mi = converter.makeMacros("P=$(P),M=$(M)");
map = mi.getMacrosMap();
assertEquals("Map size for P=$(P),M=$(M)", map.size(), 0);
// Mixed macros with parent macros
mi = converter.makeMacros("P=$(P),M=$(M),T=temp:,PREC=3");
map = mi.getMacrosMap();
assertEquals("Map size for P=$(P),M=$(M),T=temp:,PREC=3", map.size(), 2);
}
}
|
package org.eclipse.smarthome.core.thing;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import org.eclipse.smarthome.core.thing.type.ChannelGroupType;
import org.eclipse.smarthome.core.thing.type.ChannelGroupTypeUID;
import org.eclipse.smarthome.core.thing.type.ChannelKind;
import org.eclipse.smarthome.core.thing.type.ChannelType;
import org.eclipse.smarthome.core.thing.type.ChannelTypeProvider;
import org.eclipse.smarthome.core.thing.type.ChannelTypeUID;
import org.eclipse.smarthome.core.types.EventDescription;
import org.eclipse.smarthome.core.types.EventOption;
import org.eclipse.smarthome.core.types.StateDescription;
import org.eclipse.smarthome.core.types.StateOption;
/**
* Implementation providing default system wide channel types
*
* @author Ivan Iliev - Initial Contribution
* @author Chris Jackson - Added battery level
* @author Dennis Nobel - Changed to {@link ChannelTypeProvider}
* @author Markus Rathgeb - Make battery-low indication read-only
* @author Moritz Kammerer - Added system trigger types
*
*/
public class DefaultSystemChannelTypeProvider implements ChannelTypeProvider {
/**
* Signal strength default system wide {@link ChannelType}. Represents signal strength of a device as a number
* with values 0, 1, 2, 3 or 4, 0 being worst strength and 4 being best strength.
*/
public static final ChannelType SYSTEM_CHANNEL_SIGNAL_STRENGTH = new ChannelType(
new ChannelTypeUID("system:signal-strength"), false, "Number", "Signal Strength", null, "QualityOfService",
null,
new StateDescription(BigDecimal.ZERO, new BigDecimal(4), BigDecimal.ONE, null, true,
Arrays.asList(new StateOption("0", "no signal"), new StateOption("1", "weak"),
new StateOption("2", "average"), new StateOption("3", "good"), new StateOption("4", "excellent"))),
null);
/**
* Low battery default system wide {@link ChannelType}. Represents a low battery warning with possible values
* on/off.
*/
public static final ChannelType SYSTEM_CHANNEL_LOW_BATTERY = new ChannelType(
new ChannelTypeUID("system:low-battery"), false, "Switch", "Low Battery", null, "Battery", null,
new StateDescription(null, null, null, null, true, null), null);
/**
* Battery level default system wide {@link ChannelType}. Represents the battery level as a percentage.
*/
public static final ChannelType SYSTEM_CHANNEL_BATTERY_LEVEL = new ChannelType(
new ChannelTypeUID("system:battery-level"), false, "Number", "Battery Level", null, "Battery", null,
new StateDescription(BigDecimal.ZERO, new BigDecimal(100), BigDecimal.ONE, "%.0f %%", true, null), null);
/**
* System wide trigger {@link ChannelType} without event options.
*/
public static final ChannelType SYSTEM_TRIGGER = new ChannelType(new ChannelTypeUID("system:trigger"), false, null,
ChannelKind.TRIGGER, "Trigger", null, null, null, null, null, null);
/**
* System wide trigger {@link ChannelType} which triggers "PRESSED" and "RELEASED" events.
*/
public static final ChannelType SYSTEM_RAWBUTTON = new ChannelType(new ChannelTypeUID("system:rawbutton"), false,
null, ChannelKind.TRIGGER, "Raw button", null, null, null, null,
new EventDescription(Arrays.asList(new EventOption(CommonTriggerEvents.PRESSED, null),
new EventOption(CommonTriggerEvents.RELEASED, null))),
null);
/**
* System wide trigger {@link ChannelType} which triggers "SHORT_PRESSED", "DOUBLE_PRESSED" and "LONG_PRESSED"
* events.
*/
public static final ChannelType SYSTEM_BUTTON = new ChannelType(new ChannelTypeUID("system:button"), false, null,
ChannelKind.TRIGGER, "Button", null, null, null, null,
new EventDescription(Arrays.asList(new EventOption(CommonTriggerEvents.SHORT_PRESSED, null),
new EventOption(CommonTriggerEvents.DOUBLE_PRESSED, null),
new EventOption(CommonTriggerEvents.LONG_PRESSED, null))),
null);
private final Collection<ChannelType> channelTypes;
public DefaultSystemChannelTypeProvider() {
this.channelTypes = Collections.unmodifiableCollection(
Arrays.asList(new ChannelType[] { SYSTEM_CHANNEL_SIGNAL_STRENGTH, SYSTEM_CHANNEL_LOW_BATTERY,
SYSTEM_CHANNEL_BATTERY_LEVEL, SYSTEM_TRIGGER, SYSTEM_RAWBUTTON, SYSTEM_BUTTON }));
}
@Override
public Collection<ChannelType> getChannelTypes(Locale locale) {
return this.channelTypes;
}
@Override
public ChannelType getChannelType(ChannelTypeUID channelTypeUID, Locale locale) {
if (channelTypeUID.equals(SYSTEM_CHANNEL_SIGNAL_STRENGTH.getUID())) {
return SYSTEM_CHANNEL_SIGNAL_STRENGTH;
} else if (channelTypeUID.equals(SYSTEM_CHANNEL_LOW_BATTERY.getUID())) {
return SYSTEM_CHANNEL_LOW_BATTERY;
} else if (channelTypeUID.equals(SYSTEM_CHANNEL_BATTERY_LEVEL.getUID())) {
return SYSTEM_CHANNEL_BATTERY_LEVEL;
} else if (channelTypeUID.equals(SYSTEM_TRIGGER.getUID())) {
return SYSTEM_TRIGGER;
} else if (channelTypeUID.equals(SYSTEM_RAWBUTTON.getUID())) {
return SYSTEM_RAWBUTTON;
} else if (channelTypeUID.equals(SYSTEM_BUTTON.getUID())) {
return SYSTEM_BUTTON;
}
return null;
}
@Override
public ChannelGroupType getChannelGroupType(ChannelGroupTypeUID channelGroupTypeUID, Locale locale) {
return null;
}
@Override
public Collection<ChannelGroupType> getChannelGroupTypes(Locale locale) {
return Collections.emptyList();
}
}
|
package org.jboss.as.clustering.infinispan.subsystem;
import org.jboss.as.clustering.controller.ResourceDescriptor;
import org.jboss.as.clustering.controller.SimpleResourceRegistration;
import org.jboss.as.clustering.controller.ResourceServiceHandler;
import org.jboss.as.clustering.controller.validation.DoubleRangeValidatorBuilder;
import org.jboss.as.clustering.controller.validation.EnumValidatorBuilder;
import org.jboss.as.clustering.controller.validation.IntRangeValidatorBuilder;
import org.jboss.as.clustering.controller.validation.LongRangeValidatorBuilder;
import org.jboss.as.clustering.controller.validation.ParameterValidatorBuilder;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.as.controller.transform.description.AttributeConverter;
import org.jboss.as.controller.transform.description.DiscardAttributeChecker;
import org.jboss.as.controller.transform.description.RejectAttributeChecker;
import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
public class DistributedCacheResourceDefinition extends SharedStateCacheResourceDefinition {
static final PathElement WILDCARD_PATH = pathElement(PathElement.WILDCARD_VALUE);
static PathElement pathElement(String name) {
return PathElement.pathElement("distributed-cache", name);
}
enum Attribute implements org.jboss.as.clustering.controller.Attribute {
CAPACITY_FACTOR("capacity-factor", ModelType.DOUBLE, new ModelNode(1.0f), new DoubleRangeValidatorBuilder().lowerBound(0).upperBound(Float.MAX_VALUE)),
CONSISTENT_HASH_STRATEGY("consistent-hash-strategy", ModelType.STRING, new ModelNode(ConsistentHashStrategy.INTER_CACHE.name()), new EnumValidatorBuilder<>(ConsistentHashStrategy.class)),
L1_LIFESPAN("l1-lifespan", ModelType.LONG, new ModelNode(600000L), new LongRangeValidatorBuilder().min(0)),
OWNERS("owners", ModelType.INT, new ModelNode(2), new IntRangeValidatorBuilder().min(1)),
SEGMENTS("segments", ModelType.INT, new ModelNode(256), new IntRangeValidatorBuilder().min(1)),
;
private final AttributeDefinition definition;
Attribute(String name, ModelType type, ModelNode defaultValue) {
this.definition = createBuilder(name, type, defaultValue).build();
}
Attribute(String name, ModelType type, ModelNode defaultValue, ParameterValidatorBuilder validator) {
SimpleAttributeDefinitionBuilder builder = createBuilder(name, type, defaultValue);
this.definition = builder.setValidator(validator.configure(builder).build()).build();
}
private static SimpleAttributeDefinitionBuilder createBuilder(String name, ModelType type, ModelNode defaultValue) {
return new SimpleAttributeDefinitionBuilder(name, type)
.setAllowExpression(true)
.setRequired(false)
.setDefaultValue(defaultValue)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setMeasurementUnit((type == ModelType.LONG) ? MeasurementUnit.MILLISECONDS : null)
;
}
@Override
public AttributeDefinition getDefinition() {
return this.definition;
}
}
static void buildTransformation(ModelVersion version, ResourceTransformationDescriptionBuilder parent) {
ResourceTransformationDescriptionBuilder builder = parent.addChildResource(WILDCARD_PATH);
if (InfinispanModel.VERSION_4_1_0.requiresTransformation(version)) {
builder.getAttributeBuilder()
.setValueConverter(new AttributeConverter.DefaultValueAttributeConverter(Attribute.CONSISTENT_HASH_STRATEGY.getDefinition()), Attribute.CONSISTENT_HASH_STRATEGY.getDefinition())
.setValueConverter(new AttributeConverter.DefaultValueAttributeConverter(Attribute.SEGMENTS.getDefinition()), Attribute.SEGMENTS.getDefinition())
.end();
}
if (InfinispanModel.VERSION_3_0_0.requiresTransformation(version)) {
builder.getAttributeBuilder()
.setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(Attribute.CAPACITY_FACTOR.getDefinition().getDefaultValue()), Attribute.CAPACITY_FACTOR.getDefinition())
.addRejectCheck(RejectAttributeChecker.DEFINED, Attribute.CAPACITY_FACTOR.getDefinition())
.setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(new ModelNode(ConsistentHashStrategy.INTRA_CACHE.name())), Attribute.CONSISTENT_HASH_STRATEGY.getDefinition())
.addRejectCheck(RejectAttributeChecker.DEFINED, Attribute.CONSISTENT_HASH_STRATEGY.getDefinition())
.end();
}
SharedStateCacheResourceDefinition.buildTransformation(version, builder);
}
DistributedCacheResourceDefinition(PathManager pathManager, boolean allowRuntimeOnlyRegistration) {
super(WILDCARD_PATH, pathManager, allowRuntimeOnlyRegistration);
}
@SuppressWarnings("deprecation")
@Override
public void register(ManagementResourceRegistration parentRegistration) {
ManagementResourceRegistration registration = parentRegistration.registerSubModel(this);
ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver())
.addAttributes(Attribute.class)
.addAttributes(ClusteredCacheResourceDefinition.Attribute.class)
.addAttributes(ClusteredCacheResourceDefinition.DeprecatedAttribute.class)
.addAttributes(CacheResourceDefinition.Attribute.class)
.addAttributes(CacheResourceDefinition.DeprecatedAttribute.class)
.addCapabilities(CacheResourceDefinition.Capability.class)
.addCapabilities(CacheResourceDefinition.CLUSTERING_CAPABILITIES.values())
.addRequiredChildren(EvictionResourceDefinition.PATH, ExpirationResourceDefinition.PATH, LockingResourceDefinition.PATH, TransactionResourceDefinition.PATH)
.addRequiredChildren(PartitionHandlingResourceDefinition.PATH, StateTransferResourceDefinition.PATH, BackupForResourceDefinition.PATH, BackupsResourceDefinition.PATH)
.addRequiredSingletonChildren(NoStoreResourceDefinition.PATH)
;
ResourceServiceHandler handler = new DistributedCacheServiceHandler();
new SimpleResourceRegistration(descriptor, handler).register(registration);
super.register(registration);
}
}
|
package org.hisp.dhis.tracker.programrule.implementers;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.math.NumberUtils;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.rules.models.RuleActionAssign;
import org.hisp.dhis.setting.SettingKey;
import org.hisp.dhis.setting.SystemSettingManager;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.tracker.bundle.TrackerBundle;
import org.hisp.dhis.tracker.domain.*;
import org.hisp.dhis.tracker.preheat.TrackerPreheat;
import org.hisp.dhis.tracker.programrule.*;
import org.hisp.dhis.tracker.report.TrackerErrorCode;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* This implementer assign a value to a field if it is empty, otherwise returns
* an error
*
* @Author Enrico Colasante
*/
@Component
@RequiredArgsConstructor
public class AssignValueImplementer
extends AbstractRuleActionImplementer<RuleActionAssign>
implements RuleActionImplementer
{
private final SystemSettingManager systemSettingManager;
@Override
public Class<RuleActionAssign> getActionClass()
{
return RuleActionAssign.class;
}
@Override
public String getField( RuleActionAssign ruleAction )
{
return ruleAction.field();
}
@Override
public List<ProgramRuleIssue> applyToEvents( Map.Entry<String, List<EventActionRule>> eventClasses,
TrackerBundle bundle )
{
List<ProgramRuleIssue> issues = Lists.newArrayList();
Boolean canOverwrite = (Boolean) systemSettingManager
.getSystemSetting( SettingKey.RULE_ENGINE_ASSIGN_OVERWRITE );
for ( EventActionRule actionRule : eventClasses.getValue() )
{
if ( !actionRule.getDataValue().isPresent() ||
Boolean.TRUE.equals( canOverwrite ) ||
isTheSameValue( actionRule, bundle.getPreheat() ) )
{
addOrOverwriteDataValue( actionRule, bundle );
issues.add( new ProgramRuleIssue( actionRule.getRuleUid(), TrackerErrorCode.E1308,
Lists.newArrayList( actionRule.getField(), actionRule.getEvent() ), IssueType.WARNING ) );
}
else
{
issues.add( new ProgramRuleIssue( actionRule.getRuleUid(), TrackerErrorCode.E1307,
Lists.newArrayList( actionRule.getField(), actionRule.getValue() ), IssueType.ERROR ) );
}
}
return issues;
}
@Override
public List<ProgramRuleIssue> applyToEnrollments(
Map.Entry<String, List<EnrollmentActionRule>> enrollmentActionRules,
TrackerBundle bundle )
{
List<ProgramRuleIssue> issues = Lists.newArrayList();
Boolean canOverwrite = (Boolean) systemSettingManager
.getSystemSetting( SettingKey.RULE_ENGINE_ASSIGN_OVERWRITE );
for ( EnrollmentActionRule actionRule : enrollmentActionRules.getValue() )
{
if ( !actionRule.getAttribute().isPresent() ||
Boolean.TRUE.equals( canOverwrite ) ||
isTheSameValue( actionRule, bundle.getPreheat() ) )
{
addOrOverwriteAttribute( actionRule, bundle );
issues.add( new ProgramRuleIssue( actionRule.getRuleUid(), TrackerErrorCode.E1310,
Lists.newArrayList( actionRule.getField(), actionRule.getValue() ), IssueType.WARNING ) );
}
else
{
issues.add( new ProgramRuleIssue( actionRule.getRuleUid(), TrackerErrorCode.E1309,
Lists.newArrayList( actionRule.getField(), actionRule.getEnrollment() ), IssueType.ERROR ) );
}
}
return issues;
}
private boolean isTheSameValue( EventActionRule actionRule, TrackerPreheat preheat )
{
DataElement dataElement = preheat.get( DataElement.class, actionRule.getField() );
String dataValue = actionRule.getValue();
Optional<DataValue> optionalDataValue = actionRule.getDataValues().stream()
.filter( dv -> dv.getDataElement().equals( actionRule.getField() ) )
.findAny();
if ( optionalDataValue.isPresent() )
{
return areEquals( dataValue, optionalDataValue.get().getValue(), dataElement.getValueType() );
}
return false;
}
private boolean isTheSameValue( EnrollmentActionRule actionRule, TrackerPreheat preheat )
{
TrackedEntityAttribute attribute = preheat.get( TrackedEntityAttribute.class, actionRule.getField() );
String value = actionRule.getValue();
Optional<Attribute> optionalAttribute = actionRule.getAttributes().stream()
.filter( at -> at.getAttribute().equals( actionRule.getField() ) )
.findAny();
if ( optionalAttribute.isPresent() )
{
return areEquals( value, optionalAttribute.get().getValue(), attribute.getValueType() );
}
return false;
}
private boolean areEquals( String dataValue, String value, ValueType valueType )
{
if ( valueType.isNumeric() )
{
return NumberUtils.isParsable( dataValue ) &&
Double.parseDouble( value ) == Double.parseDouble( dataValue );
}
else
{
return value.equals( dataValue );
}
}
private void addOrOverwriteDataValue( EventActionRule actionRule, TrackerBundle bundle )
{
Set<DataValue> dataValues = bundle.getEvent( actionRule.getEvent() )
.map( Event::getDataValues ).orElse( Sets.newHashSet() );
Optional<DataValue> dataValue = dataValues.stream()
.filter( dv -> dv.getDataElement().equals( actionRule.getField() ) )
.findAny();
if ( dataValue.isPresent() )
{
dataValue.get().setValue( actionRule.getValue() );
}
else
{
dataValues.add( createDataValue( actionRule.getField(), actionRule.getValue() ) );
}
}
private void addOrOverwriteAttribute( EnrollmentActionRule actionRule, TrackerBundle bundle )
{
Enrollment enrollment = bundle.getEnrollment( actionRule.getEnrollment() ).get();
Optional<TrackedEntity> trackedEntity = bundle.getTrackedEntity( enrollment.getTrackedEntity() );
List<Attribute> attributes;
if ( trackedEntity.isPresent() )
{
attributes = trackedEntity.get().getAttributes();
Optional<Attribute> optionalAttribute = attributes.stream()
.filter( at -> at.getAttribute().equals( actionRule.getField() ) )
.findAny();
if ( optionalAttribute.isPresent() )
{
optionalAttribute.get().setValue( actionRule.getData() );
return;
}
}
attributes = enrollment.getAttributes();
Optional<Attribute> optionalAttribute = attributes.stream()
.filter( at -> at.getAttribute().equals( actionRule.getField() ) )
.findAny();
if ( optionalAttribute.isPresent() )
{
optionalAttribute.get().setValue( actionRule.getData() );
}
else
{
attributes.add( createAttribute( actionRule.getField(), actionRule.getData() ) );
}
}
private Attribute createAttribute( String attributeUid, String newValue )
{
Attribute attribute = new Attribute();
attribute.setAttribute( attributeUid );
attribute.setValue( newValue );
return attribute;
}
private DataValue createDataValue( String dataElementUid, String newValue )
{
DataValue dataValue = new DataValue();
dataValue.setDataElement( dataElementUid );
dataValue.setValue( newValue );
return dataValue;
}
}
|
package org.innovateuk.ifs.application;
import org.innovateuk.ifs.application.form.ApplicantInviteForm;
import org.innovateuk.ifs.application.form.ApplicationTeamAddOrganisationForm;
import org.innovateuk.ifs.application.populator.ApplicationTeamAddOrganisationModelPopulator;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.service.ApplicationService;
import org.innovateuk.ifs.commons.error.exception.ForbiddenActionException;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.controller.ValidationHandler;
import org.innovateuk.ifs.invite.resource.ApplicationInviteResource;
import org.innovateuk.ifs.invite.resource.InviteResultsResource;
import org.innovateuk.ifs.invite.service.InviteRestService;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
import static org.innovateuk.ifs.controller.ErrorToObjectErrorConverterFactory.asGlobalErrors;
import static org.innovateuk.ifs.controller.ErrorToObjectErrorConverterFactory.fieldErrorsToFieldErrors;
import static org.innovateuk.ifs.util.CollectionFunctions.forEachWithIndex;
/**
* This controller will handle all requests that are related to adding a new partner organisation to the application team.
*/
@Controller
@RequestMapping("/application/{applicationId}/team")
@PreAuthorize("hasAuthority('applicant')")
public class ApplicationTeamAddOrganisationController {
private static final String FORM_ATTR_NAME = "form";
@Autowired
private ApplicationService applicationService;
@Autowired
private InviteRestService inviteRestService;
@Autowired
private UserService userService;
@Autowired
private ApplicationTeamAddOrganisationModelPopulator applicationTeamAddOrganisationModelPopulator;
@GetMapping("/addOrganisation")
public String getAddOrganisation(Model model,
@PathVariable("applicationId") long applicationId,
@ModelAttribute("loggedInUser") UserResource loggedInUser,
@ModelAttribute(FORM_ATTR_NAME) ApplicationTeamAddOrganisationForm form) {
ApplicationResource applicationResource = applicationService.getById(applicationId);
validateRequest(applicationResource, loggedInUser.getId());
if (form.getApplicants().isEmpty()) {
form.getApplicants().add(new ApplicantInviteForm());
}
return doViewAddOrganisation(model, applicationResource);
}
@PostMapping("/addOrganisation")
public String submitAddOrganisation(Model model,
@PathVariable("applicationId") long applicationId,
@ModelAttribute("loggedInUser") UserResource loggedInUser,
@Valid @ModelAttribute(FORM_ATTR_NAME) ApplicationTeamAddOrganisationForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler) {
ApplicationResource applicationResource = applicationService.getById(applicationId);
validateRequest(applicationResource, loggedInUser.getId());
validateUniqueEmails(form, bindingResult);
Supplier<String> failureView = () -> getAddOrganisation(model, applicationId, loggedInUser, form);
return validationHandler.failNowOrSucceedWith(failureView, () -> {
ServiceResult<InviteResultsResource> updateResult = inviteRestService.createInvitesByInviteOrganisation(
form.getOrganisationName(), createInvites(form, applicationId)).toServiceResult();
return validationHandler.addAnyErrors(updateResult, fieldErrorsToFieldErrors(), asGlobalErrors())
.failNowOrSucceedWith(failureView, () -> format("redirect:/application/%s/team", applicationId));
});
}
@PostMapping(value = "/addOrganisation", params = {"addApplicant"})
public String addApplicant(Model model,
@PathVariable("applicationId") long applicationId,
@ModelAttribute("loggedInUser") UserResource loggedInUser,
@ModelAttribute(FORM_ATTR_NAME) ApplicationTeamAddOrganisationForm form) {
ApplicationResource applicationResource = applicationService.getById(applicationId);
validateRequest(applicationResource, loggedInUser.getId());
form.getApplicants().add(new ApplicantInviteForm());
return doViewAddOrganisation(model, applicationResource);
}
@PostMapping(value = "/addOrganisation", params = {"removeApplicant"})
public String removeApplicant(Model model,
@PathVariable("applicationId") long applicationId,
@ModelAttribute("loggedInUser") UserResource loggedInUser,
@ModelAttribute(FORM_ATTR_NAME) ApplicationTeamAddOrganisationForm form,
@RequestParam(name = "removeApplicant") Integer position) {
ApplicationResource applicationResource = applicationService.getById(applicationId);
validateRequest(applicationResource, loggedInUser.getId());
form.getApplicants().remove(position.intValue());
return doViewAddOrganisation(model, applicationResource);
}
private void validateRequest(ApplicationResource applicationResource, long loggedInUserId) {
checkIfApplicationAlreadySubmitted(applicationResource);
checkUserIsLeadApplicant(applicationResource, loggedInUserId);
}
private void checkIfApplicationAlreadySubmitted(ApplicationResource applicationResource) {
if (applicationResource.hasBeenSubmitted()){
throw new ForbiddenActionException("Application has already been submitted");
}
}
private void checkUserIsLeadApplicant(ApplicationResource applicationResource, long loggedInUserId) {
if (loggedInUserId != getLeadApplicantId(applicationResource)) {
throw new ForbiddenActionException("User must be Lead Applicant");
}
}
private long getLeadApplicantId(ApplicationResource applicationResource) {
return userService.getLeadApplicantProcessRoleOrNull(applicationResource).getUser();
}
private String doViewAddOrganisation(Model model, ApplicationResource applicationResource) {
model.addAttribute("model", applicationTeamAddOrganisationModelPopulator.populateModel(applicationResource));
return "application-team/add-organisation";
}
private List<ApplicationInviteResource> createInvites(ApplicationTeamAddOrganisationForm applicationTeamAddOrganisationForm,
long applicationId) {
return applicationTeamAddOrganisationForm.getApplicants().stream()
.map(applicantInviteForm -> createInvite(applicantInviteForm, applicationId)).collect(toList());
}
private ApplicationInviteResource createInvite(ApplicantInviteForm applicantInviteForm, long applicationId) {
return new ApplicationInviteResource(applicantInviteForm.getName(), applicantInviteForm.getEmail(), applicationId);
}
private void validateUniqueEmails(ApplicationTeamAddOrganisationForm form, BindingResult bindingResult) {
Set<String> emails = new HashSet<>();
forEachWithIndex(form.getApplicants(), (index, applicantInviteForm) -> {
if (!emails.add(applicantInviteForm.getEmail())) {
bindingResult.rejectValue(format("applicants[%s].email", index), "validation.applicationteamaddorganisationform.email.notUnique");
}
});
}
}
|
package io.novaordis.playground.jee.ejb.mdb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageListener;
import javax.jms.Message;
import javax.ejb.MessageDriven;
import javax.ejb.ActivationConfigProperty;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import org.jboss.ejb3.annotation.ResourceAdapter;
/**
* @author <a href="mailto:ovidiu@novardis.com">Ovidiu Feodorov</a>
* @version <tt>$Revision: 1.2 $</tt>
*/
@SuppressWarnings("unused")
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(propertyName="destination", propertyValue="/jms/queue/remote-inbound"),
})
@ResourceAdapter("hornetq-remote-ra")
public class MDB implements MessageListener {
private static final Logger log = LoggerFactory.getLogger(MDB.class);
@Resource(lookup = "java:global/remote-hornetq")
private InitialContext externalContext;
@Resource(name = "java:/RemoteJmsXA")
private ConnectionFactory cf;
public MDB() {
log.info(this + " constructed");
}
@Override
public void onMessage(Message message) {
// this example will only work with TextMessages
TextMessage tm = (TextMessage)message;
Connection c = null;
try {
String text = tm.getText();
log.info(this + " received message \"" + text + "\"");
// look up the response destination and send a response message
Queue responseQueue = (Queue)externalContext.lookup("/jms/queue/remote-outbound");
c = cf.createConnection();
Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer p = s.createProducer(responseQueue);
Message m = s.createTextMessage("processed " + text);
p.send(m);
log.info(this + " sent response");
}
catch(Exception e) {
log.error(e.getMessage(), e);
}
finally {
if (c != null) {
try {
c.close();
}
catch (Exception e) {
log.error("failed to close connection", e);
}
}
}
}
@Override
public String toString() {
return "MDB[" + Integer.toHexString(System.identityHashCode(this)) + "]";
}
}
|
package com.atlassian.jira.plugins.dvcs.spi.bitbucket;
import org.apache.commons.lang.StringUtils;
import com.atlassian.jira.plugins.dvcs.crypto.Encryptor;
import com.atlassian.jira.plugins.dvcs.model.Organization;
import com.atlassian.jira.plugins.dvcs.model.Repository;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.client.BitbucketRemoteClient;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.AuthProvider;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.BasicAuthAuthProvider;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.NoAuthAuthProvider;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.scribe.ThreeLegged10aOauthProvider;
/**
* BitbucketRemoteClientFactory
*
* @author Martin Skurla mskurla@atlassian.com
*/
public final class DefaultBitbucketRemoteClientFactory implements BitbucketClientRemoteFactory
{
private final BitbucketOAuth oauth;
private final Encryptor encryptor;
public DefaultBitbucketRemoteClientFactory(BitbucketOAuth oauth, Encryptor encryptor)
{
this.oauth = oauth;
this.encryptor = encryptor;
}
@Override
public BitbucketRemoteClient getForOrganization(Organization organization)
{
AuthProvider authProvider = createProviderForOrganization(organization);
return new BitbucketRemoteClient(authProvider);
}
@Override
public BitbucketRemoteClient getForRepository(Repository repository)
{
AuthProvider authProvider = createProviderForRepository(repository);
return new BitbucketRemoteClient(authProvider);
}
@Override
public BitbucketRemoteClient getNoAuthClient(String hostUrl)
{
AuthProvider authProvider = new NoAuthAuthProvider(hostUrl);
return new BitbucketRemoteClient(authProvider);
}
private AuthProvider createProviderForOrganization(Organization organization)
{
AuthProvider authProvider = new NoAuthAuthProvider(organization.getHostUrl());
if (StringUtils.isNotBlank(organization.getCredential().getAdminUsername()))
{
String decryptedPassword = encryptor.decrypt(organization.getCredential().getAdminPassword(),
organization.getName(),
organization.getHostUrl());
authProvider = new BasicAuthAuthProvider(organization.getHostUrl(),
organization.getCredential().getAdminUsername(),
decryptedPassword);
}
else if (StringUtils.isNotBlank( organization.getCredential().getAccessToken()) )
{
authProvider = new ThreeLegged10aOauthProvider(organization.getHostUrl(), oauth.getClientId(),
oauth.getClientSecret(), organization.getCredential().getAccessToken());
}
return authProvider;
}
private AuthProvider createProviderForRepository(Repository repository)
{
AuthProvider authProvider = new NoAuthAuthProvider(repository.getOrgHostUrl());
if (StringUtils.isNotBlank(repository.getCredential().getAdminUsername()))
{
String decryptedPassword = encryptor.decrypt(repository.getCredential().getAdminPassword(),
repository.getOrgName(),
repository.getOrgHostUrl());
authProvider = new BasicAuthAuthProvider(repository.getOrgHostUrl(),
repository.getCredential().getAdminUsername(),
decryptedPassword);
}
else if (StringUtils.isNotBlank( repository.getCredential().getAccessToken()) )
{
authProvider = new ThreeLegged10aOauthProvider(repository.getOrgHostUrl(), oauth.getClientId(),
oauth.getClientSecret(), repository.getCredential().getAccessToken());
}
return authProvider;
}
}
|
package eu.diachron.qualitymetrics.accessibility;
import java.util.List;
import com.hp.hpl.jena.sparql.core.Quad;
import de.unibonn.iai.eis.diachron.datatypes.Pair;
import de.unibonn.iai.eis.luzzu.cache.CacheManager;
import de.unibonn.iai.eis.luzzu.properties.PropertyManager;
import eu.diachron.qualitymetrics.accessibility.availability.Dereferenceability;
import eu.diachron.qualitymetrics.accessibility.availability.EstimatedDereferenceability;
import eu.diachron.qualitymetrics.accessibility.availability.EstimatedDereferenceabilityByStratified;
import eu.diachron.qualitymetrics.accessibility.availability.EstimatedDereferenceabilityByTld;
import eu.diachron.qualitymetrics.cache.DiachronCacheManager;
import eu.diachron.qualitymetrics.utilities.TestLoader;
/**
* @author Jeremy Debattista
*
*/
public class SamplingEvaluation {
protected static TestLoader loader = new TestLoader();
protected static int[] paramsEstDeref = { 50, 100, 1000, 5000, 10000, 25000, 50000, 100000};
protected static Pair<?,?>[] paramsTLDExt = new Pair<?,?>[] {
new Pair<Integer, Integer>(10,50),
new Pair<Integer, Integer>(10,100),
new Pair<Integer, Integer>(10,1000),
new Pair<Integer, Integer>(10,5000),
new Pair<Integer, Integer>(10,10000),
new Pair<Integer, Integer>(10,25000),
new Pair<Integer, Integer>(10,50000),
new Pair<Integer, Integer>(10,100000),
new Pair<Integer, Integer>(50,50),
new Pair<Integer, Integer>(50,100),
new Pair<Integer, Integer>(50,1000),
new Pair<Integer, Integer>(50,5000),
new Pair<Integer, Integer>(50,10000),
new Pair<Integer, Integer>(50,25000),
new Pair<Integer, Integer>(50,50000),
new Pair<Integer, Integer>(50,100000)
};
protected static String[] datasets = {
// "/Users/jeremy/Dropbox/pdev-lemon.nt.gz",
"/Users/jeremy/Dropbox/wals.info.nt.gz"
};
public static void dereferenceability(String dataset){
loader.loadDataSet(dataset);
PropertyManager.getInstance().addToEnvironmentVars("baseURI", "http://social.mercedes-benz.com/de/");
System.out.println("Evaluating Dereferencability");
long tMin = Long.MAX_VALUE;
long tMax = Long.MIN_VALUE;
long tAvg = 0;
for (int i = -1; i < 2; i++){
List<Quad> streamingQuads = loader.getStreamingQuads();
long tStart = System.currentTimeMillis();
Dereferenceability m = new Dereferenceability();
for(Quad quad : streamingQuads){
m.compute(quad);
}
if (i < 0){
m.metricValue();
} else {
System.out.println("Count : " + i + " Value : "+ m.metricValue());
}
long tEnd = System.currentTimeMillis();
if (i >= 0){
long difference = tEnd - tStart;
tAvg += difference;
tMax = (tMax < difference) ? difference : tMax;
tMin = (tMin > difference) ? difference : tMin;
}
}
tAvg = tAvg/2;
System.out.println("Min: "+ (tMin/1000.0) + " Max: "+ (tMax/1000.0) + " Avg: "+ (tAvg/1000.0));
}
public static void estimatedDereferenceability(String dataset){
loader.loadDataSet(dataset);
PropertyManager.getInstance().addToEnvironmentVars("baseURI", "http://social.mercedes-benz.com/de/");
System.out.println("Evaluating EstimatedDereferenceability");
for (int param : paramsEstDeref){
System.out.println("Parameter: "+ param);
long tMin = Long.MAX_VALUE;
long tMax = Long.MIN_VALUE;
long tAvg = 0;
for (int i = -1; i < 2; i++){
List<Quad> streamingQuads = loader.getStreamingQuads();
long tStart = System.currentTimeMillis();
EstimatedDereferenceability m = new EstimatedDereferenceability();
m.setMAX_FQURIS(param);
for(Quad quad : streamingQuads){
m.compute(quad);
}
if (i < 0){
m.metricValue();
} else {
System.out.println("Count : " + i + " Value : "+ m.metricValue());
}
long tEnd = System.currentTimeMillis();
if (i >= 0){
long difference = tEnd - tStart;
tAvg += difference;
tMax = (tMax < difference) ? difference : tMax;
tMin = (tMin > difference) ? difference : tMin;
}
CacheManager.getInstance().clearCache(DiachronCacheManager.HTTP_RESOURCE_CACHE);
}
tAvg = tAvg/2;
System.out.println("Min: "+ (tMin/1000.0) + " Max: "+ (tMax/1000.0) + " Avg: "+ (tAvg/1000.0));
}
}
public static void estimatedDereferenceabilityTLD(String dataset){
loader.loadDataSet(dataset);
PropertyManager.getInstance().addToEnvironmentVars("baseURI", "http://social.mercedes-benz.com/de/");
System.out.println("Evaluating EstimatedDereferenceabilityTLD");
for (Pair<?,?> param : paramsTLDExt){
System.out.println("Parameter: "+ param);
long tMin = Long.MAX_VALUE;
long tMax = Long.MIN_VALUE;
long tAvg = 0;
for (int i = -1; i < 2; i++){
List<Quad> streamingQuads = loader.getStreamingQuads();
long tStart = System.currentTimeMillis();
EstimatedDereferenceabilityByTld m = new EstimatedDereferenceabilityByTld();
m.MAX_TLDS = (Integer) param.getFirstElement();
m.MAX_FQURIS_PER_TLD = (Integer) param.getSecondElement();
for(Quad quad : streamingQuads){
m.compute(quad);
}
if (i < 0){
m.metricValue();
} else {
System.out.println("Count : " + i + " Value : "+ m.metricValue());
}
long tEnd = System.currentTimeMillis();
if (i >= 0){
long difference = tEnd - tStart;
tAvg += difference;
tMax = (tMax < difference) ? difference : tMax;
tMin = (tMin > difference) ? difference : tMin;
}
CacheManager.getInstance().clearCache(DiachronCacheManager.HTTP_RESOURCE_CACHE);
}
tAvg = tAvg/2;
System.out.println("Min: "+ (tMin/1000.0) + " Max: "+ (tMax/1000.0) + " Avg: "+ (tAvg/1000.0));
}
}
public static void estimatedDereferenceabilityByStratified(String dataset){
loader.loadDataSet(dataset);
PropertyManager.getInstance().addToEnvironmentVars("baseURI", "http://social.mercedes-benz.com/de/");
System.out.println("Evaluating EstimatedDereferenceabilityByStratified");
for (Pair<?,?> param : paramsTLDExt){
System.out.println("Parameter: "+ param);
long tMin = Long.MAX_VALUE;
long tMax = Long.MIN_VALUE;
long tAvg = 0;
for (int i = -1; i < 2; i++){
List<Quad> streamingQuads = loader.getStreamingQuads();
long tStart = System.currentTimeMillis();
EstimatedDereferenceabilityByStratified m = new EstimatedDereferenceabilityByStratified();
m.MAX_TLDS = (Integer) param.getFirstElement();
m.MAX_FQURIS_PER_TLD = (Integer) param.getSecondElement();
for(Quad quad : streamingQuads){
m.compute(quad);
}
if (i < 0){
m.metricValue();
} else {
System.out.println("Count : " + i + " Value : "+ m.metricValue());
}
long tEnd = System.currentTimeMillis();
if (i >= 0){
long difference = tEnd - tStart;
tAvg += difference;
tMax = (tMax < difference) ? difference : tMax;
tMin = (tMin > difference) ? difference : tMin;
}
CacheManager.getInstance().clearCache(DiachronCacheManager.HTTP_RESOURCE_CACHE);
}
tAvg = tAvg/2;
System.out.println("Min: "+ (tMin/1000.0) + " Max: "+ (tMax/1000.0) + " Avg: "+ (tAvg/1000.0));
}
}
public static void main (String [] args) {
for (String d : datasets){
// dereferenceability(d);
estimatedDereferenceabilityByStratified(d);
estimatedDereferenceability(d);
estimatedDereferenceabilityTLD(d);
}
}
}
|
package com.kaltura.playersdk.ima;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.google.ads.interactivemedia.v3.api.AdDisplayContainer;
import com.google.ads.interactivemedia.v3.api.AdErrorEvent;
import com.google.ads.interactivemedia.v3.api.AdEvent;
import com.google.ads.interactivemedia.v3.api.AdsLoader;
import com.google.ads.interactivemedia.v3.api.AdsManager;
import com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent;
import com.google.ads.interactivemedia.v3.api.AdsRequest;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer;
import com.google.ads.interactivemedia.v3.api.player.VideoProgressUpdate;
import com.google.android.exoplayer.ExoPlayer;
import com.google.android.libraries.mediaframework.exoplayerextensions.ExoplayerWrapper;
import com.google.android.libraries.mediaframework.exoplayerextensions.Video;
import com.google.android.libraries.mediaframework.layeredvideo.SimpleVideoPlayer;
import com.google.android.libraries.mediaframework.layeredvideo.Util;
import com.kaltura.playersdk.VideoPlayerInterface;
import com.kaltura.playersdk.events.KPlayerEventListener;
import com.kaltura.playersdk.events.OnPlayerStateChangeListener;
import com.kaltura.playersdk.events.OnPlayheadUpdateListener;
import com.kaltura.playersdk.events.OnProgressListener;
public class IMAPlayer extends RelativeLayout implements VideoPlayerInterface {
public static int PLAYHEAD_UPDATE_INTERVAL = 200;
private OnPlayerStateChangeListener mPlayerStateListener;
private OnPlayheadUpdateListener mPlayheadUpdateListener;
private OnProgressListener mProgressListener;
private KPlayerEventListener mKPlayerEventListener;
/**
* Responsible for requesting the ad and creating the
* {@link com.google.ads.interactivemedia.v3.api.AdsManager}
*/
private AdsLoader adsLoader;
/**
* Responsible for containing listeners for processing the elements of the ad.
*/
private AdsManager adsManager;
/**
* URL of the ad
*/
private Uri mAdTagUrl;
/**
* These callbacks are notified when the video is played and when it ends. The IMA SDK uses this
* to poll for video progress and when to stop the ad.
*/
private List<VideoAdPlayer.VideoAdPlayerCallback> callbacks;
FrameLayout adPlayerContainer;
FrameLayout adUiContainer;
private VideoPlayerInterface mContentPlayer;
private SimpleVideoPlayer mAdPlayer;
private boolean isInSequence;
private Activity mActivity;
private Handler mHandler;
private JSONObject mTimeRemainingObj = new JSONObject();
private Runnable runnable = new Runnable() {
@Override
public void run() {
if ( isInSequence && mKPlayerEventListener!=null ) {
try {
mTimeRemainingObj.put("time", videoAdPlayer.getProgress().getCurrentTime() );
mTimeRemainingObj.put("duration", videoAdPlayer.getProgress().getDuration() );
float remain = videoAdPlayer.getProgress().getDuration() - videoAdPlayer.getProgress().getCurrentTime();
mTimeRemainingObj.put("remain", remain );
mKPlayerEventListener.onKPlayerEvent( new Object[]{"adRemainingTimeChange", mTimeRemainingObj} );
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(this.getClass().getSimpleName(), "failed to send adRemainingTimeChange!");
}
}
mHandler.postDelayed(this, PLAYHEAD_UPDATE_INTERVAL);
}
};
public IMAPlayer(Context context) {
super(context);
}
public IMAPlayer(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IMAPlayer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setParams( VideoPlayerInterface contentPlayer, String adTagUrl, Activity activity, KPlayerEventListener listener ) {
mActivity = activity;
mKPlayerEventListener = listener;
mContentPlayer = contentPlayer;
mAdTagUrl = Uri.parse(adTagUrl);
isInSequence = false;
if ( contentPlayer instanceof View ) {
addView( (View) contentPlayer );
}
adsLoader = ImaSdkFactory.getInstance().createAdsLoader(activity, ImaSdkFactory.getInstance().createImaSdkSettings());
AdListener adListener = new AdListener();
adsLoader.addAdErrorListener(adListener);
adsLoader.addAdsLoadedListener(adListener);
callbacks = new ArrayList<VideoAdPlayer.VideoAdPlayerCallback>();
}
public void setAdTagUrl( String adTagUrl ) {
mAdTagUrl = Uri.parse(adTagUrl);
}
@Override
public String getVideoUrl() {
if ( mContentPlayer!= null ) {
return mContentPlayer.getVideoUrl();
}
return null;
}
@Override
public void setVideoUrl(String url) {
if ( mContentPlayer != null ) {
mContentPlayer.setVideoUrl( url );
}
}
@Override
public int getDuration() {
if ( mContentPlayer!=null ) {
if ( isInSequence ) {
return mAdPlayer.getDuration();
} else {
return mContentPlayer.getDuration();
}
}
return 0;
}
@Override
public boolean getIsPlaying() {
return isPlaying();
}
@Override
public void play() {
if (mAdTagUrl != null) {
requestAd();
} else {
mContentPlayer.play();
}
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void stop() {
// TODO Auto-generated method stub
}
@Override
public void seek(int msec) {
//TODO
/* if ( isInSequence ) {
mAdPlayer.seekTo( msec );
} else {
mContentPlayer.seek(msec);
}*/
}
@Override
public boolean isPlaying() {
if ( isInSequence )
return true;
if ( mContentPlayer!= null ) {
return ( mContentPlayer.isPlaying() );
}
return false;
}
@Override
public boolean canPause() {
if ( mContentPlayer!= null ) {
if ( isInSequence ) {
return false;
} else {
return mContentPlayer.canPause();
}
}
return false;
}
@Override
public void registerPlayerStateChange( OnPlayerStateChangeListener listener) {
mPlayerStateListener = listener;
if ( !isInSequence && mContentPlayer!=null ) {
mContentPlayer.registerPlayerStateChange ( listener );
}
}
@Override
public void registerReadyToPlay( MediaPlayer.OnPreparedListener listener) {
//TODO
}
@Override
public void registerError( MediaPlayer.OnErrorListener listener) {
//TODO
}
@Override
public void registerPlayheadUpdate( OnPlayheadUpdateListener listener ) {
mPlayheadUpdateListener = listener;
if ( !isInSequence && mContentPlayer!=null ) {
mContentPlayer.registerPlayheadUpdate ( listener );
}
}
@Override
public void removePlayheadUpdateListener() {
mPlayheadUpdateListener = null;
if ( !isInSequence && mContentPlayer!=null ) {
mContentPlayer.removePlayheadUpdateListener ();
}
}
@Override
public void registerProgressUpdate ( OnProgressListener listener ) {
mProgressListener = listener;
if ( !isInSequence && mContentPlayer!=null ) {
mContentPlayer.registerProgressUpdate ( listener );
}
}
private void hideContentPlayer() {
if ( !isInSequence ) {
isInSequence = true;
if ( mContentPlayer.canPause() )
mContentPlayer.pause();
if ( mContentPlayer instanceof View )
( (View) mContentPlayer ).setVisibility(View.GONE);
//unregister events
mContentPlayer.registerPlayerStateChange( null );
mContentPlayer.registerPlayheadUpdate( null );
mContentPlayer.registerProgressUpdate( null );
}
}
private void showContentPlayer() {
if ( isInSequence ) {
isInSequence = false;
destroyAdPlayer();
if ( mContentPlayer instanceof View )
addView( (View) mContentPlayer );
//register events
mContentPlayer.registerPlayerStateChange( mPlayerStateListener );
mContentPlayer.registerPlayheadUpdate( mPlayheadUpdateListener );
mContentPlayer.registerProgressUpdate( mProgressListener );
mContentPlayer.play();
}
}
/**
* Destroy the {@link SimpleVideoPlayer} responsible for playing the ad and rmeove it.
*/
private void destroyAdPlayer(){
if(adPlayerContainer != null){
removeView(adPlayerContainer);
}
if (adUiContainer != null) {
removeView(adUiContainer);
}
if(mAdPlayer != null){
mAdPlayer.release();
}
adPlayerContainer = null;
mAdPlayer = null;
}
private void createAdPlayer(){
destroyAdPlayer();
adPlayerContainer = new FrameLayout(mActivity);
addView(adPlayerContainer);
Video adVideo = new Video(mAdTagUrl.toString(), Video.VideoType.MP4);
mAdPlayer = new SimpleVideoPlayer(mActivity,
adPlayerContainer,
adVideo,
"",
true);
mAdPlayer.addPlaybackListener(playbackListener);
// Move the ad player's surface layer to the foreground so that it is overlaid on the content
// player's surface layer (which is in the background).
mAdPlayer.moveSurfaceToForeground();
mAdPlayer.play();
mAdPlayer.disableSeeking();
// mAdPlayer.setSeekbarColor(Color.YELLOW);
mAdPlayer.hideTopChrome();
//TODO? mAdPlayer.setFullscreen(contentPlayer.isFullscreen());
// Move the ad player's surface layer to the foreground so that it is overlaid on the content
// player's surface layer (which is in the background).
isInSequence = true;
adPlayerContainer.setLayoutParams(Util.getLayoutParamsBasedOnParent(
adPlayerContainer,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
if ( adUiContainer.getParent() != null ) {
removeView ( adUiContainer );
}
addView ( adUiContainer );
// Notify the callbacks that the ad has begun playing.
/*for (VideoAdPlayer.VideoAdPlayerCallback callback : callbacks) {
callback.onPlay();
}*/
}
/**
* Create an ads request which will request the VAST document with the given ad tag URL.
* @param tagUrl URL pointing to a VAST document of an ad.
* @return a request for the VAST document.
*/
private AdsRequest buildAdsRequest(String tagUrl) {
// Create the ad adDisplayContainer UI which will be used by the IMA SDK to overlay ad controls.
adUiContainer = new FrameLayout(mActivity);
addView(adUiContainer);
adUiContainer.setLayoutParams(Util.getLayoutParamsBasedOnParent(
adUiContainer,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
AdDisplayContainer adDisplayContainer = ImaSdkFactory.getInstance().createAdDisplayContainer();
adDisplayContainer.setPlayer(videoAdPlayer);
adDisplayContainer.setAdContainer(adUiContainer);
AdsRequest request = ImaSdkFactory.getInstance().createAdsRequest();
request.setAdTagUrl(tagUrl);
request.setAdDisplayContainer(adDisplayContainer);
return request;
}
/**
* Make the ads loader request an ad with the ad tag URL which this {@link ImaPlayer} was
* created with
*/
private void requestAd() {
adsLoader.requestAds(buildAdsRequest(mAdTagUrl.toString()));
}
/**
* Handles loading, playing, retrieving progress, pausing, resuming, and stopping ad.
*/
private final VideoAdPlayer videoAdPlayer = new VideoAdPlayer() {
@Override
public void playAd() {
hideContentPlayer();
}
@Override
public void loadAd(String mediaUri) {
mAdTagUrl = Uri.parse(mediaUri);
createAdPlayer();
}
@Override
public void stopAd() {
//hideAdPlayer();
showContentPlayer();
}
@Override
public void pauseAd() {
if (mAdPlayer != null){
mAdPlayer.pause();
}
}
@Override
public void resumeAd() {
if(mAdPlayer != null) {
mAdPlayer.play();
}
}
@Override
public void addCallback(VideoAdPlayerCallback videoAdPlayerCallback) {
callbacks.add(videoAdPlayerCallback);
}
@Override
public void removeCallback(VideoAdPlayerCallback videoAdPlayerCallback) {
callbacks.remove(videoAdPlayerCallback);
}
private VideoProgressUpdate oldVpu;
/**
* Reports progress in ad player or content player (whichever is currently playing).
*
* NOTE: When the ad is buffering, the video is paused. However, when the buffering is
* complete, the ad is resumed. So, as a workaround, we will attempt to resume the ad, by
* calling the start method, whenever we detect that the ad is buffering. If the ad is done
* buffering, the start method will resume playback. If the ad has not finished buffering,
* then the start method will be ignored.
*/
@Override
public VideoProgressUpdate getProgress() {
VideoProgressUpdate vpu = null;
if ( isInSequence && mAdPlayer!=null ) {
vpu = new VideoProgressUpdate(mAdPlayer.getCurrentPosition(),
mAdPlayer.getDuration());
} else {
vpu = VideoProgressUpdate.VIDEO_TIME_NOT_READY;
}
/* if (mAdPlayer != null && mAdPlayer.shouldBePlaying()) {
adPlayer.pause();
adPlayer.play();
}
}*/
oldVpu = vpu;
return vpu;
}
};
/**
* Notifies callbacks when the ad finishes.
*/
private final ExoplayerWrapper.PlaybackListener playbackListener
= new ExoplayerWrapper.PlaybackListener() {
/**
* @param e The error.
*/
@Override
public void onError(Exception e) {
}
/**
* We notify all callbacks when the ad ends.
* @param playWhenReady Whether the video should play as soon as it is loaded.
* @param playbackState The state of the Exoplayer instance.
*/
@Override
public void onStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_ENDED) {
adsLoader.contentComplete();
for (VideoAdPlayer.VideoAdPlayerCallback callback : callbacks) {
callback.onEnded();
}
}
}
/**
* We don't respond to size changes.
* @param width The new width of the player.
* @param height The new height of the player.
*/
@Override
public void onVideoSizeChanged(int width, int height) {
}
};
/**
* Sets up ads manager, responds to ad errors, and handles ad state changes.
*/
private class AdListener implements AdErrorEvent.AdErrorListener,
AdsLoader.AdsLoadedListener, AdEvent.AdEventListener {
@Override
public void onAdError(AdErrorEvent adErrorEvent) {
// If there is an error in ad playback, log the error and resume the content.
Log.d(this.getClass().getSimpleName(), adErrorEvent.getError().getMessage());
if ( mKPlayerEventListener!=null ) {
mKPlayerEventListener.onKPlayerEvent( "adsLoadError" );
}
}
@Override
public void onAdEvent(AdEvent event) {
Object[] eventObject = null;
try {
JSONObject obj = new JSONObject();
switch (event.getType()) {
case LOADED:
adsManager.start();
obj.put("isLinear", event.getAd().isLinear());
obj.put("adID", event.getAd().getAdId());
obj.put("adSystem", event.getAd().getAdSystem());
obj.put("adPosition", event.getAd().getAdPodInfo().getAdPosition());
eventObject = new Object[]{"adLoaded", obj};
if ( mHandler == null ) {
mHandler = new Handler();
}
mHandler.postDelayed(runnable, PLAYHEAD_UPDATE_INTERVAL);
if ( mKPlayerEventListener!=null && eventObject!=null ) {
mKPlayerEventListener.onKPlayerEvent( eventObject );
}
//handle bug that "STARTED" is not sent
obj.put("context", null);
obj.put("duration", event.getAd().getDuration());
//obj.put("adID", event.getAd().getAdId());
eventObject = new Object[]{"adStart", obj};
break;
case STARTED:
//not being sent?
// obj.put("context", null);
// obj.put("duration", event.getAd().getDuration());
// obj.put("adID", event.getAd().getAdId());
// eventObject = new Object[]{"adStart", obj};
break;
case COMPLETED:
obj.put("adID", event.getAd().getAdId());
eventObject = new Object[]{"adCompleted", obj};
if ( mHandler != null ) {
mHandler.removeCallbacks( runnable );
}
break;
case ALL_ADS_COMPLETED:
eventObject = new Object[]{"allAdsCompleted"};
break;
case CONTENT_PAUSE_REQUESTED:
eventObject = new Object[]{"contentPauseRequested"};
hideContentPlayer();
break;
case CONTENT_RESUME_REQUESTED:
eventObject = new Object[]{"contentResumeRequested"};
destroyAdPlayer();
showContentPlayer();
break;
case FIRST_QUARTILE:
eventObject = new Object[]{"firstQuartile"};
break;
case MIDPOINT:
eventObject = new Object[]{"midpoint"};
break;
case THIRD_QUARTILE:
eventObject = new Object[]{"thirdQuartile"};
break;
default:
break;
}
if ( mKPlayerEventListener!=null && eventObject!=null ) {
mKPlayerEventListener.onKPlayerEvent( eventObject );
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(this.getClass().getSimpleName(), "failed to handle ad events!");
}
}
@Override
public void onAdsManagerLoaded(AdsManagerLoadedEvent adsManagerLoadedEvent) {
adsManager = adsManagerLoadedEvent.getAdsManager();
adsManager.addAdErrorListener(this);
adsManager.addAdEventListener(this);
adsManager.init();
if ( mKPlayerEventListener!=null ) {
mKPlayerEventListener.onKPlayerEvent( "adLoadedEvent" );
}
}
}
@Override
public void setStartingPoint(int point) {
if ( mContentPlayer!= null ) {
mContentPlayer.setStartingPoint(point);
}
}
}
|
package com.exphc.FreeTrade;
import java.util.logging.Logger;
import java.util.regex.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.SortedSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.io.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.*;
import org.bukkit.command.*;
import org.bukkit.entity.*;
import org.bukkit.inventory.*;
import org.bukkit.enchantments.*;
import org.bukkit.configuration.*;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.*;
import info.somethingodd.bukkit.OddItem.OddItem;
enum Obtainability
{
NORMAL, SILKTOUCH, CREATIVE, HACKING, NEVER
};
class ItemQuery
{
ItemStack itemStack;
static Logger log = Logger.getLogger("Minecraft");
// Map between item names/aliases and id;dmg string
static ConcurrentHashMap<String,String> name2CodeName;
static ConcurrentHashMap<String,String> codeName2Name;
static ConcurrentHashMap<String,Obtainability> obtainMap;
static ConcurrentHashMap<Material,Boolean> isDurableMap;
public ItemQuery(String s) {
//Pattern onp = Pattern.compile( "^(\\d+)"
Pattern p = Pattern.compile(
"^(\\d*)" + // quantity
"([# :;-]?)" + // separator / stack flag
"([^/\\\\]+)" + // name
"([/\\\\]?)" + // separator / damage flag
"([\\d%]*)" + // use / damage
"/?([^/]*)$"); // enchant
Matcher m = p.matcher(s);
int quantity;
if (!m.find()) {
throw new UsageException("Unrecognized item specification: " + s);
}
String quantityString = m.group(1);
String isStackString = m.group(2);
String nameString = m.group(3);
String dmgOrUsesString = m.group(4);
String usesString = m.group(5);
String enchString = m.group(6);
if (quantityString.equals("")) {
quantity = 1;
} else {
quantity = Integer.parseInt(quantityString);
if (quantity < 1) {
throw new UsageException("Invalid quantity: " + quantity);
}
}
// Name
// Allowed to be any case, with or without any word separators
nameString = nameString.replaceAll("[ _-]", "").toLowerCase();
if (nameString.contains("*")) {
// Wildcard expressions
SortedSet<String> results = wildcardLookupName(nameString);
if (results.size() == 0) {
throw new UsageException("No items match pattern " + nameString);
}
if (results.size() > 1) {
StringBuffer nameMatches = new StringBuffer();
for (String resultName: results) {
nameMatches.append(resultName + ", ");
}
throw new UsageException("Found " + results.size() + " matching items: " + nameMatches);
}
// Exactly one hit, use it
nameString = results.first().toLowerCase();
}
// First try built-in name lookup
itemStack = directLookupName(nameString);
if (itemStack == null) {
// If available, try OddItem for better names or clever suggestions
if (Bukkit.getServer().getPluginManager().getPlugin("OddItem") != null) {
try {
itemStack = OddItem.getItemStack(nameString).clone();
} catch (IllegalArgumentException suggestion) {
throw new UsageException("No such item '" + nameString + "', did you mean '" + suggestion.getMessage() + "'?");
}
} else {
// Worst case, lookup name from Bukkit itself
// Not very good because doesn't include damage value subtypes
Material material = Material.matchMaterial(nameString);
if (material == null) {
throw new UsageException("Unrecognized item name: " + nameString + " (no suggestions available)");
}
itemStack = new ItemStack(material);
}
}
if (itemStack == null) {
throw new UsageException("Unrecognized item name: " + nameString);
}
// Quantity, shorthand 10# = 10 stacks
if (isStackString.equals("
quantity *= Math.abs(itemStack.getType().getMaxStackSize());
}
itemStack.setAmount(quantity);
// Damage value aka durability
// User specifies how much they want left, 100% = unused tool
short maxDamage = itemStack.getType().getMaxDurability();
if (usesString != null && !usesString.equals("")) {
short damage;
short value;
if (usesString.endsWith("%")) {
String percentageString = usesString.substring(0, usesString.length() - 1);
double percentage = Double.parseDouble(percentageString);
value = (short)(percentage / 100.0 * maxDamage);
} else {
value = Short.parseShort(usesString);
}
// Normally, convenient for user to specify percent or times left (inverse of damage), /
// Allow \ separator to specify damage itself
if (dmgOrUsesString.equals("\\")) {
damage = value;
} else {
damage = (short)(maxDamage - value);
}
if (damage > maxDamage) {
damage = maxDamage; // Breaks right after one use
}
if (damage < 0) {
damage = 0; // Completely unused
}
itemStack.setDurability(damage);
} else {
// If they didn't specify a durability, but they want a durable item, assume no damage (0)
// TODO: only assume 0 for wants. For gives, need to use value from inventory! Underspecified
}
// TODO: enchantments
if (enchString != null && !enchString.equals("")) {
EnchantQuery enchs = new EnchantQuery(enchString);
itemStack.addEnchantments(enchs.all);
}
}
public ItemQuery(String s, Player p) {
if (s.equals("this")) {
itemStack = p.getItemInHand();
if (itemStack == null) {
throw new UsageException("No item in hand");
}
} else {
itemStack = (new ItemQuery(s)).itemStack;
}
}
// Return whether an item degrades when used
public static boolean isDurable(Material m) {
return isDurableMap.containsKey(m);
}
public static String nameStack(ItemStack itemStack) {
if (isNothing(itemStack)) {
return "nothing";
}
String name, usesString, enchString;
Material m = itemStack.getType();
// If all else fails, use generic name from Bukkit
name = itemStack.getType().toString();
if (isDurable(m)) {
// Percentage remaining
// Round down so '100%' always means completely unused? (1 dmg = 99%)
//int percentage = Math.round(Math.floor((m.getMaxDurability() - itemStack.getDurability()) * 100.0 / m.getMaxDurability()))
// but then lower percentages are always one lower..
// So just special-case 100% to avoid misleading
int percentage;
if (itemStack.getDurability() == 0) {
percentage = 100;
} else {
percentage = (int)((m.getMaxDurability() - itemStack.getDurability()) * 100.0 / m.getMaxDurability());
if (percentage == 100) {
percentage = 99;
}
}
usesString = "/" + percentage + "%";
} else {
usesString = "";
}
// Find canonical name of item
String codeName;
codeName = itemStack.getTypeId() + "";
name = codeName2Name.get(codeName);
if (name == null) {
// durability here actually is overloaded to mean a different item
codeName = itemStack.getTypeId() + ";" + itemStack.getDurability();
name = codeName2Name.get(codeName);
}
if (name == null) {
name = "unknown="+codeName;
}
// Special case:
if (itemStack.getType() == Material.MAP) {
name += "/" + itemStack.getDurability();
}
// Enchantments
if (EnchantQuery.hasEnchantments(itemStack)) {
Map<Enchantment,Integer> enchs = itemStack.getEnchantments();
enchString = "/" + EnchantQuery.nameEnchs(enchs);
} else {
enchString = "";
}
return itemStack.getAmount() + ":" + name + usesString + enchString;
}
// Return whether two item stacks have the same item, taking into account 'subtypes'
// stored in the damage value (ex: blue wool, only same as blue wool) - but will
// ignore damage for durable items (ex: diamond sword, 50% = diamond sword, 100%)
public static boolean isSameType(ItemStack a, ItemStack b) {
if (a.getType() != b.getType()) {
return false;
}
Material m = a.getType();
if (isDurable(m)) {
return true;
}
return a.getDurability() == b.getDurability();
}
// Return whether two item stacks are identical - except for amount!
// Compares type, durability, enchantments
public static boolean isIdenticalItem(ItemStack a, ItemStack b) {
if (a == null || b == null) {
return false;
}
if (a == null && b == null) {
return true;
}
if (a.getType() != b.getType()) {
return false;
}
// Same subtype -or- durability for tools
if (a.getDurability() != b.getDurability()) {
return false;
}
// Same enchantments
// Compare by name to avoid complex duplicate enchantment traversing code
String enchNameA = EnchantQuery.nameEnchs(a.getEnchantments());
String enchNameB = EnchantQuery.nameEnchs(b.getEnchantments());
if (!enchNameA.equals(enchNameB)) {
return false;
}
return true;
}
// Identical and same amounts too
public static boolean isIdenticalStack(ItemStack a, ItemStack b) {
return isIdenticalItem(a, b) && a.getAmount() == b.getAmount();
}
// Configuration
public static void loadConfig(YamlConfiguration config) {
Map<String,Object> configValues = config.getValues(true);
MemorySection itemsSection = (MemorySection)configValues.get("items");
int i = 0;
name2CodeName = new ConcurrentHashMap<String, String>();
codeName2Name = new ConcurrentHashMap<String, String>();
isDurableMap = new ConcurrentHashMap<Material, Boolean>();
obtainMap = new ConcurrentHashMap<String, Obtainability>();
HashSet<Obtainability> tradeableCategories = new HashSet<Obtainability>();
for (String obtainString: config.getStringList("tradeableCategories")) {
tradeableCategories.add(Obtainability.valueOf(obtainString.toUpperCase()));
}
for (String codeName: itemsSection.getKeys(false)) {
String properName = config.getString("items." + codeName + ".name");
// How this item can be obtained
String obtainString = config.getString("items." + codeName + ".obtain");
Obtainability obtain = (obtainString == null) ? Obtainability. NORMAL : Obtainability.valueOf(obtainString.toUpperCase());
if (!tradeableCategories.contains(obtain)) {
log.info("Excluding untradeable " + properName);
continue;
// XXX: TODO: This doesn't work, since it falls back to Bukkit/OddItem for item names! (which it then can't reverse)
// Need to come up with another way to exclude it
}
obtainMap.put(codeName, obtain);
// Add aliases from config
List<String> aliases = config.getStringList("items." + codeName + ".aliases");
if (aliases != null) {
for (String alias: aliases) {
name2CodeName.put(alias, codeName);
i += 1;
}
}
// Generate 'proper name' alias, preprocessed for lookup
String smushedProperName = properName.replaceAll(" ","");
String aliasProperName = smushedProperName.toLowerCase();
name2CodeName.put(aliasProperName, codeName);
i += 1;
codeName2Name.put(codeName, smushedProperName);
// Generate numeric alias
name2CodeName.put(codeName, codeName);
i += 1;
// Whether loses durability when used or not (include in trades)
String purpose = config.getString("items." + codeName + ".purpose");
if (purpose != null && (purpose.equals("armor") || purpose.equals("tool") || purpose.equals("weapon"))) {
Material material = codeName2ItemStack(codeName).getType();
isDurableMap.put(material, new Boolean(true));
}
}
log.info("Loaded " + i + " item aliases");
}
// Parse a material code string with optional damage value (ex: 35;11)
private static ItemStack codeName2ItemStack(String codeName) {
Pattern p = Pattern.compile("^(\\d+)[;:/]?(\\d*)$");
Matcher m = p.matcher(codeName);
int typeCode;
short dmgCode;
if (!m.find()) {
// This is an error in the config file (TODO: preparse or detect earlier)
throw new UsageException("Invalid item code format: " + codeName);
}
typeCode = Integer.parseInt(m.group(1));
if (m.group(2) != null && !m.group(2).equals("")) {
dmgCode = Short.parseShort(m.group(2));
} else {
dmgCode = 0;
}
return new ItemStack(typeCode, 1, dmgCode);
}
// Get an ItemStack directly from one of its names or aliases, or null
private static ItemStack directLookupName(String nameString) {
String materialCode = name2CodeName.get(nameString);
if (materialCode == null) {
return null;
}
return codeName2ItemStack(materialCode);
}
// Get proper names of all aliases matching a wildcard pattern
private static SortedSet<String> wildcardLookupName(String pattern) {
SortedSet<String> results = new TreeSet<String>();
Iterator it = name2CodeName.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
String name = (String)pair.getKey();
String codeName = (String)pair.getValue();
if (matchesWildcard(pattern, name)) {
results.add(codeName2Name.get(codeName).replace(" ",""));
}
}
return results;
}
// Return whether a wildcard pattern (with asterisks = anything) matches
private static boolean matchesWildcard(String needle, String haystack) {
String[] cards = needle.split("\\*");
for (String card : cards) {
int i = haystack.indexOf(card);
if (i == -1) {
return false;
}
haystack = haystack.substring(i + card.length());
}
return true;
}
public static boolean isNothing(ItemStack itemStack) {
return itemStack == null || itemStack.getType() == Material.AIR;
}
}
class EnchantQuery
{
static Logger log = Logger.getLogger("Minecraft");
Map<Enchantment,Integer> all;
static ConcurrentHashMap<String, Enchantment> name2Code;
static ConcurrentHashMap<Enchantment, String> code2Name;
public EnchantQuery(String allString) {
all = new HashMap<Enchantment,Integer>();
String[] enchStrings = allString.split("[, /-]+");
for (String enchString: enchStrings) {
Pattern p = Pattern.compile("^([A-Za-z-]*[a-z])([IV0-9]*)$");
Matcher m = p.matcher(enchString);
if (!m.find()) {
throw new UsageException("Unrecognizable enchantment: '" + enchString + "'");
}
String baseName = m.group(1);
String levelString = m.group(2);
Enchantment ench = enchFromBaseName(baseName);
int level = levelFromString(levelString);
// Odd, what's the point of having a separate 'wrapper' class?
// Either way, it has useful methods for us
//EnchantmentWrapper enchWrapper = new EnchantmentWrapper(ench.getId());
EnchantmentWrapper enchWrapper = wrapEnch(ench);
if (level > enchWrapper.getMaxLevel()) {
level = ench.getMaxLevel();
}
log.info("Enchantment: " + ench + ", level="+level);
all.put(enchWrapper, new Integer(level));
}
}
// Return whether all the enchantments can apply to an item
public boolean canEnchantItem(ItemStack item) {
Iterator it = all.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
EnchantmentWrapper ench = wrapEnch(pair.getKey());
Integer level = (Integer)pair.getValue();
if (!ench.canEnchantItem(item)) {
log.info("Cannot apply enchantment " + ench + " to " + item);
return false;
}
}
return true;
}
public static boolean hasEnchantments(ItemStack item) {
Map<Enchantment,Integer> enchs = item.getEnchantments();
return enchs.size() != 0;
}
public String toString() {
return nameEnchs(all);
}
public static String nameEnchs(Map<Enchantment,Integer> all) {
StringBuffer names = new StringBuffer();
Iterator it = all.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
Object obj = pair.getKey();
EnchantmentWrapper ench = wrapEnch(pair.getKey());
Integer level = (Integer)pair.getValue();
names.append(nameEnch(ench));
names.append(levelToString(level));
names.append(",");
}
// Remove the trailing comma
// Would have liked to just build an array then join it, but not easier in Java either
if (names.length() > 1) {
names.deleteCharAt(names.length() - 1);
}
return names.toString();
}
// Get an EnchantmentWrapper from either an EnchantmentWrapper or Enchantment
// Not sure why Bukkit chose to have two classes, but EnchantmentWrapper is more functional
public static EnchantmentWrapper wrapEnch(Object obj) {
if (obj instanceof EnchantmentWrapper) {
return (EnchantmentWrapper)obj;
}
Enchantment ench = (Enchantment)obj;
return new EnchantmentWrapper(ench.getId());
}
static Enchantment enchFromBaseName(String name) {
// Built-in config file database..
name = name.toLowerCase();
Enchantment ench = name2Code.get(name);
if (ench != null) {
return ench;
}
// Bukkit itself?
ench = Enchantment.getByName(name);
if (ench != null) {
return ench;
}
throw new UsageException("Unrecognized enchantment: " + name);
}
static String nameEnch(EnchantmentWrapper ench) {
String name = code2Name.get(ench);
if (name != null) {
return name;
}
return "Unknown(" + ench.getId() + ")";
// There is ench.getName(), but the names don't match in-game
}
static int levelFromString(String s) {
if (s.equals("") || s.equals("I")) {
return 1;
} else if (s.equals("II")) {
return 2;
} else if (s.equals("III")) {
return 3;
} else if (s.equals("IV")) {
return 4;
} else if (s.equals("V")) {
return 5;
} else {
return Integer.parseInt(s);
}
}
static String levelToString(int n) {
switch (n) {
case 1: return "I";
case 2: return "II";
case 3: return "III";
case 4: return "IV";
case 5: return "V";
default: return Integer.toString(n);
}
}
// Return wheather itemA has >= enchantments than itemB
public static boolean equalOrBetter(ItemStack itemA, ItemStack itemB) {
Map<Enchantment,Integer> enchsB = itemB.getEnchantments();
Iterator it = enchsB.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
EnchantmentWrapper enchB = (EnchantmentWrapper)pair.getKey();
int levelB = ((Integer)pair.getValue()).intValue();
if (!itemA.containsEnchantment(Enchantment.getById(enchB.getId()))) {
log.info("Missing enchantment " + nameEnch(enchB) + " not on " + itemA + " (doesn't match " + itemB + ")");
return false;
}
int levelA = itemA.getEnchantmentLevel(Enchantment.getById(enchB.getId()));
log.info("Level " + levelB + " vs " + levelA);
if (levelA < levelB) {
log.info("Lower enchantment level " + levelA + " < " + levelB);
return false;
}
}
return true;
}
public static void loadConfig(YamlConfiguration config) {
Map<String,Object> configValues = config.getValues(true);
MemorySection enchantsSection = (MemorySection)configValues.get("enchants");
int i = 0;
name2Code = new ConcurrentHashMap<String, Enchantment>();
code2Name = new ConcurrentHashMap<Enchantment, String>();
for (String codeString: enchantsSection.getKeys(false)) {
Enchantment ench = Enchantment.getById(Integer.parseInt(codeString));
String properName = config.getString("enchants." + codeString + ".name");
List<String> aliases = config.getStringList("enchants." + codeString + ".aliases");
if (aliases != null) {
for (String alias: aliases) {
name2Code.put(alias, ench);
i += 1;
}
}
// Generate 'proper name' alias, preprocessed for lookup
String smushedProperName = properName.replaceAll(" ","");
String aliasProperName = smushedProperName.toLowerCase();
name2Code.put(aliasProperName, ench);
i += 1;
code2Name.put(ench, smushedProperName);
}
log.info("Loaded " + i + " enchantment aliases");
}
}
class Order implements Comparable
{
Player player;
ItemStack want, give;
boolean exact;
boolean free;
public Order(Player p, String wantString, String giveString) {
player = p;
if (wantString.contains("!")) {
exact = true;
wantString = wantString.replace("!", "");
}
if (giveString.contains("!")) {
exact = true;
giveString = giveString.replace("!", "");
}
want = (new ItemQuery(wantString, p)).itemStack;
give = (new ItemQuery(giveString, p)).itemStack;
if (ItemQuery.isIdenticalItem(want, give)) {
throw new UsageException("You can't trade items for themselves");
}
}
public Order(Player p, ItemStack w, ItemStack g, boolean e) {
player = p;
want = w;
give = g;
exact = e;
}
public String toString() {
// TODO: pregenerate in initialization as description, no need to relookup
return player.getDisplayName() + " wants " + ItemQuery.nameStack(want) + " for " + ItemQuery.nameStack(give) + (exact ? " (exact)" : "");
}
// Required for ConcurrentSkipListSet - Comparable interface
public int compareTo(Object obj) {
if (!(obj instanceof Order)) {
return -1;
}
Order rhs = (Order)obj;
return toString().compareTo(rhs.toString());
//return player.getName().compareTo(rhs.player.getName()) || ItemQuery.isIdenticalStack(want, rhs.want) || ItemQuery.isIdenticalStack(give, rhs.give);
}
}
// Exception to be reported back to player as invalid usage
class UsageException extends RuntimeException
{
String message;
public UsageException(String msg) {
message = msg;
}
public String toString() {
return "UsageException: " + message;
}
public String getMessage() {
return message;
}
}
class Market
{
ConcurrentSkipListSet<Order> orders;
static Logger log = Logger.getLogger("Minecraft");
public Market() {
// TODO: load from file, save to file
//orders = new ArrayList<Order>();
orders = new ConcurrentSkipListSet<Order>();
}
public boolean showOutstanding(CommandSender sender) {
sender.sendMessage("Open orders:");
int i = 0;
for (Order order: orders) {
i += 1;
sender.sendMessage(i + ". " + order);
}
sender.sendMessage("To add or fulfill an order:");
return false;
}
public void cancelOrder(Player player, String s) {
if (s == null || s.equals("-")) {
cancelOrders(player);
return;
}
ItemStack wanted = (new ItemQuery(s, player)).itemStack;
int i = 0;
for (Order order: orders) {
if (order.player.equals(player) && ItemQuery.isIdenticalItem(order.want, wanted)) {
cancelOrder(order);
i += 1;
}
}
player.sendMessage("Canceled " + i + " orders");
}
// Cancel all orders for a player
public void cancelOrders(Player player) {
int i = 0;
for (Order order: orders) {
if (order.player.equals(player)) {
cancelOrder(order);
i += 1;
}
}
player.sendMessage("Canceled all your " + i + " orders");
}
public void cancelOrder(Order order) {
if (!orders.remove(order)) {
for (Order o: orders) {
log.info("Compare " + o + " = " + o.compareTo(order));
}
throw new UsageException("Failed to find order to cancel: " + order);
}
Bukkit.getServer().broadcastMessage("Closed order " + order);
}
public void placeOrder(Order order) {
if (!order.player.hasPermission("freetrade.trade")) {
throw new UsageException("You are not allowed to trade");
}
if (ItemQuery.isNothing(order.give)) {
if (!order.player.hasPermission("freetrade.conjure")) {
throw new UsageException("You must specify or select what you want to trade for");
}
recvItems(order.player, order.want);
return;
}
if (!hasItems(order.player, order.give)) {
throw new UsageException("You don't have " + ItemQuery.nameStack(order.give) + " to give");
}
if (matchOrder(order)) {
// Executed
return;
}
// Not fulfilled; add to outstanding to match with future order
// Broadcast to all players so they know someone wants something, then add
Bukkit.getServer().broadcastMessage("Wanted: " + order);
orders.add(order);
}
// Transfer items from one player to another
public static void transferItems(Player fromPlayer, Player toPlayer, ItemStack items) {
if (!hasItems(fromPlayer, items)) {
throw new UsageException("Player " + fromPlayer.getDisplayName() + " doesn't have " + ItemQuery.nameStack(items));
}
int missing = takeItems(fromPlayer, items);
if (missing > 0) {
// Rollback order
// TODO: verify
items.setAmount(items.getAmount() - missing);
recvItems(fromPlayer, items);
// TODO: try to prevent this from happening, by watching inventory changes, player death, etc
throw new UsageException("Player " + fromPlayer.getDisplayName() + " doesn't have enough " + ItemQuery.nameStack(items) + ", missing " + missing + ", reverted");
// TODO: also, detect earlier and cancel order
}
recvItems(toPlayer, items);
// How did the items transport themselves between the players? Magic, as indicated by smoke.
toPlayer.playEffect(toPlayer.getLocation(), Effect.SMOKE, 0);
Bukkit.getServer().broadcastMessage(toPlayer.getDisplayName() + " received " +
ItemQuery.nameStack(items) + " from " + fromPlayer.getDisplayName());
}
// Remove items from player's inventory, return # of items player had < amount (insufficient items)
// Based on OddItem
public static int takeItems(Player player, ItemStack goners) {
player.saveData();
ItemStack[] inventory = player.getInventory().getContents();
int remaining = goners.getAmount();
int i = 0;
for (ItemStack slot: inventory) {
if (ItemQuery.isIdenticalItem(slot, goners)) {
if (remaining > slot.getAmount()) {
remaining -= slot.getAmount();
slot.setAmount(0);
} else if (remaining > 0) {
slot.setAmount(slot.getAmount() - remaining);
remaining = 0;
} else {
slot.setAmount(0);
}
// If removed whole slot, need to explicitly clear it
// ItemStacks with amounts of 0 are interpreted as 1 (possible Bukkit bug?)
if (slot.getAmount() == 0) {
player.getInventory().clear(i);
}
}
i += 1;
if (remaining == 0) {
break;
}
}
return remaining;
}
// Return whether player has at least the items in the stack
public static boolean hasItems(Player player, ItemStack items) {
ItemStack[] inventory = player.getInventory().getContents();
int remaining = items.getAmount();
for (ItemStack slot: inventory) {
if (ItemQuery.isIdenticalItem(slot, items)) {
remaining -= slot.getAmount();
}
}
return remaining <= 0;
}
// Have a player receive items in their inventory
public static void recvItems(Player player, ItemStack items) {
int remaining = items.getAmount();
// Get maximum size per stack, then add individually
// Prevents non-stackable items (potions, signs, boats, etc.) and semi-stackable
// (enderpearls, eggs, snowballs, etc.) from being stacked to 64
int stackSize;
if (player.hasPermission("freetrade.bigstacks")) {
stackSize = remaining;
} else {
stackSize = Math.abs(items.getType().getMaxStackSize());
// Surprisingly, this always returns -1, see http://forums.bukkit.org/threads/getmaxstacksize-always-return-1.1154/#post-13147
//int stackSize = Math.abs(items.getMaxStackSize());
}
do
{
ItemStack oneStack = items.clone();
if (remaining > stackSize) {
oneStack.setAmount(stackSize);
remaining -= stackSize;
} else {
oneStack.setAmount(remaining);
remaining = 0;
}
HashMap<Integer,ItemStack> excess = player.getInventory().addItem(oneStack);
// If player's inventory if full, drop excess items on the floor
Iterator it = excess.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
int unknown = ((Integer)pair.getKey()).intValue(); // hmm? always 0
ItemStack excessItems = (ItemStack)pair.getValue();
player.getWorld().dropItemNaturally(player.getLocation(), excessItems);
}
} while (remaining > 0);
}
public boolean matchOrder(Order newOrder) {
int i = 0;
for (Order oldOrder: orders) {
i += 1;
//log.info("oldOrder: " + oldOrder);
//log.info("newOrder: " + newOrder);
// Are they giving what anyone else wants?
if (!ItemQuery.isSameType(newOrder.give, oldOrder.want) ||
!ItemQuery.isSameType(newOrder.want, oldOrder.give)) {
log.info("Not matched, different types");
continue;
}
double newRatio = (double)newOrder.give.getAmount() / newOrder.want.getAmount();
double oldRatio = (double)oldOrder.want.getAmount() / oldOrder.give.getAmount();
// Offering a better or equal deal? (Quantity = relative value)
log.info("ratio " + newRatio + " >= " + oldRatio);
if (!(newRatio >= oldRatio)) {
log.info("Not matched, worse relative value");
continue;
}
// Is item less damaged or equally damaged than wanted? (Durability)
if (ItemQuery.isDurable(newOrder.give.getType())) {
if (newOrder.give.getDurability() > oldOrder.want.getDurability()) {
log.info("Not matched, worse damage new, " + newOrder.give.getDurability() + " < " + oldOrder.want.getDurability());
continue;
}
}
if (ItemQuery.isDurable(oldOrder.give.getType())) {
if (oldOrder.give.getDurability() > newOrder.want.getDurability()) {
log.info("Not matched, worse damage old, " + oldOrder.give.getDurability() + " < " + newOrder.want.getDurability());
continue;
}
}
// TODO: enchantment checks
if (!EnchantQuery.equalOrBetter(newOrder.give, oldOrder.want)) {
log.info("Not matched, insufficient magic new " + EnchantQuery.nameEnchs(newOrder.give.getEnchantments()) +
" < " + EnchantQuery.nameEnchs(oldOrder.want.getEnchantments()));
continue;
}
if (!EnchantQuery.equalOrBetter(oldOrder.give, newOrder.want)) {
log.info("Not matched, insufficient magic old " + EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()) +
" < " + EnchantQuery.nameEnchs(newOrder.want.getEnchantments()));
continue;
}
// TODO: Generalize to "betterness"
// Determine how much of the order can be fulfilled
int remainingWant = oldOrder.want.getAmount() - newOrder.give.getAmount();
int remainingGive = oldOrder.give.getAmount() - newOrder.want.getAmount();
log.info("remaining want="+remainingWant+", give="+remainingGive);
// They get what they want!
// Calculate amount that can be exchanged
ItemStack exchWant = new ItemStack(oldOrder.want.getType(), Math.min(oldOrder.want.getAmount(), newOrder.give.getAmount()), newOrder.give.getDurability());
ItemStack exchGive = new ItemStack(oldOrder.give.getType(), Math.min(oldOrder.give.getAmount(), newOrder.want.getAmount()), oldOrder.give.getDurability());
exchWant.addEnchantments(newOrder.give.getEnchantments());
exchGive.addEnchantments(oldOrder.give.getEnchantments());
log.info("exchWant="+ItemQuery.nameStack(exchWant));
log.info("exchGive="+ItemQuery.nameStack(exchGive));
transferItems(newOrder.player, oldOrder.player, exchWant);
transferItems(oldOrder.player, newOrder.player, exchGive);
/*
oldOrder.player.getInventory().addItem(exchWant);
newOrder.player.getInventory().remove(exchWant);
Bukkit.getServer().broadcastMessage(oldOrder.player.getDisplayName() + " received " +
ItemQuery.nameStack(exchWant) + " from " + newOrder.player.getDisplayName());
newOrder.player.getInventory().addItem(exchGive);
oldOrder.player.getInventory().remove(exchGive);
Bukkit.getServer().broadcastMessage(newOrder.player.getDisplayName() + " received " +
ItemQuery.nameStack(exchGive) + " from " + oldOrder.player.getDisplayName());
*/
// Remove oldOrder from orders, if complete, or add partial if incomplete
if (remainingWant == 0) {
// This order is finished, old player got everything they wanted
// Note: remainingWant can be negative if they got more than they bargained for
// (other player offered a better deal than expected). Either way, done deal.
cancelOrder(oldOrder);
return true;
} else if (remainingWant > 0) {
oldOrder.want.setAmount(remainingWant);
oldOrder.give.setAmount(remainingGive);
Bukkit.getServer().broadcastMessage("Updated order: " + oldOrder);
return true;
} else if (remainingWant < 0) {
// TODO: test better
cancelOrder(oldOrder);
newOrder.want.setAmount(-remainingGive);
newOrder.give.setAmount(-remainingWant);
log.info("Adding new partial order");
return false;
}
}
return false;
}
}
public class FreeTrade extends JavaPlugin {
Logger log = Logger.getLogger("Minecraft");
Market market = new Market();
YamlConfiguration config;
public void onEnable() {
loadConfig();
log.info(getDescription().getName() + " enabled");
}
public void onDisable() {
log.info(getDescription().getName() + " disabled");
}
public void loadConfig() {
String filename = getDataFolder() + System.getProperty("file.separator") + "FreeTrade.yml";
File file = new File(filename);
if (!file.exists()) {
if (!newConfig(file)) {
throw new UsageException("Could not create new configuration file");
}
}
config = YamlConfiguration.loadConfiguration(new File(filename));
if (config == null) {
throw new UsageException("Failed to load configuration file " + filename);
}
if (config.getInt("version") < 1) {
throw new UsageException("Configuration file version is outdated");
}
ItemQuery.loadConfig(config);
EnchantQuery.loadConfig(config);
}
// Copy default configuration
public boolean newConfig(File file) {
FileWriter fileWriter;
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
try {
fileWriter = new FileWriter(file);
} catch (IOException e) {
log.severe("Couldn't write config file: " + e.getMessage());
Bukkit.getServer().getPluginManager().disablePlugin(Bukkit.getServer().getPluginManager().getPlugin("FreeTrade"));
return false;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(getResource("FreeTrade.yml"))));
BufferedWriter writer = new BufferedWriter(fileWriter);
try {
String line = reader.readLine();
while (line != null) {
writer.write(line + System.getProperty("line.separator"));
line = reader.readLine();
}
log.info("Wrote default config");
} catch (IOException e) {
log.severe("Error writing config: " + e.getMessage());
} finally {
try {
writer.close();
reader.close();
} catch (IOException e) {
log.severe("Error saving config: " + e.getMessage());
Bukkit.getServer().getPluginManager().disablePlugin(Bukkit.getServer().getPluginManager().getPlugin("FreeTrade"));
}
}
return true;
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player;
int n = 0;
if (!cmd.getName().equalsIgnoreCase("want")) {
return false;
}
// /want
if (args.length == 0) {
return market.showOutstanding(sender);
}
if (sender instanceof Player) {
player = (Player)sender;
} else {
// Get player name from first argument
player = Bukkit.getServer().getPlayer(args[0]);
if (player == null) {
sender.sendMessage("no such player");
return false;
}
n++;
}
if (args.length < 1+n) {
return false;
}
String wantString, giveString;
wantString = args[n];
if (args.length < 2+n) {
// Omitted last arg, use item in hand
giveString = "this";
} else {
if (args[n+1].equalsIgnoreCase("for")) {
giveString = args[n+2];
} else {
giveString = args[n+1];
}
}
Order order;
try {
if (wantString.equals("-")) {
log.info("cancelall");
market.cancelOrder(player, null);
} else if (giveString.equals("-")) {
market.cancelOrder(player, wantString);
} else {
order = new Order(player, wantString, giveString);
sender.sendMessage(order.toString());
market.placeOrder(order);
}
} catch (UsageException e) {
log.info("Sending usage exception: " + player.getDisplayName() + " - " + e );
player.sendMessage(e.getMessage());
return false;
}
return true;
}
}
|
package FirstGame;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable, KeyListener{
private static final long serialVersionUID = 10;
//Background Color
private Color bgColor;
//Dimensions
public static int WIDTH;
public static int HEIGHT;
//FPS
private int FPS;
//Game Loop
private boolean running;
//Graphics
public Graphics2D g;
public BufferedImage image;
//Thread
private Thread thread;
//Player
public static Player player;
//Enemies
public static ArrayList<Enemy> enemies;
//Bullets
public static ArrayList<Bullet> bullets;
//explosions
public static ArrayList<Explosion> explosions;
//PowerUp
public static ArrayList<PowerUp> powerups;
//Laser
private Laser laser;
private boolean laserTaken;
//Wave System
private long waveStartTimer;
private long waveStartTimerDiff;
private int waveDelay;
private int waveNumber;
private boolean waveStart;
//Slow Motion
private long slowStartTimer;
private int slowLength;
private long slowElapsed;
//Constructor
public GamePanel(){
super();
//background Color Set
bgColor = new Color(50, 100, 100);
//Dimension Initialize
WIDTH = 600;
HEIGHT = 450;
//set size
setPreferredSize(new Dimension(WIDTH, HEIGHT));
//FPS Cap Set
FPS = 60;
//Focus Panel
setFocusable(true);
requestFocus();
//wave
waveStartTimer = 0;
waveStartTimerDiff = 0;
waveDelay = 2000;
//Slow Down
slowLength = 15000;
}
public void addNotify(){
super.addNotify();
if(thread == null){
thread = new Thread(this);
thread.start();
}
addKeyListener(this);
}
public void run(){
running = true;
//Graphics Initialize
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
//Creating Player
player = new Player();
//Create Enemies
enemies = new ArrayList<Enemy>();
//Initialize Bullets
bullets = new ArrayList<Bullet>();
//Initialize explosions
explosions = new ArrayList<Explosion>();
//Initialize PowerUps
powerups = new ArrayList<PowerUp>();
//anti-aliasing
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// FPS
long startTime;
long waitTime;
long URDTimeMillis;
long targetTime = 1000/FPS;
/**
* GAME LOOP
*/
while(running) {
startTime = System.nanoTime();
gameUpdate();
gameRender();
gameDraw();
URDTimeMillis = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - URDTimeMillis;
try {
Thread.sleep(waitTime);
}
catch(Exception e) {
}
}
}
public void gameUpdate(){
//wave system
if(waveStartTimer == 0 && enemies.size() == 0){
waveNumber++;
waveStart = false;
waveStartTimer = System.nanoTime();
} else{
waveStartTimerDiff = (System.nanoTime() - waveStartTimer)/1000000;
if(waveStartTimerDiff > waveDelay){
waveStart = true;
waveStartTimer = 0;
waveStartTimerDiff = 0;
}
}
//create enemies
if(waveStart && enemies.size() == 0)
createNewEnemies();
//Player Update
player.update();
//Bullets
for(int i = 0; i < bullets.size(); i++){
boolean remove = bullets.get(i).update();
if(remove){
bullets.remove(i);
i
}
}
//Enemy
for(int i = 0; i < enemies.size(); i++){
enemies.get(i).update();
}
//Bullet-Enemy Collision
if(!laserTaken)
for(int i = 0; i < bullets.size(); i++){
Bullet b = bullets.get(i);
//Getting Coordinates of Bullet
double bx = b.getx();
double by = b.gety();
double br = b.getr();
for(int j = 0; j < enemies.size(); j++){
Enemy e = enemies.get(j);
//Getting coordinates of enemy
double ex = e.getx();
double ey = e.gety();
double er = e.getr();
//Calculating Distance
double dx = bx - ex;
double dy = by - ey;
//Distance Formula
double dist = Math.sqrt(dx*dx + dy*dy);
boolean removed = false;
if(dist < br +er){
//Collision Detected
//Create New
if(e.getHealth() == 2){
explosions.add(new Explosion(e, e.getr()*5));
enemies.add(
new Enemy(
(e.getRank() - 1 > 0)?e.getRank() - 1:1,
(e.getType() - 1 > 0)?e.getType() - 1:1,
e.getHealth()-1, e.getAngle() + Math.toRadians(70),
e.getx() - e.getr(), e.gety()
)
);
enemies.add(
new Enemy(
(e.getRank() - 1 > 0)?e.getRank() - 1:1,
(e.getType() - 1 > 0)?e.getType() - 1:1,
e.getHealth()-1, e.getAngle() - Math.toRadians(60),
e.getx() + e.getr(), e.gety()
)
);
enemies.remove(j);
if(slowStartTimer!=0)
for(int k = 0; k < enemies.size(); k++)
enemies.get(k).setSlow(true);
removed = true;
}
if(!removed)
e.hit();
bullets.remove(i);
player.addScore(e.getType()+e.getRank());
i
break;
}
}
}
//enemy dead check
for(int i = 0; i < enemies.size(); i++){
if(enemies.get(i).isDead()){
explosions.add(new Explosion(enemies.get(i), enemies.get(i).getr() * 5));
//Chance for PowerUp
double rand = Math.random();
if(rand < 0.001) powerups.add(new PowerUp(enemies.get(i), 1));
else if(rand < 0.005) powerups.add(new PowerUp(enemies.get(i),3));
else if(rand < 0.03) powerups.add(new PowerUp(enemies.get(i),2));
else if(rand < 0.07)powerups.add(new PowerUp(enemies.get(i),5));
else if(rand < 0.1)powerups.add(new PowerUp(enemies.get(i),4));
//Remove
enemies.remove(i);
i
}
}
//Player-Enemy Collision
if(!player.isRecovering() && !player.isOver()){
//Player Coordinates
int px = player.getx();
int py = player.gety();
int pr = player.getr();
for(int i = 0; i < enemies.size(); i++){
Enemy e = enemies.get(i);
//Enemy Coordinates
double ex = e.getx();
double ey = e.gety();
double er = e.getr();
//Distance
double dx = px - ex;
double dy = py - ey;
//Distance Formula
double dist = Math.sqrt(dx*dx + dy*dy);
if(dist < pr + er){
player.loseLife();
player.addScore(-(e.getRank()+e.getType()));
explosions.add(new Explosion(enemies.get(i), enemies.get(i).getr() * 5));
enemies.remove(i);
i
player.addPower(1);
}
}
}
//explosion
for(int i = 0; i < explosions.size(); i++){
boolean remove = explosions.get(i).update();
if(remove){
explosions.remove(i);
i
}
}
//PowerUp
for(int i = 0; i < powerups.size(); i++){
boolean remove = powerups.get(i).update();
if(remove) powerups.remove(i);
}
//PowerUp - Player Collision
for(int i = 0; i < powerups.size(); i++){
PowerUp p = powerups.get(i);
double px = p.getx();
double py = p.gety();
int pr = p.getr();
int ppx = player.getx();
int ppy = player.gety();
int ppr = player.getr();
double dx = px - ppx;
double dy = py - ppy;
//Distance
double dist = Math.sqrt(dx*dx + dy*dy);
if(dist < pr+ppr){
//Collision Detected
int type = p.getType();
switch(type){
case 1: player.addLife();
break;
case 2: player.addPower(1);
break;
case 3: player.addPower(2);
break;
case 4: laser = new Laser(); laserTaken = true;
break;
case 5:{
slowStartTimer = System.nanoTime();
for(int j = 0;j < enemies.size(); j++)
enemies.get(j).setSlow(true);
}
break;
default: System.exit(0);
}
//Remove From Screen
powerups.remove(i);
}
}
//laser - enemy Collision
if(laser!=null && laserTaken && !player.isOver()){
int x = player.getx() + player.getr();
int y = player.gety();
for(int i = 0;i < enemies.size(); i++){
Enemy e = enemies.get(i);
double ex = e.getx();
double ey = e.gety();
int r = e.getr();
double dist = (ex < x)? x - ex: ex - x;
if(ey < y){
if(dist < r){
//Collision Detected
explosions.add(new Explosion(e, r*5));
player.addScore(e.getType()+e.getRank());
enemies.remove(i);
}
}
}
}
if(laser!=null){
boolean remove = laser.update();
if(player.isRecovering()) remove = player.isRecovering();
if(remove) {
laserTaken = false;
laser = null;
}
}
//Slow Down Update
if(slowStartTimer!=0){
slowElapsed = (System.nanoTime() - slowStartTimer)/1000000;
if(slowElapsed > slowLength){
slowStartTimer = 0;
for(int i = 0; i < enemies.size(); i++)
enemies.get(i).setSlow(false);
}
}
}
public void gameRender(){
//Draw Background
if(!player.isOver()){
g.setColor(bgColor);
g.fillRect(0, 0 , WIDTH, HEIGHT);
}
else{
g.setColor(new Color(200,120,100));
g.fillRect(0, 0 , WIDTH, HEIGHT);
}
if(slowStartTimer!=0){
g.setColor(new Color(255, 255, 255, 64));
g.fillRect(0, 0, WIDTH, HEIGHT);
}
//Score
g.setFont(new Font("Century Gothic", Font.BOLD, 12));
g.setColor(Color.WHITE);
g.drawString("SCORE: "+player.getScore(), WIDTH - 80, 20);
//Credits
g.setFont(new Font("Century Gothic", Font.BOLD, 15));
g.drawString("", WIDTH-170, HEIGHT-10);
//Wave Number
if(waveStartTimer != 0){
g.setFont(new Font("Century Gothic", Font.PLAIN, 30));
String s = String.format("- W A V E %d -", waveNumber);
int length = (int) g.getFontMetrics().getStringBounds(s, g).getWidth();
int alpha = (int) (255 * Math.sin(3.14 * waveStartTimerDiff/waveDelay));
if(alpha > 255) alpha = 255;
g.setColor(new Color(255, 255, 255, alpha));
g.drawString(s, WIDTH/2 - length/2, HEIGHT/2);
}
//Lives
for(int i = 0; i < player.getLives(); i++){
g.setColor(bgColor.brighter().brighter());
g.fillOval(15+(25*i), 15, player.getr()*2, player.getr()*2);
g.setStroke(new java.awt.BasicStroke(2));
g.setColor(Color.BLACK);
g.drawOval(15+(25*i),15,player.getr()*2,player.getr()*2);
g.setStroke(new java.awt.BasicStroke(1));
}
//Power
g.setColor(Color.YELLOW);
g.fillRect(20, 60, player.getPower()*8, 8);
g.setStroke(new BasicStroke(2));
g.setColor(Color.YELLOW.darker());
for(int i = 0; i < player.getRequiredPower(); i++){
g.drawRect(20 + 8*i, 60, 8, 8);
}
g.setStroke(new BasicStroke(1));
//Draw Laser
if(laserTaken)
laser.draw(g);
//Draw Player
player.draw(g);
//draw enemies
for(int i = 0; i < enemies.size(); i++)
enemies.get(i).draw(g);
//Bullet
if(!laserTaken)
for(int i = 0; i < bullets.size(); i++){
bullets.get(i).draw(g);
}
//explosion
for(int i = 0;i < explosions.size(); i++)
explosions.get(i).draw(g);
//PowerUp
for(int i = 0; i < powerups.size(); i++) powerups.get(i).draw(g);
// draw slow down meter
if(slowStartTimer != 0 && !laserTaken) {
g.setColor(Color.WHITE);
g.drawRect(10, 80, 100, 10);
g.fillRect(10, 80,
(int) (100 - 100.0 * slowElapsed / slowLength), 10);
}
else if(slowStartTimer != 0) {
g.setColor(Color.WHITE);
g.drawRect(10, 100, 100, 10);
g.fillRect(10, 100,
(int) (100 - 100.0 * slowElapsed / slowLength), 10);
}
//Laser timer
if(laserTaken){
g.setColor(Color.WHITE);
g.setStroke(new BasicStroke(1));
g.drawRect(10, 80,
100, 8);
g.fillRect(10, 80,
(int) (100 - 100.0 * Laser.elapsed / Laser.laserTimer), 8);
g.setStroke(new BasicStroke(1));
}
//over
if(player.isOver()){
//Over Display
g.setFont(new Font("Century Gothic", Font.PLAIN, 30));
String s="G A M E O V E R";
int length=(int)g.getFontMetrics().getStringBounds(s,g).getWidth();
g.setColor(Color.WHITE);
g.drawString(s, WIDTH/2-length/2,HEIGHT/2);
//setters off
player.setLeft(false);
player.setRight(false);
player.setUp(false);
player.setDown(false);
player.setFiring(false);
//Listener off
removeKeyListener(this);
}
}
public void gameDraw(){
//get graphics
Graphics g2 = this.getGraphics();
//draw
g2.drawImage(image, 0, 0, null);
//refresh
g2.dispose();
}
//Create Enemies
private void createNewEnemies(){
int n = waveNumber *3
;
int type = 0;
int rank = 0;
for(int i = 0; i < n; i++){
type=(waveNumber<3)?1:(int) (Math.random() * (3)) + 1;
rank=(type==1)?(int) (Math.random() * (2)) + 1:(int) (Math.random() * (2)) + 1;
enemies.add(new Enemy(type, rank));
}
}
//Key Pressed
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_LEFT) player.setLeft(true);
if(keyCode == KeyEvent.VK_RIGHT) player.setRight(true);
if(keyCode == KeyEvent.VK_UP) player.setUp(true);
if(keyCode == KeyEvent.VK_DOWN) player.setDown(true);
if(keyCode == KeyEvent.VK_SPACE) player.setFiring(true);
}
//Key Released
public void keyReleased(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_LEFT) player.setLeft(false);
if(keyCode == KeyEvent.VK_RIGHT) player.setRight(false);
if(keyCode == KeyEvent.VK_UP) player.setUp(false);
if(keyCode == KeyEvent.VK_DOWN) player.setDown(false);
if(keyCode == KeyEvent.VK_SPACE) player.setFiring(false);
}
public void keyTyped(KeyEvent e){}
}
|
package com.eclipsesource.gerrit.plugins.fileattachment.api.test.converter;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTarget;
import com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.FileDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.AttachmentTargetEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.AttachmentTargetEntity.TargetType;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.AttachmentTargetResponseEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.FileDescriptionEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.OperationResultEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.OperationResultEntity.ResultStatus;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.converter.BaseAttachmentTargetResponseEntityReader;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.ChangeTargetDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.GenericFileDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.PatchSetTargetDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.PatchTarget;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.PatchTargetDescription;
/**
* @author Florian Zoubek
*
*/
public class BaseAttachmentTargetResponseEntityReaderTest {
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles Success responses with file descriptions.
*/
@Test
public void testSuccessConversionWithFiles() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
// build expected result
PatchTargetDescription patchTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
List<FileDescription> expectedFileDescriptions =
new ArrayList<FileDescription>(2);
expectedFileDescriptions.add(new GenericFileDescription("/subdir/",
"file1.txt"));
expectedFileDescriptions.add(new GenericFileDescription("/subdir/",
"file2.txt"));
AttachmentTarget expectedAttachmentTarget =
new PatchTarget(patchTargetDescription, expectedFileDescriptions);
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.SUCCESS, "");
// build input parameters
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[2];
fileDescriptionEntities[0] =
new FileDescriptionEntity("/subdir/", "file1.txt");
fileDescriptionEntities[1] =
new FileDescriptionEntity("/subdir/", "file2.txt");
AttachmentTargetEntity attachmentTargetEntity =
new AttachmentTargetEntity(TargetType.PATCH, fileDescriptionEntities);
AttachmentTargetResponseEntity jsonEntity =
new AttachmentTargetResponseEntity(attachmentTargetEntity,
operationResultEntity);
// begin testing
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntity, patchTargetDescription);
Assert.assertThat(attachmentTarget,
CoreMatchers.is(expectedAttachmentTarget));
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles Success responses without file descriptions.
*/
@Test
public void testSuccessConversionWithoutFiles() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
// build expected result
PatchTargetDescription patchTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
List<FileDescription> expectedFileDescriptions =
new ArrayList<FileDescription>(0);
AttachmentTarget expectedAttachmentTarget =
new PatchTarget(patchTargetDescription, expectedFileDescriptions);
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.SUCCESS, "");
// build input parameters
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[0];
AttachmentTargetEntity attachmentTargetEntity =
new AttachmentTargetEntity(TargetType.PATCH, fileDescriptionEntities);
AttachmentTargetResponseEntity jsonEntity =
new AttachmentTargetResponseEntity(attachmentTargetEntity,
operationResultEntity);
// begin testing
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntity, patchTargetDescription);
Assert.assertThat(attachmentTarget,
CoreMatchers.is(expectedAttachmentTarget));
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles unsupported attachment targets correctly.
*/
@Test
public void testInvalidAttachmentTargetConversion() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
// build input parameters
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.SUCCESS, "");
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[0];
AttachmentTargetEntity attachmentTargetEntity =
new AttachmentTargetEntity(TargetType.PATCH, fileDescriptionEntities);
AttachmentTargetResponseEntity jsonEntity =
new AttachmentTargetResponseEntity(attachmentTargetEntity,
operationResultEntity);
// begin testing
// PatchSetTargetDescription
AttachmentTargetDescription attachmentTargetDescription =
new PatchSetTargetDescription(new ChangeTargetDescription(
"I0000000000000000"), 0);
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntity, attachmentTargetDescription);
Assert.assertThat(attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
// ChangeTargetDescription
attachmentTargetDescription =
new ChangeTargetDescription("I0000000000000000");
Assert.assertThat(attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles responses containing a failed operation result.
*/
@Test
public void testFailedOperationConversion() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.FAILED, "Some error occured");
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[2];
fileDescriptionEntities[0] =
new FileDescriptionEntity("/subdir/", "file1.txt");
fileDescriptionEntities[1] =
new FileDescriptionEntity("/subdir/", "file2.txt");
for (TargetType targetType : TargetType.values()) {
// build input parameters
AttachmentTargetEntity attachmentTargetEntityWithFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithFiles =
new AttachmentTargetResponseEntity(attachmentTargetEntityWithFiles,
operationResultEntity);
AttachmentTargetEntity attachmentTargetEntityWithoutFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithoutFiles =
new AttachmentTargetResponseEntity(
attachmentTargetEntityWithoutFiles, operationResultEntity);
AttachmentTargetDescription attachmentTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
// begin testing
// without files
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntityWithoutFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithoutFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
// with files
attachmentTarget =
entityReader.toObject(jsonEntityWithFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
}
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles responses containing a "not permitted" operation result.
*/
@Test
public void testNotPermittedOperationConversion() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.NOTPERMITTED, "Some error occured");
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[2];
fileDescriptionEntities[0] =
new FileDescriptionEntity("/subdir/", "file1.txt");
fileDescriptionEntities[1] =
new FileDescriptionEntity("/subdir/", "file2.txt");
for (TargetType targetType : TargetType.values()) {
// build input parameters
AttachmentTargetEntity attachmentTargetEntityWithFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithFiles =
new AttachmentTargetResponseEntity(attachmentTargetEntityWithFiles,
operationResultEntity);
AttachmentTargetEntity attachmentTargetEntityWithoutFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithoutFiles =
new AttachmentTargetResponseEntity(
attachmentTargetEntityWithoutFiles, operationResultEntity);
AttachmentTargetDescription attachmentTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
// begin testing
// without files
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntityWithoutFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithoutFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
// with files
attachmentTarget =
entityReader.toObject(jsonEntityWithFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
}
}
}
|
// need to make ids be able to be non-simple (e.g. a[3] or b.c), but that takes effort
// not sure how to represent them, since don't want to re-evaluate every time
package ambroscum.lines;
import java.util.*;
import ambroscum.*;
import ambroscum.errors.*;
import ambroscum.values.*;
import ambroscum.parser.*;
public class AssignmentLine extends Line
{
private ExpressionReference[] assignIDs; // list of the ids being set to
private Expression[] expressions;
AssignmentLine(TokenStream idStream, TokenStream valueStream)
{
ArrayList<ExpressionReference> assignIDsList = new ArrayList<ExpressionReference>();
while (true) {
assignIDsList.add(ExpressionReference.createExpressionReference(idStream.removeFirst(), idStream));
if (idStream.size() > 0) {
Token comma = idStream.removeFirst(); // Remove the comma
if (comma != Token.COMMA) {
throw new SyntaxError("Expected a comma delimiter in assignment");
}
} else {
break;
}
}
ArrayList<Expression> exprsList = new ArrayList<Expression>();
while (true) {
exprsList.add(Expression.interpret(valueStream));
if (valueStream.size() > 0) {
Token first = valueStream.getFirst();
if (Token.COMMA == first) {
valueStream.removeFirst();
} else if (Token.NEWLINE == first) {
valueStream.removeFirst();
break;
} else {
throw new SyntaxError("Expected a comma delimiter or newline in assignment");
}
} else {
throw new SyntaxError("Expected value to assign");
}
}
assignIDs = new ExpressionReference[assignIDsList.size()];
assignIDsList.toArray(assignIDs);
expressions = new Expression[exprsList.size()];
exprsList.toArray(expressions);
if (expressions.length != assignIDs.length)
throw new RuntimeException("need to find better exceptions"); // comment to be easier to find
}
@Override
public void evaluate(IdentifierMap values)
{
Value[] targetVals = new Value[assignIDs.length];
for (int i = 0; i < expressions.length; i++) {
targetVals[i] = expressions[i].evaluate(values);
}
for (int i = 0; i < expressions.length; i++) {
assignIDs[i].setValue(targetVals[i], values);
}
}
@Override
public String toString()
{
return Arrays.toString(assignIDs) + " = " + Arrays.toString(expressions);
}
}
|
package eu.bcvsolutions.idm.core.scheduler.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.FutureTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.google.common.collect.ImmutableMap;
import eu.bcvsolutions.idm.core.api.domain.CoreResultCode;
import eu.bcvsolutions.idm.core.api.domain.OperationState;
import eu.bcvsolutions.idm.core.api.dto.DefaultResultModel;
import eu.bcvsolutions.idm.core.api.dto.ResultModel;
import eu.bcvsolutions.idm.core.api.entity.OperationResult;
import eu.bcvsolutions.idm.core.api.exception.ResultCodeException;
import eu.bcvsolutions.idm.core.api.service.ConfigurationService;
import eu.bcvsolutions.idm.core.api.service.EntityEventManager;
import eu.bcvsolutions.idm.core.api.utils.AutowireHelper;
import eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto;
import eu.bcvsolutions.idm.core.scheduler.api.dto.LongRunningFutureTask;
import eu.bcvsolutions.idm.core.scheduler.api.service.LongRunningTaskExecutor;
import eu.bcvsolutions.idm.core.scheduler.api.service.LongRunningTaskManager;
import eu.bcvsolutions.idm.core.scheduler.service.api.IdmLongRunningTaskService;
import eu.bcvsolutions.idm.core.security.api.service.SecurityService;
public class DefaultLongRunningTaskManager implements LongRunningTaskManager {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DefaultLongRunningTaskManager.class);
private final IdmLongRunningTaskService service;
private final Executor executor;
private final ConfigurationService configurationService;
private final SecurityService securityService;
private final EntityEventManager entityEventManager;
@Autowired
public DefaultLongRunningTaskManager(
IdmLongRunningTaskService service,
Executor executor,
EntityEventManager entityEventManager,
ConfigurationService configurationService,
SecurityService securityService) {
Assert.notNull(service);
Assert.notNull(executor);
Assert.notNull(entityEventManager);
Assert.notNull(configurationService);
Assert.notNull(securityService);
this.service = service;
this.executor = executor;
this.entityEventManager = entityEventManager;
this.configurationService = configurationService;
this.securityService = securityService;
}
/**
* cancel all previously runned tasks
*/
@Override
@Transactional
public void init() {
LOG.info("Cancel unprocessed long running task - tasks was interrupt during instance restart");
String instanceId = configurationService.getInstanceId();
service.findAllByInstance(instanceId, OperationState.RUNNING).forEach(task -> {
LOG.info("Cancel unprocessed long running task [{}] - tasks was interrupt during instance [{}] restart", task, instanceId);
task.setRunning(false);
ResultModel resultModel = new DefaultResultModel(CoreResultCode.LONG_RUNNING_TASK_CANCELED_BY_RESTART,
ImmutableMap.of(
"taskId", task.getId(),
"taskType", task.getTaskType(),
"instanceId", task.getInstanceId()));
task.setResult(new OperationResult.Builder(OperationState.CANCELED).setModel(resultModel).build());
service.saveInternal(task);
});
}
@Override
@Transactional
@Scheduled(fixedDelayString = "${scheduler.task.queue.process:60000}")
public void scheduleProcessCreated() {
processCreated();
}
/**
* Executes long running task on this instance
*/
@Override
@Transactional
public List<LongRunningFutureTask<?>> processCreated() {
LOG.debug("Processing created tasks from long running task queue");
// run as system - called from scheduler internally
securityService.setSystemAuthentication();
List<LongRunningFutureTask<?>> taskList = new ArrayList<LongRunningFutureTask<?>>();
service.findAllByInstance(configurationService.getInstanceId(), OperationState.CREATED).forEach(task -> {
LongRunningTaskExecutor<?> taskExecutor = null;
ResultModel resultModel = null;
Exception ex = null;
try {
taskExecutor = (LongRunningTaskExecutor<?>) AutowireHelper.createBean(Class.forName(task.getTaskType()));
taskExecutor.setLongRunningTaskId(task.getId());
taskExecutor.init((Map<String, Object>) task.getTaskProperties());
} catch (ClassNotFoundException e) {
ex = e;
resultModel = new DefaultResultModel(CoreResultCode.LONG_RUNNING_TASK_NOT_FOUND,
ImmutableMap.of(
"taskId", task.getId(),
"taskType", task.getTaskType(),
"instanceId", task.getInstanceId()));
} catch (Exception e) {
ex = e;
resultModel = new DefaultResultModel(CoreResultCode.LONG_RUNNING_TASK_INIT_FAILED,
ImmutableMap.of(
"taskId", task.getId(),
"taskType", task.getTaskType(),
"instanceId", task.getInstanceId()));
}
if (ex != null) {
LOG.error(resultModel.toString(), ex);
task.setResult(new OperationResult.Builder(OperationState.EXCEPTION).setModel(resultModel).setCause(ex).build());
service.save(task);
} else {
taskList.add(execute(taskExecutor));
}
});
return taskList;
}
@Override
@Transactional
public <V> LongRunningFutureTask<V> execute(LongRunningTaskExecutor<V> taskExecutor) {
// autowire task properties
AutowireHelper.autowire(taskExecutor);
// persist LRT
persistTask(taskExecutor);
LongRunningFutureTask<V> longRunnigFutureTask = new LongRunningFutureTask<>(taskExecutor, new FutureTask<>(taskExecutor));
// execute - after original transaction is commited
entityEventManager.publishEvent(longRunnigFutureTask);
return longRunnigFutureTask;
}
/**
* We need to wait to transaction commit, when asynchronous task is executed - data is prepared in previous transaction mainly.
*/
@Override
public <V> void executeInternal(LongRunningFutureTask<V> futureTask) {
Assert.notNull(futureTask);
Assert.notNull(futureTask.getExecutor());
Assert.notNull(futureTask.getFutureTask());
LOG.debug("Execute task [{}] asynchronously", futureTask.getExecutor().getLongRunningTaskId());
executor.execute(futureTask.getFutureTask());
}
@Override
@Transactional
public <V> V executeSync(LongRunningTaskExecutor<V> taskExecutor) {
// autowire task properties
AutowireHelper.autowire(taskExecutor);
// persist LRT
IdmLongRunningTaskDto task = persistTask(taskExecutor);
LOG.debug("Execute task [{}] synchronously", task.getId());
// execute
try {
return taskExecutor.call();
} catch (Exception ex) {
throw new ResultCodeException(CoreResultCode.LONG_RUNNING_TASK_FAILED,
ImmutableMap.of(
"taskId", task.getId(),
"taskType", task.getTaskType(),
"instanceId", task.getInstanceId()), ex);
} finally {
LOG.debug("Executing task [{}] synchronously ended", task.getId());
}
}
@Override
@Transactional
public void cancel(UUID longRunningTaskId) {
Assert.notNull(longRunningTaskId);
IdmLongRunningTaskDto task = service.get(longRunningTaskId);
Assert.notNull(longRunningTaskId);
if (OperationState.RUNNING != task.getResult().getState()) {
throw new ResultCodeException(CoreResultCode.LONG_RUNNING_TASK_NOT_RUNNING,
ImmutableMap.of(
"taskId", longRunningTaskId,
"taskType", task.getTaskType(),
"instanceId", task.getInstanceId())
);
}
task.setResult(new OperationResult.Builder(OperationState.CANCELED).build());
// running to false will be setted by task himself
service.save(task);
}
@Override
@Transactional
public boolean interrupt(UUID longRunningTaskId) {
Assert.notNull(longRunningTaskId);
IdmLongRunningTaskDto task = service.get(longRunningTaskId);
Assert.notNull(longRunningTaskId);
String instanceId = configurationService.getInstanceId();
if (!task.getInstanceId().equals(instanceId)) {
throw new ResultCodeException(CoreResultCode.LONG_RUNNING_TASK_DIFFERENT_INSTANCE,
ImmutableMap.of(
"taskId", longRunningTaskId,
"taskInstanceId", task.getInstanceId(),
"currentInstanceId", instanceId));
}
if (OperationState.RUNNING != task.getResult().getState()) {
throw new ResultCodeException(CoreResultCode.LONG_RUNNING_TASK_NOT_RUNNING,
ImmutableMap.of(
"taskId", longRunningTaskId,
"taskType", task.getTaskType(),
"instanceId", task.getInstanceId()));
}
// interrupt thread
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread thread : threadSet) {
if (thread.getId() == task.getThreadId()) {
ResultModel resultModel = new DefaultResultModel(CoreResultCode.LONG_RUNNING_TASK_INTERRUPT,
ImmutableMap.of(
"taskId", task.getId(),
"taskType", task.getTaskType(),
"instanceId", task.getInstanceId()));
Exception ex = null;
try {
thread.interrupt();
} catch(Exception e) {
ex = e;
LOG.error(resultModel.toString(), e);
}
task.setRunning(false);
if (ex == null) {
task.setResult(new OperationResult.Builder(OperationState.CANCELED).setModel(resultModel).build());
} else {
task.setResult(new OperationResult.Builder(OperationState.EXCEPTION).setModel(resultModel).setCause(ex).build());
}
service.save(task);
return true;
}
}
LOG.warn("Long ruuning task with id");
return false;
}
/**
* Persists task state do long running task
*
* @param taskExecutor
* @return
*/
private IdmLongRunningTaskDto persistTask(LongRunningTaskExecutor<?> taskExecutor) {
// prepare task
IdmLongRunningTaskDto task;
if (taskExecutor.getLongRunningTaskId() == null) {
task = new IdmLongRunningTaskDto();
task.setTaskType(taskExecutor.getName());
task.setTaskDescription(taskExecutor.getDescription());
task.setInstanceId(configurationService.getInstanceId());
task.setResult(new OperationResult.Builder(OperationState.RUNNING).build());
task = service.save(task);
taskExecutor.setLongRunningTaskId(task.getId());
} else {
task = service.get(taskExecutor.getLongRunningTaskId());
Assert.notNull(task);
if (task.isRunning()) {
throw new ResultCodeException(CoreResultCode.LONG_RUNNING_TASK_IS_RUNNING, ImmutableMap.of("taskId", task.getId()));
}
if (!OperationState.isRunnable(task.getResultState())) {
throw new ResultCodeException(CoreResultCode.LONG_RUNNING_TASK_IS_PROCESSED, ImmutableMap.of("taskId", task.getId()));
}
if (!task.getInstanceId().equals(configurationService.getInstanceId())) {
throw new ResultCodeException(CoreResultCode.LONG_RUNNING_TASK_DIFFERENT_INSTANCE,
ImmutableMap.of("taskId", task.getId(), "taskInstanceId", task.getInstanceId(), "currentInstanceId", configurationService.getInstanceId()));
}
}
return task;
}
}
|
package eu.modelwriter.traceability.validation.core.fol.interpreter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.antlr.v4.runtime.tree.TerminalNode;
import eu.modelwriter.traceability.validation.core.fol.model.Relation;
import eu.modelwriter.traceability.validation.core.fol.model.Tuple;
import eu.modelwriter.traceability.validation.core.fol.model.Universe;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLBaseVisitor;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLLexer;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLParser.ConjunctionContext;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLParser.DisjunctionContext;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLParser.ExprContext;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLParser.NegationContext;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLParser.QuantificationContext;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLParser.QuantifierContext;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLParser.RelationContext;
import eu.modelwriter.traceability.validation.core.fol.recognizer.FOLParser.SentenceContext;
public class Interpreter extends FOLBaseVisitor<Boolean> {
Universe universe;
HashMap<String, String> quantOfIdent = new HashMap<String, String>();
HashMap<String, String> constOfIdent = new HashMap<String, String>();
public Interpreter(Universe universe) {
this.universe = universe;
}
@Override
public Boolean visitConjunction(ConjunctionContext ctx) {
boolean leftResult = this.visit(ctx.left);
boolean rightResult = this.visit(ctx.right);
return leftResult && rightResult;
}
@Override
public Boolean visitDisjunction(DisjunctionContext ctx) {
boolean leftResult = this.visit(ctx.left);
boolean rightResult = this.visit(ctx.right);
return leftResult || rightResult;
}
@Override
public Boolean visitNegation(NegationContext ctx) {
boolean result = this.visit(ctx.expr());
return !result;
}
@Override
public Boolean visitQuantification(QuantificationContext ctx) {
ArrayList<TerminalNode> identifiers = new ArrayList<TerminalNode>();
// String op = ctx.quantifier().op.getText().toLowerCase();
int opType = ctx.quantifier().op.getType();
int identSize = ctx.quantifier().IDENTIFIER().size();
for (TerminalNode terminalNode : ctx.quantifier().IDENTIFIER()) {
identifiers.add(terminalNode);
// this.quantOfIdent.put(terminalNode.getText(), op);
this.constOfIdent.put(terminalNode.getText(), this.universe.getFirstAtomText());
}
boolean result = false;
int truthCounter = 0;
for (;;) {
result = this.visit(ctx.scope);
if (result)
truthCounter++;
if (opType == FOLLexer.ALL && !result) { // if result is false, all is not valid.
return false;
} else if (opType == FOLLexer.SOME && result) { // if result is true, some is valid.
return true;
} else if (opType == FOLLexer.NO && result) { // if result is true, no is not valid.
return false;
} else if ((opType == FOLLexer.LONE || opType == FOLLexer.ONE) && truthCounter > 1) {
return false;
}
Boolean nextConst =
this.visit(ctx.quantifier().IDENTIFIER(identSize - 1)); /*
* change const of last ident
*/
if (!nextConst) { // if all combinations are tried
if (opType == FOLLexer.ALL) {
return true;
} else if (opType == FOLLexer.SOME) {
return false;
} else if (opType == FOLLexer.NO) {
return true;
} else if (opType == FOLLexer.LONE) { // if result is true, no is not valid.
return true;
} else if (opType == FOLLexer.ONE) { // if result is true, no is not valid.
return truthCounter == 0 ? false : true;
}
}
}
}
@Override
public Boolean visitRelation(RelationContext ctx) {
String relationName = ctx.RELATION_NAME().getText();
List<TerminalNode> relIdents = ctx.IDENTIFIER();
Relation relation = this.universe.getRelation(relationName);
if (relation == null) {
// System.out.println("Relation is not found. " + this.i);
return false;
}
int arity = relIdents.size();
if (arity == 0 && relation.getTupleCount() == 0) {
// System.out.println(relationName + " is an empty set. " + this.i);
return false;
}
int truth = 0;
for (Tuple tuple : relation.getTuples()) {
truth = 0;
for (int i = 0; i < arity; i++) {
String constant = this.constOfIdent.get(relIdents.get(i).getText());
if (constant == null) { // some z | R(z,d);
if (tuple.getAtom(i).getText().equals(relIdents.get(i).getText())) {
truth++;
}
} else {
if (tuple.getAtom(i).getText().equals(constant)) {
truth++;
}
}
}
if (truth == arity) {
return true;
}
}
return false;
}
@Override
public Boolean visitSentence(SentenceContext ctx) {
this.quantOfIdent = new HashMap<String, String>();
this.constOfIdent = new HashMap<String, String>();
ExprContext expr = ctx.expr();
boolean result = this.visit(expr);
System.out.println(ctx.getText() + " = " + result);
return result;
}
@Override
public Boolean visitTerminal(TerminalNode node) {
if (node.getSymbol().getType() == FOLLexer.IDENTIFIER
&& node.getParent() instanceof QuantifierContext) {
QuantifierContext parent = (QuantifierContext) node.getParent();
String currentConst = this.constOfIdent.get(node.getText());
String nextConst = this.universe.getNextAtomText(currentConst);
if (nextConst == null) { // if last const
nextConst = this.universe.getFirstAtomText();
this.constOfIdent.replace(node.getText(), nextConst);
for (int i = 1; i < parent.IDENTIFIER().size(); i++) { // if node is not only identifier of
// parent
if (parent.IDENTIFIER(i).getText().equals(node.getText())) {
this.visit(parent.IDENTIFIER(i - 1));
return true;
}
}
return false; // if node is only identifier of parent
}
this.constOfIdent.replace(node.getText(), nextConst); // if not last const
}
return true;
}
}
|
package org.eclipse.birt.report.designer.internal.ui.views.attributes.page;
import java.io.ByteArrayOutputStream;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.ComboPropertyDescriptorProvider;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.TextPropertyDescriptorProvider;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.ComboSection;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.TextAndTwoButtonSection;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.section.TextSection;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.dialogs.ThumbnailBuilder;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.widgets.Composite;
/**
* The general attribute page of Report element.
*/
public class ReportPage extends ModulePage
{
private TextAndTwoButtonSection prvImageSection;
public void buildUI( Composite parent )
{
super.buildUI( parent );
ComboPropertyDescriptorProvider layoutProvider = new ComboPropertyDescriptorProvider( ReportDesignHandle.LAYOUT_PREFERENCE_PROP,
ReportDesignConstants.REPORT_DESIGN_ELEMENT );
ComboSection layoutSection = new ComboSection( layoutProvider.getDisplayName( ),
container,
true );
layoutSection.setProvider( layoutProvider );
layoutSection.setWidth( 500 );
layoutSection.setGridPlaceholder( 2, true );
addSection( PageSectionId.REPORT_LAYOUT_PREFERENCE, layoutSection );
TextPropertyDescriptorProvider displayProvider = new TextPropertyDescriptorProvider( ModuleHandle.DISPLAY_NAME_PROP,
ReportDesignConstants.REPORT_DESIGN_ELEMENT );
TextSection displaySection = new TextSection( displayProvider.getDisplayName( ),
container,
true );
displaySection.setProvider( displayProvider );
displaySection.setWidth( 500 );
displaySection.setGridPlaceholder( 2, true );
addSection( PageSectionId.REPORT_DISPLAY, displaySection );
TextPropertyDescriptorProvider prvImageProvider = new TextPropertyDescriptorProvider( ReportDesignHandle.ICON_FILE_PROP,
ReportDesignConstants.REPORT_DESIGN_ELEMENT );
prvImageSection = new TextAndTwoButtonSection( prvImageProvider.getDisplayName( ),
container,
true );
prvImageSection.setProvider( prvImageProvider );
prvImageSection.addSecondSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
ThumbnailBuilder dialog = new ThumbnailBuilder( );
dialog.setImageName( prvImageSection.getTextControl( ).getText( ) );
ReportDesignHandle handle = (ReportDesignHandle) SessionHandleAdapter.getInstance( )
.getReportDesignHandle( );
dialog.setReportDesignHandle( handle );
if ( dialog.open( ) != Dialog.OK )
{
Image image = dialog.getImage( );
if ( image != null )
{
image.dispose( );
image = null;
}
return;
}
if ( dialog.shouldSetThumbnail( ) )
{
Image image = dialog.getImage( );
ImageData imageData = image.getImageData( );
ImageLoader imageLoader = new ImageLoader( );
imageLoader.data = new ImageData[1];
imageLoader.data[0] = imageData;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
imageLoader.save( outputStream, SWT.IMAGE_BMP );
try
{
handle.setThumbnail( outputStream.toByteArray( ) );
}
catch ( SemanticException e1 )
{
ExceptionHandler.handle( e1 );
}
if ( image != null )
{
image.dispose( );
image = null;
}
prvImageSection.setStringValue( dialog.getImageName( ) );
prvImageSection.forceFocus( );
}
else
{
if ( handle.getThumbnail( ) != null
&& handle.getThumbnail( ).length != 0 )
{
try
{
handle.deleteThumbnail( );
}
catch ( SemanticException e1 )
{
ExceptionHandler.handle( e1 );
}
}
prvImageSection.setStringValue("");
prvImageSection.forceFocus( );
}
}
} );
prvImageSection.setWidth( 500 );
// prvImageSection.setFristButtonText( Messages.getString( "ReportPage.text.Browse" ) );
prvImageSection.setSecondButtonText( "..." );
prvImageSection.setSecondButtonTooltipText(Messages.getString( "ReportPage.PreviewImage.Button.ToolTip"));
addSection( PageSectionId.REPORT_PRVIMAGE, prvImageSection );
createSections( );
layoutSections( );
}
}
|
package brownshome.scriptwars.game.tanks;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.logging.Level;
import java.util.stream.Collectors;
import brownshome.scriptwars.connection.Network;
import brownshome.scriptwars.game.*;
import brownshome.scriptwars.server.Server;
public class World {
private List<Shot> shots = new LinkedList<>();
private Map<Player<?>, Tank> tanks = new HashMap<>();
private Set<Tank> clientTanks = new HashSet<>();
private boolean[][] map;
private Tank[][] tankMap;
private Shot[][] shotMap;
private Set<Coordinates> ammoPickup = new HashSet<>();
private Set<Tank> tanksToFire = new HashSet<>();
private Set<Player<?>> playersToSpawn = new HashSet<>();
private Collection<Shot> deadShotsToRender = new ArrayList<>();
Collection<Tank> deadTanksToRender = new ArrayList<>();
private TankGame game;
protected World(boolean[][] map, TankGame game) {
assert map.length > 0 && map[0].length > 0;
this.map = map;
this.game = game;
tankMap = new Tank[map.length][map[0].length];
shotMap = new Shot[map.length][map[0].length];
}
/**
* Constructs a world using data from the given network
* @param network The network to read from
*/
public World(Network network) {
int width = network.getByte();
int height = network.getByte();
map = new boolean[height][width];
tankMap = new Tank[height][width];
shotMap = new Shot[height][width];
for(boolean[] row : map) {
for(int x = 0; x < width; x++) {
row[x] = network.getBoolean();
}
}
int tanks = network.getByte();
for(int t = 0; t < tanks; t++) {
Tank tank = new Tank(network);
tankMap[tank.getPosition().getY()][tank.getPosition().getX()] = tank;
clientTanks.add(tank);
}
int shotCount = network.getByte();
for(int s = 0; s < shotCount; s++) {
Shot shot = new Shot(network);
shots.add(shot);
addToShotMap(shot);
}
int ammoCount = network.getByte();
for(int i = 0; i < ammoCount; i++) {
Coordinates coord = new Coordinates(network);
ammoPickup.add(coord);
}
}
/**
* @param x
* @param y
* @return null if there is no tank, returns the tank otherwise
*/
public Tank getTank(int x, int y) {
return tankMap[y][x];
}
public Shot getShot(int x, int y) {
return shotMap[y][x];
}
public Tank getTank(Coordinates c) {
return getTank(c.getX(), c.getY());
}
public Shot getShot(Coordinates c) {
return getShot(c.getX(), c.getY());
}
private void setTank(Coordinates c, Tank tank) {
tankMap[c.getY()][c.getX()] = tank;
}
public boolean isWall(Coordinates c) {
return isWall(c.getX(), c.getY());
}
public boolean isWall(int x, int y) {
return map[y][x];
}
public Collection<Shot> getShots() {
return shots;
}
public int getWidth() {
return map[0].length;
}
public int getHeight() {
return map.length;
}
protected void moveTank(Player<?> player, Direction direction) {
if(!isAlive(player))
throw new IllegalStateException("You are not alive, you cannot move.");
Tank tank = tanks.get(player);
tank.getPosition();
tank.move(direction);
setTank(tank.getPosition(), tank);
}
protected void fireNextTick(Player<?> player) {
tanksToFire.add(getTank(player));
}
//Check if every tank is in the spot they think they are. For any tanks that
//are overwrote roll them back as well as the tank overriding them. Then repeat.
protected void finalizeMovement() {
Set<Tank> tanksToRollBack = new HashSet<>();
for(Tank tank : tanks.values()) {
Tank other = getTank(tank.getPosition());
if(other != tank) {
if(other != null)
tanksToRollBack.add(other);
tanksToRollBack.add(tank);
}
}
//clear tankMap
tankMap = new Tank[getHeight()][getWidth()];
if(tanksToRollBack.isEmpty()) {
//CHECK FOR TANKS SWAPPING POSITIONS
//For each tank, if it moved. Check if there is a tank on it's old space
//that just moved from it's space.
for(Tank tank : tanks.values())
setTank(tank.getPosition(), tank);
for(Tank tank : tanks.values()) {
if(tank.hasMoved()) {
Coordinates space = tank.getPosition();
Coordinates oldSpace = tank.getDirection().opposite().move(tank.getPosition());
Tank otherTank = getTank(oldSpace);
if(
otherTank != null
&& otherTank.hasMoved()
&& otherTank.getDirection().opposite() == tank.getDirection()
) {
tanksToRollBack.add(tank);
tanksToRollBack.add(otherTank);
}
}
}
if(tanksToRollBack.isEmpty()) {
return;
}
}
for(Tank tank : tanksToRollBack) {
tank.rollBack();
}
for(Tank tank : tanks.values()) {
setTank(tank.getPosition(), tank);
}
//at most we recurse MAX_PLAYERS times. No risk of stack overflow
finalizeMovement();
}
protected void pickupAmmo() {
for(Tank tank : tanks.values()) {
if(ammoPickup.remove(tank.getPosition())) {
tank.refilAmmo();
}
}
try {
while(ammoPickup.size() < game.numberOfAmmoPickups()) {
ammoPickup.add(getAmmoSpawnCoordinate());
}
} catch(IllegalStateException e) { /*No valid spawn slots*/ }
}
private Coordinates getAmmoSpawnCoordinate() {
List<Coordinates> possibleSpawns = new ArrayList<>(getWidth() * getHeight());
for(int x = 0; x < getWidth(); x++) {
for(int y = 0; y < getHeight(); y++) {
Coordinates coord = new Coordinates(x, y);
if(!isWall(coord) && getTank(coord) == null && !ammoPickup.contains(coord)) {
possibleSpawns.add(coord);
}
}
}
if(possibleSpawns.isEmpty()) throw new IllegalStateException();
return possibleSpawns.get(new Random().nextInt(possibleSpawns.size()));
}
protected void fireTanks() {
for(Tank tank : tanksToFire) {
fireTank(tank);
}
tanksToFire.clear();
//Check to see if any shots are in the same spot, delete them
Set<Shot> shotsToRemove = new HashSet<>();
for(Shot shot : shots) {
Shot other = getShot(shot.getPosition());
if(other != shot) {
shotsToRemove.add(other);
shotsToRemove.add(shot);
deadShotsToRender.add(other);
deadShotsToRender.add(shot);
}
}
shots.removeIf(s -> {
if(shotsToRemove.contains(s)) {
removeShotFromMap(s);
return true;
}
return false;
});
}
private void fireTank(Tank tank) {
Direction direction = tank.getDirection();
Coordinates bulletSpawn = direction.move(tank.getPosition());
if(!tank.removeAmmo())
return;
Shot shot = new Shot(bulletSpawn, tank, this, direction);
if(isWall(bulletSpawn)) {
deadShotsToRender.add(shot);
return;
}
Tank otherTank = getTank(bulletSpawn);
if(otherTank != null) {
tank.getOwner().addScore(1);
tank.refilAmmo();
otherTank.kill();
deadShotsToRender.add(shot);
return;
}
shots.add(shot);
addToShotMap(shot);
}
private void addToShotMap(Shot shot) {
shotMap[shot.getPosition().getY()][shot.getPosition().getX()] = shot;
}
protected void moveShots() {
shots.forEach(Shot::updatePrevious);
for(int i = 0; i < Shot.SPEED; i++) {
moveShotsOnce();
}
}
private void moveShotsOnce() {
//Delete shots that are swapping
//Delete shots that will collide
//Move shots, taking into account walls and such things
List<Shot> deadShots = new ArrayList<>(shots.size());
//Check swapping
shots.removeIf(s -> {
Shot other;
Coordinates nextPos = s.getDirection().move(s.getPosition());
//There is a shot in nextPos and it is coming towards us.
if((other = getShot(nextPos)) != null && other.getDirection().opposite() == s.getDirection()) {
deadShots.add(s);
return true;
}
return false;
});
for(Shot s : deadShots) {
removeShotFromMap(s);
//TODO have the shots collide at the half extents
}
deadShots.clear();
//Check for collisions
shots.removeIf(s -> {
Coordinates nextPos = s.getDirection().move(s.getPosition());
if(isWall(nextPos)) {
deadShots.add(s);
return true;
}
//Check every direction into the new space other than the one we came from
for(Direction dir = s.getDirection().opposite().clockwise(); dir != s.getDirection().opposite(); dir = dir.clockwise()) {
Shot other = getShot(dir.move(nextPos));
if(other != null && other.getDirection().opposite() == dir) {
deadShots.add(s);
return true;
}
}
return false;
});
for(Shot s : deadShots) {
removeShotFromMap(s);
s.tickShot(); //Make the position of the shot correct
deadShotsToRender.add(s);
}
deadShots.clear();
shots.removeIf(s -> {
removeShotFromMap(s);
if(s.tickShot()) {
deadShots.add(s);
deadShotsToRender.add(s);
return true;
} else {
addToShotMap(s);
}
return false;
});
for(Shot s : deadShots) {
s.completeTick();
}
}
private void removeShotFromMap(Shot shot) {
if(shotMap[shot.getPosition().getY()][shot.getPosition().getX()] == shot)
shotMap[shot.getPosition().getY()][shot.getPosition().getX()] = null;
}
protected boolean isAlive(Player<?> player) {
return tanks.containsKey(player);
}
protected Collection<Tank> getVisibleTanks(Player<?> player) {
Tank tank = getTank(player);
return tanks.values().stream()
.filter(otherTank -> otherTank != tank)
.filter(otherTank -> canSee(tank.getPosition(), otherTank.getPosition()))
.collect(Collectors.toList());
}
protected void writeWorld(ByteBuffer data) {
byte buffer = 0;
int index = 0;
for(boolean[] row : map) {
for(boolean isWall : row) {
buffer |= (isWall ? 1 : 0) << index++;
if(index == 8) {
index = 0;
data.put(buffer);
buffer = 0;
}
}
}
if(index != 0) {
data.put(buffer);
}
}
protected void spawnTank(Player<?> player) {
playersToSpawn.add(player);
}
protected void spawnPlayers() {
Player<?> player;
for(Iterator<Player<?>> iterator = playersToSpawn.iterator(); iterator.hasNext(); ) {
player = iterator.next();
Coordinates coord = getSpawningCoordinate();
if(coord == null) {
Server.LOG.log(Level.INFO, "Unable to spawn all players");
continue;
}
iterator.remove();
Tank tank = new Tank(coord, player, this);
tanks.put(player, tank);
setTank(coord, tank);
}
}
private Coordinates getSpawningCoordinate() {
//spawn tanks in the farthest position away from players, weighting more towards open spaces.
Coordinates bestCoordinate = null;
float bestRank = Float.NEGATIVE_INFINITY;
for(int x = 0; x < getWidth(); x++) {
for(int y = 0; y < getHeight(); y++) {
Coordinates coord = new Coordinates(x, y);
if(!isWall(coord) && getTank(coord) == null) {
float rank = rankCoordinate(coord);
if(bestRank < rank) {
bestCoordinate = coord;
bestRank = rank;
}
}
}
}
return bestCoordinate;
}
private float rankCoordinate(Coordinates coord) {
final float UNSAFE_RANK = -2f; //The rank lost for every turn under 10 that the space might be safe for.
final float IS_CORNER = .5f; //The rank gained for being a corner
final float IS_SEEN = 2f; //The rank gained for not being seen
final float DISTANCE = .125f; //The rank gained for being far away from the nearest tank
float rank = 0;
for(Shot shot : shots) {
Coordinates shotCoord = shot.getPosition();
if(Direction.getDirection(coord, shotCoord) == shot.getDirection()) {
int timeSurvived = 10;
for(; !isWall(shotCoord); shotCoord = shot.getDirection().move(shotCoord)) {
timeSurvived
if(timeSurvived == 0) {
break;
}
if(shotCoord.equals(coord)) {
rank += UNSAFE_RANK * timeSurvived;
break;
}
}
}
}
for(Direction dir : Direction.values()) {
if(!isWall(dir.move(coord)) && !isWall(dir.clockwise().move(coord))) {
rank += IS_CORNER;
break;
}
}
boolean isSeen = false;
int closestDistance = -1;
for(Tank tank : tanks.values()) {
if(!isSeen && canSee(tank.getPosition(), coord)) {
rank -= IS_SEEN;
isSeen = true;
}
int distance = distance(coord, tank.getPosition());
if(closestDistance == -1 || distance < closestDistance) {
closestDistance = distance;
}
}
rank += DISTANCE * closestDistance;
return rank;
}
private int distance(Coordinates a, Coordinates b) {
return Math.abs(a.getX() - b.getX()) + Math.abs(a.getY() - b.getY());
}
private boolean canSee(Coordinates a, Coordinates b) {
int dx = 0;
if(a.getX() < b.getX()) dx = 1;
if(a.getX() > b.getX()) dx = -1;
int dy = 0;
if(a.getY() < b.getY()) dy = 1;
if(a.getY() > b.getY()) dy = -1;
if(dx == 0) {
if(dy == 0) {
return isWall(a);
}
for(int y = a.getY(); y != b.getY() + dy; y += dy) {
if(isWall(a.getX(), y))
return false;
}
return true;
}
if(dy == 0) {
for(int x = a.getX(); x != b.getX() + dx; x += dx) {
if(isWall(x, a.getY()))
return false;
}
return true;
}
for(int x = a.getX(); x != b.getX() + dx; x += dx) {
for(int y = a.getY(); y != b.getY() + dy; y += dy) {
if(isWall(x, y))
return false;
}
}
return true;
}
private class TankGridItem implements GridItem {
private final Coordinates start, end;
private final byte code;
public TankGridItem(Tank tank) {
if(tank.hasMoved()) {
Direction dir = tank.getDirection().opposite();
end = tank.getPosition();
start = dir.move(end);
} else {
start = end = tank.getPosition();
}
code = (byte) (game.getIndex(tank.getOwner()) + TankGameDisplayHandler.DynamicSprites.TANK_START.ordinal());
}
@Override public byte code() { return code; }
@Override public Coordinates start() { return start; }
@Override public Coordinates end() { return end; }
}
public static class ShotGridItem implements GridItem {
private final Coordinates start, end;
public ShotGridItem(Shot shot) {
start = shot.getPrevious();
end = shot.getPosition();
}
@Override public byte code() { return (byte) TankGameDisplayHandler.DynamicSprites.SHOT.ordinal(); }
@Override public Coordinates start() { return start; }
@Override public Coordinates end() { return end; }
}
public static class AmmoPickupGridItem implements GridItem {
private final Coordinates position;
public AmmoPickupGridItem(Coordinates position) {
this.position = position;
}
@Override public byte code() { return (byte) TankGameDisplayHandler.DynamicSprites.AMMO.ordinal(); }
@Override public Coordinates start() { return position; }
@Override public Coordinates end() { return position; }
}
public void displayWorld(TankGameDisplayHandler handler) {
//TODO add dead shots and tanks
Collection<GridItem> items = new ArrayList<>();
for(Tank tank : tanks.values()) {
items.add(new TankGridItem(tank));
tank.clearHasMoved();
}
for(Shot shot : shots) {
items.add(new ShotGridItem(shot));
}
for(Shot shot : deadShotsToRender) {
items.add(new ShotGridItem(shot)); //This includes shots that never existed
}
for(Tank tank : deadTanksToRender) {
items.add(new TankGridItem(tank));
}
for(Coordinates pickup : ammoPickup) {
items.add(new AmmoPickupGridItem(pickup));
}
deadTanksToRender.clear();
deadShotsToRender.clear();
handler.setDynamicItems(items);
}
protected void removeTank(Tank tank) {
removeTank(tank.getOwner());
}
protected Tank getTank(Player<?> player) {
return tanks.get(player);
}
protected int getDataSize() {
return (getWidth() * getHeight() - 1) / Byte.SIZE + 1;
}
protected void removeTank(Player<?> player) {
Tank tank = tanks.remove(player);
setTank(tank.getPosition(), null);
shots.removeIf(s -> {
if(s.getOwner() == tank) {
removeShotFromMap(s);
return true;
}
return false;
});
}
/**
* Only use on the client side, do not edit.
* @return The tanks.
*/
public Collection<Tank> getTanks() {
return clientTanks;
}
boolean[][] getMap() {
return map;
}
public Collection<Coordinates> getAmmoPickups() {
return ammoPickup;
}
public boolean isAmmoPickup(Coordinates coord) {
return ammoPickup.contains(coord);
}
}
|
package org.jetel.component;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import org.jetel.component.rollup.RecordRollup;
import org.jetel.component.rollup.RecordRollupDescriptor;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.Defaults;
import org.jetel.data.DoubleRecordBuffer;
import org.jetel.data.HashKey;
import org.jetel.data.RecordKey;
import org.jetel.exception.AttributeNotFoundException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.ConfigurationStatus.Priority;
import org.jetel.exception.ConfigurationStatus.Severity;
import org.jetel.exception.JetelException;
import org.jetel.exception.NotInitializedException;
import org.jetel.exception.TransformException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.SynchronizeUtils;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.property.RefResFlag;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
/**
* <h3>Rollup Component</h3>
*
* <p>Executes the rollup transform on all the input data records.</p>
*
* <h4>Component:</h4>
* <table border="1">
* <tr>
* <td><b>Name:</b></td>
* <td>Rollup</td>
* </tr>
* <tr>
* <td><b>Category:</b></td>
* <td>transformers</td>
* </tr>
* <tr>
* <td><b>Description:</b></td>
* <td>
* A general transformation component that serves as an executor of rollup transforms written in Java or CTL.
* See the {@link RecordRollup} interface for more details on the life cycle of the rollup transform.
* </td>
* </tr>
* <tr>
* <td><b>Inputs:</b></td>
* <td>[0] - input data records</td>
* </tr>
* <tr>
* <td><b>Outputs:</b></td>
* <td>At least one connected output port.</td>
* </tr>
* </table>
*
* <h4>XML attributes:</h4>
* <table border="1">
* <tr>
* <td><b>id</b></td>
* <td>ID of the component.</td>
* </tr>
* <tr>
* <td><b>type</b></td>
* <td>ROLLUP</td>
* </tr>
* <tr>
* <td>
* <b>groupKeyFields</b>
* <i>optional</i>
* </td>
* <td>Field names that form the group key separated by ':', ';' or '|'.</td>
* </tr>
* <tr>
* <td>
* <b>groupAccumulatorMetadataId</b><br>
* <i>optional</i>
* </td>
* <td>ID of data record metadata that should be used to create group "accumulators" (if required).</td>
* </tr>
* <tr>
* <td><b>transform</b></td>
* <td>Rollup transform as a Java or CTL source code.</td>
* </tr>
* <tr>
* <td><b>transformUrl</b></td>
* <td>URL of an external Java/CTL source code of the rollup transform.</td>
* </tr>
* <tr>
* <td>
* <b>transformUrlCharset</b><br>
* <i>optional</i>
* </td>
* <td>Character set used in the source code of the rollup transform specified via an URL.</td>
* </tr>
* <tr>
* <td><b>transformClassName</b></td>
* <td>Class name of a Java class implementing the rollup transform.</td>
* </tr>
* <tr>
* <td>
* <b>inputSorted</b><br>
* <i>optional</i>
* </td>
* <td>
* Flag specifying whether the input data records are sorted or not. If set to false, the order of output
* data records is not specified.
* </td>
* </tr>
* <tr>
* <td>
* <b>equalNULL</b><br>
* <i>optional</i>
* </td>
* <td>Flag specifying whether the null values are considered equal or not.</td>
* </tr>
* </table>
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 22nd June 2010
* @created 30th April 2009
*
* @see RecordRollup
*/
public class Rollup extends Node {
/** the type of the component */
private static final String COMPONENT_TYPE = "ROLLUP";
// names of XML attributes
/** the name of an XML attribute used to store the group key fields */
public static final String XML_GROUP_KEY_FIELDS_ATTRIBUTE = "groupKeyFields";
/** the name of an XML attribute used to store the ID of the group "accumulator" metadata */
public static final String XML_GROUP_ACCUMULATOR_METADATA_ID_ATTRIBUTE = "groupAccumulatorMetadataId";
/** the name of an XML attribute used to store the source code of a Java/CTL transform */
public static final String XML_TRANSFORM_ATTRIBUTE = "transform";
/** the name of an XML attribute used to store the URL of an external Java/CTL transform */
public static final String XML_TRANSFORM_URL_ATTRIBUTE = "transformUrl";
/** the name of an XML attribute used to store the character set used in the rollup transform specified via an URL */
public static final String XML_TRANSFORM_URL_CHARSET_ATTRIBUTE = "transformUrlCharset";
/** the name of an XML attribute used to store the class name of a Java transform */
public static final String XML_TRANSFORM_CLASS_NAME_ATTRIBUTE = "transformClassName";
/** the name of an XML attribute used to store the "input sorted" flag */
public static final String XML_INPUT_SORTED_ATTRIBUTE = "inputSorted";
/** the name of an XML attribute used to store the "equal NULL" flag */
public static final String XML_EQUAL_NULL_ATTRIBUTE = "equalNULL";
// constants used during execution
/** the port index used for data record input */
private static final int INPUT_PORT_NUMBER = 0;
/**
* Creates an instance of the <code>Rollup</code> component from an XML element.
*
* @param transformationGraph the transformation graph the component belongs to
* @param xmlElement the XML element that should be used for construction
*
* @return an instance of the <code>Rollup</code> component
*
* @throws XMLConfigurationException when some attribute is missing
* @throws AttributeNotFoundException
*/
public static Node fromXML(TransformationGraph transformationGraph, Element xmlElement)
throws XMLConfigurationException, AttributeNotFoundException {
Rollup rollup = null;
ComponentXMLAttributes componentAttributes = new ComponentXMLAttributes(xmlElement, transformationGraph);
rollup = new Rollup(componentAttributes.getString(XML_ID_ATTRIBUTE));
String groupKeyString = componentAttributes.getString(XML_GROUP_KEY_FIELDS_ATTRIBUTE, null);
rollup.setGroupKeyFields(!StringUtils.isEmpty(groupKeyString)
? groupKeyString.trim().split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX) : null);
rollup.setGroupAccumulatorMetadataId(
componentAttributes.getString(XML_GROUP_ACCUMULATOR_METADATA_ID_ATTRIBUTE, null));
rollup.setTransform(componentAttributes.getStringEx(XML_TRANSFORM_ATTRIBUTE, null, RefResFlag.SPEC_CHARACTERS_OFF));
rollup.setTransformUrl(componentAttributes.getStringEx(XML_TRANSFORM_URL_ATTRIBUTE, null, RefResFlag.URL));
rollup.setTransformUrlCharset(componentAttributes.getString(XML_TRANSFORM_URL_CHARSET_ATTRIBUTE, null));
rollup.setTransformClassName(componentAttributes.getString(XML_TRANSFORM_CLASS_NAME_ATTRIBUTE, null));
rollup.setTransformParameters(componentAttributes.attributes2Properties(new String[] {
XML_TYPE_ATTRIBUTE, XML_ID_ATTRIBUTE, XML_GROUP_KEY_FIELDS_ATTRIBUTE,
XML_GROUP_ACCUMULATOR_METADATA_ID_ATTRIBUTE, XML_TRANSFORM_ATTRIBUTE, XML_TRANSFORM_URL_ATTRIBUTE,
XML_TRANSFORM_URL_CHARSET_ATTRIBUTE, XML_TRANSFORM_CLASS_NAME_ATTRIBUTE, XML_INPUT_SORTED_ATTRIBUTE,
XML_EQUAL_NULL_ATTRIBUTE }));
rollup.setInputSorted(componentAttributes.getBoolean(XML_INPUT_SORTED_ATTRIBUTE, true));
rollup.setEqualNULL(componentAttributes.getBoolean(XML_EQUAL_NULL_ATTRIBUTE, true));
return rollup;
}
// component attributes read from or written to an XML document
/** the key fields specifying a key used to separate data records into groups */
private String[] groupKeyFields;
/** the ID of data record meta to be used for the group "accumulator" */
private String groupAccumulatorMetadataId;
/** the source code of a Java/CTL rollup transform */
private String transform;
/** the URL of an external Java/CTL rollup transform */
private String transformUrl;
/** the character set used in the rollup transform specified via an URL */
private String transformUrlCharset;
/** the class name of a Java rollup transform */
private String transformClassName;
/** the parameters passed to the init() method of the rollup transform */
private Properties transformParameters;
/** the flag specifying whether the input data records are sorted or not */
private boolean inputSorted = true;
/** the flag specifying whether the null values are considered equal or not */
private boolean equalNULL = true;
// runtime attributes initialized in the init() method
/** the group key used to separate data records into groups */
private RecordKey groupKey;
/** an instance of the rollup transform used during the execution */
private RecordRollup recordRollup;
/** the data records used for output */
private DataRecord[] outputRecords;
/**
* Constructs an instance of the <code>Rollup</code> component with the given ID.
*
* @param id an ID of the component
*/
public Rollup(String id) {
super(id);
}
public Rollup(String id, RecordRollup recordRollup) {
this(id);
this.recordRollup = recordRollup;
}
public void setGroupKeyFields(String[] groupKeyFields) {
this.groupKeyFields = groupKeyFields;
}
public void setGroupAccumulatorMetadataId(String groupAccumulatorMetadataId) {
this.groupAccumulatorMetadataId = groupAccumulatorMetadataId;
}
public void setTransform(String transform) {
this.transform = transform;
}
public void setTransformUrl(String transformUrl) {
this.transformUrl = transformUrl;
}
public void setTransformUrlCharset(String transformUrlCharset) {
this.transformUrlCharset = transformUrlCharset;
}
public void setTransformClassName(String transformClassName) {
this.transformClassName = transformClassName;
}
public void setTransformParameters(Properties transformParameters) {
this.transformParameters = transformParameters;
}
public void setInputSorted(boolean inputSorted) {
this.inputSorted = inputSorted;
}
public void setEqualNULL(boolean equalNULL) {
this.equalNULL = equalNULL;
}
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if (!checkInputPorts(status, 1, 1) || !checkOutputPorts(status, 1, Integer.MAX_VALUE)) {
return status;
}
if (groupKeyFields != null && groupKeyFields.length != 0) {
DataRecordMetadata metadata = getInputPort(INPUT_PORT_NUMBER).getMetadata();
for (String groupKeyField : groupKeyFields) {
if (metadata.getField(groupKeyField) == null) {
status.add(new ConfigurationProblem("The group key field " + StringUtils.quote(groupKeyField)
+ " doesn't exist!", Severity.ERROR, this, Priority.HIGH, XML_GROUP_KEY_FIELDS_ATTRIBUTE));
}
}
}
if (groupAccumulatorMetadataId != null && getGraph().getDataRecordMetadata(groupAccumulatorMetadataId, false) == null) {
status.add(new ConfigurationProblem("The group \"accumulator\" metadata ID is not valid!",
Severity.ERROR, this, Priority.HIGH, XML_GROUP_ACCUMULATOR_METADATA_ID_ATTRIBUTE));
}
if (transformUrlCharset != null && !Charset.isSupported(transformUrlCharset)) {
status.add(new ConfigurationProblem("The transform URL character set is not supported!",
Severity.ERROR, this, Priority.NORMAL, XML_TRANSFORM_URL_CHARSET_ATTRIBUTE));
}
//check transformation
if (recordRollup == null) {
getTransformFactory().checkConfig(status);
}
return status;
}
@Override
public synchronized void init() throws ComponentNotReadyException {
if (isInitialized()) {
throw new IllegalStateException("The component has already been initialized!");
}
super.init();
if (groupKeyFields != null && groupKeyFields.length != 0) {
groupKey = new RecordKey(groupKeyFields, getInputPort(INPUT_PORT_NUMBER).getMetadata());
groupKey.setEqualNULLs(equalNULL);
groupKey.init();
}
if (recordRollup == null) {
recordRollup = getTransformFactory().createTransform();
}
recordRollup.init(transformParameters, getInputPort(INPUT_PORT_NUMBER).getMetadata(),
getGraph().getDataRecordMetadata(groupAccumulatorMetadataId),
getOutMetadata().toArray(new DataRecordMetadata[getOutPorts().size()]));
outputRecords = new DataRecord[getOutPorts().size()];
for (int i = 0; i < outputRecords.length; i++) {
outputRecords[i] = DataRecordFactory.newRecord(getOutputPort(i).getMetadata());
}
}
private TransformFactory<RecordRollup> getTransformFactory() {
TransformFactory<RecordRollup> transformFactory = TransformFactory.createTransformFactory(RecordRollupDescriptor.newInstance());
transformFactory.setTransform(transform);
transformFactory.setTransformClass(transformClassName);
transformFactory.setTransformUrl(transformUrl);
transformFactory.setCharset(transformUrlCharset);
transformFactory.setComponent(this);
transformFactory.setInMetadata(getInMetadata());
transformFactory.setOutMetadata(getOutMetadata());
return transformFactory;
}
@Override
@SuppressWarnings("deprecation")
public void preExecute() throws ComponentNotReadyException {
super.preExecute();
recordRollup.preExecute();
if (firstRun()) {//a phase-dependent part of initialization
//all necessary elements have been initialized in init()
} else {
recordRollup.reset();
}
}
@Override
public Result execute() throws Exception {
if (!isInitialized()) {
throw new NotInitializedException(this);
}
if (inputSorted || groupKey == null) {
executeInputSorted();
} else {
executeInputUnsorted();
}
broadcastEOF();
return (runIt ? Result.FINISHED_OK : Result.ABORTED);
}
/**
* Execution code specific for sorted input of data records.
*
* @throws IOException if an error occurred while reading or writing data records
* @throws InterruptedException if an error occurred while reading or writing data records
* @throws JetelException if input data records are not sorted or an error occurred during the transformation
*/
private void executeInputSorted() throws IOException, InterruptedException, JetelException {
InputPort inputPort = getInputPort(INPUT_PORT_NUMBER);
DoubleRecordBuffer inputRecords = new DoubleRecordBuffer(inputPort.getMetadata());
DataRecord groupAccumulator = null;
if (groupAccumulatorMetadataId != null) {
groupAccumulator = DataRecordFactory.newRecord(getGraph().getDataRecordMetadata(groupAccumulatorMetadataId));
}
if (inputPort.readRecord(inputRecords.getCurrent()) != null) {
try {
recordRollup.initGroup(inputRecords.getCurrent(), groupAccumulator);
} catch (Exception exception) {
recordRollup.initGroupOnError(exception, inputRecords.getCurrent(), groupAccumulator);
}
boolean updateGroupResult = false;
try {
updateGroupResult = recordRollup.updateGroup(inputRecords.getCurrent(), groupAccumulator);
} catch (Exception exception) {
updateGroupResult = recordRollup.updateGroupOnError(exception,
inputRecords.getCurrent(), groupAccumulator);
}
if (updateGroupResult) {
updateTransform(inputRecords.getCurrent(), groupAccumulator);
}
inputRecords.swap();
int sortDirection = 0;
while (runIt && inputPort.readRecord(inputRecords.getCurrent()) != null) {
int comparisonResult = (groupKey != null) ? groupKey.compare(
inputRecords.getCurrent(), inputRecords.getPrevious()) : 0;
if (comparisonResult != 0) {
if (sortDirection == 0) {
sortDirection = comparisonResult;
} else if (comparisonResult != sortDirection) {
throw new JetelException("Input data records not sorted!");
}
boolean finishGroupResult = false;
try {
finishGroupResult = recordRollup.finishGroup(inputRecords.getPrevious(), groupAccumulator);
} catch (Exception exception) {
finishGroupResult = recordRollup.finishGroupOnError(exception,
inputRecords.getPrevious(), groupAccumulator);
}
if (finishGroupResult) {
transform(inputRecords.getPrevious(), groupAccumulator);
}
if (groupAccumulator != null) {
groupAccumulator.reset();
}
try {
recordRollup.initGroup(inputRecords.getCurrent(), groupAccumulator);
} catch (Exception exception) {
recordRollup.initGroupOnError(exception, inputRecords.getCurrent(), groupAccumulator);
}
}
try {
updateGroupResult = recordRollup.updateGroup(inputRecords.getCurrent(), groupAccumulator);
} catch (Exception exception) {
updateGroupResult = recordRollup.updateGroupOnError(exception,
inputRecords.getCurrent(), groupAccumulator);
}
if (updateGroupResult) {
updateTransform(inputRecords.getCurrent(), groupAccumulator);
}
inputRecords.swap();
SynchronizeUtils.cloverYield();
}
boolean finishGroupResult = false;
try {
finishGroupResult = recordRollup.finishGroup(inputRecords.getPrevious(), groupAccumulator);
} catch (Exception exception) {
finishGroupResult = recordRollup.finishGroupOnError(exception,
inputRecords.getPrevious(), groupAccumulator);
}
if (finishGroupResult) {
transform(inputRecords.getPrevious(), groupAccumulator);
}
}
}
/**
* Execution code specific for unsorted input of data records.
*
* @throws TransformException if an error occurred during the transformation
* @throws IOException if an error occurred while reading or writing data records
* @throws InterruptedException if an error occurred while reading or writing data records
*/
private void executeInputUnsorted() throws TransformException, IOException, InterruptedException {
InputPort inputPort = getInputPort(INPUT_PORT_NUMBER);
DataRecord inputRecord = DataRecordFactory.newRecord(inputPort.getMetadata());
DataRecordMetadata groupAccumulatorMetadata = (groupAccumulatorMetadataId != null)
? getGraph().getDataRecordMetadata(groupAccumulatorMetadataId) : null;
Map<HashKey, DataRecord> groupAccumulators = new LinkedHashMap<HashKey, DataRecord>();
HashKey lookupKey = new HashKey(groupKey, inputRecord);
while (runIt && inputPort.readRecord(inputRecord) != null) {
DataRecord groupAccumulator = groupAccumulators.get(lookupKey);
if (groupAccumulator == null && !groupAccumulators.containsKey(lookupKey)) {
if (groupAccumulatorMetadata != null) {
groupAccumulator = DataRecordFactory.newRecord(groupAccumulatorMetadata);
}
groupAccumulators.put(new HashKey(groupKey, inputRecord.duplicate()), groupAccumulator);
try {
recordRollup.initGroup(inputRecord, groupAccumulator);
} catch (Exception exception) {
recordRollup.initGroupOnError(exception, inputRecord, groupAccumulator);
}
}
boolean updateGroupResult = false;
try {
updateGroupResult = recordRollup.updateGroup(inputRecord, groupAccumulator);
} catch (Exception exception) {
updateGroupResult = recordRollup.updateGroupOnError(exception, inputRecord, groupAccumulator);
}
if (updateGroupResult) {
updateTransform(inputRecord, groupAccumulator);
}
SynchronizeUtils.cloverYield();
}
Iterator<Map.Entry<HashKey, DataRecord>> groupAccumulatorsIterator = groupAccumulators.entrySet().iterator();
while (runIt && groupAccumulatorsIterator.hasNext()) {
Map.Entry<HashKey, DataRecord> entry = groupAccumulatorsIterator.next();
boolean finishGroupResult = false;
try {
finishGroupResult = recordRollup.finishGroup(entry.getKey().getDataRecord(), entry.getValue());
} catch (Exception exception) {
finishGroupResult = recordRollup.finishGroupOnError(exception,
entry.getKey().getDataRecord(), entry.getValue());
}
if (finishGroupResult) {
transform(entry.getKey().getDataRecord(), entry.getValue());
}
}
}
/**
* Calls the updateTransform() method on the rollup transform and performs further processing based on the result.
*
* @param inputRecord the current input data record
* @param groupAccumulator the group "accumulator" for the current group
*
* @throws TransformException if an error occurred during the transformation
* @throws IOException if an error occurred while writing a data record to an output port
* @throws InterruptedException if an error occurred while writing a data record to an output port
*/
private void updateTransform(DataRecord inputRecord, DataRecord groupAccumulator)
throws TransformException, IOException, InterruptedException {
int counter = 0;
while (true) {
for (DataRecord outputRecord : outputRecords) {
outputRecord.reset();
}
int transformResult = -1;
try {
transformResult = recordRollup.updateTransform(counter, inputRecord, groupAccumulator, outputRecords);
} catch (Exception exception) {
transformResult = recordRollup.updateTransformOnError(exception, counter,
inputRecord, groupAccumulator, outputRecords);
}
counter++;
if (transformResult == RecordRollup.SKIP) {
break;
}
if (transformResult == RecordRollup.ALL) {
for (int i = 0; i < outputRecords.length; i++) {
writeRecord(i, outputRecords[i]);
}
} else if (transformResult >= 0) {
writeRecord(transformResult, outputRecords[transformResult]);
} else {
throw new TransformException("Transformation finished with error " + transformResult + ": "
+ recordRollup.getMessage());
}
}
}
/**
* Calls the transform() method on the rollup transform and performs further processing based on the result.
*
* @param inputRecord the current input data record
* @param groupAccumulator the group "accumulator" for the current group
*
* @throws TransformException if an error occurred during the transformation
* @throws IOException if an error occurred while writing a data record to an output port
* @throws InterruptedException if an error occurred while writing a data record to an output port
*/
private void transform(DataRecord inputRecord, DataRecord groupAccumulator)
throws TransformException, IOException, InterruptedException {
int counter = 0;
while (true) {
for (DataRecord outputRecord : outputRecords) {
outputRecord.reset();
}
int transformResult = -1;
try {
transformResult = recordRollup.transform(counter, inputRecord, groupAccumulator, outputRecords);
} catch (Exception exception) {
transformResult = recordRollup.transformOnError(exception, counter,
inputRecord, groupAccumulator, outputRecords);
}
counter++;
if (transformResult == RecordRollup.SKIP) {
break;
}
if (transformResult == RecordRollup.ALL) {
for (int i = 0; i < outputRecords.length; i++) {
writeRecord(i, outputRecords[i]);
}
} else if (transformResult >= 0) {
writeRecord(transformResult, outputRecords[transformResult]);
} else {
throw new TransformException("Transformation finished with error " + transformResult + ": "
+ recordRollup.getMessage());
}
}
}
@Override
@SuppressWarnings("deprecation")
public void postExecute() throws ComponentNotReadyException {
super.postExecute();
recordRollup.postExecute();
recordRollup.finished();
}
@Override
public synchronized void free() {
groupKey = null;
recordRollup = null;
outputRecords = null;
super.free();
}
}
|
package ikube.toolkit;
import ikube.Constants;
import org.apache.commons.lang.SerializationUtils;
import org.apache.log4j.Logger;
import javax.persistence.Transient;
import java.beans.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author Michael Couck
* @since 21-11-2010
* @version 01.00
*/
public final class SERIALIZATION {
private static final Logger LOGGER = Logger.getLogger(SERIALIZATION.class);
private static ExceptionListener EXCEPTION_LISTENER = new ExceptionListener() {
@Override
public void exceptionThrown(final Exception exception) {
LOGGER.error("General exception : " + exception.getMessage());
LOGGER.info(null, exception);
}
};
public static String serialize(final Object object) {
XMLEncoder xmlEncoder = null;
try {
setTransientFields(object.getClass(), new ArrayList<Class<?>>());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
xmlEncoder = new XMLEncoder(byteArrayOutputStream);
xmlEncoder.setExceptionListener(EXCEPTION_LISTENER);
xmlEncoder.writeObject(object);
xmlEncoder.flush();
xmlEncoder.close();
xmlEncoder = null;
return byteArrayOutputStream.toString(Constants.ENCODING);
} catch (final UnsupportedEncodingException e) {
LOGGER.error("Unsupported encoding : ", e);
} catch (final Exception e) {
LOGGER.error("Exception serializing object : " + object, e);
} finally {
if (xmlEncoder != null) {
xmlEncoder.close();
}
}
return null;
}
public static Object deserialize(final String xml) {
byte[] bytes;
XMLDecoder xmlDecoder = null;
try {
bytes = xml.getBytes(Constants.ENCODING);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
xmlDecoder = new XMLDecoder(byteArrayInputStream);
xmlDecoder.setExceptionListener(EXCEPTION_LISTENER);
return xmlDecoder.readObject();
} catch (final UnsupportedEncodingException e) {
LOGGER.error("Unsupported encoding : ", e);
} catch (final Exception e) {
LOGGER.error("Exception de-serialising object : " + xml, e);
} finally {
if (xmlDecoder != null) {
xmlDecoder.close();
}
}
return null;
}
public static Object clone(final Object object) {
Object clone = SerializationUtils.clone((Serializable) object);
// try {
// BeanUtilsBean2.getInstance().copyProperties(clone, object);
// LOGGER.error("Exception setting properties to cloned object : " + clone, e);
return clone;
}
@SuppressWarnings({"unchecked", "UnusedParameters"})
public static <T> T clone(final Class<T> klass, T t) {
return (T) clone(t);
}
public static void setTransientFields(Class<?>... classes) {
List<Class<?>> doneClasses = new ArrayList<>();
for (Class<?> klass : classes) {
setTransientFields(klass, doneClasses);
}
}
public static void setTransientFields(final Class<?> klass, final List<Class<?>> doneClasses) {
Class<?> currentClass = klass;
do {
if (doneClasses.contains(currentClass)) {
return;
}
doneClasses.add(currentClass);
BeanInfo info;
try {
info = Introspector.getBeanInfo(currentClass);
} catch (final IntrospectionException e) {
LOGGER.error("Exception setting the transient fields in the serializer : ", e);
return;
}
PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
for (final PropertyDescriptor pd : propertyDescriptors) {
String fieldName = pd.getName();
try {
Field field = SERIALIZATION.getField(currentClass, fieldName);
if (field == null) {
continue;
}
Transient transientAnnotation = field.getAnnotation(Transient.class);
boolean isTransient = Modifier.isTransient(field.getModifiers());
if (transientAnnotation != null || isTransient) {
field.setAccessible(Boolean.TRUE);
pd.setValue("transient", Boolean.TRUE);
}
if (Collection.class.isAssignableFrom(field.getType())) {
Type parametrisedType = field.getGenericType();
if (parametrisedType != null) {
if (ParameterizedType.class.isAssignableFrom(parametrisedType.getClass())) {
Type[] typeArguments = ((ParameterizedType) parametrisedType).getActualTypeArguments();
for (final Type typeArgument : typeArguments) {
if (ParameterizedType.class.isAssignableFrom(typeArgument.getClass())) {
Type rawType = ((ParameterizedType) typeArgument).getRawType();
if (Class.class.isAssignableFrom(rawType.getClass())) {
setTransientFields((Class<?>) rawType, doneClasses);
}
}
}
}
}
}
} catch (final SecurityException e) {
LOGGER.error("Exception setting the transient fields in the serializer : ", e);
}
}
Field[] fields = currentClass.getDeclaredFields();
for (final Field field : fields) {
Class<?> fieldClass = field.getType();
setTransientFields(fieldClass, doneClasses);
}
currentClass = currentClass.getSuperclass();
} while (currentClass != null);
}
/**
* Gets a field in the class or in the hierarchy of the class.
*
* @param klass the original class
* @param name the name of the field
* @return the field in the object or super classes of the object
*/
public static Field getField(final Class<?> klass, final String name) {
Class<?> currentClass = klass;
do {
try {
return klass.getDeclaredField(name);
} catch (Exception ignore) {
// Swallow
}
currentClass = currentClass.getSuperclass();
} while (currentClass != null);
return null;
}
/**
* Singularity.
*/
private SERIALIZATION() {
// Documented
}
}
|
package org.neo4j.examples;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import org.junit.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.neo4j.management.Kernel;
public class JmxTest
{
@Test
public void readJmxProperties()
{
GraphDatabaseService graphDbService = new EmbeddedGraphDatabase(
"target/jmx-db" );
Date startTime = getStartTimeFromManagementBean( graphDbService );
Date now = new Date();
System.out.println( startTime + " " + now );
assertTrue( startTime.before( now ) || startTime.equals( now ) );
}
// START SNIPPET: getStartTime
private static Date getStartTimeFromManagementBean(
GraphDatabaseService graphDbService )
{
// use EmbeddedGraphDatabase to access management beans
EmbeddedGraphDatabase graphDb = (EmbeddedGraphDatabase) graphDbService;
Kernel kernel = graphDb.getManagementBean( Kernel.class );
Date startTime = kernel.getKernelStartTime();
return startTime;
}
// END SNIPPET: getStartTime
}
|
package org.funcj.codec;
import org.funcj.codec.utils.ReflectionUtils;
import org.funcj.control.Exceptions;
import org.funcj.util.Functions.F;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
import static java.util.stream.Collectors.toList;
import static org.funcj.codec.TypeConstructor.createTypeConstructor;
/**
* Base class for classes which implement an encoding into a specific target type.
* @param <E> the encoded type
*/
public abstract class CodecCore<E> {
/**
* A map from class name to {@code Codec}, associating a class with its {@code Codec}.
* Although {@code Codec}s can be registered by the caller prior to en/decoding,
* the primary populator of the registry is this {@code CodecCore} implementation.
* As and when new classes are encountered, they are inspected via Reflection,
* and a {@code Codec} is constructed and registered.
* To support thread-safe use of this class, this field is a {@code ConcurrentHashMap}.
*/
protected final ConcurrentMap<String, Codec<?, E>> codecRegistry = new ConcurrentHashMap<>();
/**
* A map from class name to {@code TypeConstructor}, associating a class with its {@code TypeConstructor}.
* Although {@code TypeConstructor}s can be registered by the caller prior to en/decoding,
* the primary populator of the registry is this {@code CodecCore} implementation.
* As and when new classes are encountered, they are inspected via Reflection,
* and a {@code TypeConstructor} is constructed and registered.
* To support thread-safe use of this class, this field is a {@code ConcurrentHashMap}.
*/
protected final ConcurrentMap<String, TypeConstructor<?>> typeCtorRegistry = new ConcurrentHashMap<>();
/**
* A map from class name to its type proxy, associating a class with its type proxy.
*/
protected final Map<String, Class<?>> typeProxyRegistry = new HashMap<>();
protected CodecCore() {
}
/**
* Register a {@code Codec} for a class.
* @param clazz the class to register codec against
* @param codec the codec
* @param <T> the codec value type
*/
public <T> void registerCodec(Class<? extends T> clazz, Codec<T, E> codec) {
registerCodec(classToName(clazz), codec);
}
/**
* Register a {@code Codec} for a class.
* @param className name of class to register codec against
* @param codec the codec
* @param <T> the codec value type
*/
public <T> void registerCodec(String className, Codec<T, E> codec) {
codecRegistry.put(className, codec);
}
/**
* Register a type proxy.
* A type proxy maps a type to its proxy before selecting its {@code Codec}.
* @param type type to be mapped
* @param proxyType proxy type
*/
public void registerTypeProxy(Class<?> type, Class<?> proxyType) {
registerTypeProxy(classToName(type), proxyType);
}
/**
* Register a type proxy.
* A type proxy maps a type to its proxy before selecting its {@code Codec}.
* @param typeName name of type to be mapped
* @param proxyType proxy type
*/
public void registerTypeProxy(String typeName, Class<?> proxyType) {
typeProxyRegistry.put(typeName, proxyType);
}
/**
* Create a {@code ObjectCodecBuilder} for the specified class.
* <p>
* Create a {@code ObjectCodecBuilder}, essentially a fluent interface
* for creating and registering a {@code Codec}.
* @param clazz the class to register codec against
* @param <T> the codec value type
* @return an {@code ObjectCodecBuilder}
*/
public <T> ObjectCodecBuilder<T, E> codecBuilder(Class<T> clazz) {
return objectCodecDeferredRegister(clazz);
}
/**
* Register a {@code TypeConstructor} for the specified class.
* @param clazz the class to register the {@code TypeConstructor} against
* @param typeCtor the {@code TypeConstructor}
* @param <T> the type constructed by the {@code TypeConstructor}
*/
public <T> void registerTypeConstructor(
Class<? extends T> clazz,
TypeConstructor<T> typeCtor) {
typeCtorRegistry.put(classToName(clazz), typeCtor);
}
/**
* Encode a non-null value of type {@code T} into encoded form {@code E}
* @param val the value to encode
* @param enc the encoded parent (may be null for certain encodings)
* @param <T> the unencoded value type
* @return the encoded value
*/
public <T> E encode(T val, E enc) {
return encode((Class<T>)val.getClass(), val, enc);
}
/**
* Encode a value of type {@code T} into encoded form {@code E}.
* @param type the class of the unencoded value
* @param val the value to encode
* @param enc the encoded parent (may be null for certain encodings)
* @param <T> the unencoded value type
* @return the encoded value
*/
public <T> E encode(Class<T> type, T val, E enc) {
return dynamicCodec(type).encode(val, enc);
}
/**
* Decode a value of type {@code T} from encoded value of type {@code E}.
* @param type the type of unencoded value
* @param enc the value to decode
* @param <T> the unencoded value type
* @return
*/
public <T> T decode(Class<T> type, E enc) {
return dynamicCodec(type).decode(enc);
}
/**
* Map a class to a class name.
* This method exists primarily to allow it to be overridden in one place.
* @param clazz the class
* @return the class name
*/
public String classToName(Class<?> clazz) {
return clazz.getName();
}
public <X> Class<X> remapType(Class<X> type) {
final String typeName = classToName(type);
if (typeProxyRegistry.containsKey(typeName)) {
return (Class<X>) typeProxyRegistry.get(typeName);
} else {
return type;
}
}
public <T> Class<T> nameToClass(String name) {
return (Class<T>) Exceptions.wrap(() -> Class.forName(name), this::wrapException);
}
public abstract RuntimeException wrapException(Exception ex);
public <T> TypeConstructor<T> getTypeConstructor(Class<T> clazz) {
final String name = classToName(clazz);
return (TypeConstructor<T>) typeCtorRegistry.computeIfAbsent(
name,
n -> Exceptions.wrap(() -> createTypeConstructor(clazz), this::wrapException));
}
public <T> Codec<T, E> makeNullSafeCodec(Codec<T, E> codec) {
final Codec.NullCodec<E> nullCodec = nullCodec();
return new Codec<T, E>() {
@Override
public E encode(T val, E enc) {
if (val == null) {
return nullCodec.encode(null, enc);
} else {
return codec.encode(val, enc);
}
}
@Override
public T decode(Class<T> dynType, E enc) {
if (nullCodec.isNull(enc)) {
return (T)nullCodec.decode(enc);
} else {
return codec.decode(dynType, enc);
}
}
@Override
public T decode(E enc) {
if (nullCodec.isNull(enc)) {
return (T)nullCodec.decode(enc);
} else {
return codec.decode(enc);
}
}
};
}
public abstract Codec.NullCodec<E> nullCodec();
public abstract Codec.BooleanCodec<E> booleanCodec();
public abstract Codec<boolean[], E> booleanArrayCodec();
public abstract Codec.ByteCodec<E> byteCodec();
public abstract Codec<byte[], E> byteArrayCodec();
public abstract Codec.CharCodec<E> charCodec();
public abstract Codec<char[], E> charArrayCodec();
public abstract Codec.ShortCodec<E> shortCodec();
public abstract Codec<short[], E> shortArrayCodec();
public abstract Codec.IntCodec<E> intCodec();
public abstract Codec<int[], E> intArrayCodec();
public abstract Codec.LongCodec<E> longCodec();
public abstract Codec<long[], E> longArrayCodec();
public abstract Codec.FloatCodec<E> floatCodec();
public abstract Codec<float[], E> floatArrayCodec();
public abstract Codec.DoubleCodec<E> doubleCodec();
public abstract Codec<double[], E> doubleArrayCodec();
public abstract Codec<String, E> stringCodec();
public abstract <EM extends Enum<EM>> Codec<EM, E> enumCodec(Class<? super EM> enumType);
public <K, V> Codec<Map<K, V>, E> mapCodec(Class<K> keyType, Class<V> valType) {
final Codec<V, E> valueCodec = dynamicCodec(valType);
if (String.class.equals(keyType)) {
return (Codec)mapCodec(valueCodec);
} else {
final Codec<K, E> keyCodec = dynamicCodec(keyType);
return mapCodec(keyCodec, valueCodec);
}
}
public abstract <V> Codec<Map<String, V>, E> mapCodec(Codec<V, E> valueCodec);
public abstract <K, V> Codec<Map<K, V>, E> mapCodec(
Codec<K, E> keyCodec,
Codec<V, E> valueCodec);
public abstract <T> Codec<Collection<T>, E> collCodec(
Class<T> elemType,
Codec<T, E> elemCodec);
public abstract <T> Codec<T[], E> objectArrayCodec(
Class<T> elemType,
Codec<T, E> elemCodec);
public Codec<Object, E> dynamicCodec() {
return dynamicCodec(Object.class);
}
public abstract <T> Codec<T, E> dynamicCodec(Class<T> stcType);
public abstract <T> Codec<T, E> dynamicCodec(Codec<T, E> codec, Class<T> stcType);
public <T> Codec<T, E> getNullSafeCodec(Class<T> type) {
return makeNullSafeCodec(getNullUnsafeCodec(type));
}
public <T> Codec<T, E> getNullUnsafeCodec(Class<T> type) {
final Class<T> type2 = remapType(type);
final String name = classToName(type2);
return (Codec<T, E>) codecRegistry.computeIfAbsent(name, n -> getNullUnsafeCodecImplDyn(type2));
}
public <T> Codec<T, E> getNullUnsafeCodecImplDyn(Class<T> dynType) {
final Codec<T, E> codec = getNullUnsafeCodecImpl(dynType);
if (codec == null) {
return createObjectCodec(dynType);
} else {
return codec;
}
}
public <T> Codec<T, E> getNullUnsafeCodecImplStc(Class<T> stcType) {
final Codec<T, E> codec = getNullUnsafeCodecImpl(stcType);
if (codec == null) {
if (Modifier.isFinal(stcType.getModifiers())) {
final String name = classToName(stcType);
return (Codec<T, E>) codecRegistry.computeIfAbsent(name, n -> createObjectCodec(stcType));
} else {
return dynamicCodec(stcType);
}
} else {
return codec;
}
}
public <T> Codec<T, E> getNullUnsafeCodecImpl(Class<T> type) {
if (type.isPrimitive()) {
if (type.equals(boolean.class)) {
return (Codec<T, E>)booleanCodec();
} else if (type.equals(byte.class)) {
return (Codec<T, E>) byteCodec();
} else if (type.equals(char.class)) {
return (Codec<T, E>) charCodec();
} else if (type.equals(short.class)) {
return (Codec<T, E>) shortCodec();
} else if (type.equals(int.class)) {
return (Codec<T, E>) intCodec();
} else if (type.equals(long.class)) {
return (Codec<T, E>) longCodec();
} else if (type.equals(float.class)) {
return (Codec<T, E>) floatCodec();
} else if (type.equals(double.class)) {
return (Codec<T, E>) doubleCodec();
} else {
throw new IllegalStateException("Unexpected primitive type - " + type);
}
} else {
final Codec<T, E> codec;
if (type.isArray()) {
final Class<?> elemType = type.getComponentType();
if (elemType.equals(boolean.class)) {
codec = (Codec<T, E>) booleanArrayCodec();
} else if (elemType.equals(byte.class)) {
codec = (Codec<T, E>) byteArrayCodec();
} else if (elemType.equals(char.class)) {
codec = (Codec<T, E>) charArrayCodec();
} else if (elemType.equals(short.class)) {
codec = (Codec<T, E>) shortArrayCodec();
} else if (elemType.equals(int.class)) {
codec = (Codec<T, E>) intArrayCodec();
} else if (elemType.equals(long.class)) {
codec = (Codec<T, E>) longArrayCodec();
} else if (elemType.equals(float.class)) {
codec = (Codec<T, E>) floatArrayCodec();
} else if (elemType.equals(double.class)) {
codec = (Codec<T, E>) doubleArrayCodec();
} else {
if (elemType.equals(Boolean.class)) {
codec = (Codec<T, E>) objectArrayCodec(Boolean.class, booleanCodec());
} else if (elemType.equals(Byte.class)) {
codec = (Codec<T, E>) objectArrayCodec(Byte.class, byteCodec());
} else if (elemType.equals(Character.class)) {
codec = (Codec<T, E>) objectArrayCodec(Character.class, charCodec());
} else if (elemType.equals(Short.class)) {
codec = (Codec<T, E>) objectArrayCodec(Short.class, shortCodec());
} else if (elemType.equals(Integer.class)) {
codec = (Codec<T, E>) objectArrayCodec(Integer.class, intCodec());
} else if (elemType.equals(Long.class)) {
codec = (Codec<T, E>) objectArrayCodec(Long.class, longCodec());
} else if (elemType.equals(Float.class)) {
codec = (Codec<T, E>) objectArrayCodec(Float.class, floatCodec());
} else if (elemType.equals(Double.class)) {
codec = (Codec<T, E>) objectArrayCodec(Double.class, doubleCodec());
} else {
final Codec<Object, E> elemCodec = makeNullSafeCodec(dynamicCodec((Class<Object>) elemType));
codec = (Codec<T, E>) objectArrayCodec((Class<Object>) elemType, elemCodec);
}
}
} else if (type.isEnum()) {
codec = enumCodec((Class) type);
} else if (type.equals(Boolean.class)) {
codec = (Codec<T, E>) booleanCodec();
} else if (type.equals(Byte.class)) {
codec = (Codec<T, E>) byteCodec();
} else if (type.equals(Character.class)) {
codec = (Codec<T, E>) charCodec();
} else if (type.equals(Short.class)) {
codec = (Codec<T, E>) shortCodec();
} else if (type.equals(Integer.class)) {
codec = (Codec<T, E>) intCodec();
} else if (type.equals(Long.class)) {
codec = (Codec<T, E>) longCodec();
} else if (type.equals(Float.class)) {
codec = (Codec<T, E>) floatCodec();
} else if (type.equals(Double.class)) {
codec = (Codec<T, E>) doubleCodec();
} else if (type.equals(String.class)) {
codec = (Codec<T, E>) stringCodec();
} else if (Map.class.isAssignableFrom(type)) {
final ReflectionUtils.TypeArgs typeArgs = ReflectionUtils.getTypeArgs(type, Map.class);
final Class<?> keyType = typeArgs.get(0);
final Class<?> valueType = typeArgs.get(1);
codec = dynamicCheck((Codec<T, E>) mapCodec(keyType, valueType), type);
} else if (Collection.class.isAssignableFrom(type)) {
final ReflectionUtils.TypeArgs typeArgs = ReflectionUtils.getTypeArgs(type, Collection.class);
if (typeArgs.size() == 1) {
final Class<Object> elemType = (Class<Object>) typeArgs.get(0);
final Codec<Object, E> elemCodec = makeNullSafeCodec(dynamicCodec(elemType));
codec = dynamicCheck((Codec<T, E>) collCodec(elemType, elemCodec), type);
} else {
codec = null;
}
} else {
codec = null;
}
return codec;
}
}
public <T> Codec<T, E> createObjectCodec(Class<T> type) {
final Map<String, FieldCodec<E>> fieldCodecs = new LinkedHashMap<>();
Class<?> clazz = type;
for (int depth = 0; !clazz.equals(Object.class); depth++) {
final Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
final int fm = field.getModifiers();
if (!Modifier.isStatic(fm) && !Modifier.isTransient(fm)) {
final String fieldName = getFieldName(field, depth, fieldCodecs.keySet());
fieldCodecs.put(fieldName, getFieldCodec(field));
}
}
clazz = clazz.getSuperclass();
}
return createObjectCodec(fieldCodecs);
}
public static abstract class ObjectMeta<T, E, RA extends ObjectMeta.ResultAccumlator<T>> implements Iterable<ObjectMeta.Field<T, E, RA>> {
public interface ResultAccumlator<T> {
T construct();
}
public interface Field<T, E, RA> {
String name();
E encodeField(T val, E enc);
RA decodeField(RA acc, E enc);
}
public abstract RA startDecode(Class<T> type);
public Stream<Field<T, E, RA>> stream() {
return StreamSupport.stream(spliterator(), false);
}
public abstract int size();
}
public <T> Codec<T, E> createObjectCodec(Map<String, FieldCodec<E>> fieldCodecs) {
final class ResultAccumlatorImpl implements ObjectMeta.ResultAccumlator<T> {
final T val;
ResultAccumlatorImpl(Class<T> type) {
this.val = Exceptions.wrap(
() -> getTypeConstructor(type).construct(),
CodecCore.this::wrapException);
}
@Override
public T construct() {
return val;
}
}
final List<ObjectMeta.Field<T, E, ResultAccumlatorImpl>> fieldMetas = fieldCodecs.entrySet().stream()
.map(en -> {
final String name = en.getKey();
final FieldCodec<E> codec = en.getValue();
return (ObjectMeta.Field<T, E, ResultAccumlatorImpl>)new ObjectMeta.Field<T, E, ResultAccumlatorImpl>() {
@Override
public String name() {
return name;
}
@Override
public E encodeField(T val, E enc) {
return codec.encodeField(val, enc);
}
@Override
public ResultAccumlatorImpl decodeField(ResultAccumlatorImpl acc, E enc) {
codec.decodeField(acc.val, enc);
return acc;
}
};
}).collect(toList());
return createObjectCodec(new ObjectMeta<T, E, ResultAccumlatorImpl>() {
@Override
public Iterator<Field<T, E, ResultAccumlatorImpl>> iterator() {
return fieldMetas.iterator();
}
@Override
public ResultAccumlatorImpl startDecode(Class<T> type) {
return new ResultAccumlatorImpl(type);
}
@Override
public int size() {
return fieldMetas.size();
}
});
}
public <T> ObjectCodecBuilder<T, E> objectCodec(Class<T> clazz) {
return new ObjectCodecBuilder<T, E>(this);
}
public <T> ObjectCodecBuilder<T, E> objectCodecDeferredRegister(Class<T> clazz) {
return new ObjectCodecBuilder<T, E>(this) {
@Override
protected Codec<T, E> registration(Codec<T, E> codec) {
registerCodec(clazz, codec);
return codec;
}
};
}
public <T> Codec<T, E> createObjectCodec(
Map<String, ObjectCodecBuilder.FieldCodec<T, E>> fieldCodecs,
F<Object[], T> ctor) {
final class ResultAccumlatorImpl implements ObjectMeta.ResultAccumlator<T> {
final Object[] ctorArgs;
int i = 0;
ResultAccumlatorImpl(Class<T> type) {
this.ctorArgs = new Object[fieldCodecs.size()];
}
@Override
public T construct() {
return ctor.apply(ctorArgs);
}
}
final List<ObjectMeta.Field<T, E, ResultAccumlatorImpl>> fieldMetas = fieldCodecs.entrySet().stream()
.map(en -> {
final String name = en.getKey();
final ObjectCodecBuilder.FieldCodec<T, E> codec = en.getValue();
return (ObjectMeta.Field<T, E, ResultAccumlatorImpl>)new ObjectMeta.Field<T, E, ResultAccumlatorImpl>() {
@Override
public String name() {
return name;
}
@Override
public E encodeField(T val, E enc) {
return codec.encodeField(val, enc);
}
@Override
public ResultAccumlatorImpl decodeField(ResultAccumlatorImpl acc, E enc) {
acc.ctorArgs[acc.i++] = codec.decodeField(enc);
return acc;
}
};
}).collect(toList());
return createObjectCodec(new ObjectMeta<T, E, ResultAccumlatorImpl>() {
@Override
public Iterator<Field<T, E, ResultAccumlatorImpl>> iterator() {
return fieldMetas.iterator();
}
@Override
public ResultAccumlatorImpl startDecode(Class<T> type) {
return new ResultAccumlatorImpl(type);
}
@Override
public int size() {
return fieldMetas.size();
}
});
}
public abstract <T, RA extends ObjectMeta.ResultAccumlator<T>> Codec<T, E> createObjectCodec(ObjectMeta<T, E, RA> objMeta);
public String getFieldName(Field field, int depth, Set<String> existingNames) {
String name = field.getName();
while (existingNames.contains(name)) {
name = "*" + name;
}
return name;
}
public <T> FieldCodec<E> getFieldCodec(Field field) {
final Class<T> stcType = (Class<T>)field.getType();
if (stcType.isPrimitive()) {
if (stcType.equals(boolean.class)) {
return new FieldCodec.BooleanFieldCodec<E>(field, booleanCodec());
} else if (stcType.equals(byte.class)) {
return new FieldCodec.ByteFieldCodec<E>(field, byteCodec());
} else if (stcType.equals(char.class)) {
return new FieldCodec.CharFieldCodec<E>(field, charCodec());
} else if (stcType.equals(short.class)) {
return new FieldCodec.ShortFieldCodec<E>(field, shortCodec());
} else if (stcType.equals(int.class)) {
return new FieldCodec.IntegerFieldCodec<E>(field, intCodec());
} else if (stcType.equals(long.class)) {
return new FieldCodec.LongFieldCodec<E>(field, longCodec());
} else if (stcType.equals(float.class)) {
return new FieldCodec.FloatFieldCodec<E>(field, floatCodec());
} else if (stcType.equals(double.class)) {
return new FieldCodec.DoubleFieldCodec<E>(field, doubleCodec());
} else {
throw new IllegalStateException("Unexpected primitive type - " + stcType);
}
} else {
if (stcType.isArray()) {
final Class<?> elemType = stcType.getComponentType();
if (elemType.equals(boolean.class)) {
final Codec<boolean[], E> codec = getNullSafeCodec((Class<boolean[]>)stcType);
return new FieldCodec.BooleanArrayFieldCodec<E>(field, codec);
} else if (elemType.equals(byte.class)) {
final Codec<byte[], E> codec = getNullSafeCodec((Class<byte[]>)stcType);
return new FieldCodec.ByteArrayFieldCodec<E>(field, codec);
} else if (elemType.equals(char.class)) {
final Codec<char[], E> codec = getNullSafeCodec((Class<char[]>)stcType);
return new FieldCodec.CharArrayFieldCodec<E>(field, codec);
} else if (elemType.equals(short.class)) {
final Codec<short[], E> codec = getNullSafeCodec((Class<short[]>)stcType);
return new FieldCodec.ShortArrayFieldCodec<E>(field, codec);
} else if (elemType.equals(int.class)) {
final Codec<int[], E> codec = getNullSafeCodec((Class<int[]>)stcType);
return new FieldCodec.IntegerArrayFieldCodec<E>(field, codec);
} else if (elemType.equals(long.class)) {
final Codec<long[], E> codec = getNullSafeCodec((Class<long[]>)stcType);
return new FieldCodec.LongArrayFieldCodec<E>(field, codec);
} else if (elemType.equals(float.class)) {
final Codec<float[], E> codec = getNullSafeCodec((Class<float[]>)stcType);
return new FieldCodec.FloatArrayFieldCodec<E>(field, codec);
} else if (elemType.equals(double.class)) {
final Codec<double[], E> codec = getNullSafeCodec((Class<double[]>)stcType);
return new FieldCodec.DoubleArrayFieldCodec<E>(field, codec);
} else {
final Codec<T[], E> codec = getNullSafeCodec((Class<T[]>)stcType);
return new FieldCodec.ObjectArrayFieldCodec<>(field, codec);
}
} else {
Codec<T, E> codec = null;
if (stcType.isEnum() ||
stcType.equals(Boolean.class) ||
stcType.equals(Byte.class) ||
stcType.equals(Character.class) ||
stcType.equals(Short.class) ||
stcType.equals(Integer.class) ||
stcType.equals(Long.class) ||
stcType.equals(Float.class) ||
stcType.equals(Double.class) ||
stcType.equals(String.class)) {
codec = getNullSafeCodec(stcType);
} else if (Collection.class.isAssignableFrom(stcType)) {
final ReflectionUtils.TypeArgs typeArgs = ReflectionUtils.getTypeArgs(field, Collection.class);
if (typeArgs.size() == 1) {
final Class<Object> elemType = (Class<Object>) typeArgs.get(0);
final Codec<Object, E> elemCodec = makeNullSafeCodec(getNullUnsafeCodecImplStc(elemType));
final Codec<Collection<Object>, E> collCodec = collCodec(elemType, elemCodec);
codec = makeNullSafeCodec(dynamicCheck((Codec) collCodec, stcType));
}
} else if (Map.class.isAssignableFrom(stcType)) {
final ReflectionUtils.TypeArgs typeArgs = ReflectionUtils.getTypeArgs(field, Map.class);
final Class keyType = typeArgs.get(0);
final Class valType = typeArgs.get(1);
final Codec<Map<?, ?>, E> mapCodec = mapCodec(keyType, valType);
codec = makeNullSafeCodec(dynamicCheck((Codec) mapCodec, stcType));
}
if (codec == null) {
codec = makeNullSafeCodec(getNullUnsafeCodecImplStc(stcType));
}
return new FieldCodec.ObjectFieldCodec<>(field, codec);
}
}
}
public <T> Codec<T, E> dynamicCheck(Codec<T, E> codec, Class<T> stcType) {
if (Modifier.isFinal(stcType.getModifiers())) {
return codec;
} else {
return dynamicCodec(codec, stcType);
}
}
}
|
package com.tapad.sample;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import com.tapad.tapestry.R;
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_tabs);
FragmentTabHost host = (FragmentTabHost)findViewById(android.R.id.tabhost);
host.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
host.addTab(host.newTabSpec("demo")
.setIndicator("Demo"),
CarExampleFragment.class, null);
host.addTab(host.newTabSpec("test")
.setIndicator("Debug"),
DebugFragment.class, null);
}
}
|
package mb.statix.scopegraph.reference;
import java.io.Serializable;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import io.usethesource.capsule.Map;
import io.usethesource.capsule.Set;
import mb.nabl2.util.CapsuleUtil;
import mb.nabl2.util.ImmutableTuple2;
import mb.nabl2.util.Tuple2;
import mb.nabl2.util.collections.ConsList;
import mb.statix.scopegraph.IScopeGraph;
public abstract class ScopeGraph<S extends D, L, D> implements IScopeGraph<S, L, D> {
protected ScopeGraph() {
}
@Override public abstract Map<Tuple2<S, L>, ConsList<S>> getEdges();
@Override public Iterable<S> getEdges(S scope, L label) {
return getEdges().getOrDefault(ImmutableTuple2.of(scope, label), ConsList.nil());
}
@Override public abstract Map<Tuple2<S, L>, ConsList<D>> getData();
@Override public Iterable<D> getData(S scope, L relation) {
return getData().getOrDefault(ImmutableTuple2.of(scope, relation), ConsList.nil());
}
public static class Immutable<S extends D, L, D> extends ScopeGraph<S, L, D>
implements IScopeGraph.Immutable<S, L, D>, Serializable {
private static final long serialVersionUID = 42L;
private final Set.Immutable<L> edgeLabels;
private final Set.Immutable<L> dataLabels;
private final L noDataLabel;
private final Map.Immutable<Tuple2<S, L>, ConsList<S>> edges;
private final Map.Immutable<Tuple2<S, L>, ConsList<D>> data;
Immutable(Set.Immutable<L> edgeLabels, Set.Immutable<L> dataLabels, L noDataLabel,
Map.Immutable<Tuple2<S, L>, ConsList<S>> edges, Map.Immutable<Tuple2<S, L>, ConsList<D>> data) {
this.edgeLabels = edgeLabels;
this.dataLabels = dataLabels;
this.noDataLabel = noDataLabel;
this.edges = edges;
this.data = data;
}
@Override public Set.Immutable<L> getEdgeLabels() {
return edgeLabels;
}
@Override public Set.Immutable<L> getDataLabels() {
return dataLabels;
}
@Override public L getNoDataLabel() {
return noDataLabel;
}
@Override public Map<Tuple2<S, L>, ConsList<S>> getEdges() {
return edges;
}
@Override public Map<Tuple2<S, L>, ConsList<D>> getData() {
return data;
}
@Override public ScopeGraph.Immutable<S, L, D> addEdge(S sourceScope, L label, S targetScope) {
final ScopeGraph.Transient<S, L, D> scopeGraph = melt();
scopeGraph.addEdge(sourceScope, label, targetScope);
return scopeGraph.freeze();
}
@Override public ScopeGraph.Immutable<S, L, D> addDatum(S sourceScope, L relation, D datum) {
final ScopeGraph.Transient<S, L, D> scopeGraph = melt();
scopeGraph.addDatum(sourceScope, relation, datum);
return scopeGraph.freeze();
}
@Override public IScopeGraph.Immutable<S, L, D> addAll(IScopeGraph<S, L, D> other) {
final ScopeGraph.Transient<S, L, D> scopeGraph = melt();
scopeGraph.addAll(other);
return scopeGraph.freeze();
}
@Override public ScopeGraph.Transient<S, L, D> melt() {
return new ScopeGraph.Transient<>(edgeLabels, dataLabels, noDataLabel, edges.asTransient(),
data.asTransient());
}
@Override public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + edges.hashCode();
result = prime * result + data.hashCode();
return result;
}
@Override public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
@SuppressWarnings("unchecked") ScopeGraph.Immutable<S, L, D> other = (ScopeGraph.Immutable<S, L, D>) obj;
if(!edges.equals(other.edges))
return false;
if(!data.equals(other.data))
return false;
return true;
}
public static <S extends D, L, D> ScopeGraph.Immutable<S, L, D> of(Iterable<L> edgeLabels,
Iterable<L> dataLabels, L noDataLabel) {
return new ScopeGraph.Immutable<>(CapsuleUtil.toSet(edgeLabels), CapsuleUtil.toSet(dataLabels), noDataLabel,
Map.Immutable.of(), Map.Immutable.of());
}
@Override public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("{");
final AtomicBoolean first = new AtomicBoolean(true);
edges.forEach((key, targetScope) -> {
sb.append(first.getAndSet(false) ? " " : ", ");
sb.append(key._1());
sb.append(" -");
sb.append(key._2());
sb.append("-> ");
sb.append(targetScope);
});
data.forEach((key, datum) -> {
sb.append(first.getAndSet(false) ? " " : ", ");
sb.append(key._1());
sb.append(" -");
sb.append(key._2());
sb.append("-[ ");
sb.append(datum);
sb.append("] ");
});
sb.append(first.get() ? "}" : " }");
return sb.toString();
}
}
public static class Transient<S extends D, L, D> extends ScopeGraph<S, L, D>
implements IScopeGraph.Transient<S, L, D> {
private final Set.Immutable<L> edgeLabels;
private final Set.Immutable<L> dataLabels;
private final L noDataLabel;
private final Map.Transient<Tuple2<S, L>, ConsList<S>> edges;
private final Map.Transient<Tuple2<S, L>, ConsList<D>> data;
Transient(Set.Immutable<L> edgeLabels, Set.Immutable<L> dataLabels, L noDataLabel,
Map.Transient<Tuple2<S, L>, ConsList<S>> edges, Map.Transient<Tuple2<S, L>, ConsList<D>> data) {
this.edgeLabels = edgeLabels;
this.dataLabels = dataLabels;
this.noDataLabel = noDataLabel;
this.edges = edges;
this.data = data;
}
@Override public Set.Immutable<L> getEdgeLabels() {
return edgeLabels;
}
@Override public Set.Immutable<L> getDataLabels() {
return dataLabels;
}
@Override public L getNoDataLabel() {
return noDataLabel;
}
@Override public Map<Tuple2<S, L>, ConsList<S>> getEdges() {
return edges;
}
@Override public Map<Tuple2<S, L>, ConsList<D>> getData() {
return data;
}
@Override public boolean addEdge(S sourceScope, L label, S targetScope) {
final Tuple2<S, L> key = ImmutableTuple2.of(sourceScope, label);
final ConsList<S> scopes = edges.getOrDefault(key, ConsList.nil());
edges.__put(key, scopes.prepend(targetScope));
return true;
}
@Override public boolean addDatum(S scope, L relation, D datum) {
final Tuple2<S, L> key = ImmutableTuple2.of(scope, relation);
final ConsList<D> datums = data.getOrDefault(key, ConsList.nil());
data.__put(key, datums.prepend(datum));
return true;
}
@Override public boolean addAll(IScopeGraph<S, L, D> other) {
for(Entry<? extends Entry<S, L>, ? extends Iterable<S>> entry : other.getEdges().entrySet()) {
final Tuple2<S, L> key = Tuple2.of(entry.getKey());
final Iterable<S> otherScopes = entry.getValue();
final ConsList<S> scopes = edges.getOrDefault(key, ConsList.nil());
final ConsList<S> mergedScopes = scopes.prepend(ConsList.of(otherScopes));
edges.__put(Tuple2.of(key), mergedScopes);
}
for(Entry<? extends Entry<S, L>, ? extends Iterable<D>> entry : other.getData().entrySet()) {
final Tuple2<S, L> key = Tuple2.of(entry.getKey());
final Iterable<D> otherDatums = entry.getValue();
final ConsList<D> datums = data.getOrDefault(key, ConsList.nil());
final ConsList<D> mergedDatums = datums.prepend(ConsList.of(otherDatums));
data.__put(Tuple2.of(key), mergedDatums);
}
return true;
}
@Override public ScopeGraph.Immutable<S, L, D> freeze() {
return new ScopeGraph.Immutable<>(edgeLabels, dataLabels, noDataLabel, edges.freeze(), data.freeze());
}
public static <S extends D, L, D> ScopeGraph.Transient<S, L, D> of(Iterable<L> edgeLabels,
Iterable<L> dataLabels, L noDataLabel) {
return new ScopeGraph.Transient<>(CapsuleUtil.toSet(edgeLabels), CapsuleUtil.toSet(dataLabels), noDataLabel,
Map.Transient.of(), Map.Transient.of());
}
}
}
|
package jp.ne.smma.EventList;
import java.util.ArrayList;
import java.util.List;
import jp.ne.smma.R;
import jp.ne.smma.Ultis.ConnectionDetector;
import jp.ne.smma.Ultis.Constance;
import jp.ne.smma.Ultis.ImageLoader;
import jp.ne.smma.Ultis.JSONParser;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Place detail activity
*/
public class PlaceDetailActivity extends Activity implements OnClickListener {
private WebView imgMain;
private ImageView imageMap;
private TextView strTitle;
private TextView strAdd;
private TextView strPhone;
private TextView strUrl;
private TextView textContent;
private LinearLayout linearBannerPlaceDetail;
private Intent intent;
private int index = 0;
private String colorCode;
private String titleItem;
private String placeID;
private double latitude;
private double longitude;
private String content;
private String textTel;
private String textWeb;
private String text1;
private String text2;
private String urlImagePlace;
private WebView mWebViewDetail;
ProgressDialog pDialog;
public JSONArray mJsonArray;
Boolean isInternet = false;
ConnectionDetector checkInternet;
ImageLoader mImgLoader;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.place_detail_activity);
if (Constance.checkPortrait) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
// get data from xml
linearBannerPlaceDetail = (LinearLayout) findViewById(R.id.linearBannerPlaceDetail);
//imgMain = (ImageView) findViewById(R.id.imgContent);
strTitle = (TextView) findViewById(R.id.title);
strAdd = (TextView) findViewById(R.id.addPlace);
strPhone = (TextView) findViewById(R.id.telPlace);
strUrl = (TextView) findViewById(R.id.urlPlace);
imgMain = (WebView) findViewById(R.id.image_place_detail);
WebSettings settings = imgMain.getSettings();
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
imgMain.setBackgroundColor(Color.TRANSPARENT);
imgMain.getSettings().setUseWideViewPort(true);
// textContent = (TextView)findViewById(R.id.text_content);
mWebViewDetail = (WebView) findViewById(R.id.web_view_about);
imageMap = (ImageView) findViewById(R.id.imageMap);
imageMap.setVisibility(View.GONE);
mImgLoader = new ImageLoader(
PlaceDetailActivity.this.getApplicationContext());
// get data from
intent = getIntent();
titleItem = intent.getStringExtra(Constance.COLOR_TEXT_INDEX_ABOUT);
colorCode = intent.getStringExtra(Constance.COLOR_ITEM_ABOUT);
placeID = intent.getStringExtra(Constance.KEY_ABOUT_PLACE);
Log.e("kkkkkkkkkkkkk", placeID);
latitude = intent.getDoubleExtra(Constance.LATITUDE_ABOUT, 40.714728);
longitude = intent
.getDoubleExtra(Constance.LONGITUDE_ABOUT, -73.998672);
// set data
// strTitle.setText(titleItem);
// linearBannerPlaceDetail.setBackgroundColor(Color.parseColor(colorCode));
// strAdd.setText("982-0815");
// strPhone.setText("TEL : 022-307-5665");
// strUrl.setText("10-1 ");
pDialog = new ProgressDialog(PlaceDetailActivity.this);
new loadData().execute("");
strPhone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Starting a new async task
String phone = strPhone.getText().toString();
String phoneNumber = phone.replaceAll("TEL: ", "");
phoneNumber = phoneNumber.replace(" ", "");
Log.d("phone number", phoneNumber);
Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri
.parse("tel:" + phoneNumber));
startActivity(callIntent);
}
});
strUrl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Starting a new async task
String url = strUrl.getText().toString();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
public void showMap(View v) {
try {
String label = titleItem;
String uriBegin = "geo:" + latitude + "," + longitude;
String query = latitude + "," + longitude + "(" + label + ")";
String encodedQuery = Uri.encode(query);
String uriString = uriBegin + "?q=" + encodedQuery + "&z=16";
Uri uri = Uri.parse(uriString);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Device don't have Google Map application",
Toast.LENGTH_SHORT).show();
}
}
// public void clickCall(View v){
// String phone = strPhone.getText().toString();
// String phoneNumber = phone.replaceAll("TEL: ", "");
// phoneNumber = phoneNumber.replace(" ", "");
// Log.d("phone number", phoneNumber);
// Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri
// .parse("tel:" + phoneNumber));
// startActivity(callIntent);
// public void openURL(View v){
// String url = strUrl.getText().toString();
// Intent i = new Intent(Intent.ACTION_VIEW);
// i.setData(Uri.parse(url));
// startActivity(i);
public void backIcon(View v) {
finish();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (pDialog != null) {
pDialog.dismiss();
}
}
private class loadData extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
JSONParser jsonParser = new JSONParser();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("id", placeID));
params1.add(new BasicNameValuePair("name_event",
"get-company-place"));
JSONObject mJson = jsonParser
.getJSONFromUrl(Constance.url, params1);
if (mJson == null) {
// showAlertDialog(getActivity(), "", "TIME OUT", false);
// Log.e("aaaaaaa", "bbbbbbbb");
} else {
try {
// Toast.makeText(this, "success = 0",
// Toast.LENGTH_LONG).show();
mJsonArray = mJson.getJSONArray(Constance.KEY_DATA);
// mJsonArray = jsonData;
for (int i = 0; i < mJsonArray.length(); i++) {
JSONObject json = mJsonArray.getJSONObject(i);
// Log.e("json about",
// json.getString(Constance.KEY_ABOUT_COLOR)+
// json.getString(Constance.KEY_ABOUT_PATH_IMAGE)+json.getString(Constance.KEY_ABOUT_COMPANY_NAME));
urlImagePlace = json
.getString(Constance.PATH_IMG_PALCE_DETAIL);
content = json
.getString(Constance.CONTENT_PALCE_DETAIL);
textTel = json.getString(Constance.TEL_PALCE_DETAIL);
textWeb = json.getString(Constance.WEB_PALCE_DETAIL);
text1 = json.getString("c_add_text_1");
text2 = json.getString("c_add_text_2");
}
} catch (Exception e) {
e.printStackTrace();
// bCheck = true;
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (pDialog != null) {
pDialog.dismiss();
}
imageMap.setVisibility(View.VISIBLE);
runOnUiThread(new Runnable() {
public void run() {
// some code #3 (Write your code here to run in UI thread)
// imgMain.setBackgroundResource(R.drawable.image_main_index);
// textContent.setText(Html.fromHtml(content));
mWebViewDetail.setBackgroundColor(0x00000000);
mWebViewDetail.setLayerType(WebView.LAYER_TYPE_SOFTWARE,
null);
mWebViewDetail.loadDataWithBaseURL(null, content,
"text/html", "UTF-8", null);
String img = "<img src=" + urlImagePlace + " " + "width="+ "100%" + " " + "style=" + "margin: 0px 0px" + ">" ;
imgMain.loadDataWithBaseURL(null,img ,
"text/html", "UTF-8", null);
strTitle.setText(titleItem);
linearBannerPlaceDetail.setBackgroundColor(Color
.parseColor(colorCode));
strAdd.setText(text1);
strPhone.setText("TEL:" + textTel);
strUrl.setText(textWeb);
}
});
}
@Override
protected void onPreExecute() {
pDialog.setMessage("loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
}
}
|
package org.openhab.binding.zwave.internal.converter;
import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.State;
import org.openhab.binding.zwave.handler.ZWaveThingHandler.ZWaveThingChannel;
import org.openhab.binding.zwave.internal.protocol.SerialMessage;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;;
/**
* ZWaveCommandClassConverter class. Base class for all converters that convert between Z-Wave command classes and
* openHAB channels.
*
* @author Chris Jackson
*/
public abstract class ZWaveCommandClassConverter {
private static final Map<CommandClass, Class<? extends ZWaveCommandClassConverter>> converterMap;
static {
Map<CommandClass, Class<? extends ZWaveCommandClassConverter>> temp = new HashMap<CommandClass, Class<? extends ZWaveCommandClassConverter>>();
temp.put(CommandClass.ALARM, ZWaveAlarmConverter.class);
temp.put(CommandClass.BASIC, ZWaveBasicConverter.class);
temp.put(CommandClass.BATTERY, ZWaveBatteryConverter.class);
temp.put(CommandClass.COLOR, ZWaveColorConverter.class);
temp.put(CommandClass.CONFIGURATION, ZWaveConfigurationConverter.class);
temp.put(CommandClass.METER, ZWaveMeterConverter.class);
temp.put(CommandClass.SENSOR_ALARM, ZWaveAlarmSensorConverter.class);
temp.put(CommandClass.SENSOR_BINARY, ZWaveBinarySensorConverter.class);
temp.put(CommandClass.SENSOR_MULTILEVEL, ZWaveMultiLevelSensorConverter.class);
temp.put(CommandClass.SWITCH_BINARY, ZWaveBinarySwitchConverter.class);
temp.put(CommandClass.SWITCH_MULTILEVEL, ZWaveMultiLevelSwitchConverter.class);
temp.put(CommandClass.THERMOSTAT_FAN_MODE, ZWaveThermostatFanModeConverter.class);
temp.put(CommandClass.THERMOSTAT_FAN_STATE, ZWaveThermostatFanStateConverter.class);
temp.put(CommandClass.THERMOSTAT_MODE, ZWaveThermostatModeConverter.class);
temp.put(CommandClass.THERMOSTAT_OPERATING_STATE, ZWaveThermostatOperatingStateConverter.class);
temp.put(CommandClass.THERMOSTAT_SETPOINT, ZWaveThermostatSetpointConverter.class);
temp.put(CommandClass.CENTRAL_SCENE, ZWaveCentralSceneConverter.class);
converterMap = Collections.unmodifiableMap(temp);
}
private static Logger logger = LoggerFactory.getLogger(ZWaveCommandClassConverter.class);
private static BigDecimal ONE_POINT_EIGHT = new BigDecimal("1.8");
private static BigDecimal THIRTY_TWO = new BigDecimal("32");
/**
* Constructor. Creates a new instance of the {@link ZWaveCommandClassConverter} class.
*
*/
public ZWaveCommandClassConverter() {
super();
}
/**
* Execute refresh method. This method is called every time a binding item is refreshed and the corresponding node
* should be sent a message.
*
* @param node the {@link ZWaveNode} that is bound to the item.
* @param endpointId the endpoint id to send the message.
*/
public List<SerialMessage> executeRefresh(ZWaveThingChannel channel, ZWaveNode node) {
return new ArrayList<SerialMessage>();
}
/**
* Handles an incoming {@link ZWaveCommandClassValueEvent}. Implement this message in derived classes to convert the
* value and post an update on the openHAB bus.
*
* @param event the received {@link ZWaveCommandClassValueEvent}.
* @return
*/
public State handleEvent(ZWaveThingChannel channel, ZWaveCommandClassValueEvent event) {
return null;
}
/**
* Receives a command from openHAB and translates it to an operation on the Z-Wave network.
*
* @param command the received command
* @param node the {@link ZWaveNode} to send the command to
* @param commandClass the {@link ZWaveCommandClass} to send the command to.
* @param endpointId the endpoint ID to send the command to.
*/
public List<SerialMessage> receiveCommand(ZWaveThingChannel channel, ZWaveNode node, Command command) {
return new ArrayList<SerialMessage>();
}
public int getRefreshInterval() {
return 0;
}
public static ZWaveCommandClassConverter getConverter(CommandClass commandClass) {
Constructor<? extends ZWaveCommandClassConverter> constructor;
try {
if (converterMap.get(commandClass) == null) {
logger.warn("CommandClass converter {} is not implemented!", commandClass.getLabel());
return null;
}
constructor = converterMap.get(commandClass).getConstructor();
return constructor.newInstance();
} catch (Exception e) {
logger.error("Error getting converter {}", e.getMessage());
return null;
}
}
// Common Conversions...
/**
* Convert temperature scales
*
* @param fromScale scale to convert FROM (0=C, 1=F)
* @param toScale scale to convert TO (0=C, 1=F)
* @param val value to convert
* @return converted value
*/
protected BigDecimal convertTemperature(int fromScale, int toScale, BigDecimal val) {
BigDecimal valConverted;
// For temperature, there are only two scales, so we simplify the conversion
if (fromScale == 0 && toScale == 1) {
// Scale is celsius, convert to fahrenheit
valConverted = val.multiply(ONE_POINT_EIGHT).add(THIRTY_TWO).movePointRight(1).setScale(1,
RoundingMode.HALF_DOWN);
} else if (fromScale == 1 && toScale == 0) {
// Scale is fahrenheit, convert to celsius
valConverted = val.subtract(THIRTY_TWO).divide(ONE_POINT_EIGHT, MathContext.DECIMAL32).setScale(1,
RoundingMode.HALF_DOWN);
} else {
valConverted = val;
}
logger.debug("Converted temperature from {}{} to {}{}", val, fromScale == 0 ? "C" : "F", valConverted,
toScale == 0 ? "C" : "F");
return valConverted;
}
}
|
package org.apereo.cas.configuration.metadata;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.PrettyPrinter;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.BooleanLiteralExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.LiteralStringValueExpr;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.google.common.base.Predicate;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.configuration.model.core.authentication.PasswordPolicyProperties;
import org.apereo.cas.configuration.model.core.authentication.PrincipalTransformationProperties;
import org.apereo.cas.configuration.model.support.ldap.AbstractLdapProperties;
import org.apereo.cas.configuration.model.support.ldap.LdapSearchEntryHandlersProperties;
import org.apereo.cas.configuration.support.RequiredProperty;
import org.apereo.cas.configuration.support.RequiresModule;
import org.apereo.services.persondir.support.QueryType;
import org.apereo.services.persondir.util.CaseCanonicalizationMode;
import org.jooq.lambda.Unchecked;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeElementsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.boot.bind.RelaxedNames;
import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty;
import org.springframework.boot.configurationmetadata.ValueHint;
import org.springframework.core.io.Resource;
import org.springframework.util.ReflectionUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* This is {@link ConfigurationMetadataGenerator}.
* This class is invoked by the build during the finalization of the compile phase.
* Its job is to scan the generated configuration metadata and produce metadata
* for settings that the build process is unable to parse. Specifically,
* this includes fields that are of collection type (indexed) where the inner type is an
* externalized class.
* <p>
* Example:
* {@code
* private List<SomeClassProperties> list = new ArrayList<>()
* }
* The generator additionally adds hints to the metadata generated to indicate
* required properties and modules.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
@Slf4j
public class ConfigurationMetadataGenerator {
private static final Pattern PATTERN_GENERICS = Pattern.compile(".+\\<(.+)\\>");
private static final Pattern NESTED_TYPE_PATTERN = Pattern.compile("java\\.util\\.\\w+<(org\\.apereo\\.cas\\..+)>");
private final String buildDir;
private final String sourcePath;
private final Map<String, Class> cachedPropertiesClasses = new HashMap<>();
public ConfigurationMetadataGenerator(final String buildDir, final String sourcePath) {
this.buildDir = buildDir;
this.sourcePath = sourcePath;
}
/**
* Main.
*
* @param args the args
* @throws Exception the exception
*/
public static void main(final String[] args) throws Exception {
final String buildDir = args[0];
final String projectDir = args[1];
new ConfigurationMetadataGenerator(buildDir, projectDir).execute();
}
/**
* Execute.
*
* @throws Exception the exception
*/
public void execute() throws Exception {
final File jsonFile = new File(buildDir, "classes/java/main/META-INF/spring-configuration-metadata.json");
final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final TypeReference<Map<String, Set<ConfigurationMetadataProperty>>> values = new TypeReference<Map<String, Set<ConfigurationMetadataProperty>>>() {
};
final Map<String, Set> jsonMap = mapper.readValue(jsonFile, values);
final Set<ConfigurationMetadataProperty> properties = jsonMap.get("properties");
final Set<ConfigurationMetadataProperty> groups = jsonMap.get("groups");
final Set<ConfigurationMetadataProperty> collectedProps = new HashSet<>();
final Set<ConfigurationMetadataProperty> collectedGroups = new HashSet<>();
properties.stream()
.filter(p -> NESTED_TYPE_PATTERN.matcher(p.getType()).matches())
.forEach(Unchecked.consumer(p -> {
final Matcher matcher = NESTED_TYPE_PATTERN.matcher(p.getType());
final boolean indexBrackets = matcher.matches();
final String typeName = matcher.group(1);
final String typePath = buildTypeSourcePath(typeName);
parseCompilationUnit(collectedProps, collectedGroups, p, typePath, typeName, indexBrackets);
}));
properties.addAll(collectedProps);
groups.addAll(collectedGroups);
final Set<ConfigurationMetadataHint> hints = processHints(properties, groups);
jsonMap.put("properties", properties);
jsonMap.put("groups", groups);
jsonMap.put("hints", hints);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
final PrettyPrinter pp = new DefaultPrettyPrinter();
mapper.writer(pp).writeValue(jsonFile, jsonMap);
}
private String buildTypeSourcePath(final String type) {
final String newName = type.replace(".", File.separator);
return sourcePath + "/src/main/java/" + newName + ".java";
}
@SneakyThrows
private void parseCompilationUnit(final Set<ConfigurationMetadataProperty> collectedProps,
final Set<ConfigurationMetadataProperty> collectedGroups,
final ConfigurationMetadataProperty p,
final String typePath,
final String typeName,
final boolean indexNameWithBrackets) {
try (InputStream is = new FileInputStream(typePath)) {
final CompilationUnit cu = JavaParser.parse(is);
new FieldVisitor(collectedProps, collectedGroups, indexNameWithBrackets, typeName).visit(cu, p);
if (cu.getTypes().size() > 0) {
final ClassOrInterfaceDeclaration decl = ClassOrInterfaceDeclaration.class.cast(cu.getType(0));
for (int i = 0; i < decl.getExtendedTypes().size(); i++) {
final ClassOrInterfaceType parentType = decl.getExtendedTypes().get(i);
final Class parentClazz = locatePropertiesClassForType(parentType);
final String parentTypePath = buildTypeSourcePath(parentClazz.getName());
parseCompilationUnit(collectedProps, collectedGroups, p,
parentTypePath, parentClazz.getName(), indexNameWithBrackets);
}
}
}
}
private class FieldVisitor extends VoidVisitorAdapter<ConfigurationMetadataProperty> {
private final Set<ConfigurationMetadataProperty> properties;
private final Set<ConfigurationMetadataProperty> groups;
private final String parentClass;
private final boolean indexNameWithBrackets;
FieldVisitor(final Set<ConfigurationMetadataProperty> properties, final Set<ConfigurationMetadataProperty> groups,
final boolean indexNameWithBrackets, final String clazz) {
this.properties = properties;
this.groups = groups;
this.indexNameWithBrackets = indexNameWithBrackets;
this.parentClass = clazz;
}
@Override
public void visit(final FieldDeclaration field, final ConfigurationMetadataProperty property) {
if (field.getVariables().isEmpty()) {
throw new IllegalArgumentException("Field " + field + " has no variable definitions");
}
final VariableDeclarator var = field.getVariable(0);
if (field.getModifiers().contains(Modifier.STATIC)) {
LOGGER.debug("Field [{}] is static and will be ignored for metadata generation", var.getNameAsString());
return;
}
if (field.getJavadoc().isPresent()) {
final ConfigurationMetadataProperty prop = createConfigurationProperty(field, property);
processNestedClassOrInterfaceTypeIfNeeded(field, prop);
} else {
LOGGER.error("Field " + field + " has no Javadoc defined");
}
}
private ConfigurationMetadataProperty createConfigurationProperty(final FieldDeclaration n,
final ConfigurationMetadataProperty arg) {
final VariableDeclarator variable = n.getVariables().get(0);
final String name = StreamSupport.stream(RelaxedNames.forCamelCase(variable.getNameAsString()).spliterator(), false)
.map(Object::toString)
.findFirst()
.orElse(variable.getNameAsString());
final String indexedGroup = arg.getName().concat(indexNameWithBrackets ? "[]" : StringUtils.EMPTY);
final String indexedName = indexedGroup.concat(".").concat(name);
final ConfigurationMetadataProperty prop = new ConfigurationMetadataProperty();
final String description = n.getJavadoc().get().getDescription().toText();
prop.setDescription(description);
prop.setShortDescription(StringUtils.substringBefore(description, "."));
prop.setName(indexedName);
prop.setId(indexedName);
final String elementType = n.getElementType().asString();
if (elementType.equals(String.class.getSimpleName())
|| elementType.equals(Integer.class.getSimpleName())
|| elementType.equals(Long.class.getSimpleName())
|| elementType.equals(Double.class.getSimpleName())
|| elementType.equals(Float.class.getSimpleName())) {
prop.setType("java.lang." + elementType);
} else {
prop.setType(elementType);
}
if (variable.getInitializer().isPresent()) {
final Expression exp = variable.getInitializer().get();
if (exp instanceof LiteralStringValueExpr) {
prop.setDefaultValue(((LiteralStringValueExpr) exp).getValue());
} else if (exp instanceof BooleanLiteralExpr) {
prop.setDefaultValue(((BooleanLiteralExpr) exp).getValue());
}
}
properties.add(prop);
final ConfigurationMetadataProperty grp = new ConfigurationMetadataProperty();
grp.setId(indexedGroup);
grp.setName(indexedGroup);
grp.setType(this.parentClass);
groups.add(grp);
return prop;
}
private void processNestedClassOrInterfaceTypeIfNeeded(final FieldDeclaration n, final ConfigurationMetadataProperty prop) {
if (n.getElementType() instanceof ClassOrInterfaceType) {
final ClassOrInterfaceType type = (ClassOrInterfaceType) n.getElementType();
if (!shouldTypeBeExcluded(type)) {
final Class clz = locatePropertiesClassForType(type);
if (clz != null && !clz.isMemberClass()) {
final String typePath = buildTypeSourcePath(clz.getName());
parseCompilationUnit(properties, groups, prop, typePath, clz.getName(), false);
}
}
}
}
private boolean shouldTypeBeExcluded(final ClassOrInterfaceType type) {
return type.getNameAsString().matches(
String.class.getSimpleName() + "|"
+ Integer.class.getSimpleName() + "|"
+ Double.class.getSimpleName() + "|"
+ Long.class.getSimpleName() + "|"
+ Float.class.getSimpleName() + "|"
+ Boolean.class.getSimpleName() + "|"
+ PrincipalTransformationProperties.CaseConversion.class.getSimpleName() + "|"
+ QueryType.class.getSimpleName() + "|"
+ AbstractLdapProperties.LdapType.class.getSimpleName() + "|"
+ CaseCanonicalizationMode.class.getSimpleName() + "|"
+ PasswordPolicyProperties.PasswordPolicyHandlingOptions.class.getSimpleName() + "|"
+ LdapSearchEntryHandlersProperties.SearchEntryHandlerTypes.class.getSimpleName() + "|"
+ Map.class.getSimpleName() + "|"
+ Resource.class.getSimpleName() + "|"
+ List.class.getSimpleName() + "|"
+ Set.class.getSimpleName());
}
}
private Class locatePropertiesClassForType(final ClassOrInterfaceType type) {
if (cachedPropertiesClasses.containsKey(type.getNameAsString())) {
return cachedPropertiesClasses.get(type.getNameAsString());
}
final Predicate<String> filterInputs = s -> s.contains(type.getNameAsString());
final Predicate<String> filterResults = s -> s.endsWith(type.getNameAsString());
final String packageName = ConfigurationMetadataGenerator.class.getPackage().getName();
final Reflections reflections =
new Reflections(new ConfigurationBuilder()
.filterInputsBy(filterInputs)
.setUrls(ClasspathHelper.forPackage(packageName))
.setScanners(new TypeElementsScanner()
.includeFields(false)
.includeMethods(false)
.includeAnnotations(false)
.filterResultsBy(filterResults),
new SubTypesScanner(false)));
final Class clz = reflections.getSubTypesOf(Serializable.class).stream()
.filter(c -> c.getSimpleName().equalsIgnoreCase(type.getNameAsString()))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Cant locate class for " + type.getNameAsString()));
cachedPropertiesClasses.put(type.getNameAsString(), clz);
return clz;
}
private Set<ConfigurationMetadataHint> processHints(final Collection<ConfigurationMetadataProperty> props,
final Collection<ConfigurationMetadataProperty> groups) {
final Set<ConfigurationMetadataHint> hints = new LinkedHashSet<>();
for (final ConfigurationMetadataProperty entry : props) {
try {
final String propName = StringUtils.substringAfterLast(entry.getName(), ".");
final String groupName = StringUtils.substringBeforeLast(entry.getName(), ".");
final ConfigurationMetadataProperty grp = groups
.stream()
.filter(g -> g.getName().equalsIgnoreCase(groupName))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Cant locate group " + groupName));
final Matcher matcher = PATTERN_GENERICS.matcher(grp.getType());
final String className = matcher.find() ? matcher.group(1) : grp.getType();
final Class clazz = ClassUtils.getClass(className);
final ConfigurationMetadataHint hint = new ConfigurationMetadataHint();
hint.setName(entry.getName());
if (clazz.isAnnotationPresent(RequiresModule.class)) {
final RequiresModule annotation = Arrays.stream(clazz.getAnnotations())
.filter(a -> a.annotationType().equals(RequiresModule.class))
.findFirst()
.map(RequiresModule.class::cast)
.get();
final ValueHint valueHint = new ValueHint();
valueHint.setValue(Stream.of(RequiresModule.class.getName(), annotation.automated()).collect(Collectors.toList()));
valueHint.setDescription(annotation.name());
hint.getValues().add(valueHint);
}
final boolean foundRequiredProperty = StreamSupport.stream(RelaxedNames.forCamelCase(propName).spliterator(), false)
.map(n -> ReflectionUtils.findField(clazz, n))
.anyMatch(f -> f != null && f.isAnnotationPresent(RequiredProperty.class));
if (foundRequiredProperty) {
final ValueHint valueHint = new ValueHint();
valueHint.setValue(RequiredProperty.class.getName());
hint.getValues().add(valueHint);
}
if (!hint.getValues().isEmpty()) {
hints.add(hint);
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
return hints;
}
}
|
package fr.openwide.core.basicapp.web.application;
import org.apache.wicket.Application;
import org.apache.wicket.Page;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.WebPage;
import org.springframework.beans.factory.annotation.Autowired;
import fr.openwide.core.basicapp.web.application.administration.page.AdministrationUserDescriptionPage;
import fr.openwide.core.basicapp.web.application.administration.page.AdministrationUserGroupDescriptionPage;
import fr.openwide.core.basicapp.web.application.administration.page.AdministrationUserGroupPortfolioPage;
import fr.openwide.core.basicapp.web.application.administration.page.AdministrationUserPortfolioPage;
import fr.openwide.core.basicapp.web.application.common.template.MainTemplate;
import fr.openwide.core.basicapp.web.application.console.notification.demo.page.ConsoleNotificationDemoIndexPage;
import fr.openwide.core.basicapp.web.application.navigation.page.HomePage;
import fr.openwide.core.basicapp.web.application.navigation.page.SignInPage;
import fr.openwide.core.spring.config.CoreConfigurer;
import fr.openwide.core.wicket.more.application.CoreWicketAuthenticatedApplication;
import fr.openwide.core.wicket.more.console.common.model.ConsoleMenuSection;
import fr.openwide.core.wicket.more.console.template.ConsoleConfiguration;
import fr.openwide.core.wicket.more.link.descriptor.parameter.CommonParameters;
import fr.openwide.core.wicket.more.markup.html.pages.monitoring.DatabaseMonitoringPage;
import fr.openwide.core.wicket.more.security.page.LoginFailurePage;
import fr.openwide.core.wicket.more.security.page.LoginSuccessPage;
public class BasicApplicationApplication extends CoreWicketAuthenticatedApplication {
public static final String NAME = "BasicApplicationApplication";
@Autowired
private CoreConfigurer configurer;
public static BasicApplicationApplication get() {
final Application application = Application.get();
if (application instanceof BasicApplicationApplication) {
return (BasicApplicationApplication) application;
}
throw new WicketRuntimeException("There is no BasicApplicationApplication attached to current thread " +
Thread.currentThread().getName());
}
@Override
public void init() {
super.init();
// if (!configurer.isConfigurationTypeDevelopment()) {
// preloadStyleSheets(
// ConsoleLessCssResourceReference.get(),
// NotificationLessCssResourceReference.get(),
// SignInLessCssResourceReference.get(),
// StylesLessCssResourceReference.get()
}
@Override
protected void mountApplicationPages() {
// Sign in
mountPage("/login/", getSignInPageClass());
mountPage("/login/failure/", LoginFailurePage.class);
mountPage("/login/success/", LoginSuccessPage.class);
// Administration
mountPage("/administration/user/", AdministrationUserPortfolioPage.class);
mountParameterizedPage("/administration/user/${" + CommonParameters.ID + "}/",
AdministrationUserDescriptionPage.class);
mountPage("/administration/user-group/", AdministrationUserGroupPortfolioPage.class);
mountParameterizedPage("/administration/user-group/${" + CommonParameters.ID + "}/",
AdministrationUserGroupDescriptionPage.class);
// Console
ConsoleConfiguration consoleConfiguration = ConsoleConfiguration.build("console");
consoleConfiguration.mountPages(this);
ConsoleMenuSection notificationMenuSection = new ConsoleMenuSection("notificationsMenuSection", "console.notifications",
"notifications", ConsoleNotificationDemoIndexPage.class);
consoleConfiguration.addMenuSection(notificationMenuSection);
mountPage("/console/notifications/", ConsoleNotificationDemoIndexPage.class);
// Monitoring
mountPage("/monitoring/db-access/", DatabaseMonitoringPage.class);
}
@Override
protected void mountApplicationResources() {
mountStaticResourceDirectory("/application", MainTemplate.class);
}
@Override
protected Class<? extends AuthenticatedWebSession> getWebSessionClass() {
return BasicApplicationSession.class;
}
@Override
public Class<? extends Page> getHomePage() {
return HomePage.class;
}
@Override
public Class<? extends WebPage> getSignInPageClass() {
return SignInPage.class;
}
}
|
package org.openhab.binding.tcp.protocol.internal;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.tcp.protocol.ProtocolBindingProvider;
import org.openhab.core.binding.BindingConfig;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.core.types.TypeParser;
import org.openhab.model.item.binding.AbstractGenericBindingProvider;
import org.openhab.model.item.binding.BindingConfigParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* The "standard" TCP and UDP network bindings follow the same configuration format:
*
* tcp=">[ON:192.168.0.1:3000:some text], >[OFF:192.168.0.1:3000:some other command]"
* tcp="<[*:192.168.0.1:3000:some text]" - for String Items
*
* direction[openhab command:hostname:port number:protocol command]
*
* For String Items, the "protocol command" is quite irrelevant as the Item will be updated with the incoming string
* openhab commands can be repeated more than once for a given Item, e.g. receiving ON command could trigger to pieces
* of data to be sent to for example to different host:port combinations,...
*
* @author Karel Goderis
* @since 1.1.0
*/
abstract class ProtocolGenericBindingProvider extends AbstractGenericBindingProvider implements ProtocolBindingProvider {
static final Logger logger =
LoggerFactory.getLogger(ProtocolGenericBindingProvider.class);
/** {@link Pattern} which matches a binding configuration part */
private static final Pattern BASE_CONFIG_PATTERN = Pattern.compile("([<|>|\\*]\\[.*?\\])*");
private static final Pattern ACTION_CONFIG_PATTERN = Pattern.compile("(<|>|\\*)\\[(.*?):(.*?):(.*?):\'?(.*?)\'?\\]");
private static final Pattern STATUS_CONFIG_PATTERN = Pattern.compile("(<|>|\\*)\\[(.*):(.*)\\]");
static int counter = 0;
@Override
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException {
// All Item Types are accepted by ProtocolGenericBindingProvider
}
/**
* {@inheritDoc}
*/
@Override
public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException {
super.processBindingConfiguration(context, item, bindingConfig);
if (bindingConfig != null) {
parseAndAddBindingConfig(item, bindingConfig);
} else {
logger.warn(getBindingType()+" bindingConfig is NULL (item=" + item
+ ") -> processing bindingConfig aborted!");
}
}
private void parseAndAddBindingConfig(Item item, String bindingConfig) throws BindingConfigParseException {
ProtocolBindingConfig newConfig = new ProtocolBindingConfig();
Matcher matcher = BASE_CONFIG_PATTERN.matcher(bindingConfig);
if (!matcher.matches()) {
throw new BindingConfigParseException("bindingConfig '" + bindingConfig + "' doesn't contain a valid binding configuration");
}
matcher.reset();
while (matcher.find()) {
String bindingConfigPart = matcher.group(1);
if (StringUtils.isNotBlank(bindingConfigPart)) {
parseBindingConfig(newConfig,item, bindingConfigPart);
addBindingConfig(item, newConfig);
}
}
}
/**
* Parses the configuration string and update the provided config
*
* @param config - the Configuration that needs to be updated with the parsing results
* @param item - the Item that this configuration is intented for
* @param bindingConfig - the configuration string that will be parsed
* @throws BindingConfigParseException
*/
private void parseBindingConfig(ProtocolBindingConfig config,Item item,
String bindingConfig) throws BindingConfigParseException {
String direction = null;
Direction directionType = null;
String commandAsString = null;
String host = null;
String port = null;
String protocolCommand = null;
if(bindingConfig != null){
Matcher actionMatcher = ACTION_CONFIG_PATTERN.matcher(bindingConfig);
Matcher statusMatcher = STATUS_CONFIG_PATTERN.matcher(bindingConfig);
if ((!actionMatcher.matches() && !statusMatcher.matches())) {
throw new BindingConfigParseException(getBindingType()+
" binding configuration must consist of three [config="+statusMatcher+"] or five parts [config="
+ actionMatcher + "]");
} else {
if(actionMatcher.matches()) {
direction = actionMatcher.group(1);
directionType = Direction.BIDIRECTIONAL;
commandAsString = actionMatcher.group(2);
host = actionMatcher.group(3);
port = actionMatcher.group(4);
protocolCommand = actionMatcher.group(5);
} else if (statusMatcher.matches()) {
direction = statusMatcher.group(1);
directionType = Direction.BIDIRECTIONAL;
commandAsString = null;
host = statusMatcher.group(2);
port = statusMatcher.group(3);
}
if (direction.equals(">")){
directionType = Direction.OUT;
} else if (direction.equals("<")){
directionType = Direction.IN;
} else if (direction.equals("*")){
directionType = Direction.BIDIRECTIONAL;
}
ProtocolBindingConfigElement newElement = new ProtocolBindingConfigElement(host,Integer.parseInt(port),directionType,protocolCommand,item.getAcceptedDataTypes());
Command command = null;
if(commandAsString == null) {
// for those configuration strings that are not really linked to a openHAB command we
// create a dummy Command to be able to store the configuration information
// I have choosen to do that with NumberItems
NumberItem dummy = new NumberItem(Integer.toString(counter));
command = createCommandFromString(dummy,Integer.toString(counter));
counter++;
config.put(command, newElement);
} else {
command = createCommandFromString(item, commandAsString);
config.put(command, newElement);
}
config.put(command, newElement);
}
}
else
{
return;
}
}
/**
* Creates a {@link Command} out of the given <code>commandAsString</code>
* incorporating the {@link TypeParser}.
*
* @param item
* @param commandAsString
*
* @return an appropriate Command (see {@link TypeParser} for more
* information
*
* @throws BindingConfigParseException if the {@link TypeParser} couldn't
* create a command appropriately
*
* @see {@link TypeParser}
*/
private Command createCommandFromString(Item item, String commandAsString) throws BindingConfigParseException {
Command command = TypeParser.parseCommand(
item.getAcceptedCommandTypes(), commandAsString);
if (command == null) {
throw new BindingConfigParseException("couldn't create Command from '" + commandAsString + "' ");
}
return command;
}
/**
* {@inheritDoc}
*/
public String getHost(String itemName, Command command) {
ProtocolBindingConfig config = (ProtocolBindingConfig) bindingConfigs.get(itemName);
return config != null && config.get(command) != null ? config.get(command).getHost() : null;
}
/**
* {@inheritDoc}
*/
public int getPort(String itemName, Command command) {
ProtocolBindingConfig config = (ProtocolBindingConfig) bindingConfigs.get(itemName);
return config != null && config.get(command) != null ? config.get(command).getPort() : null;
}
/**
* {@inheritDoc}
*/
public Direction getDirection(String itemName, Command command) {
ProtocolBindingConfig config = (ProtocolBindingConfig) bindingConfigs.get(itemName);
return config != null && config.get(command) != null ? config.get(command).getDirection() : null;
}
/**
* {@inheritDoc}
*/
public String getProtocolCommand(String itemName, Command command) {
ProtocolBindingConfig config = (ProtocolBindingConfig) bindingConfigs.get(itemName);
return config != null && config.get(command) != null ? config.get(command).getNetworkCommand() : null;
}
/**
* {@inheritDoc}
*/
public List<Command> getAllCommands(String itemName){
List<Command> commands = new ArrayList<Command>();
ProtocolBindingConfig aConfig = (ProtocolBindingConfig) bindingConfigs.get(itemName);
for(Command aCommand : aConfig.keySet()) {
commands.add(aCommand);
}
return commands;
}
/**
* This is an internal data structure to map commands to
* {@link ProtocolBindingConfigElement }. There will be map like
* <code>ON->ProtocolBindingConfigElement</code>
*/
static class ProtocolBindingConfig extends HashMap<Command, ProtocolBindingConfigElement> implements BindingConfig {
private static final long serialVersionUID = 6363085986521089771L;
}
static class ProtocolBindingConfigElement implements BindingConfig {
final private String host;
final private int port;
final private Direction direction;
final private String networkCommand;
final private List<Class<? extends State>> acceptedTypes;
public ProtocolBindingConfigElement(String host, int port, Direction direction, String networkCommand,List<Class<? extends State>> acceptedTypes) {
this.host = host;
this.port = port;
this.direction = direction;
this.networkCommand = networkCommand;
this.acceptedTypes = acceptedTypes;
}
@Override
public String toString() {
return "ProtocolBindingConfigElement [Direction=" + direction
+ ", host=" + host + ", port=" + port
+ ", cmd=" + networkCommand + "]";
}
/**
* @return the networkCommand
*/
public String getNetworkCommand() {
return networkCommand;
}
/**
* @return the direction
*/
public Direction getDirection() {
return direction;
}
/**
* @return the host
*/
public String getHost() {
return host;
}
/**
* @return the port
*/
public int getPort() {
return port;
}
/**
* @return the list of accepted DataTypes for the Item linked to this Binding Config Element
*/
public List<Class<? extends State>> getAcceptedTypes() {
return acceptedTypes;
}
}
@Override
public InetSocketAddress getInetSocketAddress(String itemName, Command command) {
ProtocolBindingConfig config = (ProtocolBindingConfig) bindingConfigs.get(itemName);
ProtocolBindingConfigElement element = config.get(command);
InetSocketAddress socketAddress = new InetSocketAddress(element.getHost(),element.getPort());
return socketAddress;
}
@Override
public List<InetSocketAddress> getInetSocketAddresses(String itemName){
//logger.debug("getInetSocketAddresses for "+itemName);
List<InetSocketAddress> theList = new ArrayList<InetSocketAddress>();
ProtocolBindingConfig config = (ProtocolBindingConfig) bindingConfigs.get(itemName);
if(config != null ){
for(Command command : config.keySet()) {
//logger.debug("found command "+command.toString()+" for this item, will try to create InetAddress "+config.get(command).getHost()+":"+config.get(command).getPort());
InetSocketAddress anAddress = null;
try {
anAddress = new InetSocketAddress(InetAddress.getByName(config.get(command).getHost()),config.get(command).getPort());
} catch (UnknownHostException e) {
logger.warn("Could not resolve the hostname {} for item {}",config.get(command).getHost(),itemName);
}
theList.add(anAddress);
}
}
return theList;
}
public Collection<String> getItemNames(String host, int port) {
List<String> items = new ArrayList<String>();
for (String itemName : bindingConfigs.keySet()) {
ProtocolBindingConfig aConfig = (ProtocolBindingConfig) bindingConfigs.get(itemName);
for(Command aCommand : aConfig.keySet()) {
ProtocolBindingConfigElement anElement = (ProtocolBindingConfigElement) aConfig.get(aCommand);
if(anElement.getHost().equals(host) && anElement.getPort()==port) {
if(!items.contains(itemName)) {
items.add(itemName);
}
}
}
}
return items;
}
@Override
public List<String> getItemNames(String protocolCommand) {
List<String> itemNames = new ArrayList<String>();
for (String itemName : bindingConfigs.keySet()) {
ProtocolBindingConfig aConfig = (ProtocolBindingConfig) bindingConfigs.get(itemName);
for(Command aCommand : aConfig.keySet()) {
ProtocolBindingConfigElement anElement = (ProtocolBindingConfigElement) aConfig.get(aCommand);
if(anElement.networkCommand.equals(protocolCommand)) {
itemNames.add(itemName);
}
}
}
return itemNames;
}
public List<Command> getAllCommands(String itemName, String protocolCommand){
List<Command> commands = new ArrayList<Command>();
ProtocolBindingConfig aConfig = (ProtocolBindingConfig) bindingConfigs.get(itemName);
for(Command aCommand : aConfig.keySet()) {
ProtocolBindingConfigElement anElement = (ProtocolBindingConfigElement) aConfig.get(aCommand);
if(anElement.networkCommand.equals(protocolCommand)) {
commands.add(aCommand);
}
}
return commands;
}
public List<Class<? extends State>> getAcceptedDataTypes(String itemName, Command command) {
if(itemName != null) {
ProtocolBindingConfig config = (ProtocolBindingConfig) bindingConfigs.get(itemName);
if(config != null) {
ProtocolBindingConfigElement element = config.get(command);
if(element != null) {
return element.getAcceptedTypes();
}
}
}
return null;
}
}
|
package org.eclipse.smarthome.core.thing.internal.type;
import java.net.URI;
import java.util.Collection;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.smarthome.core.thing.type.ChannelType;
/**
* Interface for ChannelTypeBuilder
*
* @author Stefan Triller - Initial contribution
*
*/
@NonNullByDefault
public interface IChannelTypeBuilder<T extends IChannelTypeBuilder<T>> {
/**
* Specify whether this is an advanced channel, default is false
*
* @param advanced true if this is an advanced {@link ChannelType}
* @return this Builder
*/
T isAdvanced(boolean advanced);
/**
* Sets the Description for the ChannelType
*
* @param description StateDescription for the ChannelType
* @return this Builder
*/
T withDescription(String description);
/**
* Sets the Category for the ChannelType
*
* @param category Category for the ChannelType
* @return this Builder
*/
T withCategory(String category);
/**
* Adds a tag to the ChannelType
*
* @param tag Tag to be added to the ChannelType
* @return this Builder
*/
T withTag(String tag);
/**
* Sets the StateDescription for the ChannelType
*
* @param tags Collection of tags to be added to the ChannelType
* @return this Builder
*/
T withTags(Collection<String> tags);
/**
* Sets the ConfigDescriptionURI for the ChannelType
*
* @param configDescriptionURI URI that references the ConfigDescription of the ChannelType
* @return this Builder
*/
T withConfigDescriptionURI(URI configDescriptionURI);
/**
* Build the ChannelType with the given values
*
* @return the created ChannelType
*/
ChannelType build();
}
|
package org.eclipse.emf.emfstore.internal.client.ui.dialogs.login;
import java.util.List;
import java.util.concurrent.Callable;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.emfstore.client.ESServer;
import org.eclipse.emf.emfstore.client.ESUsersession;
import org.eclipse.emf.emfstore.client.util.RunESCommand;
import org.eclipse.emf.emfstore.internal.client.model.ESWorkspaceProviderImpl;
import org.eclipse.emf.emfstore.internal.client.model.Usersession;
import org.eclipse.emf.emfstore.internal.client.model.impl.api.ESUsersessionImpl;
import org.eclipse.emf.emfstore.internal.client.model.impl.api.ESWorkspaceImpl;
import org.eclipse.emf.emfstore.internal.client.ui.common.RunInUI;
import org.eclipse.emf.emfstore.internal.common.APIUtil;
import org.eclipse.emf.emfstore.internal.server.exceptions.AccessControlException;
import org.eclipse.emf.emfstore.server.exceptions.ESException;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
/**
* The login dialog controller manages a given {@link ESUsersession} and/or a {@link ESServer} to determine when it is
* necessary to open a {@link LoginDialog} in order to authenticate the user. It does not, however,
* open a dialog, if the usersession is already logged in.
*
* @author ovonwesen
* @author emueller
*/
public class LoginDialogController implements ILoginDialogController {
private ESUsersession usersession;
private ESServer server;
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.client.ui.dialogs.login.ILoginDialogController#getKnownUsersessions()
*/
public List<ESUsersession> getKnownUsersessions() {
return APIUtil.mapToAPI(
ESUsersession.class,
ESWorkspaceProviderImpl.getInstance().getWorkspace().getInternalAPIImpl().getUsersessions());
}
private ESUsersession login(final boolean force) throws ESException {
return RunInUI.WithException
.runWithResult(new Callable<ESUsersession>() {
public ESUsersession call() throws Exception {
if (server != null
&& server.getLastUsersession() != null
&& server.getLastUsersession().isLoggedIn()
&& !force) {
return server.getLastUsersession();
}
LoginDialog dialog = new LoginDialog(Display
.getCurrent().getActiveShell(),
LoginDialogController.this);
dialog.setBlockOnOpen(true);
if (dialog.open() != Window.OK || usersession == null) {
throw new AccessControlException("Couldn't login.");
}
// contract: #validate() sets the usersession;
return usersession;
}
});
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.client.ui.dialogs.login.ILoginDialogController#isUsersessionLocked()
*/
public boolean isUsersessionLocked() {
if (getUsersession() == null) {
return false;
}
return true;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.client.ui.dialogs.login.ILoginDialogController#getServerLabel()
*/
public String getServerLabel() {
return getServer().getName();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.client.ui.dialogs.login.ILoginDialogController#validate(org.eclipse.emf.emfstore.internal.client.model.Usersession)
*/
public void validate(final ESUsersession session) throws ESException {
final Usersession usersession = ((ESUsersessionImpl) session).getInternalAPIImpl();
final ESWorkspaceImpl workspace = ESWorkspaceProviderImpl.getInstance().getWorkspace();
final EList<Usersession> usersessions = workspace.getInternalAPIImpl().getUsersessions();
RunESCommand.WithException.run(ESException.class, new Callable<Void>() {
public Void call() throws Exception {
// TODO login code
usersession.logIn();
// if successful, else exception is thrown prior reaching this code
if (!usersessions.contains(usersession)) {
usersessions.add(usersession);
}
return null;
}
});
this.usersession = session;
// TODO OTS auto save
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.client.ui.dialogs.login.ILoginDialogController#getUsersession()
*/
public ESUsersession getUsersession() {
return usersession;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.client.ui.dialogs.login.ILoginDialogController#getServer()
*/
public ESServer getServer() {
if (server != null) {
return server;
}
return usersession.getServer();
}
/**
* Perform a login using an {@link ESUsersession} that can be determined with
* the given {@link ESServer}.
*
*
* @param server
* the server info to be used in order to determine a valid
* usersession
* @param force
* whether to force requesting the password
* @return a logged-in usersession
* @throws ESException
* in case the login fails
*/
public ESUsersession login(ESServer server, boolean force)
throws ESException {
this.server = server;
this.usersession = null;
return login(force);
}
/**
* Perform a login using the given {@link ESUsersession}.
*
* @param usersession
* the usersession to be used during login
* @param force
* whether to force requesting the password
* @throws ESException
* in case the login fails
*/
public void login(ESUsersession usersession, boolean force)
throws ESException {
this.server = null;
this.usersession = usersession;
login(force);
}
/**
* Perform a login using an {@link ESUsersession} that can be determined with
* the given {@link ESServer}.
*
*
* @param server
* the server info to be used in order to determine a valid
* usersession
* @return a logged-in usersession
* @throws ESException
* in case the login fails
*/
public ESUsersession login(ESServer server) throws ESException {
this.server = server;
this.usersession = null;
return login(false);
}
/**
* Perform a login using the given {@link ESUsersession}.
*
* @param usersession
* the usersession to be used during login
* @throws ESException
* in case the login fails
*/
public void login(ESUsersession usersession) throws ESException {
this.server = null;
this.usersession = usersession;
login(false);
}
}
|
// OmeroReader.java
package loci.ome.io;
import Glacier2.CannotCreateSessionException;
import Glacier2.PermissionDeniedException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.List;
import loci.common.DateTools;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tools.ImageInfo;
import ome.xml.model.primitives.PositiveFloat;
import ome.xml.model.primitives.PositiveInteger;
import omero.RDouble;
import omero.RInt;
import omero.RTime;
import omero.ServerError;
import omero.api.GatewayPrx;
import omero.api.RawPixelsStorePrx;
import omero.api.ServiceFactoryPrx;
import omero.model.Channel;
import omero.model.Image;
import omero.model.LogicalChannel;
import omero.model.Pixels;
public class OmeroReader extends FormatReader {
// -- Constants --
public static final int DEFAULT_PORT = 4064;
// -- Fields --
private String server;
private String username;
private String password;
private int thePort = DEFAULT_PORT;
private omero.client client;
private RawPixelsStorePrx store;
private Image img;
private Pixels pix;
// -- Constructors --
public OmeroReader() {
super("OMERO", "*");
}
// -- OmeroReader methods --
public void setServer(String server) {
this.server = server;
}
public void setPort(int port) {
thePort = port;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
// -- IFormatReader methods --
@Override
public boolean isThisType(String name, boolean open) {
return name.startsWith("omero:");
}
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
FormatTools.checkBufferSize(this, buf.length, w, h);
final int[] zct = FormatTools.getZCTCoords(this, no);
final byte[] plane;
try {
plane = store.getPlane(zct[0], zct[1], zct[2]);
}
catch (ServerError e) {
throw new FormatException(e);
}
RandomAccessInputStream s = new RandomAccessInputStream(plane);
readPlane(s, x, y, w, h, buf);
s.close();
return buf;
}
@Override
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly && client != null) {
client.closeSession();
}
}
@Override
protected void initFile(String id) throws FormatException, IOException {
LOGGER.debug("OmeroReader.initFile({})", id);
super.initFile(id);
if (!id.startsWith("omero:")) {
throw new IllegalArgumentException("Not an OMERO id: " + id);
}
// parse credentials from id string
LOGGER.info("Parsing credentials");
String address = server, user = username, pass = password;
int port = thePort;
long iid = -1;
final String[] tokens = id.substring(6).split("\n");
for (String token : tokens) {
final int equals = token.indexOf("=");
if (equals < 0) continue;
final String key = token.substring(0, equals);
final String val = token.substring(equals + 1);
if (key.equals("server")) address = val;
else if (key.equals("user")) user = val;
else if (key.equals("pass")) pass = val;
else if (key.equals("port")) {
try {
port = Integer.parseInt(val);
}
catch (NumberFormatException exc) { }
}
else if (key.equals("iid")) {
try {
iid = Long.parseLong(val);
}
catch (NumberFormatException exc) { }
}
}
if (address == null) {
throw new FormatException("Invalid server address");
}
if (user == null) {
throw new FormatException("Invalid username");
}
if (pass == null) {
throw new FormatException("Invalid password");
}
if (iid < 0) {
throw new FormatException("Invalid image ID");
}
try {
// authenticate with OMERO server
LOGGER.info("Logging in");
client = new omero.client(address, port);
final ServiceFactoryPrx serviceFactory = client.createSession(user, pass);
// get raw pixels store and pixels
store = serviceFactory.createRawPixelsStore();
store.setPixelsId(iid, false);
final GatewayPrx gateway = serviceFactory.createGateway();
img = gateway.getImage(iid);
long pixelsId = img.getPixels(0).getId().getValue();
pix = gateway.getPixels(pixelsId);
final int sizeX = pix.getSizeX().getValue();
final int sizeY = pix.getSizeY().getValue();
final int sizeZ = pix.getSizeZ().getValue();
final int sizeC = pix.getSizeC().getValue();
final int sizeT = pix.getSizeT().getValue();
final String pixelType = pix.getPixelsType().getValue().getValue();
// populate metadata
LOGGER.info("Populating metadata");
core[0].sizeX = sizeX;
core[0].sizeY = sizeY;
core[0].sizeZ = sizeZ;
core[0].sizeC = sizeC;
core[0].sizeT = sizeT;
core[0].rgb = false;
core[0].littleEndian = false;
core[0].dimensionOrder = "XYZCT";
core[0].imageCount = sizeZ * sizeC * sizeT;
core[0].pixelType = FormatTools.pixelTypeFromString(pixelType);
RDouble x = pix.getPhysicalSizeX();
Double px = x == null ? null : x.getValue();
RDouble y = pix.getPhysicalSizeY();
Double py = y == null ? null : y.getValue();
RDouble z = pix.getPhysicalSizeZ();
Double pz = z == null ? null : z.getValue();
RDouble t = pix.getTimeIncrement();
Double time = t == null ? null : t.getValue();
String name = img.getName().getValue();
String description = img.getDescription().getValue();
RTime date = img.getAcquisitionDate();
MetadataStore store = getMetadataStore();
MetadataTools.populatePixels(store, this);
store.setImageName(name, 0);
store.setImageDescription(description, 0);
if (date != null) {
store.setImageAcquiredDate(DateTools.convertDate(date.getValue(),
(int) DateTools.UNIX_EPOCH), 0);
}
if (px != null) {
store.setPixelsPhysicalSizeX(new PositiveFloat(px), 0);
}
if (py != null) {
store.setPixelsPhysicalSizeY(new PositiveFloat(py), 0);
}
if (pz != null) {
store.setPixelsPhysicalSizeZ(new PositiveFloat(pz), 0);
}
if (time != null) {
store.setPixelsTimeIncrement(time, 0);
}
List<Channel> channels = pix.copyChannels();
for (int c=0; c<channels.size(); c++) {
LogicalChannel channel = channels.get(c).getLogicalChannel();
RInt emWave = channel.getEmissionWave();
RInt exWave = channel.getExcitationWave();
RDouble pinholeSize = channel.getPinHoleSize();
Integer emission = emWave == null ? null : emWave.getValue();
Integer excitation = exWave == null ? null : exWave.getValue();
String channelName = channel.getName().getValue();
Double pinhole = pinholeSize == null ? null : pinholeSize.getValue();
if (channelName != null) {
store.setChannelName(channelName, 0, c);
}
if (pinhole != null) {
store.setChannelPinholeSize(pinhole, 0, c);
}
if (emission != null) {
store.setChannelEmissionWavelength(
new PositiveInteger(emission), 0, c);
}
if (excitation != null) {
store.setChannelExcitationWavelength(
new PositiveInteger(excitation), 0, c);
}
}
}
catch (CannotCreateSessionException e) {
throw new FormatException(e);
}
catch (PermissionDeniedException e) {
throw new FormatException(e);
}
catch (ServerError e) {
throw new FormatException(e);
}
}
/** A simple command line tool for downloading images from OMERO. */
public static void main(String[] args) throws Exception {
// parse OMERO credentials
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Server? ");
final String server = con.readLine();
System.out.printf("Port [%d]? ", DEFAULT_PORT);
final String portString = con.readLine();
final int port = portString.equals("") ? DEFAULT_PORT :
Integer.parseInt(portString);
System.out.print("Username? ");
final String user = con.readLine();
System.out.print("Password? ");
final String pass = new String(con.readLine());
System.out.print("Image ID? ");
final int imageId = Integer.parseInt(con.readLine());
System.out.print("\n\n");
// construct the OMERO reader
final OmeroReader omeroReader = new OmeroReader();
omeroReader.setUsername(user);
omeroReader.setPassword(pass);
omeroReader.setServer(server);
omeroReader.setPort(port);
final String id = "omero:iid=" + imageId;
try {
omeroReader.setId(id);
}
catch (Exception e) {
omeroReader.close();
throw e;
}
omeroReader.close();
// delegate the heavy lifting to Bio-Formats ImageInfo utility
final ImageInfo imageInfo = new ImageInfo();
imageInfo.setReader(omeroReader); // override default image reader
String[] readArgs = new String[args.length + 1];
System.arraycopy(args, 0, readArgs, 0, args.length);
readArgs[args.length] = id;
if (!imageInfo.testRead(readArgs)) {
omeroReader.close();
System.exit(1);
}
}
}
|
import java.io.*;
import java.util.*;
public class Dimension
{
public static final int TOTAL_NEIGHBOURS = 27;
public Dimension (String dataFile, boolean debug)
{
_theWorld = new Vector<Cube>();
_width = 0;
_height = 0;
_minZ = 0;
_maxZ = 0;
_debug = debug;
loadLayer(dataFile); // load the world
}
/**
* During a cycle, all cubes simultaneously change their state according to the following rules:
*
* If a cube is active and exactly 2 or 3 of its neighbors are also active, the cube remains active.
* Otherwise, the cube becomes inactive.
* If a cube is inactive but exactly 3 of its neighbors are active, the cube becomes active.
* Otherwise, the cube remains inactive.
*/
public boolean cycle ()
{
Vector<Cube> nextWorld = new Vector<Cube>();
// go through the entries in the current world first.
for (int i = 0; i < _theWorld.size(); i++)
{
Cube theCube = _theWorld.elementAt(i);
if (_debug)
System.out.println("\nChecking: "+theCube);
Cube[] cubes = neighbours(theCube);
int activeCount = -1; // account for the fact "we" are active
for (int j = 0; j < cubes.length; j++)
{
if (_theWorld.contains(cubes[j]))
activeCount++;
}
if (_debug)
System.out.println(theCube+" active count: "+activeCount);
if (theCube.isActive())
{
if ((activeCount != 2) && (activeCount == 3))
theCube.deactivate();
}
else
{
if (activeCount == 3)
theCube.activate();
}
nextWorld.add(theCube);
}
_theWorld = nextWorld;
return true;
}
@Override
public String toString ()
{
String str = "";
for (int z = _minZ; z <= _maxZ; z++)
{
str += "z="+z+"\n";
for (int y = 0; y < _height; y++)
{
for (int x = 0; x < _width; x++)
{
Cube point = new Cube(new ThreeDPoint(x, y, z));
int index = _theWorld.indexOf(point);
point = _theWorld.elementAt(index);
if (point.isActive())
str += CubeId.ACTIVE;
else
str += CubeId.INACTIVE;
}
str += "\n";
}
}
return str;
}
public Cube[] neighbours (Cube theCube)
{
int index = 0;
Cube[] n = new Cube[TOTAL_NEIGHBOURS];
ThreeDPoint coord = theCube.position();
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
for (int z = -1; z <= 1; z++)
{
ThreeDPoint v = new ThreeDPoint(coord.getX() + x, coord.getY() + y, coord.getZ() +z);
System.out.println(v);
n[index] = new Cube(v);
index++;
}
}
}
return n;
}
private void loadLayer (String inputFile)
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(inputFile));
String line = null;
while ((line = reader.readLine()) != null)
{
if (_debug)
System.out.println("Loaded line: "+line);
_width = line.length();
for (int i = 0; i < line.length(); i++)
{
ThreeDPoint p = new ThreeDPoint(i, _height, 0);
if (CubeId.ACTIVE == line.charAt(i))
{
if (_debug)
System.out.println("Active cell at: "+p);
_theWorld.add(new Cube(p, true));
}
else
{
if (_debug)
System.out.println("Inactive cell at: "+p);
_theWorld.add(new Cube(p, false));
}
}
_height++;
}
}
catch (Throwable ex)
{
ex.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (Throwable ex)
{
}
}
}
private Vector<Cube> _theWorld;
private int _width;
private int _height;
private int _minZ;
private int _maxZ;
private boolean _debug;
}
|
package com.intellij.diagnostic;
import com.intellij.openapi.diagnostic.IdeaLoggingEvent;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import org.apache.log4j.spi.LoggingEvent;
import org.jetbrains.annotations.NonNls;
import java.util.*;
public class MessagePool {
private static int MAX_POOL_SIZE_FOR_FATALS = 100;
private static MessagePool ourInstance;
private List<AbstractMessage> myIdeFatals = new ArrayList<AbstractMessage>();
private Set<MessagePoolListener> myListeners = new HashSet<MessagePoolListener>();
private MessageGrouper myFatalsGrouper;
private boolean ourJvmIsShuttingDown = false;
MessagePool(int maxGroupSize, int timeout) {
myFatalsGrouper = new MessageGrouper("Fatal Errors Grouper", timeout, maxGroupSize);
}
public static MessagePool getInstance() {
if (ourInstance == null) {
ourInstance = new MessagePool(20, 1000);
}
return ourInstance;
}
public void addIdeFatalMessage(LoggingEvent aEvent) {
addIdeFatalMessage(new LogMessage(aEvent));
}
public void addIdeFatalMessage(IdeaLoggingEvent aEvent) {
addIdeFatalMessage(new LogMessage(aEvent));
}
private void addIdeFatalMessage(LogMessage message) {
if (myIdeFatals.size() < MAX_POOL_SIZE_FOR_FATALS) {
myFatalsGrouper.add(message);
} else if (myIdeFatals.size() == MAX_POOL_SIZE_FOR_FATALS) {
myFatalsGrouper.add(new LogMessage(new LoggingEvent(DiagnosticBundle.message("error.monitor.too.many.errors"),
Category.getRoot(), Priority.ERROR, null, new TooManyErrorsException())));
}
}
public boolean isFatalErrorsPoolEmpty() {
return myIdeFatals.isEmpty();
}
public boolean hasUnreadMessages() {
for (int i = 0; i < myIdeFatals.size(); i++) {
AbstractMessage message = myIdeFatals.get(i);
if (!message.isRead()) return true;
}
return false;
}
public List<AbstractMessage> getFatalErrors(boolean aIncludeReadMessages, boolean aIncludeSubmittedMessages) {
List<AbstractMessage> result = new ArrayList<AbstractMessage>();
for (int i = 0; i < myIdeFatals.size(); i++) {
AbstractMessage each = myIdeFatals.get(i);
if (!each.isRead() && !each.isSubmitted()) {
result.add(each);
} else if ((each.isRead() && aIncludeReadMessages) || (each.isSubmitted() && aIncludeSubmittedMessages)) {
result.add(each);
}
}
return result;
}
public void clearFatals() {
myIdeFatals.clear();
notifyListenersClear();
}
public void addListener(MessagePoolListener aListener) {
myListeners.add(aListener);
}
public void removeListener(MessagePoolListener aListener) {
myListeners.remove(aListener);
}
private void notifyListenersAdd() {
if (ourJvmIsShuttingDown) return;
final MessagePoolListener[] messagePoolListeners = myListeners.toArray(new MessagePoolListener[myListeners.size()]);
for (int i = 0; i < messagePoolListeners.length; i++) {
messagePoolListeners[i].newEntryAdded();
}
}
private void notifyListenersClear() {
final MessagePoolListener[] messagePoolListeners = myListeners.toArray(new MessagePoolListener[myListeners.size()]);
for (int i = 0; i < messagePoolListeners.length; i++) {
messagePoolListeners[i].poolCleared();
}
}
public void setJvmIsShuttingDown() {
ourJvmIsShuttingDown = true;
}
private class MessageGrouper extends Thread {
private int myTimeOut;
private int myMaxGroupSize;
private final List<AbstractMessage> myMessages = new ArrayList<AbstractMessage>();
private int myAccumulatedTime;
public MessageGrouper(@NonNls String name, int timeout, int maxGroupSize) {
setName(name);
myTimeOut = timeout;
myMaxGroupSize = maxGroupSize;
start();
}
/** @noinspection BusyWait*/
public void run() {
while (true) {
try {
sleep(50);
myAccumulatedTime += 50;
if (myAccumulatedTime > myTimeOut) {
synchronized(myMessages) {
if (myMessages.size() > 0) {
post();
}
}
}
} catch (InterruptedException e) {
return;
}
}
}
private void post() {
AbstractMessage message;
if (myMessages.size() == 1) {
message = myMessages.get(0);
} else {
message = new GroupedLogMessage(new ArrayList<AbstractMessage>(myMessages));
}
myMessages.clear();
myIdeFatals.add(message);
notifyListenersAdd();
myAccumulatedTime = 0;
}
public void add(AbstractMessage message) {
myAccumulatedTime = 0;
synchronized(myMessages) {
myMessages.add(message);
if (myMessages.size() >= myMaxGroupSize) {
post();
}
}
}
}
static class TooManyErrorsException extends Exception {
TooManyErrorsException() {
super(DiagnosticBundle.message("error.monitor.too.many.errors"));
}
}
}
|
package org.jasig.portal.i18n;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import org.jasig.portal.PropertiesManager;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.DocumentFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Manages locales on behalf of a user.
* This class currently keeps track of locales at the following levels:<br>
* <ol>
* <li>User's locale preferences (associated with a user ID)</li>
* <li>Browser's locale preferences (from the Accept-Language request header)</li>
* <li>Session's locale preferences (set via the portal request parameter uP_locales)</li>
* <li>Portal's locale preferences (set in portal.properties)</li>
* </ol>
* Eventually, this class will also keep track of locale preferences at
* the following levels:<br>
* <ol>
* <li>Layout node's locale preferences</li>
* <li>User profile's locale preferences</li>
* </ol>
* @author Shoji Kajita <a href="mailto:">kajita@itc.nagoya-u.ac.jp</a>
* @author Ken Weiner, kweiner@unicon.net
* @version $Revision$
*/
public class LocaleManager {
private IPerson person;
private static boolean localeAware = PropertiesManager.getPropertyAsBoolean("org.jasig.portal.i18n.LocaleManager.locale_aware");
private static Locale jvmLocale;
private static Locale[] portalLocales;
private Locale[] sessionLocales;
private Locale[] browserLocales;
private Locale[] userLocales;
/**
* Constructor that associates a locale manager with a user.
* @param person the user
*/
public LocaleManager(IPerson person) {
this.person = person;
if (localeAware) {
jvmLocale = Locale.getDefault();
portalLocales = loadPortalLocales();
try {
userLocales = LocaleStoreFactory.getLocaleStoreImpl().getUserLocales(person);
} catch (Exception e) {
LogService.log(LogService.ERROR, e);
}
}
}
/**
* Constructor that sets up locales according to
* the <code>Accept-Language</code> request header
* from a user's browser.
* @param person the user
* @param acceptLanguage the Accept-Language request header from a user's browser
*/
public LocaleManager(IPerson person, String acceptLanguage) {
this(person);
this.browserLocales = parseLocales(acceptLanguage);
}
// Getters
public boolean isLocaleAware() { return localeAware; }
public static Locale getJvmLocale() { return jvmLocale; }
public static Locale[] getPortalLocales() { return portalLocales; }
public Locale[] getBrowserLocales() { return browserLocales; }
public Locale[] getUserLocales() { return userLocales; }
public Locale[] getSessionLocales() { return sessionLocales; }
// Setters
public static void setJvmLocale(Locale jvmLocale) { LocaleManager.jvmLocale = jvmLocale; }
public static void setPortalLocales(Locale[] portalLocales) { LocaleManager.portalLocales = portalLocales; }
public void setBrowserLocales(Locale[] browserLocales) { this.browserLocales = browserLocales; }
public void setUserLocales(Locale[] userLocales) { this.userLocales = userLocales; }
public void setSessionLocales(Locale[] sessionLocales) { this.sessionLocales = sessionLocales; }
/**
* Read and parse portal_locales from portal.properties.
* portal_locales will be in the form of a comma-separated
* list, e.g. en_US,ja_JP,sv_SE
*/
private Locale[] loadPortalLocales() {
String portalLocalesString = PropertiesManager.getProperty("org.jasig.portal.i18n.LocaleManager.portal_locales");
return parseLocales(portalLocalesString);
}
/**
* Produces a sorted list of locales according to locale preferences
* obtained from several places. The following priority is given:
* session, user, browser, portal, and jvm.
* @return the sorted list of locales
*/
public Locale[] getLocales() {
// Need logic to construct ordered locale list.
// Consider creating a separate ILocaleResolver
// interface to do this work.
List locales = new ArrayList();
// Add highest priority locales first
addToLocaleList(locales, sessionLocales);
addToLocaleList(locales, userLocales);
// We will ignore browser locales until we know how to
// translate them into proper java.util.Locales
//addToLocaleList(locales, browserLocales);
addToLocaleList(locales, portalLocales);
addToLocaleList(locales, new Locale[] { jvmLocale });
return (Locale[])locales.toArray(new Locale[0]);
}
/**
* Add locales to the locale list if they aren't in there already
*/
private void addToLocaleList(List localeList, Locale[] locales) {
if (locales != null) {
for (int i = 0; i < locales.length; i++) {
if (!localeList.contains(locales[i]))
localeList.add(locales[i]);
}
}
}
/**
* Helper method to produce a <code>java.util.Locale</code> array from
* a comma-delimited locale string list, e.g. "en_US,ja_JP"
* @param localeStringList the locales to parse
* @return an array of locales representing the locale string list
*/
public static Locale[] parseLocales(String localeStringList) {
Locale[] locales = null;
if (localeStringList != null) {
StringTokenizer st = new StringTokenizer(localeStringList, ",");
locales = new Locale[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++) {
String localeString = st.nextToken().trim();
locales[i] = parseLocale(localeString);
}
}
return locales;
}
/**
* Helper method to produce a <code>java.util.Locale</code> object from
* a locale string such as en_US or ja_JP.
* @param localeString a locale string such as en_US
* @return a java.util.Locale object representing the locale string
*/
public static Locale parseLocale(String localeString) {
String language = null;
String country = null;
String variant = null;
StringTokenizer st = new StringTokenizer(localeString, "_");
if (st.hasMoreTokens()) {
language = st.nextToken();
}
if (st.hasMoreTokens()) {
country = st.nextToken();
}
if (st.hasMoreTokens()) {
variant = st.nextToken();
}
Locale locale = null;
if (variant != null) {
locale = new Locale(language, country, variant);
} else if (country != null) {
locale = new Locale(language, country);
} else if (language != null) {
locale = new Locale(language);
}
return locale;
}
/**
* Constructs a comma-delimited list of locales
* that could be parsed back into a Locale
* array with parseLocales(String localeStringList).
* @param locales the list of locales
* @return a string representing the list of locales
*/
public String stringValueOf(Locale[] locales) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < locales.length; i++) {
Locale locale = locales[i];
sb.append(locale.toString());
if (i < locales.length - 1) {
sb.append(",");
}
}
return sb.toString();
}
/**
* Stores the user locales persistantly.
* @param userLocales the user locales preference
* @throws Exception
*/
public void persistUserLocales(Locale[] userLocales) throws Exception {
setUserLocales(userLocales);
LocaleStoreFactory.getLocaleStoreImpl().updateUserLocales(person, userLocales);
}
/**
* Creates an XML representation of a list of locales.
* @param locales the locale list
* @return the locale list as XML
*/
public static Document xmlValueOf(Locale[] locales) {
return xmlValueOf(locales, null);
}
/**
* Creates an XML representation of a list of locales.
* If a selected locale is supplied, the XML element representing
* the selected locale will have an attribute of selected with value
* of true. This is helpful when constructing user interfaces that
* indicate which locale is selected.
* @param locales the locale list
* @param selectedLocale a locale that should be selected if it is in the list
* @return the locale list as XML
*/
public static Document xmlValueOf(Locale[] locales, Locale selectedLocale) {
Document doc = DocumentFactory.getNewDocument();
// <locales>
Element localesE = doc.createElement("locales");
for (int i = 0; i < locales.length; i++) {
Element locE = doc.createElement("locale");
locE.setAttribute("displayName", locales[i].getDisplayName(locales[0]));
locE.setAttribute("code", locales[i].toString());
// Mark which locale is the user's preference
if (selectedLocale != null && selectedLocale.equals(locales[i])) {
locE.setAttribute("selected", "true");
}
// <language iso2="..." iso3="..." displayName="..."/>
Element languageE = doc.createElement("language");
languageE.setAttribute("iso2", locales[i].getLanguage());
try {
languageE.setAttribute("iso3", locales[i].getISO3Language());
} catch (Exception e) {
// Do nothing
}
languageE.setAttribute("displayName", locales[i].getDisplayLanguage(locales[0]));
locE.appendChild(languageE);
// <country iso2="..." iso3="..." displayName="..."/>
Element countryE = doc.createElement("country");
countryE.setAttribute("iso2", locales[i].getCountry());
try {
countryE.setAttribute("iso3", locales[i].getISO3Country());
} catch (Exception e) {
// Do nothing
}
countryE.setAttribute("displayName", locales[i].getDisplayCountry(locales[0]));
locE.appendChild(countryE);
// <variant code="..." displayName="..."/>
Element variantE = doc.createElement("variant");
variantE.setAttribute("code", locales[i].getVariant());
variantE.setAttribute("displayName", locales[i].getDisplayVariant(locales[0]));
locE.appendChild(variantE);
localesE.appendChild(locE);
}
doc.appendChild(localesE);
return doc;
}
public String toString() {
StringBuffer sb = new StringBuffer(1024);
sb.append("LocaleManager's locales").append("\n");
sb.append("
sb.append("Session locales: ");
if (sessionLocales != null) {
sb.append(stringValueOf(sessionLocales));
}
sb.append("\n");
sb.append("User locales: ");
if (userLocales != null) {
sb.append(stringValueOf(userLocales));
}
sb.append("\n");
sb.append("Browser locales: ");
if (browserLocales != null) {
sb.append(stringValueOf(browserLocales));
}
sb.append("\n");
sb.append("Portal locales: ");
if (portalLocales != null) {
sb.append(stringValueOf(portalLocales));
}
sb.append("\n");
sb.append("JVM locale: ");
if (jvmLocale != null) {
sb.append(jvmLocale.toString());
}
sb.append("\n");
sb.append("Sorted locales: ");
Locale[] sortedLocales = getLocales();
if (sortedLocales != null) {
sb.append(stringValueOf(sortedLocales));
}
sb.append("\n");
return sb.toString();
}
}
|
package TobleMiner.MineFight.Language;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import TobleMiner.MineFight.Debug.Debugger;
import TobleMiner.MineFight.ErrorHandling.Error;
import TobleMiner.MineFight.ErrorHandling.ErrorReporter;
import TobleMiner.MineFight.ErrorHandling.ErrorSeverity;
import TobleMiner.MineFight.Util.IO.File.FileUtil;
public class Langfile
{
private final File langDir;
private final HashMap<String,List<String>> dictionary = new HashMap<String,List<String>>();
public Langfile(File file)
{
this.langDir = new File(file,"lang");
try
{
if(!langDir.exists())
{
langDir.mkdirs();
}
String[] files = {"DE_de.lang","EN_uk.lang","EN_us.lang"};
for(String s : files)
{
File langFile = new File(this.langDir,s);
if(!(langFile.exists() && langFile.isFile()))
{
if(!langFile.isFile())
{
langFile.delete();
}
InputStream is = this.getClass().getResourceAsStream(s);
FileUtil.copyFromInputStreamToFileUtf8(langFile, is);
}
}
}
catch(Exception ex)
{
Error error = new Error("Failed handling languagefiles!","An error occured while checking the languagefiles: "+ex.getMessage(),"Most messages will be missing until this problem is fixed!",this.getClass().getCanonicalName(),ErrorSeverity.ETERNALCHAOS);
ErrorReporter.reportError(error);
ex.printStackTrace();
}
}
public void loadLanguageFileExt(File langFile)
{
if(langFile.exists() && langFile.isFile())
{
try
{
FileReader fr = new FileReader(langFile);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
int cnt = 0;
String alltrans = "";
while(line != null)
{
int i = line.indexOf("
if(i > -1)
{
if(i < 4)
{
line = br.readLine();
continue;
}
line = line.substring(0, i-1);
}
int equ = line.indexOf('=');
if(equ > 0)
{
String key = line.substring(0,equ);
String s = line.substring(equ,line.length());
List<String> alternatives = new ArrayList<String>();
boolean openDoublequotes = false;
int j = 0;
int lastDoubleQuotePos=0;
while(j<s.length())
{
int quotePos = s.indexOf('\"',j);
if(quotePos < 0)
{
break;
}
j = quotePos+1;
if(quotePos > 0)
{
if(s.charAt(quotePos-1) != '\\')
{
openDoublequotes = !openDoublequotes;
if(!openDoublequotes)
{
alternatives.add(s.substring(lastDoubleQuotePos+1,quotePos).replace("\\",""));
}
lastDoubleQuotePos = quotePos;
}
}
else
{
openDoublequotes = true;
}
}
this.dictionary.put(key, alternatives);
alltrans += key+"=";
for(String alt : alternatives)
alltrans += "\""+alt+"\",";
alltrans = alltrans.substring(0, alltrans.length() - 1);
alltrans += "\n";
cnt++;
}
else
{
Error error = new Error("Langfile parse-error!","An error occured while parsing the languagefile '"+langFile.getAbsoluteFile()+"' : "+line,"The message belonging to this entry will be broken!",this.getClass().getCanonicalName(),ErrorSeverity.WARNING);
ErrorReporter.reportError(error);
}
line = br.readLine();
}
fr.close();
br.close();
Debugger.writeDebugOut(String.format("Added %d translations:\n", cnt) + alltrans);
}
catch(Exception ex)
{
Error error = new Error("Failed loading languagefile!","An error occured while loading languagefile from '"+langFile.getAbsoluteFile()+"' : "+ex.getMessage(),"Most messages will be missing until this problem is fixed!",this.getClass().getCanonicalName(),ErrorSeverity.ETERNALCHAOS);
ex.printStackTrace();
ErrorReporter.reportError(error);
}
}
else
{
Error error = new Error("Failed loading languagefile!","The languagefile '"+langFile.getAbsoluteFile()+"' doesn't exist!","Most messages will be missing until this problem is fixed!",this.getClass().getCanonicalName(),ErrorSeverity.ETERNALCHAOS);
ErrorReporter.reportError(error);
}
}
public void loadLanguageFile(String name)
{
File langFile = new File(this.langDir,name);
this.loadLanguageFileExt(langFile);
}
public String get(String key)
{
if(key == null || key.length() == 0)
return "";
List<String> vals = this.dictionary.get(key);
if(vals == null || vals.size() == 0)
{
return String.format("{%s}", key);
}
Random rand = new Random();
return vals.get(rand.nextInt(vals.size()));
}
}
|
package cc.mallet.classify.tui;
import java.util.logging.*;
import java.util.Iterator;
import java.util.Random;
import java.util.BitSet;
import java.util.ArrayList;
import java.util.Collections;
import java.io.*;
import cc.mallet.classify.*;
import cc.mallet.pipe.*;
import cc.mallet.pipe.iterator.*;
import cc.mallet.types.*;
import cc.mallet.util.*;
/**
A command-line tool for manipulating InstanceLists. For example,
reducing the feature space by information gain.
@author Andrew McCallum <a href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a>
*/
public class Vectors2Vectors {
private static Logger logger = MalletLogger.getLogger(Vectors2Vectors.class.getName());
static CommandOption.File inputFile = new CommandOption.File
(Vectors2Vectors.class, "input", "FILE", true, new File("-"),
"Read the instance list from this file; Using - indicates stdin.", null);
static CommandOption.File outputFile = new CommandOption.File
(Vectors2Vectors.class, "output", "FILE", true, new File("-"),
"Write pruned instance list to this file (use --training-file etc. if you are splitting the list). Using - indicates stdin.", null);
static CommandOption.File trainingFile = new CommandOption.File
(Vectors2Vectors.class, "training-file", "FILE", true, new File("training.vectors"),
"Write the training set instance list to this file (or use --output if you are only pruning features); Using - indicates stdout.", null);
static CommandOption.File testFile = new CommandOption.File
(Vectors2Vectors.class, "testing-file", "FILE", true, new File("test.vectors"),
"Write the test set instance list to this file; Using - indicates stdout.", null);
static CommandOption.File validationFile = new CommandOption.File
(Vectors2Vectors.class, "validation-file", "FILE", true, new File("validation.vectors"),
"Write the validation set instance list to this file; Using - indicates stdout.", null);
static CommandOption.Double trainingProportion = new CommandOption.Double
(Vectors2Vectors.class, "training-portion", "DECIMAL", true, 1.0,
"The fraction of the instances that should be used for training.", null);
static CommandOption.Double validationProportion = new CommandOption.Double
(Vectors2Vectors.class, "validation-portion", "DECIMAL", true, 0.0,
"The fraction of the instances that should be used for validation.", null);
static CommandOption.Integer randomSeed = new CommandOption.Integer
(Vectors2Vectors.class, "random-seed", "INTEGER", true, 0,
"The random seed for randomly selecting a proportion of the instance list for training", null);
static CommandOption.Integer pruneInfogain = new CommandOption.Integer
(Vectors2Vectors.class, "prune-infogain", "N", false, 0,
"Reduce features to the top N by information gain.", null);
static CommandOption.Integer pruneCount = new CommandOption.Integer
(Vectors2Vectors.class, "prune-count", "N", false, 0,
"Reduce features to those that occur more than N times.", null);
static CommandOption.Boolean vectorToSequence = new CommandOption.Boolean
(Vectors2Vectors.class, "vector-to-sequence", "[TRUE|FALSE]", false, false,
"Convert FeatureVector's to FeatureSequence's.", null);
static CommandOption.Boolean hideTargets = new CommandOption.Boolean
(Vectors2Vectors.class, "hide-targets", "[TRUE|FALSE]", false, false,
"Hide targets.", null);
static CommandOption.Boolean revealTargets = new CommandOption.Boolean
(Vectors2Vectors.class, "reveal-targets", "[TRUE|FALSE]", false, false,
"Reveal targets.", null);
public static void main (String[] args) throws FileNotFoundException, IOException {
// Process the command-line options
CommandOption.setSummary (Vectors2Vectors.class,
"A tool for manipulating instance lists of feature vectors.");
CommandOption.process (Vectors2Vectors.class, args);
// Print some helpful messages for error cases
if (args.length == 0) {
CommandOption.getList(Vectors2Vectors.class).printUsage(false);
System.exit (-1);
}
if (false && !inputFile.wasInvoked()) {
System.err.println ("You must specify an input instance list, with --input.");
System.exit (-1);
}
Random r = randomSeed.wasInvoked() ? new Random (randomSeed.value) : new Random ();
double t = trainingProportion.value;
double v = validationProportion.value;
logger.info ("Training portion = "+t);
logger.info ("Validation portion = "+v);
logger.info ("Testing portion = "+(1-v-t));
logger.info ("Prune info gain = "+pruneInfogain.value);
logger.info ("Prune count = "+pruneCount.value);
// Read the InstanceList
InstanceList instances = InstanceList.load (inputFile.value);
if (t == 1.0 && ! (pruneInfogain.wasInvoked() || pruneCount.wasInvoked())
&& ! (hideTargets.wasInvoked() || revealTargets.wasInvoked())) {
System.err.println("Vectors2Vectors was invoked, but did not change anything");
instances.save(trainingFile.value());
System.exit(0);
}
if (pruneInfogain.wasInvoked() || pruneCount.wasInvoked()) {
// Are we also splitting the instances?
// Current code doesn't want to do this, so I'm
// not changing it, but I don't know a reason. -DM
if (t != 1.0) {
throw new UnsupportedOperationException("Infogain/count processing of test or validation lists not yet supported.");
}
if (pruneCount.value > 0) {
// Check which type of data element the instances contain
Instance firstInstance = instances.get(0);
if (firstInstance.getData() instanceof FeatureSequence) {
// Version for feature sequences
Alphabet oldAlphabet = instances.getDataAlphabet();
Alphabet newAlphabet = new Alphabet();
// It's necessary to create a new instance list in
// order to make sure that the data alphabet is correct.
Noop newPipe = new Noop (newAlphabet, instances.getTargetAlphabet());
InstanceList newInstanceList = new InstanceList (newPipe);
// Iterate over the instances in the old list, adding
// up occurrences of features.
int numFeatures = oldAlphabet.size();
double[] counts = new double[numFeatures];
for (int ii = 0; ii < instances.size(); ii++) {
Instance instance = instances.get(ii);
FeatureSequence fs = (FeatureSequence) instance.getData();
fs.addFeatureWeightsTo(counts);
}
Instance instance, newInstance;
// Next, iterate over the same list again, adding
// each instance to the new list after pruning.
while (instances.size() > 0) {
instance = instances.get(0);
FeatureSequence fs = (FeatureSequence) instance.getData();
fs.prune(counts, newAlphabet, pruneCount.value);
newInstanceList.add(newPipe.instanceFrom(new Instance(fs, instance.getTarget(),
instance.getName(),
instance.getSource())));
instances.remove(0);
}
logger.info("features: " + oldAlphabet.size() +
" -> " + newAlphabet.size());
// Make the new list the official list.
instances = newInstanceList;
}
else if (firstInstance.getData() instanceof FeatureVector) {
// Version for FeatureVector
Alphabet alpha2 = new Alphabet ();
Noop pipe2 = new Noop (alpha2, instances.getTargetAlphabet());
InstanceList instances2 = new InstanceList (pipe2);
int numFeatures = instances.getDataAlphabet().size();
double[] counts = new double[numFeatures];
for (int ii = 0; ii < instances.size(); ii++) {
Instance instance = instances.get(ii);
FeatureVector fv = (FeatureVector) instance.getData();
fv.addTo(counts);
}
BitSet bs = new BitSet(numFeatures);
for (int fi = 0; fi < numFeatures; fi++) {
if (counts[fi] > pruneCount.value) {
bs.set(fi);
}
}
logger.info ("Pruning "+(numFeatures-bs.cardinality())+" features out of "+numFeatures
+"; leaving "+(bs.cardinality())+" features.");
FeatureSelection fs = new FeatureSelection (instances.getDataAlphabet(), bs);
for (int ii = 0; ii < instances.size(); ii++) {
Instance instance = instances.get(ii);
FeatureVector fv = (FeatureVector) instance.getData();
FeatureVector fv2 = FeatureVector.newFeatureVector (fv, alpha2, fs);
instances2.add(new Instance(fv2, instance.getTarget(), instance.getName(), instance.getSource()),
instances.getInstanceWeight(ii));
instance.unLock();
instance.setData(null); // So it can be freed by the garbage collector
}
instances = instances2;
}
else {
throw new UnsupportedOperationException("Pruning features from " +
firstInstance.getClass().getName() +
" is not currently supported");
}
}
if (pruneInfogain.value > 0) {
Alphabet alpha2 = new Alphabet ();
Noop pipe2 = new Noop (alpha2, instances.getTargetAlphabet());
InstanceList instances2 = new InstanceList (pipe2);
InfoGain ig = new InfoGain (instances);
FeatureSelection fs = new FeatureSelection (ig, pruneInfogain.value);
for (int ii = 0; ii < instances.size(); ii++) {
Instance instance = instances.get(ii);
FeatureVector fv = (FeatureVector) instance.getData();
FeatureVector fv2 = FeatureVector.newFeatureVector (fv, alpha2, fs);
instance.unLock();
instance.setData(null); // So it can be freed by the garbage collector
instances2.add(pipe2.instanceFrom(new Instance(fv2, instance.getTarget(), instance.getName(), instance.getSource())),
instances.getInstanceWeight(ii));
}
instances = instances2;
}
if (vectorToSequence.value) {
// Convert FeatureVector's to FeatureSequence's by simply randomizing the order
// of all the word occurrences, including repetitions due to values larger than 1.
Alphabet alpha = instances.getDataAlphabet();
Noop pipe2 = new Noop (alpha, instances.getTargetAlphabet());
InstanceList instances2 = new InstanceList (pipe2);
for (int ii = 0; ii < instances.size(); ii++) {
Instance instance = instances.get(ii);
FeatureVector fv = (FeatureVector) instance.getData();
ArrayList seq = new ArrayList();
for (int loc = 0; loc < fv.numLocations(); loc++)
for (int count = 0; count < fv.valueAtLocation(loc); count++)
seq.add (new Integer(fv.indexAtLocation(loc)));
Collections.shuffle(seq);
int[] indices = new int[seq.size()];
for (int i = 0; i < indices.length; i++)
indices[i] = ((Integer)seq.get(i)).intValue();
FeatureSequence fs = new FeatureSequence (alpha, indices);
instance.unLock();
instance.setData(null); // So it can be freed by the garbage collector
instances2.add(pipe2.instanceFrom(new Instance(fs, instance.getTarget(), instance.getName(), instance.getSource())),
instances.getInstanceWeight(ii));
}
instances = instances2;
}
if (outputFile.wasInvoked()) {
writeInstanceList (instances, outputFile.value());
}
else if (trainingFile.wasInvoked()) {
writeInstanceList (instances, trainingFile.value());
}
else {
throw new IllegalArgumentException("You must specify a file to write to, using --output [filename]");
}
}
else if (trainingProportion.wasInvoked() || validationProportion.wasInvoked()) {
// Split into three lists...
InstanceList[] instanceLists = instances.split (r, new double[] {t, 1-t-v, v});
// And write them out
if (instanceLists[0].size() > 0)
writeInstanceList(instanceLists[0], trainingFile.value());
if (instanceLists[1].size() > 0)
writeInstanceList(instanceLists[1], testFile.value());
if (instanceLists[2].size() > 0)
writeInstanceList(instanceLists[2], validationFile.value());
}
else if (hideTargets.wasInvoked()) {
Iterator<Instance> iter = instances.iterator();
while (iter.hasNext()) {
Instance instance = iter.next();
instance.unLock();
instance.setProperty("target", instance.getTarget());
instance.setTarget(null);
instance.lock();
}
writeInstanceList (instances, outputFile.value());
}
else if (revealTargets.wasInvoked()) {
Iterator<Instance> iter = instances.iterator();
while (iter.hasNext()) {
Instance instance = iter.next();
instance.unLock();
instance.setTarget(instance.getProperty("target"));
instance.lock();
}
writeInstanceList (instances, outputFile.value());
}
}
private static void writeInstanceList(InstanceList instances, File file)
throws FileNotFoundException, IOException {
logger.info ("Writing instance list to "+file);
instances.save(file);
}
}
|
package ch.ffhs.esa.bewegungsmelder;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.FragmentManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import ch.ffhs.esa.bewegungsmelder.KontaktDBContract.KontaktTabelle;
public class AddContact extends Activity {
private static final int ADD_KONTAKT_DIALOG = 1;
private static final String TAG = AddContact.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
// Show the Up button in the action bar.
setupActionBar();
updateList();
}
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_contact, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void contactAdd (View view){
/*
Intent intent = new Intent(this, KontaktManuellHinzu.class);
startActivity(intent);
*/
FragmentManager manager = getFragmentManager();
KontaktDialogFragment d = new KontaktDialogFragment ();
d.show(manager, "KontaktDialogFragment");
}
public void updateList(){
Log.d(TAG, "Updating List");
List<Kontakt> updatelist = new ArrayList<Kontakt>();
//ArrayList<String> updatelist = new ArrayList<String>();
KontaktDBHelper mDbHelper = new KontaktDBHelper(this);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
KontaktTabelle._ID,
KontaktTabelle.COLUMN_NAME_NAME,
KontaktTabelle.COLUMN_NAME_NUMBER,
};
Cursor c = null;
try {
c = db.query(KontaktTabelle.TABLE_NAME, projection, null, null, null, null, null);
} catch (Exception e) {
c = db.rawQuery("SELECT * FROM " + KontaktTabelle.TABLE_NAME, null);
for (int i = 0; i < c.getColumnCount();i++){
Log.d(TAG, "Catched an exception on query!!!! Raw Query of column " +i + ":" + c.getColumnName(i) );
}
e.printStackTrace();
}
Log.d(TAG, "Cursor: " + c.toString());
if (c.moveToFirst()){
do {
String name = c.getString(1);
String phoneNumber = c.getString(2);
Kontakt objContact = new Kontakt();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
updatelist.add(objContact);
} while (c.moveToNext());
}
KontaktAdapter objAdapter = new KontaktAdapter(this, R.layout.alluser_row, updatelist);
setContentView(R.layout.activity_add_contact);
ListView list = (ListView) findViewById(R.id.updateList);
list.setAdapter(objAdapter);
}
};
|
package com.android.email.activity;
//import android.os.Debug;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.util.Config;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import com.android.email.K9ListActivity;
import com.android.email.Account;
import com.android.email.Email;
import com.android.email.MessagingController;
import com.android.email.MessagingListener;
import com.android.email.R;
import com.android.email.Utility;
import com.android.email.MessagingController.SORT_TYPE;
import com.android.email.activity.setup.FolderSettings;
import com.android.email.mail.Address;
import com.android.email.mail.Flag;
import com.android.email.mail.Folder;
import com.android.email.mail.Message;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Store;
import com.android.email.mail.Message.RecipientType;
import com.android.email.mail.store.LocalStore;
import com.android.email.mail.store.LocalStore.LocalFolder;
import com.android.email.mail.store.LocalStore.LocalMessage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* MessageList is the primary user interface for the program. This
* Activity shows a two level list of the Account's folders and each folder's
* messages. From this Activity the user can perform all standard message
* operations.
*
*
* TODO Break out seperate functions for: refresh local folders refresh remote
* folders refresh open folder local messages refresh open folder remote
* messages
*
* And don't refresh remote folders ever unless the user runs a refresh. Maybe
* not even then.
*/
public class MessageList extends K9ListActivity {
private static final String INTENT_DATA_PATH_SUFFIX = "/accounts";
private static final int DIALOG_MARK_ALL_AS_READ = 1;
private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1;
private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2;
private static final boolean FORCE_REMOTE_SYNC = true;
private static final String EXTRA_ACCOUNT = "account";
private static final String EXTRA_STARTUP = "startup";
private static final String EXTRA_CLEAR_NOTIFICATION = "clearNotification";
private static final String EXTRA_FOLDER = "folder";
private static final String STATE_KEY_LIST = "com.android.email.activity.messagelist_state";
private static final String STATE_CURRENT_FOLDER = "com.android.email.activity.messagelist_folder";
private static final String STATE_KEY_SELECTION = "com.android.email.activity.messagelist_selection";
private static final int[] colorChipResIds = new int[] {
R.drawable.appointment_indicator_leftside_1,
R.drawable.appointment_indicator_leftside_2,
R.drawable.appointment_indicator_leftside_3,
R.drawable.appointment_indicator_leftside_4,
R.drawable.appointment_indicator_leftside_5,
R.drawable.appointment_indicator_leftside_6,
R.drawable.appointment_indicator_leftside_7,
R.drawable.appointment_indicator_leftside_8,
R.drawable.appointment_indicator_leftside_9,
R.drawable.appointment_indicator_leftside_10,
R.drawable.appointment_indicator_leftside_11,
R.drawable.appointment_indicator_leftside_12,
R.drawable.appointment_indicator_leftside_13,
R.drawable.appointment_indicator_leftside_14,
R.drawable.appointment_indicator_leftside_15,
R.drawable.appointment_indicator_leftside_16,
R.drawable.appointment_indicator_leftside_17,
R.drawable.appointment_indicator_leftside_18,
R.drawable.appointment_indicator_leftside_19,
R.drawable.appointment_indicator_leftside_20,
R.drawable.appointment_indicator_leftside_21,
};
private ListView mListView;
private int colorChipResId;
private MessageListAdapter mAdapter;
private FolderInfoHolder mCurrentFolder;
private LayoutInflater mInflater;
private Account mAccount;
/**
* Stores the name of the folder that we want to open as soon as possible
* after load. It is set to null once the folder has been opened once.
*/
private String mFolderName;
private boolean mRestoringState;
private boolean mRefreshRemote;
private MessageListHandler mHandler = new MessageListHandler();
private DateFormat dateFormat = null;
private DateFormat timeFormat = null;
private SORT_TYPE sortType = SORT_TYPE.SORT_DATE;
private boolean sortAscending = true;
private boolean sortDateAscending = false;
private boolean mStartup = false;
private static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 1, 120000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
private DateFormat getDateFormat() {
if (dateFormat == null) {
String dateFormatS = android.provider.Settings.System.getString(getContentResolver(),
android.provider.Settings.System.DATE_FORMAT);
if (dateFormatS != null) {
dateFormat = new java.text.SimpleDateFormat(dateFormatS);
} else {
dateFormat = new java.text.SimpleDateFormat(Email.BACKUP_DATE_FORMAT);
}
}
return dateFormat;
}
private DateFormat getTimeFormat() {
if (timeFormat == null) {
String timeFormatS = android.provider.Settings.System.getString(getContentResolver(),
android.provider.Settings.System.TIME_12_24);
boolean b24 = !(timeFormatS == null || timeFormatS.equals("12"));
timeFormat = new java.text.SimpleDateFormat(b24 ? Email.TIME_FORMAT_24 : Email.TIME_FORMAT_12);
}
return timeFormat;
}
private void clearFormats() {
dateFormat = null;
timeFormat = null;
}
class MessageListHandler extends Handler {
private static final int MSG_PROGRESS = 2;
private static final int MSG_DATA_CHANGED = 3;
private static final int MSG_FOLDER_LOADING = 7;
private static final int MSG_REMOVE_MESSAGE = 11;
private static final int MSG_SYNC_MESSAGES = 13;
private static final int MSG_FOLDER_SYNCING = 18;
private static final int MSG_SENDING_OUTBOX = 19;
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_PROGRESS:
showProgressIndicator(msg.arg1 != 0 );
break;
case MSG_DATA_CHANGED:
mAdapter.notifyDataSetChanged();
break;
case MSG_REMOVE_MESSAGE: {
FolderInfoHolder folder = (FolderInfoHolder)((Object[]) msg.obj)[0];
MessageInfoHolder message = (MessageInfoHolder)((Object[]) msg.obj)[1];
folder.messages.remove(message);
mAdapter.notifyDataSetChanged();
break;
}
case MSG_SYNC_MESSAGES: {
FolderInfoHolder folder = (FolderInfoHolder)((Object[]) msg.obj)[0];
Message[] messages = (Message[])((Object[]) msg.obj)[1];
for(MessageInfoHolder message : mAdapter.messages) {
message.dirty = true;
}
for (Message message : messages) {
mAdapter.addOrUpdateMessage(folder, message, true, false);
mAdapter.notifyDataSetChanged();
}
mAdapter.removeDirtyMessages();
break;
}
case MSG_FOLDER_SYNCING: {
String folderName = (String)((Object[]) msg.obj)[0];
String dispString;
dispString = mAccount.getDescription();
if (folderName != null) {
dispString += " (" + getString(R.string.status_loading)
+ folderName + ")";
}
setTitle(dispString);
break;
}
case MSG_FOLDER_LOADING:
{
FolderInfoHolder folder = mAdapter.getFolder((String) msg.obj);
if (folder != null)
{
folder.loading = msg.arg1 != 0;
mAdapter.notifyDataSetChanged();
}
break;
}
case MSG_SENDING_OUTBOX: {
boolean sending = (msg.arg1 != 0);
String dispString;
dispString = mAccount.getDescription();
if (sending) {
dispString += " (" + getString(R.string.status_sending) + ")";
}
setTitle(dispString);
break;
}
default:
super.handleMessage(msg);
}
}
public void synchronizeMessages(FolderInfoHolder folder, Message[] messages) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_SYNC_MESSAGES;
msg.obj = new Object[] { folder, messages };
sendMessage(msg);
}
public void removeMessage(MessageInfoHolder message) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_REMOVE_MESSAGE;
msg.obj = new Object[] { message.folder, message };
sendMessage(msg);
}
public void folderLoading(String folder, boolean loading) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_FOLDER_LOADING;
msg.arg1 = loading ? 1 : 0;
msg.obj = folder;
sendMessage(msg);
}
public void progress(boolean progress) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_PROGRESS;
msg.arg1 = progress ? 1 : 0;
sendMessage(msg);
}
public void dataChanged() {
sendEmptyMessage(MSG_DATA_CHANGED);
}
public void folderSyncing(String folder) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_FOLDER_SYNCING;
msg.obj = new String[]
{ folder };
sendMessage(msg);
}
public void sendingOutbox(boolean sending) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_SENDING_OUTBOX;
msg.arg1 = sending ? 1 : 0;
sendMessage(msg);
}
}
/**
* This class is responsible for reloading the list of local messages for a
* given folder, notifying the adapter that the message have been loaded and
* queueing up a remote update of the folder.
*/
public static void actionHandleFolder(Context context, Account account, String folder, boolean startup) {
Intent intent = new Intent(context, MessageList.class);
intent.putExtra(EXTRA_ACCOUNT, account);
intent.putExtra(EXTRA_STARTUP, startup);
if (folder != null) {
intent.putExtra(EXTRA_FOLDER, folder);
}
context.startActivity(intent);
}
@Override
public void onCreate(Bundle savedInstanceState) {
//Debug.startMethodTracing("k9");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
mListView = getListView();
mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
mListView.setLongClickable(true);
//mListView.setFastScrollEnabled(true); // XXX TODO - reenable when we switch to 1.5
mListView.setScrollingCacheEnabled(true);
registerForContextMenu(mListView);
/*
* We manually save and restore the list's state because our adapter is
* slow.
*/
mListView.setSaveEnabled(false);
mInflater = getLayoutInflater();
Intent intent = getIntent();
mAccount = (Account)intent.getSerializableExtra(EXTRA_ACCOUNT);
mStartup = (boolean)intent.getBooleanExtra(EXTRA_STARTUP, false);
// Take the initial folder into account only if we are *not* restoring the
// activity already
if (savedInstanceState == null) {
mFolderName = intent.getStringExtra(EXTRA_FOLDER);
if (mFolderName == null) {
mFolderName = mAccount.getAutoExpandFolderName();
}
} else {
mFolderName = savedInstanceState.getString(STATE_CURRENT_FOLDER);
}
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int itemPosition, long id){
if ((itemPosition+1) == (mAdapter.getCount() )) {
MessagingController.getInstance(getApplication()).loadMoreMessages(
mAccount,
mFolderName,
mAdapter.mListener);
onRefresh(FORCE_REMOTE_SYNC);
return;
} else {
MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem( itemPosition);
onOpenMessage( message);
}
}
});
/*
* Since the color chip is always the same color for a given account we just
* cache the id of the chip right here.
*/
colorChipResId = colorChipResIds[mAccount.getAccountNumber() % colorChipResIds.length];
mAdapter = new MessageListAdapter();
mCurrentFolder = mAdapter.getFolder(mFolderName);
setListAdapter(mAdapter);
if (savedInstanceState != null) {
mRestoringState = true;
onRestoreListState(savedInstanceState);
mRestoringState = false;
}
setTitle(
mAccount.getDescription()
+ " - " +
mCurrentFolder.displayName
);
}
private void onRestoreListState(Bundle savedInstanceState) {
String currentFolder = savedInstanceState.getString(STATE_CURRENT_FOLDER);
int selectedChild = savedInstanceState.getInt( STATE_KEY_SELECTION, -1);
if (selectedChild != 0 ){
mListView.setSelection(selectedChild);
}
if (currentFolder != null ) {
mCurrentFolder = mAdapter.getFolder(currentFolder);
}
mListView.onRestoreInstanceState(savedInstanceState.getParcelable(STATE_KEY_LIST));
}
@Override
public void onPause() {
super.onPause();
//Debug.stopMethodTracing();
MessagingController.getInstance(getApplication()).removeListener( mAdapter.mListener);
}
/**
* On resume we refresh
* messages for any folder that is currently open. This guarantees that things
* like unread message count and read status are updated.
*/
@Override
public void onResume() {
super.onResume();
clearFormats();
sortType = MessagingController.getInstance(getApplication()).getSortType();
sortAscending = MessagingController.getInstance(getApplication()).isSortAscending(sortType);
sortDateAscending = MessagingController.getInstance(getApplication()).isSortAscending(SORT_TYPE.SORT_DATE);
MessagingController.getInstance(getApplication()).addListener( mAdapter.mListener);
onRefresh(!FORCE_REMOTE_SYNC);
NotificationManager notifMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(mAccount.getAccountNumber());
notifMgr.cancel(-1000 - mAccount.getAccountNumber());
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(STATE_KEY_LIST, mListView.onSaveInstanceState());
outState.putInt(STATE_KEY_SELECTION, mListView .getSelectedItemPosition());
outState.putString(STATE_CURRENT_FOLDER, mCurrentFolder.name);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Shortcuts that work no matter what is selected
switch (keyCode) {
case KeyEvent.KEYCODE_C: { onCompose(); return true;}
case KeyEvent.KEYCODE_Q: { onShowFolderList(); return true; }
case KeyEvent.KEYCODE_O: { onCycleSort(); return true; }
case KeyEvent.KEYCODE_I: { onToggleSortAscending(); return true; }
case KeyEvent.KEYCODE_H: {
Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG);
toast.show();
return true;
}
}//switch
int position = mListView.getSelectedItemPosition();
try {
if (position >= 0 ) {
MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position);
if (message != null) {
switch (keyCode) {
case KeyEvent.KEYCODE_DEL: { onDelete(message, position); return true;}
case KeyEvent.KEYCODE_D: { onDelete(message, position); return true;}
case KeyEvent.KEYCODE_F: { onForward(message); return true;}
case KeyEvent.KEYCODE_A: { onReplyAll(message); return true; }
case KeyEvent.KEYCODE_R: { onReply(message); return true; }
case KeyEvent.KEYCODE_G: { onToggleFlag(message); return true; }
case KeyEvent.KEYCODE_M: { onMove(message); return true; }
case KeyEvent.KEYCODE_Y: { onCopy(message); return true; }
case KeyEvent.KEYCODE_Z: { onToggleRead(message); return true; }
}
}
}
} finally {
return super.onKeyDown(keyCode, event);
}
}//onKeyDown
private void onRefresh(final boolean forceRemote) {
if (forceRemote) {
mRefreshRemote = true;
}
new Thread() {
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
if (forceRemote) {
MessagingController.getInstance(getApplication()).synchronizeMailbox( mAccount, mFolderName, mAdapter.mListener);
MessagingController.getInstance(getApplication()).sendPendingMessages(mAccount, null);
}
MessagingController.getInstance(getApplication()).listLocalMessages(mAccount, mFolderName, mAdapter.mListener);
}
}
.start();
}
private void onOpenMessage( MessageInfoHolder message) {
/*
* We set read=true here for UI performance reasons. The actual value will
* get picked up on the refresh when the Activity is resumed but that may
* take a second or so and we don't want this to show and then go away. I've
* gone back and forth on this, and this gives a better UI experience, so I
* am putting it back in.
*/
if (!message.read) {
message.read = true;
mHandler.dataChanged();
}
if (message.folder.name.equals(mAccount.getDraftsFolderName())) {
MessageCompose.actionEditDraft(this, mAccount, message.message);
} else {
ArrayList<String> folderUids = new ArrayList<String>();
for (MessageInfoHolder holder : mAdapter.messages) {
folderUids.add(holder.uid);
}
MessageView.actionView(this, mAccount, message.folder.name, message.uid, folderUids);
}
}
private void onShowFolderList() {
// If we're a child activity (say because Welcome dropped us straight to the message list
// we won't have a parent activity and we'll need to get back to it
if (mStartup
|| isTaskRoot()) {
FolderList.actionHandleAccount(this, mAccount, false);
}
finish();
}
private void onCompose() {
MessageCompose.actionCompose(this, mAccount);
}
private void changeSort(SORT_TYPE newSortType) {
sortType = newSortType;
MessagingController.getInstance(getApplication()).setSortType(sortType);
sortAscending = MessagingController.getInstance(getApplication()).isSortAscending(sortType);
sortDateAscending = MessagingController.getInstance(getApplication()).isSortAscending(SORT_TYPE.SORT_DATE);
reSort();
}
private void reSort() {
int toastString = sortType.getToast(sortAscending);
Toast toast = Toast.makeText(this, toastString, Toast.LENGTH_SHORT);
toast.show();
sortMessages();
mAdapter.notifyDataSetChanged();
}
private void sortMessages()
{
synchronized(mAdapter.messages)
{
Collections.sort(mAdapter.messages);
}
}
private void onCycleSort() {
SORT_TYPE[] sorts = SORT_TYPE.values();
int curIndex = 0;
for (int i = 0; i < sorts.length; i++) {
if (sorts[i] == sortType) {
curIndex = i;
break;
}
}
curIndex++;
if (curIndex == sorts.length) {
curIndex = 0;
}
changeSort(sorts[curIndex]);
}
private void onToggleSortAscending() {
MessagingController.getInstance(getApplication()).setSortAscending(sortType, !sortAscending);
sortAscending = MessagingController.getInstance(getApplication()).isSortAscending(sortType);
sortDateAscending = MessagingController.getInstance(getApplication()).isSortAscending(SORT_TYPE.SORT_DATE);
reSort();
}
private void onDelete(MessageInfoHolder holder, int position) {
if (holder.read == false && holder.folder.unreadMessageCount > 0) {
holder.folder.unreadMessageCount
}
FolderInfoHolder trashHolder = mAdapter.getFolder(mAccount.getTrashFolderName());
if (trashHolder != null) {
trashHolder.needsRefresh = true;
}
mAdapter.removeMessage(holder);
mListView.setSelection(position);
MessagingController.getInstance(getApplication()).deleteMessage(mAccount, holder.message.getFolder().getName(), holder.message, null);
}
private void onMove(MessageInfoHolder holder) {
if (MessagingController.getInstance(getApplication()).isMoveCapable(mAccount) == false) {
return;
}
if (MessagingController.getInstance(getApplication()).isMoveCapable(holder.message) == false) {
Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
Intent intent = new Intent(this, ChooseFolder.class);
intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount);
intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name);
intent.putExtra(ChooseFolder.EXTRA_MESSAGE_UID, holder.message.getUid());
startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE);
}
private void onCopy(MessageInfoHolder holder) {
if (MessagingController.getInstance(getApplication()).isCopyCapable(mAccount) == false) {
return;
}
if (MessagingController.getInstance(getApplication()).isCopyCapable(holder.message) == false) {
Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
Intent intent = new Intent(this, ChooseFolder.class);
intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount);
intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name);
intent.putExtra(ChooseFolder.EXTRA_MESSAGE_UID, holder.message.getUid());
startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case ACTIVITY_CHOOSE_FOLDER_MOVE:
case ACTIVITY_CHOOSE_FOLDER_COPY:
if (data == null)
return;
String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER);
String srcFolderName = data.getStringExtra(ChooseFolder.EXTRA_CUR_FOLDER);
String uid = data.getStringExtra(ChooseFolder.EXTRA_MESSAGE_UID);
FolderInfoHolder srcHolder = mAdapter.getFolder(srcFolderName);
FolderInfoHolder destHolder = mAdapter.getFolder(destFolderName);
if (srcHolder != null && destHolder != null) {
MessageInfoHolder m = mAdapter.getMessage( uid);
if (m != null) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FOLDER_MOVE:
onMoveChosen(m, destHolder);
break;
case ACTIVITY_CHOOSE_FOLDER_COPY:
onCopyChosen(m, destHolder);
break;
}
}
}
}
}
private void onMoveChosen(MessageInfoHolder holder, FolderInfoHolder folder) {
if (MessagingController.getInstance(getApplication()).isMoveCapable(mAccount) == false) {
return;
}
// String destFolderName = folder.name;
// FolderInfoHolder destHolder = mAdapter.getFolder(destFolderName);
if (folder == null) {
return;
}
if (holder.read == false) {
if (holder.folder.unreadMessageCount > 0) {
holder.folder.unreadMessageCount
}
folder.unreadMessageCount++;
}
folder.needsRefresh = true;
mAdapter.removeMessage(holder);
MessagingController.getInstance(getApplication()).moveMessage(mAccount, holder.message.getFolder().getName(), holder.message, folder.name, null);
}
private void onCopyChosen(MessageInfoHolder holder, FolderInfoHolder folder) {
if (MessagingController.getInstance(getApplication()).isCopyCapable(mAccount) == false) {
return;
}
if (folder == null) {
return;
}
if (holder.read == false) {
folder.unreadMessageCount++;
}
folder.needsRefresh = true;
MessagingController.getInstance(getApplication()).copyMessage(mAccount,
holder.message.getFolder().getName(), holder.message, folder.name, null);
}
private void onReply(MessageInfoHolder holder) {
MessageCompose.actionReply(this, mAccount, holder.message, false);
}
private void onReplyAll(MessageInfoHolder holder) {
MessageCompose.actionReply(this, mAccount, holder.message, true);
}
private void onForward(MessageInfoHolder holder) {
MessageCompose.actionForward(this, mAccount, holder.message);
}
private Account mSelectedContextAccount = null;
private FolderInfoHolder mSelectedContextFolder = null;
private void onMarkAllAsRead(final Account account, final String folder) {
mSelectedContextAccount = account;
mSelectedContextFolder = mAdapter.getFolder(folder);
showDialog(DIALOG_MARK_ALL_AS_READ);
}
@Override
public Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_MARK_ALL_AS_READ:
return createMarkAllAsReadDialog();
}
return super.onCreateDialog(id);
}
public void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_MARK_ALL_AS_READ:
((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt,
mSelectedContextFolder.displayName));
break;
default:
super.onPrepareDialog(id, dialog);
}
}
private Dialog createMarkAllAsReadDialog() {
return new AlertDialog.Builder(this)
.setTitle(R.string.mark_all_as_read_dlg_title)
.setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt,
mSelectedContextFolder.displayName))
.setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_MARK_ALL_AS_READ);
try {
MessagingController.getInstance(getApplication()).markAllMessagesRead(mSelectedContextAccount, mSelectedContextFolder.name);
for (MessageInfoHolder holder : mSelectedContextFolder.messages) {
holder.read = true;
}
mSelectedContextFolder.unreadMessageCount = 0;
mHandler.dataChanged();
} catch (Exception e) {
// Ignore
}
}
})
.setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_MARK_ALL_AS_READ);
}
})
.create();
}
private void onToggleRead(MessageInfoHolder holder) {
holder.folder.unreadMessageCount += (holder.read ? 1 : -1);
if (holder.folder.unreadMessageCount < 0) {
holder.folder.unreadMessageCount = 0;
}
MessagingController.getInstance(getApplication()).markMessageRead(mAccount, holder.message.getFolder().getName(), holder.uid, !holder.read);
holder.read = !holder.read;
mHandler.dataChanged();
}
private void onToggleFlag(MessageInfoHolder holder) {
MessagingController.getInstance(getApplication()).setMessageFlag(mAccount, holder.message.getFolder().getName(), holder.uid, Flag.FLAGGED, !holder.flagged);
holder.flagged = !holder.flagged;
mHandler.dataChanged();
}
// private void checkMail(final Account account) {
// MessagingController.getInstance(getApplication()).checkMail(this, account, true, true, mAdapter.mListener);
private void checkMail(Account account, String folderName) {
MessagingController.getInstance(getApplication()).synchronizeMailbox( account, folderName, mAdapter.mListener);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.check_mail:
checkMail(mAccount, mFolderName);
return true;
case R.id.compose:
onCompose();
return true;
case R.id.set_sort_date:
changeSort(SORT_TYPE.SORT_DATE);
return true;
case R.id.set_sort_subject:
changeSort(SORT_TYPE.SORT_SUBJECT);
return true;
case R.id.set_sort_sender:
changeSort(SORT_TYPE.SORT_SENDER);
return true;
case R.id.set_sort_flag:
changeSort(SORT_TYPE.SORT_FLAGGED);
return true;
case R.id.set_sort_unread:
changeSort(SORT_TYPE.SORT_UNREAD);
return true;
case R.id.set_sort_attach:
changeSort(SORT_TYPE.SORT_ATTACHMENT);
return true;
case R.id.reverse_sort:
onToggleSortAscending();
return true;
case R.id.list_folders:
onShowFolderList();
return true;
case R.id.mark_all_as_read:
onMarkAllAsRead(mAccount, mFolderName);
return true;
case R.id.folder_settings:
FolderSettings.actionSettings(this, mAccount, mFolderName);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.message_list_option, menu);
return true;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo();
MessageInfoHolder holder = (MessageInfoHolder) mAdapter.getItem(info.position);
switch (item.getItemId()) {
case R.id.open:
onOpenMessage(holder);
break;
case R.id.delete:
onDelete(holder, info.position);
break;
case R.id.reply:
onReply(holder);
break;
case R.id.reply_all:
onReplyAll(holder);
break;
case R.id.forward:
onForward(holder);
break;
case R.id.mark_as_read:
onToggleRead(holder);
break;
case R.id.flag:
onToggleFlag(holder);
break;
case R.id.move:
onMove(holder);
break;
case R.id.copy:
onCopy(holder);
break;
case R.id.send_alternate:
onSendAlternate(mAccount, holder);
break;
}
return super.onContextItemSelected(item);
}
public void onSendAlternate(Account account, MessageInfoHolder holder) {
MessagingController.getInstance(getApplication()).sendAlternate(this, account, holder.message);
}
public void showProgressIndicator(boolean status) {
setProgressBarIndeterminateVisibility(status);
ProgressBar bar = (ProgressBar)mListView.findViewById( R.id.message_list_progress);
if (bar == null) {
return;
}
bar.setIndeterminate(true);
if (status) {
bar.setVisibility(bar.VISIBLE);
} else {
bar.setVisibility(bar.INVISIBLE);
}
}
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(info.position );
if (message == null) {
return;
}
getMenuInflater().inflate(R.menu.message_list_context, menu);
menu.setHeaderTitle((CharSequence) message.subject);
if (message.read) {
menu.findItem(R.id.mark_as_read).setTitle( R.string.mark_as_unread_action);
}
if (message.flagged) {
menu.findItem(R.id.flag).setTitle( R.string.unflag_action);
}
if (MessagingController.getInstance(getApplication()).isCopyCapable(mAccount) == false) {
menu.findItem(R.id.copy).setVisible(false);
}
if (MessagingController.getInstance(getApplication()).isMoveCapable(mAccount) == false) {
menu.findItem(R.id.move).setVisible(false);
}
}
private String truncateStatus(String mess) {
if (mess != null && mess.length() > 27) {
mess = mess.substring(0, 27);
}
return mess;
}
class MessageListAdapter extends BaseAdapter {
private List<MessageInfoHolder> messages = java.util.Collections.synchronizedList(new ArrayList<MessageInfoHolder>());
private MessagingListener mListener = new MessagingListener() {
@Override
public void synchronizeMailboxStarted(Account account, String folder) {
if (!account.equals(mAccount) || !folder.equals(mFolderName)) {
return;
}
mHandler.progress(true);
mHandler.folderLoading(folder, true);
mHandler.folderSyncing(folder);
}
@Override
public void synchronizeMailboxFinished(Account account, String folder,
int totalMessagesInMailbox, int numNewMessages) {
if (!account.equals(mAccount) || !folder.equals(mFolderName)) {
return;
}
mHandler.progress(false);
mHandler.folderLoading(folder, false);
mHandler.folderSyncing(null);
}
@Override
public void synchronizeMailboxFailed(Account account, String folder, String message) {
if (!account.equals(mAccount) || !folder.equals(mFolderName)) {
return;
}
Toast.makeText(MessageList.this, message, Toast.LENGTH_LONG).show();
mHandler.progress(false);
mHandler.folderLoading(folder, false);
mHandler.folderSyncing(null);
}
@Override
public void synchronizeMailboxNewMessage(Account account, String folder, Message message) {
if (!account.equals(mAccount) || !folder.equals(mFolderName)) {
return;
}
addOrUpdateMessage(folder, message, true, true);
}
@Override
public void synchronizeMailboxRemovedMessage(Account account, String folder,Message message) {
removeMessage(getMessage( message.getUid()));
}
@Override
public void listLocalMessagesStarted(Account account, String folder) {
if (!account.equals(mAccount)) {
return;
}
mHandler.progress(true);
mHandler.folderLoading(folder, true);
}
@Override
public void listLocalMessagesFailed(Account account, String folder, String message) {
if (!account.equals(mAccount)) {
return;
}
sortMessages();
mHandler.dataChanged();
mHandler.progress(false);
mHandler.folderLoading(folder, false);
}
@Override
public void listLocalMessagesFinished(Account account, String folder) {
if (!account.equals(mAccount)) {
return;
}
sortMessages();
mHandler.dataChanged();
mHandler.progress(false);
mHandler.folderLoading(folder, false);
}
@Override
public void listLocalMessages(Account account, String folder, Message[] messages) {
if (!account.equals(mAccount)) {
return;
}
if (folder != mFolderName) {
return;
}
//synchronizeMessages(folder, messages);
}
@Override
public void listLocalMessagesRemoveMessage(Account account, String folder,Message message) {
if (!account.equals(mAccount) || !folder.equals(mFolderName)) {
return;
}
MessageInfoHolder holder = getMessage(message.getUid());
if (holder != null ) {
removeMessage(getMessage( message.getUid()));
}
}
@Override
public void listLocalMessagesAddMessage(Account account, String folder, Message message) {
if (!account.equals(mAccount) || !folder.equals(mFolderName)) {
return;
}
addOrUpdateMessage(folder, message, false, false);//true, true);
if (mAdapter.messages.size() % 10 == 0 ) {
sortMessages();
mHandler.dataChanged();
}
}
@Override
public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) {
if (!account.equals(mAccount) || !folder.equals(mFolderName)) {
return;
}
addOrUpdateMessage(folder, message, false, true);
}
};
private Drawable mAttachmentIcon;
private Drawable mAnsweredIcon;
private View footerView = null;
MessageListAdapter() {
mAttachmentIcon = getResources().getDrawable( R.drawable.ic_mms_attachment_small);
mAnsweredIcon = getResources().getDrawable( R.drawable.ic_mms_answered_small);
}
public void removeDirtyMessages() {
Iterator<MessageInfoHolder> iter = messages.iterator();
while(iter.hasNext()) {
MessageInfoHolder message = iter.next();
if (message.dirty) {
iter.remove();
}
}
notifyDataSetChanged();
}
public void removeMessage(MessageInfoHolder holder) {
if (holder.folder == null) {
return;
}
if (holder == null) {
return;
}
mAdapter.messages.remove(holder);
mHandler.removeMessage(holder);
sortMessages();
mHandler.dataChanged();
}
public void synchronizeMessages(String folder, Message[] messages) {
FolderInfoHolder f = getFolder(folder);
if (f == null) {
return;
}
mHandler.synchronizeMessages(f, messages);
}
public void addOrUpdateMessage(String folder, Message message) {
addOrUpdateMessage(folder, message, true, true);
}
private void addOrUpdateMessage(FolderInfoHolder folder, Message message, boolean sort, boolean notify) {
MessageInfoHolder m = getMessage( message.getUid());
if (m == null) {
m = new MessageInfoHolder(message, folder);
mAdapter.messages.add(m);
} else {
m.populate(message, folder);
}
if (sort) {
sortMessages();
}
if (notify) {
mHandler.dataChanged();
}
}
private void addOrUpdateMessage(String folder, Message message, boolean sort, boolean notify) {
FolderInfoHolder f = getFolder(folder);
if (f == null) {
return;
}
addOrUpdateMessage(f, message, sort, notify);
}
// XXX TODO - make this not use a for loop
public MessageInfoHolder getMessage( String messageUid) {
MessageInfoHolder searchHolder = new MessageInfoHolder();
searchHolder.uid = messageUid;
int index = mAdapter.messages.indexOf((Object) searchHolder);
if (index >= 0) {
return (MessageInfoHolder)mAdapter.messages.get( index );
}
return null;
}
public FolderInfoHolder getFolder(String folder) {
try {
LocalStore localStore = (LocalStore)Store.getInstance( mAccount.getLocalStoreUri(), getApplication());
LocalFolder local_folder = localStore.getFolder(folder);
FolderInfoHolder holder = new FolderInfoHolder ((Folder)local_folder);
return holder;
} catch (Exception e) {
Log.e(Email.LOG_TAG, "getFolder(" + folder + ") goes boom: ",e);
return null;
}
}
private static final int NON_MESSAGE_ITEMS = 1;
public int getCount() {
if (mAdapter.messages == null || mAdapter.messages.size() == 0) {
return NON_MESSAGE_ITEMS ;
}
return mAdapter.messages.size() +NON_MESSAGE_ITEMS ;
}
public long getItemId(int position) {
try {
MessageInfoHolder messageHolder =(MessageInfoHolder) getItem(position);
if (messageHolder != null) {
return ((LocalStore.LocalMessage) messageHolder.message).getId();
}
} catch ( Exception e) {
Log.i(Email.LOG_TAG,"getItemId("+position+") ",e);
}
return -1;
}
public Object getItem(long position) {
return getItem((int)position);
}
public Object getItem(int position) {
try {
if (position < mAdapter.messages.size()) {
return mAdapter.messages.get(position);
}
} catch (Exception e) {
Log.e(Email.LOG_TAG, "getItem(" + position + "), but folder.messages.size() = " + mAdapter.messages.size(), e);
}
return null;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (position == mAdapter.messages.size() ) {
return getFooterView(position, convertView, parent);
} else {
return getItemView(position, convertView, parent);
}
}
public View getItemView(int position, View convertView, ViewGroup parent) {
MessageInfoHolder message = (MessageInfoHolder) getItem(position);
View view;
if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) {
view = convertView;
} else {
view = mInflater.inflate(R.layout.message_list_item, parent, false);
view.setId(R.layout.message_list_item);
}
MessageViewHolder holder = (MessageViewHolder) view.getTag();
if (holder == null) {
holder = new MessageViewHolder();
holder.subject = (TextView) view.findViewById(R.id.subject);
holder.from = (TextView) view.findViewById(R.id.from);
holder.date = (TextView) view.findViewById(R.id.date);
holder.chip = view.findViewById(R.id.chip);
holder.chip.setBackgroundResource(colorChipResId);
view.setTag(holder);
}
if (message != null) {
holder.chip.getBackground().setAlpha(message.read ? 0 : 255);
holder.subject.setTypeface(null, message.read && !message.flagged ? Typeface.NORMAL : Typeface.BOLD);
int subjectColor = holder.from.getCurrentTextColor(); // Get from another field that never changes color
if (message.flagged) {
subjectColor = Email.FLAGGED_COLOR;
}
if (message.downloaded) {
holder.chip.getBackground().setAlpha(message.read ? 0 : 127);
view.getBackground().setAlpha(0);
} else {
view.getBackground().setAlpha(127);
}
holder.subject.setTextColor( 0xff000000 | subjectColor);
holder.subject.setText(message.subject);
holder.from.setText(message.sender);
holder.from.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD);
holder.date.setText(message.date);
holder.subject.setCompoundDrawablesWithIntrinsicBounds(
message.answered ? mAnsweredIcon : null, // left
null, // top
message.hasAttachments ? mAttachmentIcon : null, // right
null); // bottom
} else {
holder.chip.getBackground().setAlpha(0);
holder.subject.setText("No subject");
holder.subject.setTypeface(null, Typeface.NORMAL);
holder.from.setText("No sender");
holder.from.setTypeface(null, Typeface.NORMAL);
holder.date.setText("No date");
holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
}
return view;
}
public View getFooterView(int position, View convertView, ViewGroup parent) {
if (footerView == null) {
footerView = mInflater.inflate(R.layout.message_list_item_footer, parent, false);
footerView.setId(R.layout.message_list_item_footer);
FooterViewHolder holder = new FooterViewHolder();
holder.progress = (ProgressBar)footerView.findViewById(R.id.message_list_progress);
holder.main = (TextView)footerView.findViewById(R.id.main_text);
footerView.setTag(holder);
}
FooterViewHolder holder = (FooterViewHolder)footerView.getTag();
if (mCurrentFolder.loading) {
holder.main.setText(getString(R.string.status_loading_more));
mHandler.progress(true);
} else {
if (mCurrentFolder.lastCheckFailed == false) {
holder.main.setText(String.format(getString(R.string.load_more_messages_fmt).toString(), mAccount.getDisplayCount()));
} else {
holder.main.setText(getString(R.string.status_loading_more_failed));
}
}
return footerView;
}
public boolean hasStableIds() {
return true;
}
public boolean isItemSelectable(int position) {
if ( position < mAdapter.messages.size() ) {
return true;
} else {
return false;
}
}
}
public class MessageInfoHolder implements Comparable<MessageInfoHolder> {
public String subject;
public String date;
public Date compareDate;
public String compareSubject;
public String sender;
public String compareCounterparty;
public String[] recipients;
public boolean hasAttachments;
public String uid;
public boolean read;
public boolean dirty;
public boolean answered;
public boolean flagged;
public boolean downloaded;
public boolean partially_downloaded;
public Message message;
public FolderInfoHolder folder;
// Empty constructor for comparison
public MessageInfoHolder() {}
public MessageInfoHolder(Message m, FolderInfoHolder folder) {
populate(m, folder);
}
public void populate(Message m, FolderInfoHolder folder) {
try {
LocalMessage message = (LocalMessage) m;
Date date = message.getSentDate();
this.compareDate = date;
this.folder = folder;
this.dirty = false;
if (Utility.isDateToday(date)) {
this.date = getTimeFormat().format(date);
} else {
this.date = getDateFormat().format(date);
}
this.hasAttachments = message.getAttachmentCount() > 0;
this.read = message.isSet(Flag.SEEN);
this.answered = message.isSet(Flag.ANSWERED);
this.flagged = message.isSet(Flag.FLAGGED);
this.downloaded = message.isSet(Flag.X_DOWNLOADED_FULL);
this.partially_downloaded = message.isSet(Flag.X_DOWNLOADED_PARTIAL);
Address[] addrs = message.getFrom();
if (addrs.length > 0 && mAccount.isAnIdentity(addrs[0])) {
this.compareCounterparty = Address.toFriendly(message .getRecipients(RecipientType.TO));
this.sender = String.format(getString(R.string.message_list_to_fmt), this.compareCounterparty);
} else {
this.sender = Address.toFriendly(addrs);
this.compareCounterparty = this.sender;
}
this.subject = message.getSubject();
this.uid = message.getUid();
this.message = m;
} catch (MessagingException me) {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "Unable to load message info", me);
}
}
}
public boolean equals(Object o) {
if (this.uid.equals(((MessageInfoHolder)o).uid)) {
return true;
} else {
return false;
}
}
public int compareTo(MessageInfoHolder o) {
int ascender = (sortAscending ? 1 : -1);
int comparison = 0;
if (sortType == SORT_TYPE.SORT_SUBJECT) {
if (compareSubject == null) {
compareSubject = stripPrefixes(subject).toLowerCase();
}
if (o.compareSubject == null) {
o.compareSubject = stripPrefixes(o.subject).toLowerCase();
}
comparison = this.compareSubject.compareTo(o.compareSubject);
} else if (sortType == SORT_TYPE.SORT_SENDER) {
comparison = this.compareCounterparty.toLowerCase().compareTo(o.compareCounterparty.toLowerCase());
} else if (sortType == SORT_TYPE.SORT_FLAGGED) {
comparison = (this.flagged ? 0 : 1) - (o.flagged ? 0 : 1);
} else if (sortType == SORT_TYPE.SORT_UNREAD) {
comparison = (this.read ? 1 : 0) - (o.read ? 1 : 0);
} else if (sortType == SORT_TYPE.SORT_ATTACHMENT) {
comparison = (this.hasAttachments ? 0 : 1) - (o.hasAttachments ? 0 : 1);
}
if (comparison != 0) {
return comparison * ascender;
}
int dateAscender = (sortDateAscending ? 1 : -1);
return this.compareDate.compareTo(o.compareDate) * dateAscender;
}
Pattern pattern = null;
String patternString = "^ *(re|fw|fwd): *";
private String stripPrefixes(String in) {
synchronized (patternString) {
if (pattern == null) {
pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
}
}
Matcher matcher = pattern.matcher(in);
int lastPrefix = -1;
while (matcher.find()) {
lastPrefix = matcher.end();
}
if (lastPrefix > -1 && lastPrefix < in.length() - 1) {
return in.substring(lastPrefix);
} else {
return in;
}
}
}
class MessageViewHolder {
public TextView subject;
public TextView preview;
public TextView from;
public TextView date;
public View chip;
}
class FooterViewHolder {
public ProgressBar progress;
public TextView main;
}
/* THERE IS NO FUCKING REASON THIS IS CLONED HERE */
public class FolderInfoHolder implements Comparable<FolderInfoHolder> {
public String name;
public String displayName;
public ArrayList<MessageInfoHolder> messages;
public long lastChecked;
public int unreadMessageCount;
public boolean loading;
public String status;
public boolean lastCheckFailed;
public boolean needsRefresh = false;
/**
* Outbox is handled differently from any other folder.
*/
public boolean outbox;
public int compareTo(FolderInfoHolder o) {
String s1 = this.name;
String s2 = o.name;
if (Email.INBOX.equalsIgnoreCase(s1)) {
return -1;
} else if (Email.INBOX.equalsIgnoreCase(s2)) {
return 1;
} else
return s1.compareToIgnoreCase(s2);
}
public FolderInfoHolder(Folder folder) {
populate(folder);
}
public void populate (Folder folder) {
int unreadCount = 0;
try {
folder.open(Folder.OpenMode.READ_WRITE);
unreadCount = folder.getUnreadMessageCount();
} catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Folder.getUnreadMessageCount() failed", me);
}
this.name = folder.getName();
if (this.name.equalsIgnoreCase(Email.INBOX)) {
this.displayName = getString(R.string.special_mailbox_name_inbox);
} else {
this.displayName = folder.getName();
}
if (this.name.equals(mAccount.getOutboxFolderName())) {
this.displayName = String.format( getString(R.string.special_mailbox_name_outbox_fmt), this.name);
this.outbox = true;
}
if (this.name.equals(mAccount.getDraftsFolderName())) {
this.displayName = String.format( getString(R.string.special_mailbox_name_drafts_fmt), this.name);
}
if (this.name.equals(mAccount.getTrashFolderName())) {
this.displayName = String.format( getString(R.string.special_mailbox_name_trash_fmt), this.name);
}
if (this.name.equals(mAccount.getSentFolderName())) {
this.displayName = String.format( getString(R.string.special_mailbox_name_sent_fmt), this.name);
}
if (this.messages == null) {
this.messages = new ArrayList<MessageInfoHolder>();
}
this.lastChecked = folder.getLastChecked();
String mess = truncateStatus(folder.getStatus());
this.status = mess;
this.unreadMessageCount = unreadCount;
try {
folder.close(false);
} catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Folder.close() failed", me);
}
}
}
}
|
package com.ecyrd.jspwiki.search;
import java.io.IOException;
import java.util.Collection;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.NoRequiredPropertyException;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.WikiPage;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Manages searching the Wiki.
*
* @author Arent-Jan Banck for Informatica
* @since 2.2.21.
*/
public class SearchManager
{
private static final Logger log = Logger.getLogger(SearchManager.class);
private static String DEFAULT_SEARCHPROVIDER = "com.ecyrd.jspwiki.LuceneSearchProvider";
public static final String PROP_USE_LUCENE = "jspwiki.useLucene";
public static final String PROP_SEARCHPROVIDER = "jspwiki.searchProvider";
private SearchProvider m_searchProvider = null;
public SearchManager( WikiEngine engine, Properties properties )
throws WikiException
{
initialize( engine, properties );
}
/**
* This particular method starts off indexing and all sorts of various activities,
* so you need to run this last, after things are done.
*
* @param engine
* @param properties
* @throws WikiException
*/
public void initialize(WikiEngine engine, Properties properties)
throws WikiException
{
loadSearchProvider(properties);
try
{
m_searchProvider.initialize(engine, properties);
}
catch (NoRequiredPropertyException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void loadSearchProvider(Properties properties)
{
// See if we're using Lucene, and if so, ensure that its
// index directory is up to date.
String useLucene = properties.getProperty(PROP_USE_LUCENE);
// FIXME: Obsolete, remove, or change logic to first load searchProvder?
// If the old jspwiki.useLucene property is set we use that instead of the searchProvider class.
if( useLucene != null )
{
log.info( PROP_USE_LUCENE+" is deprecated; please use "+PROP_SEARCHPROVIDER+"=<your search provider> instead." );
if( TextUtil.isPositive( useLucene ) )
{
m_searchProvider = new LuceneSearchProvider();
}
else
{
m_searchProvider = new BasicSearchProvider();
}
log.debug("useLucene was set, loading search provider " + m_searchProvider);
return;
}
String providerClassName = properties.getProperty( PROP_SEARCHPROVIDER,
DEFAULT_SEARCHPROVIDER );
try
{
Class providerClass = ClassUtil.findClass( "com.ecyrd.jspwiki.search", providerClassName );
m_searchProvider = (SearchProvider)providerClass.newInstance();
}
catch( ClassNotFoundException e )
{
log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e);
}
catch( InstantiationException e )
{
log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e);
}
catch( IllegalAccessException e )
{
log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e);
}
if( null == m_searchProvider )
{
// FIXME: Make a static with the default search provider
m_searchProvider = new BasicSearchProvider();
}
log.debug("Loaded search provider " + m_searchProvider);
}
public SearchProvider getSearchEngine()
{
return m_searchProvider;
}
public Collection findPages( String query )
{
return m_searchProvider.findPages( query );
}
/**
* Removes the page from the search cache (if any).
* @param page The page to remove
*/
public void deletePage(WikiPage page)
{
m_searchProvider.deletePage(page);
}
public void addToQueue(WikiPage page)
{
m_searchProvider.addToQueue(page);
}
}
|
package com.fullmetalgalaxy.model.persist;
import java.util.ArrayList;
import java.util.Date;
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 javax.persistence.Transient;
import com.fullmetalgalaxy.model.BoardFireCover;
import com.fullmetalgalaxy.model.EnuColor;
import com.fullmetalgalaxy.model.GameEventStack;
import com.fullmetalgalaxy.model.GameStatus;
import com.fullmetalgalaxy.model.HexCoordinateSystem;
import com.fullmetalgalaxy.model.HexTorusCoordinateSystem;
import com.fullmetalgalaxy.model.LandType;
import com.fullmetalgalaxy.model.Location;
import com.fullmetalgalaxy.model.MapShape;
import com.fullmetalgalaxy.model.Mobile;
import com.fullmetalgalaxy.model.RpcFmpException;
import com.fullmetalgalaxy.model.RpcUtil;
import com.fullmetalgalaxy.model.Sector;
import com.fullmetalgalaxy.model.SharedMethods;
import com.fullmetalgalaxy.model.Tide;
import com.fullmetalgalaxy.model.TokenType;
import com.fullmetalgalaxy.model.constant.ConfigGameTime;
import com.fullmetalgalaxy.model.constant.FmpConstant;
import com.fullmetalgalaxy.model.pathfinder.PathGraph;
import com.fullmetalgalaxy.model.pathfinder.PathMobile;
import com.fullmetalgalaxy.model.pathfinder.PathNode;
import com.fullmetalgalaxy.model.persist.gamelog.AnEvent;
import com.fullmetalgalaxy.model.persist.gamelog.EbEvtMessage;
import com.fullmetalgalaxy.model.persist.gamelog.EbEvtMove;
import com.fullmetalgalaxy.model.persist.gamelog.EventsPlayBuilder;
import com.fullmetalgalaxy.model.persist.triggers.EbTrigger;
/**
* @author Kroc
* This class represent the board model on both client/server side.
* ie: all data needed by the board application on client side to run correctly.
*/
public class Game extends GameData implements PathGraph, GameEventStack
{
private static final long serialVersionUID = -717221858626185781L;
transient private TokenIndexSet m_tokenIndexSet = null;
transient private GameEventStack m_eventStack = this;
transient private BoardFireCover m_fireCover = null;
transient private HexCoordinateSystem m_coordinateSystem = null;
public Game()
{
super();
init();
}
public Game(EbGamePreview p_preview, EbGameData p_data)
{
super(p_preview, p_data);
}
private void init()
{
setConfigGameTime( ConfigGameTime.Standard );
}
@Override
public void reinit()
{
super.reinit();
this.init();
}
public HexCoordinateSystem getCoordinateSystem()
{
if( m_coordinateSystem == null )
{
if( getMapShape() == MapShape.Flat )
{
m_coordinateSystem = new HexCoordinateSystem();
} else {
m_coordinateSystem = new HexTorusCoordinateSystem( getMapShape(), getLandWidth(),
getLandHeight() );
}
}
return m_coordinateSystem;
}
/**
*
* @return true if game message start with recording tag
*/
public boolean isRecordingScript()
{
return getMessage() != null
&& getMessage().startsWith( EventsPlayBuilder.GAME_MESSAGE_RECORDING_TAG );
}
/**
* if game is in parallel mode, search the registration that lock an hexagon.
* @param p_position
* @return null if no registration lock that hexagon
*/
public EbTeam getOtherTeamBoardLocked(EbRegistration p_myRegistration,
AnBoardPosition p_position, long p_currentTime)
{
if( !isParallel() || p_position == null || p_position.getX() < 0 )
{
return null;
}
for( EbTeam team : getTeams() )
{
if( p_myRegistration.getTeam( this ) != team && team.getEndTurnDate() != null
&& team.getLockedPosition() != null )
{
if( team.getEndTurnDate().getTime() < p_currentTime )
{
team.setEndTurnDate( null );
team.setLockedPosition( null );
}
else if( getCoordinateSystem().getDiscreteDistance(
team.getLockedPosition(), p_position ) <= FmpConstant.parallelLockRadius )
{
return team;
}
}
}
return null;
}
public void addToken(EbToken p_token)
{
if( p_token.getId() == 0 )
{
p_token.setId( getNextLocalId() );
p_token.setVersion( 1 );
}
if( !getSetToken().contains( p_token ) )
{
getSetToken().add( p_token );
getTokenIndexSet().addToken( p_token );
getBoardFireCover().incFireCover( p_token );
if( p_token.containToken() )
{
for( EbToken token : p_token.getContains() )
{
addToken( token );
}
}
}
updateLastTokenUpdate( null );
}
public boolean haveNewMessage(Date p_since)
{
if( p_since == null )
return true;
int index = getLogs().size() - 1;
Date lastEventDate = null;
while( index > 0 && (lastEventDate == null || lastEventDate.after( p_since )) )
{
if( getLogs().get( index ) instanceof EbEvtMessage )
{
return true;
}
lastEventDate = getLogs().get( index ).getLastUpdate();
index
}
return false;
}
public void addEvent(AnEvent p_action)
{
p_action.setGame( this );
if( p_action.getId() == 0 )
{
p_action.setId( getNextLocalId() );
}
else if( p_action.getId() != getNextLocalId() )
{
RpcUtil.logError( "EbGame::addEvent(): p_action.getId() != getNextLocalId()" );
}
if( !getLogs().contains( p_action ) )
{
getLogs().add( p_action );
}
else
{
RpcUtil.logError( "EbGame::addEvent(): logs already contain " + p_action );
}
}
public Date getEndDate()
{
if( getLastLog() != null )
{
return getLastLog().getLastUpdate();
}
else
{
return getLastUpdate();
}
}
@Override
public AnEvent getLastGameLog()
{
if( getLogs().size() > 0 )
{
return getLogs().get( getLogs().size() - 1 );
}
return null;
}
@Override
public AnEvent getLastGameLog(int p_count)
{
if( getLogs().size() < p_count )
{
return null;
}
return getLogs().get( getLogs().size() - (1 + p_count) );
}
public AnEvent getLastLog()
{
if( m_eventStack == null )
{
return getLastGameLog();
}
AnEvent event = m_eventStack.getLastGameLog();
if( event == null )
{
return getLastGameLog();
}
return event;
}
public AnEvent getLastLog(int p_count)
{
if( m_eventStack == null )
{
return getLastGameLog( p_count );
}
AnEvent event = m_eventStack.getLastGameLog( p_count );
if( event == null )
{
return getLastGameLog( p_count );
}
return event;
}
public GameEventStack getGameEventStack()
{
return m_eventStack;
}
public void setGameEventStack(GameEventStack p_stack)
{
m_eventStack = p_stack;
}
public int getNextTideChangeTimeStep()
{
return getLastTideChange() + getEbConfigGameTime().getTideChangeFrequency();
}
public Date estimateTimeStepDate(int p_step)
{
long timeStepDurationInMili = getEbConfigGameTime().getTimeStepDurationInMili();
if( !isParallel() )
{
timeStepDurationInMili *= getSetRegistration().size();
}
return new Date( getLastTimeStepChange().getTime() + (p_step - getCurrentTimeStep())
* timeStepDurationInMili );
}
public Date estimateNextTimeStep()
{
return estimateTimeStepDate( getCurrentTimeStep() + 1 );
}
public Date estimateNextTideChange()
{
return estimateTimeStepDate( getNextTideChangeTimeStep() );
}
/**
* If the game is paused, return a dummy value
* @return the endingDate
*/
public Date estimateEndingDate()
{
Date date = null;
if( getStatus() != GameStatus.Running )
{
date = new Date( Long.MAX_VALUE );
}
else
{
date = estimateTimeStepDate( getEbConfigGameTime().getTotalTimeStep() );
}
return date;
}
/**
* return the bitfields of all opponents fire cover at the given position.
* @param p_token
* @return
*/
public EnuColor getOpponentFireCover(int p_myColorValue, AnBoardPosition p_position)
{
EnuColor fireCover = getBoardFireCover().getFireCover( p_position );
fireCover.removeColor( p_myColorValue );
return fireCover;
}
/**
* @return true if the colored player have at least one weather hen to predict future tides.
*/
public int countWorkingWeatherHen(EnuColor p_color)
{
int count = 0;
for( Iterator<EbToken> it = getSetToken().iterator(); it.hasNext(); )
{
EbToken token = (EbToken)it.next();
if( (p_color.isColored( token.getColor() ))
&& (token.getType() == TokenType.WeatherHen)
&& (token.getColor() != EnuColor.None)
&& (token.getLocation() == Location.Board)
&& (isTokenTideActive( token ))
&& (isTokenFireActive( token ) ) )
{
count++;
}
}
return count;
}
/**
* @return true if the logged player have at least one Freighter landed.
*/
public boolean isLanded(EnuColor p_color)
{
for( Iterator<EbToken> it = getSetToken().iterator(); it.hasNext(); )
{
EbToken token = (EbToken)it.next();
if( (p_color.isColored( token.getColor() )) && (token.getType() == TokenType.Freighter)
&& (token.getLocation() == Location.Board) )
{
return true;
}
}
return false;
}
/**
*
* @param p_token
* @return all color of this token owner. no color if p_token have no color
*/
public EnuColor getTokenOwnerColor(EbToken p_token)
{
// first determine the token owner color
EnuColor tokenOwnerColor = p_token.getEnuColor();
if( tokenOwnerColor.getValue() != EnuColor.None )
{
for( EbRegistration registration : getSetRegistration() )
{
if( registration.getEnuColor().isColored( p_token.getColor() ) )
{
tokenOwnerColor.addColor( registration.getColor() );
break;
}
}
}
return tokenOwnerColor;
}
public EnuColor getTokenTeamColors(EbToken p_token)
{
// first determine the token owner color
EnuColor tokenOwnerColor = p_token.getEnuColor();
if( tokenOwnerColor.getValue() != EnuColor.None )
{
for( EbTeam team : getTeams() )
{
EnuColor color = new EnuColor(team.getColors( getPreview() ));
if( color.isColored( p_token.getColor() ) )
{
tokenOwnerColor.addColor( color );
break;
}
}
}
return tokenOwnerColor;
}
/**
* return the bitfields of all opponents fire cover on this token.<br/>
* note: if p_token is color less or not on board, always return EnuColor.None
* @param p_token
* @return
*/
public EnuColor getOpponentFireCover(EbToken p_token)
{
if( p_token.getLocation() != Location.Board || p_token.getColor() == EnuColor.None )
{
return new EnuColor( EnuColor.None );
}
// first determine the token owner color
EnuColor tokenTeamColor = getTokenTeamColors( p_token );
EnuColor fireCover = getOpponentFireCover( tokenTeamColor.getValue(), p_token.getPosition() );
if( p_token.getHexagonSize() == 2 )
{
fireCover.addColor( getOpponentFireCover( tokenTeamColor.getValue(),
(AnBoardPosition)p_token.getExtraPositions(getCoordinateSystem()).get( 0 ) ) );
}
return fireCover;
}
/**
* @param p_token
* true if this token is in a forbidden position. ie: if p_token is a tank near another on mountain.
* @return the token with witch this token is cheating
*/
public EbToken getTankCheating(EbToken p_token)
{
if( p_token.getType() != TokenType.Tank || p_token.getLocation() != Location.Board )
{
return null;
}
AnBoardPosition tokenPosition = p_token.getPosition();
if( getLand( tokenPosition ) != LandType.Montain )
{
return null;
}
Sector sectorValues[] = Sector.values();
for( int i = 0; i < sectorValues.length; i++ )
{
AnBoardPosition neighborPosition = getCoordinateSystem().getNeighbor( tokenPosition, sectorValues[i] );
EnuColor tokenTeamColor = getTokenTeamColors( p_token );
if( getLand( neighborPosition ) == LandType.Montain )
{
EbToken token = getToken( neighborPosition );
if( (token != null) && (token.getType() == TokenType.Tank)
&& (tokenTeamColor.isColored( token.getColor() )) )
{
// this tank is cheating
return token;
}
}
}
return null;
}
/**
* similar to 'getTankCheating' but simply return true if this token is in a forbidden position
* AND is the one which should be tag as cheater.
* => only of the tow tank: the lower ID
* @param p_token
* @return
*/
public boolean isTankCheating(EbToken p_token)
{
EbToken nearTank = getTankCheating(p_token);
return (nearTank!=null) && (nearTank.getId() > p_token.getId());
}
/**
* Should be called only on server side.
* Move a token and all token he contain into any other token in the game.
* @param p_tokenToMove
* @param p_tokenCarrier must be included in TokenList
* @throws RpcFmpException
*
*/
public void moveToken(EbToken p_tokenToMove, EbToken p_tokenCarrier) // throws
// RpcFmpException
{
getBoardFireCover().decFireCover( p_tokenToMove );
m_tokenIndexSet.setPosition( p_tokenToMove, Location.Token );
if( p_tokenToMove.getCarrierToken() != null )
{
// first unload from token
p_tokenToMove.getCarrierToken().unloadToken( p_tokenToMove );
}
p_tokenCarrier.loadToken( p_tokenToMove );
if( p_tokenToMove.canBeColored() )
{
// if a token enter inside another token, it take his color
p_tokenToMove.setColor( p_tokenCarrier.getColor() );
}
getBoardFireCover().incFireCover( p_tokenToMove );
// incFireCover( p_tokenToMove );
// this update is here only to refresh token display during time mode
updateLastTokenUpdate( null );
}
/**
* Warning: this method don't check anything about fire disabling flag.
* @param p_token
* @param p_newColor
*/
public void changeTokenColor(EbToken p_token, int p_newColor)
{
getBoardFireCover().decFireCover( p_token );
p_token.setColor( p_newColor );
getBoardFireCover().incFireCover( p_token );
if( p_token.containToken() )
{
for( EbToken token : p_token.getContains() )
{
if( token.canBeColored() )
{
token.setColor( p_newColor );
}
}
}
}
/**
* Move a token to any other position on the board.
* @param p_token
* @param p_position have to be inside the board (no check are performed).
*/
public void moveToken(EbToken p_token, AnBoardPosition p_position)
{
getBoardFireCover().decFireCover( p_token );
if( p_token.getCarrierToken() != null )
{
// first unload from token
p_token.getCarrierToken().unloadToken( p_token );
}
getTokenIndexSet().setPosition( p_token, new AnBoardPosition( p_position ) );
getBoardFireCover().incFireCover( p_token );
// this update is here only to refresh token display during time mode
updateLastTokenUpdate( null );
}
/**
* Warning: if you use this method with p_location == Board, you should be sure
* that his position is already set to the right value.
* @param p_token
* @param p_locationValue should be EnuLocation.Graveyard or EnuLocation.Orbit
* @throws RpcFmpException
*/
public void moveToken(EbToken p_token, Location p_location) throws RpcFmpException
{
getBoardFireCover().decFireCover( p_token );
if( p_token.getCarrierToken() != null )
{
// first unload from token
p_token.getCarrierToken().unloadToken( p_token );
}
getTokenIndexSet().setPosition( p_token, p_location );
getBoardFireCover().incFireCover( p_token );
// this update is here only to refresh token display during time mode
updateLastTokenUpdate( null );
}
public void removeToken(EbToken p_token)
{
try
{
moveToken( p_token, Location.Graveyard );
} catch( RpcFmpException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
getTokenIndexSet().removeToken( p_token );
getSetToken().remove( p_token );
p_token.incVersion();
}
public EbTeam getWinnerTeam()
{
EbTeam winner = null;
int point = 0;
for( EbTeam team : getTeams() )
{
if( team.estimateWinningScore(this) > point )
{
winner = team;
point = team.estimateWinningScore( this );
}
}
return winner;
}
public List<EbTeam> getTeamByWinningRank()
{
List<EbTeam> sortedTeam = new ArrayList<EbTeam>();
Map<EbTeam, Integer> winningPoint = new HashMap<EbTeam, Integer>();
for( EbTeam team : getTeams() )
{
int wp = team.estimateWinningScore(this);
int index = 0;
while( index < sortedTeam.size() )
{
if( wp > winningPoint.get( sortedTeam.get( index ) ) )
{
break;
}
index++;
}
winningPoint.put( team, wp );
sortedTeam.add( index, team );
}
return sortedTeam;
}
/**
* return next registration which control at least one freighter on board.
* If no registration control any freighter on board, return the current players registration.
* If p_currentIndex == -1, return the first registration that control one freighter
* @param p_currentIndex
* @return
*/
public EbTeam getNextTeam2Play(int p_currentIndex)
{
int index = p_currentIndex;
List<EbTeam> teams = getTeamByPlayOrder();
EbTeam team = null;
do
{
index++;
try
{
team = teams.get( index );
} catch( Exception e )
{
team = null;
}
if( team == null )
{
// next turn !
index = 0;
team = teams.get( index );
// avoid infinite loop
if( p_currentIndex < 0 )
break;
}
assert team != null;
} while( (team.getOnBoardFreighterCount( this ) == 0 || !team.haveAccount( getPreview() ))
&& (index != p_currentIndex) );
return team;
}
/**
* count the number of freighter remaining on board this player control
* @param p_registration
* @return true if player have at least one freighter on board or in orbit
*/
protected boolean haveBoardFreighter(EbRegistration p_registration)
{
if( p_registration.getColor() == EnuColor.None )
{
return false;
}
if( !getAllowedTakeOffTurns().isEmpty()
&& getCurrentTimeStep() < getAllowedTakeOffTurns().get( 0 ) )
{
return true;
}
for( EbToken token : getSetToken() )
{
if( (token.getType() == TokenType.Freighter)
&& (p_registration.getEnuColor().isColored( token.getColor() ))
&& ((token.getLocation() == Location.Board) || (token.getLocation() == Location.Orbit)) )
{
return true;
}
}
return false;
}
/**
*
* @param p_registration
* @return false if player can't deploy unit for free
*/
public boolean canDeployUnit(EbRegistration p_registration)
{
if( getEbConfigGameTime().getDeploymentTimeStep() < getCurrentTimeStep() )
{
// too late
return false;
}
if( !isParallel() && getEbConfigGameTime().getDeploymentTimeStep() != getCurrentTimeStep() )
{
// too early
return false;
}
// check that, in parallel, player don't wan't to deploy after his first
// move
if( isParallel() )
{
int index = getLogs().size();
while( index > 0 )
{
index
AnEvent event = getLogs().get( index );
if( event instanceof EbEvtMove
&& ((EbEvtMove)event).getMyRegistration( this ).getId() == p_registration.getId() )
{
return false;
}
}
}
return true;
}
/**
*
* @return time step duration multiply by the players count.
*/
public long getFullTurnDurationInMili()
{
return getEbConfigGameTime().getTimeStepDurationInMili() * getSetRegistration().size();
}
/**
* offset height in pixel to display token image in tactic zoom.
* it represent the land height.
* take in account tide.
* @param p_x
* @param p_y
* @return
*/
public int getLandPixOffset(AnPair p_position)
{
LandType land = getLand( p_position );
switch( land )
{
default:
return getLandPixOffset( land );
case Sea:
if( getCurrentTide() == Tide.Low )
{
return getLandPixOffset( LandType.Sea );
}
case Reef:
if( getCurrentTide() != Tide.Hight )
{
return getLandPixOffset( LandType.Reef );
}
case Marsh:
return getLandPixOffset( LandType.Marsh );
}
}
/**
* offset height in pixel to display token image in tactic zoom.
* it represent the land height.
* do not take in account tide
*/
public static int getLandPixOffset(LandType p_landValue)
{
switch( p_landValue )
{
case Montain:
return -7;
case Sea:
return 6;
case Reef:
return 5;
case Marsh:
return 2;
default:
return 0;
}
}
// come from token list
/**
* it keep the latest lastUpdate of the token list.
*/
@Transient
private Date m_lastTokenUpdate = new Date( 0 );
public Date getLastTokenUpdate()
{
if( m_lastTokenUpdate == null )
{
m_lastTokenUpdate = new Date( SharedMethods.currentTimeMillis() );
}
return m_lastTokenUpdate;
}
public void updateLastTokenUpdate(Date p_lastUpdate)
{
if( p_lastUpdate == null )
{
m_lastTokenUpdate = new Date( SharedMethods.currentTimeMillis() );
}
else if( p_lastUpdate.after( m_lastTokenUpdate ) )
{
m_lastTokenUpdate = p_lastUpdate;
}
}
/**
*
* @param p_registration
* @return first freighter owned by p_registration. null if not found.
*/
public EbToken getFreighter( EbRegistration p_registration)
{
if( p_registration == null )
{
return null;
}
EnuColor color = p_registration.getEnuColor();
for( EbToken token : getSetToken() )
{
if( token.getType() == TokenType.Freighter && token.getColor() != EnuColor.None
&& color.isColored( token.getColor() ) )
{
return token;
}
}
return null;
}
public List<EbToken> getAllFreighter(int p_color)
{
EnuColor color = new EnuColor( p_color );
List<EbToken> list = new ArrayList<EbToken>();
if( color == null || color.getNbColor() == 0 )
{
return list;
}
for( EbToken token : getSetToken() )
{
if( token.getType() == TokenType.Freighter && token.getColor() != EnuColor.None
&& color.isColored( token.getColor() ) )
{
list.add( token );
}
}
return list;
}
/**
* search over m_token for a token
* @param p_id
* @return null if no token found
*/
public EbToken getToken(long p_id)
{
return getTokenIndexSet().getToken( p_id );
}
/**
* search over m_token and m_tokenLocation for the most relevant token at a given position
* @param p_position
* @return the first colored (or by default the first colorless) token encountered at given position.
*/
public EbToken getToken(AnBoardPosition p_position)
{
Set<EbToken> list = getAllToken( p_position );
EbToken token = null;
for( Iterator<EbToken> it = list.iterator(); it.hasNext(); )
{
EbToken nextToken = (EbToken)it.next();
if( (token == null)
|| (token.getType().getZIndex( token.getPosition().getSector() ) < nextToken.getType()
.getZIndex( nextToken.getPosition().getSector() )) )
{
token = nextToken;
}
}
return token;
}
/**
* This method extract one specific token in the token list.
* @param p_position
* @param p_tokenType
* @return null if not found
*/
public EbToken getToken(AnBoardPosition p_position, TokenType p_tokenType)
{
EbToken token = null;
for( Iterator<EbToken> it = getAllToken( p_position ).iterator(); it.hasNext(); )
{
EbToken nextToken = (EbToken)it.next();
if( nextToken.getType() == p_tokenType )
{
token = nextToken;
}
}
return token;
}
/**
* note: this method assume that every token are located only once to a single position.
* (ie the couple [tokenId;position] is unique in m_tokenLocation)
* @param p_position
* @return a list of all token located at p_position
*/
public Set<EbToken> getAllToken(AnBoardPosition p_position)
{
Set<EbToken> allTokens = getTokenIndexSet().getAllToken(
getCoordinateSystem().normalizePosition( p_position ) );
if( allTokens != null )
{
return new HashSet<EbToken>(allTokens);
}
return new HashSet<EbToken>();
}
/**
* determine if this token can load the given token
* @param p_carrier the token we want load
* @param p_token the token we want load
* @return
*/
public boolean canTokenLoad(EbToken p_carrier, EbToken p_token)
{
assert p_carrier != null;
assert p_token != null;
if( !p_carrier.canLoad( p_token.getType() ) )
{
return false;
}
int freeLoadingSpace = p_carrier.getType().getLoadingCapability();
if( p_carrier.containToken() )
{
for( EbToken token : p_carrier.getContains() )
{
freeLoadingSpace -= token.getType().getLoadingSize();
}
}
return freeLoadingSpace >= p_token.getFullLoadingSize();
}
/**
* the number of destructor owned by p_registration which can fire on this hexagon
* @param p_x
* @param p_y
* @param p_registration
* @return
*/
public int getFireCover(int p_x, int p_y, EbTeam p_team)
{
EnuColor regColor = new EnuColor( p_team.getFireColor() );
return getBoardFireCover().getFireCover( new AnBoardPosition( p_x, p_y ), regColor );
}
public void invalidateFireCover()
{
getBoardFireCover().invalidateFireCover();
}
public BoardFireCover getBoardFireCover()
{
if( m_fireCover == null )
{
m_fireCover = new BoardFireCover( this );
}
return m_fireCover;
}
/**
* determine if this token is active depending of current tide.
* ie: not under water for lands unit or land for see units.
* @param p_token
* @return
*/
public boolean isTokenTideActive(EbToken p_token)
{
if( (p_token == null) )
{
return false;
}
// if p_token is contained by another token, p_token is active only if
// this
// other token is active
if( (p_token.getLocation() == Location.Token)
|| (p_token.getLocation() == Location.ToBeConstructed) )
{
return isTokenTideActive( (EbToken)p_token.getCarrierToken() );
}
if( (p_token.getLocation() == Location.Graveyard) )
{
return false;
}
if( p_token.getLocation() == Location.Orbit )
{
return true;
}
// ok so token if on board.
// determine, according to current tide, if the first position is sea,
// plain or montain
LandType landValue = getLand( p_token.getPosition() ).getLandValue( getCurrentTide() );
if( landValue == LandType.None )
{
return false;
}
switch( p_token.getType() )
{
case Barge:
LandType extraLandValue = getLand( p_token.getExtraPositions(getCoordinateSystem()).get( 0 ) )
.getLandValue( getCurrentTide() );
if( extraLandValue != LandType.Sea )
{
if( getToken( p_token.getExtraPositions(getCoordinateSystem()).get( 0 ), TokenType.Sluice ) != null )
{
return true;
}
return false;
}
case Speedboat:
case Tarask:
case Crayfish:
if( landValue != LandType.Sea )
{
if( getToken( p_token.getPosition(), TokenType.Sluice ) != null )
{
return true;
}
return false;
}
return true;
case Heap:
case Tank:
case Crab:
case WeatherHen:
case Ore0:
case Ore:
case Ore3:
case Ore5:
if( landValue == LandType.Sea )
{
if( getToken( p_token.getPosition(), TokenType.Pontoon ) != null )
{
return true;
}
return false;
}
return true;
case Turret:
case Freighter:
case Pontoon:
case Sluice:
case Hovertank:
default:
return true;
}
}
/**
* determine if this token is active depending of opponents fire cover.<br/>
* note that even if we don't display any warning, this method will return false
* for an uncolored token.
* @param p_token
* @return
*/
public boolean isTokenFireActive(EbToken p_token)
{
EnuColor teamColor = getTokenTeamColors( p_token );
return((p_token.getLocation() != Location.Board) || (p_token.getType() == TokenType.Freighter)
|| (p_token.getType() == TokenType.Turret) || (teamColor.getValue() == EnuColor.None) || (getOpponentFireCover(
teamColor.getValue(), p_token.getPosition() ).getValue() == EnuColor.None));
}
/**
* determine weather the given token can produce or not a fire cover.
* If not, his fire cover will increment the disabled fire cover to show it to player
* @param p_token
* @return
*/
public boolean isTokenFireCoverDisabled(EbToken p_token)
{
if( p_token == null || !p_token.getType().isDestroyer() )
{
return false;
}
// if( !isTokenFireActive( p_token ) )
if( p_token.isFireDisabled() )
{
return true;
}
if( !isTokenTideActive( p_token ) )
{
return true;
}
if( isTankCheating( p_token ) )
{
return true;
}
return false;
}
/**
* TODO half redundant with isTokenTideActive
* note that any token are allowed to voluntary stuck themself into reef of marsh
* @param p_token
* @param p_position
* @return true if token can move to p_position according to tide
*/
public boolean canTokenMoveOn(EbToken p_token, AnBoardPosition p_position)
{
if( (p_token == null) || (!isTokenTideActive( p_token )) || (p_position == null)
|| (p_position.getX() < 0) || (p_position.getY() < 0) )
{
return false;
}
if( p_token.getHexagonSize() == 2 )
{
AnBoardPosition position = getCoordinateSystem().getNeighbor( p_position, p_position.getSector() );
EbToken tokenPontoon = getToken( position, TokenType.Pontoon );
if( tokenPontoon == null )
tokenPontoon = getToken( position, TokenType.Sluice );
if( tokenPontoon != null )
{
return tokenPontoon.canLoad( p_token.getType() );
}
// check this token is allowed to move on this hexagon
if( p_token.canMoveOn( this, getLand( position ) ) == false )
{
return false;
}
}
EbToken tokenPontoon = getToken( p_position, TokenType.Pontoon );
if( tokenPontoon == null )
tokenPontoon = getToken( p_position, TokenType.Sluice );
if( tokenPontoon != null )
{
return tokenPontoon.canLoad( p_token.getType() );
}
// check this token is allowed to move on this hexagon
return p_token.canMoveOn( this, getLand( p_position ) );
}
/**
* determine if this token can fire onto a given position
* Warning: it doesn't check tide or fire disable flag !
* @param p_token
* @param p_position
* @return
*/
public boolean canTokenFireOn(EbToken p_token, AnBoardPosition p_position)
{
if( (p_token.getLocation() != Location.Board) || (!p_token.getType().isDestroyer()) )
{
return false;
}
return getCoordinateSystem().getDiscreteDistance( p_token.getPosition(), p_position ) <= (getTokenFireLength( p_token ));
}
/**
* determine if this token can fire onto a given token
* Warning: it doesn't check tide or fire disable flag !
* @param p_token
* @param p_tokenTarget
* @return
*/
public boolean canTokenFireOn(EbToken p_token, EbToken p_tokenTarget)
{
if( canTokenFireOn( p_token, p_tokenTarget.getPosition() ) )
{
return true;
}
for( AnBoardPosition position : p_tokenTarget.getExtraPositions(getCoordinateSystem()) )
{
if( canTokenFireOn( p_token, position ) )
{
return true;
}
}
return false;
}
/**
*
* @return the fire length of this token.
*/
public int getTokenFireLength(EbToken p_token)
{
if( (p_token == null) || p_token.getLocation() != Location.Board )
{
return 0;
}
switch( p_token.getType() )
{
case Turret:
case Speedboat:
case Hovertank:
return 2;
case Tank:
if( getLand( p_token.getPosition() ) == LandType.Montain )
{
return 3;
}
return 2;
case Heap:
case Tarask:
return 3;
case Freighter:
case Barge:
case Crab:
case WeatherHen:
case Pontoon:
case Ore:
default:
return 0;
}
}
public boolean isPontoonLinkToGround(EbToken p_token)
{
if( p_token.getType() != TokenType.Pontoon )
{
return false;
}
Set<EbToken> checkedPontoon = new HashSet<EbToken>();
return isPontoonLinkToGround( p_token, checkedPontoon );
}
public boolean isPontoonLinkToGround(AnBoardPosition p_position)
{
LandType land = getLand( p_position ).getLandValue( getCurrentTide() );
if( (land == LandType.Plain) || (land == LandType.Montain) )
{
return true;
}
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_position ) )
{
land = getLand( neighborPosition ).getLandValue( getCurrentTide() );
if( (land == LandType.Plain) || (land == LandType.Montain) )
{
return true;
}
}
EbToken otherPontoon = getToken( p_position, TokenType.Pontoon );
Set<EbToken> checkedPontoon = new HashSet<EbToken>();
if( otherPontoon != null )
{
checkedPontoon.add( otherPontoon );
}
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_position ) )
{
otherPontoon = getToken( neighborPosition, TokenType.Pontoon );
if( otherPontoon != null )
{
checkedPontoon.add( otherPontoon );
if( isPontoonLinkToGround( otherPontoon, checkedPontoon ) )
{
return true;
}
}
}
// check if pontoon is connected to freighter at high tide
if( getCurrentTide() == Tide.Hight )
{
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_position ) )
{
if( getToken( neighborPosition, TokenType.Freighter ) != null )
return true;
}
}
return false;
}
private boolean isPontoonLinkToGround(EbToken p_token, Set<EbToken> p_checkedPontoon)
{
LandType land = getLand( p_token.getPosition() ).getLandValue( getCurrentTide() );
if( (land == LandType.Plain) || (land == LandType.Montain) )
{
return true;
}
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_token.getPosition() ) )
{
land = getLand( neighborPosition )
.getLandValue( getCurrentTide() );
if( (land == LandType.Plain) || (land == LandType.Montain) )
{
return true;
}
}
EbToken otherPontoon = null;
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_token.getPosition() ) )
{
otherPontoon = getToken( neighborPosition, TokenType.Pontoon );
if( (otherPontoon != null) && (!p_checkedPontoon.contains( otherPontoon )) )
{
p_checkedPontoon.add( otherPontoon );
if( isPontoonLinkToGround( otherPontoon, p_checkedPontoon ) )
{
return true;
}
}
}
// check if pontoon is connected to freighter at high tide
if( getCurrentTide() == Tide.Hight )
{
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_token.getPosition() ) )
{
if( getToken( neighborPosition, TokenType.Freighter ) != null )
return true;
}
}
return false;
}
/**
* put p_token and all linked pontoon to graveyard.
* @param p_token must be a pontoon
* @param p_fdRemoved fire disabling that was removed are added to this list
* @return list of all tokens removed from board to graveyard (pontoons and token on them).
* Token have to be put back on board in the same order.
* @throws RpcFmpException
*/
public ArrayList<Long> chainRemovePontoon(EbToken p_token, List<FireDisabling> p_fdRemoved) throws RpcFmpException
{
assert p_token.getType() == TokenType.Pontoon;
ArrayList<Long> pontoons = new ArrayList<Long>();
// backup pontoon's id first (to put back on board first)
pontoons.add( p_token.getId() );
AnBoardPosition position = p_token.getPosition();
// remove all tokens on pontoon
Set<EbToken> tokens = getAllToken( position );
for(EbToken token : tokens)
{
if(token != p_token)
{
// remove his fire disabling list
if( token.getFireDisablingList() != null )
{
List<FireDisabling> fdRemoved = new ArrayList<FireDisabling>();
fdRemoved.addAll( token.getFireDisablingList() );
p_fdRemoved.addAll( fdRemoved );
getBoardFireCover().removeFireDisabling( fdRemoved );
}
// remove token on pontoon
pontoons.add( token.getId() );
moveToken( token, Location.Graveyard );
token.incVersion();
}
}
// then remove pontoon
moveToken( p_token, Location.Graveyard );
p_token.incVersion();
// finally remove other linked pontoons
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( position ) )
{
EbToken otherPontoon = getToken( neighborPosition, TokenType.Pontoon );
if( otherPontoon != null )
{
pontoons.addAll( chainRemovePontoon( otherPontoon, p_fdRemoved ) );
}
}
return pontoons;
}
// TODO move this to another class
@Transient
private Set<com.fullmetalgalaxy.model.persist.AnBoardPosition> m_allowedNodeGraphCache = new HashSet<com.fullmetalgalaxy.model.persist.AnBoardPosition>();
@Transient
private Set<com.fullmetalgalaxy.model.persist.AnBoardPosition> m_forbidenNodeGraphCache = new HashSet<com.fullmetalgalaxy.model.persist.AnBoardPosition>();
public void resetPathGraph()
{
m_allowedNodeGraphCache.clear();
m_forbidenNodeGraphCache.clear();
}
/* (non-Javadoc)
* @see com.fullmetalgalaxy.model.pathfinder.PathGraph#getAvailableNode(com.fullmetalgalaxy.model.pathfinder.PathNode)
*/
@Override
public Set<com.fullmetalgalaxy.model.pathfinder.PathNode> getAvailableNode(PathNode p_fromNode,
PathMobile p_mobile)
{
assert p_mobile != null;
AnBoardPosition position = (AnBoardPosition)p_fromNode;
Mobile mobile = (Mobile)p_mobile;
Set<com.fullmetalgalaxy.model.pathfinder.PathNode> nodes = new HashSet<com.fullmetalgalaxy.model.pathfinder.PathNode>();
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( position ) )
{
if( mobile.getToken() == null )
{
nodes.add( neighborPosition );
}
else
{
// looking in cache first
if( m_allowedNodeGraphCache.contains( neighborPosition ) )
{
nodes.add( neighborPosition );
}
else if( m_forbidenNodeGraphCache.contains( neighborPosition ) )
{
// do nothing
}
else
{
// this position wasn't explored yet
if( mobile.getToken().canMoveOn( this, mobile.getRegistration(), neighborPosition ) )
{
m_allowedNodeGraphCache.add( neighborPosition );
nodes.add( neighborPosition );
}
else
{
m_forbidenNodeGraphCache.add( neighborPosition );
}
}
}
}
return nodes;
}
/* (non-Javadoc)
* @see com.fullmetalgalaxy.model.pathfinder.PathGraph#heuristic(com.fullmetalgalaxy.model.pathfinder.PathNode, com.fullmetalgalaxy.model.pathfinder.PathNode)
*/
@Override
public float heuristic(PathNode p_fromNode, PathNode p_toNode, PathMobile p_mobile)
{
return (float)getCoordinateSystem().getDiscreteDistance( ((AnBoardPosition)p_fromNode), (AnBoardPosition)p_toNode );
}
public List<AnEvent> createTriggersEvents()
{
// get all events
List<AnEvent> events = new ArrayList<AnEvent>();
for( EbTrigger trigger : getTriggers() )
{
events.addAll( trigger.createEvents( this ) );
}
return events;
}
/**
* execute all game's trigger
* @return true if at least on trigger was executed.
*/
public void execTriggers()
{
// execute new events
for( AnEvent event : createTriggersEvents() )
{
try
{
event.exec( this );
addEvent( event );
} catch( RpcFmpException e )
{
// print error and continue executing events
e.printStackTrace();
}
}
}
/**
* @return the tokenIndexSet. never return null;
*/
private TokenIndexSet getTokenIndexSet()
{
if( m_tokenIndexSet == null )
{
m_tokenIndexSet = new TokenIndexSet( getCoordinateSystem(), getSetToken() );
}
return m_tokenIndexSet;
}
}
|
package com.globalsight.tools;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
/**
* Create a job. By default, use all the target locales
* indicated by the file profile (selected by name or id).
* Generate a job name based on the name of the first file uploaded,
* unless one is specified on the command line.
*/
@SuppressWarnings("static-access")
// TODO: I should assume the fileprofile target locale by default, but allow overrides
// via --target
public class CreateJobCommand extends WebServiceCommand {
@Override
protected void execute(CommandLine command, UserData userData,
WebService webService) throws Exception {
// Make sure we have at least one file to upload
if (command.getArgs().length == 0) {
die("Must specify at least one file to import.");
}
if (command.hasOption(FILEPROFILE) &&
command.hasOption(FILEPROFILEID)) {
usage("Can't specify both " + FILEPROFILE +
" and " + FILEPROFILEID + " options.");
}
if (!(command.hasOption(FILEPROFILE) ||
command.hasOption(FILEPROFILEID))) {
usage("Must specify either " + FILEPROFILE +
" or " + FILEPROFILEID + " option.");
}
FileProfile fp = null;
if (command.hasOption(FILEPROFILE)) {
String fpName = command.getOptionValue(FILEPROFILE);
fp = findByName(webService.getFileProfiles(), fpName);
if (fp == null) {
die("No such file profile: '" + fpName + "'");
}
}
else {
String fpId = command.getOptionValue(FILEPROFILEID);
fp = findById(webService.getFileProfiles(), fpId);
if (fp == null) {
die("No such file profile id: '" + fpId + "'");
}
}
// TODO target locale overrides
// Convert all remaining arguments to files
List<File> files = new ArrayList<File>();
for (String path : command.getArgs()) {
File f = new File(path);
if (!f.exists() || f.isDirectory()) {
die("Not a file: " + f);
}
files.add(f.getCanonicalFile());
}
// Get a job name either from command line or first file
// uploaded, then uniquify
String baseJobName = files.get(0).getName();
if (command.hasOption(JOBNAME)) {
command.getOptionValue(JOBNAME);
}
String jobName = webService.getUniqueJobName(baseJobName);
verbose("Got unique job name: " + jobName);
List<String> filePaths = new ArrayList<String>();
for (File f : files) {
filePaths.add(uploadFile(f, jobName, fp, webService));
}
webService.createJob(jobName, filePaths, fp);
}
FileProfile findByName(List<FileProfile> fileProfiles, String name) {
for (FileProfile fp : fileProfiles) {
if (fp.getName().equalsIgnoreCase(name)) {
return fp;
}
}
return null;
}
FileProfile findById(List<FileProfile> fileProfiles, String id) {
for (FileProfile fp : fileProfiles) {
if (fp.getId().equals(id)) {
return fp;
}
}
return null;
}
private static long MAX_SEND_SIZE = 5 * 1000 * 1024;
// Returns the filepath that was sent to the server
String uploadFile(File file, String jobName, FileProfile fileProfile,
WebService webService) throws Exception {
String filePath = file.getAbsolutePath();
// XXX This is so janky - why do we have to do this?
filePath = filePath.substring(filePath.indexOf(File.separator) + 1);
verbose("Uploading " + filePath + " to job " + jobName);
InputStream is = null;
try {
long bytesRemaining = file.length();
is = new BufferedInputStream(new FileInputStream(file));
while (bytesRemaining > 0) {
// Safe cast because it's bounded by MAX_SEND_SIZE
int size = (int)Math.min(bytesRemaining, MAX_SEND_SIZE);
byte[] bytes = new byte[size];
int count = is.read(bytes);
if (count <= 0) {
break;
}
bytesRemaining -= count;
verbose("Uploading chunk 1: " + size + " bytes");
webService.uploadFile(filePath, jobName, fileProfile.getId(), bytes);
}
verbose("Finished uploading " + filePath);
}
catch (IOException e) {
throw new RuntimeException(e);
}
finally {
if (is != null) {
is.close();
}
}
return filePath;
}
static final String TARGET = "target",
FILEPROFILE = "fileprofile",
FILEPROFILEID = "fileprofileid",
JOBNAME = "name";
static final Option TARGET_OPT = OptionBuilder
.withArgName("targetLocale")
.hasArg()
.withDescription("target locale code")
.create(TARGET);
static final Option FILEPROFILE_OPT = OptionBuilder
.withArgName("fileProfile")
.hasArg()
.withDescription("file profile to use")
.create(FILEPROFILE);
static final Option FILEPROFILEID_OPT = OptionBuilder
.withArgName("fileProfileId")
.hasArg()
.withDescription("numeric ID file profile to use")
.create(FILEPROFILEID);
static final Option JOBNAME_OPT = OptionBuilder
.withArgName("jobName")
.hasArg()
.withDescription("job name")
.create(JOBNAME);
@Override
public Options getOptions() {
Options opts = getDefaultOptions();
opts.addOption(TARGET_OPT);
opts.addOption(FILEPROFILE_OPT);
opts.addOption(FILEPROFILEID_OPT);
opts.addOption(JOBNAME_OPT);
return opts;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getName() {
return "create-job";
}
}
|
package com.maddyhome.idea.vim.command;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.editor.actionSystem.EditorAction;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.maddyhome.idea.vim.handler.AbstractEditorActionHandler;
import java.util.List;
/**
* This represents a single Vim command to be executed. It may optionally include an argument if appropriate for
* the command. The command has a count and a type.
*/
public class Command
{
/** Motion flags */
public static final int FLAG_MOT_LINEWISE = 1 << 1;
public static final int FLAG_MOT_CHARACTERWISE = 1 << 2;
public static final int FLAG_MOT_INCLUSIVE = 1 << 3;
public static final int FLAG_MOT_EXCLUSIVE = 1 << 4;
/** Indicates that the cursor position should be saved prior to this motion command */
public static final int FLAG_SAVE_JUMP = 1 << 5;
/** Special command flag that indicates it is not to be repeated */
public static final int FLAG_NO_REPEAT = 1 << 8;
/** This insert command should clear all saved keystrokes from the current insert */
public static final int FLAG_CLEAR_STROKES = 1 << 9;
/** This keystroke should be saved as part of the current insert */
public static final int FLAG_SAVE_STROKE = 1 << 10;
/** Search Flags */
public static final int FLAG_SEARCH_FWD = 1 << 16;
public static final int FLAG_SEARCH_REV = 1 << 17;
/** Special flag used for any mappings involving operators */
public static final int FLAG_OP_PEND = 1 << 24;
/** This command starts a multi-command undo transaction */
public static final int FLAG_MULTIKEY_UNDO = 1 << 25;
/** This command should be followed by another command */
public static final int FLAG_EXPECT_MORE = 1 << 26;
/** This flag indicates the command's argument isn't used while recording */
public static final int FLAG_NO_ARG_RECORDING = 1 << 27;
/** Represents commands that actually move the cursor and can be arguments to operators */
public static final int MOTION = 1;
/** Represents commands that insert new text into the editor */
public static final int INSERT = 2;
/** Represents commands that remove text from the editor */
public static final int DELETE = 3;
/** Represents commands that change text in the editor */
public static final int CHANGE = 4;
/** Represents commands that copy text in the editor */
public static final int COPY = 5;
/** Represents commands that paste text into the editor */
public static final int PASTE = 6;
public static final int RESET = 7;
/** Represents commands that select the register */
public static final int SELECT_REGISTER = 8;
/** Represents other types of commands */
public static final int OTHER_READONLY = 9;
public static final int OTHER_WRITABLE = 10;
public static final int OTHER_READ_WRITE = 11;
public static boolean isReadType(int type)
{
boolean res = false;
switch (type)
{
case MOTION:
case COPY:
case SELECT_REGISTER:
case OTHER_READONLY:
case OTHER_READ_WRITE:
res = true;
}
return res;
}
public static boolean isWriteType(int type)
{
boolean res = false;
switch (type)
{
case INSERT:
case DELETE:
case CHANGE:
case PASTE:
case RESET:
case OTHER_WRITABLE:
case OTHER_READ_WRITE:
res = true;
}
return res;
}
/**
* Creates a command that doesn't require an argument
* @param count The number entered prior to the command (zero if no specific number)
* @param action The action to be executed when the command is run
* @param type The type of the command
* @param flags Any custom flags specific to this command
*/
public Command(int count, AnAction action, int type, int flags)
{
this(count, action, type, flags, null);
}
/**
* Creates a command that requires an argument
* @param count The number entered prior to the command (zero if no specific number)
* @param action The action to be executed when the command is run
* @param type The type of the command
* @param flags Any custom flags specific to this command
* @param arg The argument to this command
*/
public Command(int count, AnAction action, int type, int flags, Argument arg)
{
this.count = count;
this.action = action;
this.type = type;
this.flags = flags;
this.argument = arg;
if (action instanceof EditorAction)
{
EditorAction eaction = (EditorAction)action;
EditorActionHandler handler = eaction.getHandler();
if (handler instanceof AbstractEditorActionHandler)
{
((AbstractEditorActionHandler)handler).process(this);
}
}
}
/**
* Returns the command count. A zero count is returned as one since that is the default for most commands
* @return The command count
*/
public int getCount()
{
return count == 0 ? 1 : count;
}
/**
* Updates the command count to the new value
* @param count The new command count
*/
public void setCount(int count)
{
this.count = count;
}
/**
* Gets to actual count entered by the user, including zero if no count was specified. Some commands need to
* know whether an actual count was specified or not.
* @return The actual count entered by the user
*/
public int getRawCount()
{
return count;
}
/**
* Gets the command type
* @return The command type
*/
public int getType()
{
return type;
}
/**
* Gets the flags associated with the command
* @return The command flags
*/
public int getFlags()
{
return flags;
}
/**
* Sets new flags for the command
* @param flags The new flags
*/
public void setFlags(int flags)
{
this.flags = flags;
}
/**
* Gets the action to execute when the command is run
* @return The command's action
*/
public AnAction getAction()
{
return action;
}
/**
* Sets a new action for the command
* @param action The new action
*/
public void setAction(AnAction action)
{
this.action = action;
}
/**
* Gets the command's argument, if any.
* @return The command's argument, null if there isn't one
*/
public Argument getArgument()
{
return argument;
}
/**
* Sets the command's argument to the new value
* @param argument The new argument, can be null to clear the argument
*/
public void setArgument(Argument argument)
{
this.argument = argument;
}
public List getKeys()
{
return keys;
}
public void setKeys(List keys)
{
this.keys = keys;
}
private int count;
private AnAction action;
private int type;
private int flags;
private Argument argument;
private List keys;
}
|
package com.mcbans.firestar.mcbans.request;
import static com.mcbans.firestar.mcbans.I18n._;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import net.h31ix.anticheat.api.AnticheatAPI;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import com.mcbans.firestar.mcbans.ActionLog;
import com.mcbans.firestar.mcbans.I18n;
import com.mcbans.firestar.mcbans.MCBans;
import com.mcbans.firestar.mcbans.events.PlayerBanEvent;
import com.mcbans.firestar.mcbans.events.PlayerBannedEvent;
import com.mcbans.firestar.mcbans.events.PlayerGlobalBanEvent;
import com.mcbans.firestar.mcbans.events.PlayerLocalBanEvent;
import com.mcbans.firestar.mcbans.events.PlayerTempBanEvent;
import com.mcbans.firestar.mcbans.events.PlayerUnbanEvent;
import com.mcbans.firestar.mcbans.events.PlayerUnbannedEvent;
import com.mcbans.firestar.mcbans.org.json.JSONException;
import com.mcbans.firestar.mcbans.org.json.JSONObject;
import com.mcbans.firestar.mcbans.util.Util;
import fr.neatmonster.nocheatplus.checks.ViolationHistory;
import fr.neatmonster.nocheatplus.checks.ViolationHistory.ViolationLevel;
public class Ban implements Runnable {
private final MCBans plugin;
private final ActionLog log;
private String playerName = null;
private String playerIP = null;
private String senderName = null;
private String reason = null;
private String action = null;
private String duration = null;
private String measure = null;
private boolean rollback = false;
private String badword = null;
private JSONObject actionData = null;
private HashMap<String, Integer> responses = new HashMap<String, Integer>();
private int action_id;
public Ban(MCBans plugin, String action, String playerName, String playerIP, String senderName, String reason, String duration,
String measure, JSONObject actionData, boolean rollback) {
this.plugin = plugin;
this.log = plugin.getLog();
this.playerName = playerName;
this.playerIP = playerIP;
this.senderName = senderName;
this.reason = reason;
this.rollback = rollback;
this.duration = duration;
this.measure = measure;
this.action = action;
this.actionData = (actionData != null) ? actionData : new JSONObject();
responses.put("globalBan", 0);
responses.put("localBan", 1);
responses.put("tempBan", 2);
responses.put("unBan", 3);
}
public Ban(MCBans plugin, String action, String playerName, String playerIP, String senderName, String reason, String duration,
String measure) {
this (plugin, action, playerName, playerIP, senderName, reason, duration, measure, null, false);
}
public void kickPlayer(String playerToKick, final String kickReason) {
final Player target = plugin.getServer().getPlayerExact(playerToKick);
if (target != null) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
target.kickPlayer(kickReason);
}
}, 0L);
}
}
@Override
public void run() {
while (plugin.apiServer == null) {
// waiting for server select
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
if (responses.containsKey(action)) {
action_id = responses.get(action);
// Call BanEvent
if (action_id != 3){
PlayerBanEvent banEvent = new PlayerBanEvent(playerName, playerIP, senderName, reason, action_id, duration, measure);
plugin.getServer().getPluginManager().callEvent(banEvent);
if (banEvent.isCancelled()){
return;
}
senderName = banEvent.getSenderName();
reason = banEvent.getReason();
action_id = banEvent.getActionID();
duration = banEvent.getDuration();
measure = banEvent.getMeasure();
}
switch (action_id) {
case 0:
globalBan();
break;
case 1:
localBan();
break;
case 2:
tempBan();
break;
case 3:
unBan();
break;
}
} else {
log.warning("Error, caught invalid action! Another plugin using mcbans improperly?");
}
}
public void unBan() {
// Call PlayerUnbanEvent
PlayerUnbanEvent unBanEvent = new PlayerUnbanEvent(playerName, senderName);
plugin.getServer().getPluginManager().callEvent(unBanEvent);
if (unBanEvent.isCancelled()){
return;
}
senderName = unBanEvent.getSenderName();
JsonHandler webHandle = new JsonHandler(plugin);
HashMap<String, String> url_items = new HashMap<String, String>();
url_items.put("player", playerName);
url_items.put("admin", senderName);
url_items.put("exec", "unBan");
HashMap<String, String> response = webHandle.mainRequest(url_items);
if (response.containsKey("error")){
Util.message(senderName, ChatColor.RED + "Error: " + response.get("error"));
return;
}
if (!response.containsKey("result")) {
Util.message(senderName, ChatColor.RED + _("unBanError", I18n.PLAYER, playerName, I18n.SENDER, senderName));
return;
}
if (response.get("result").equals("y")) {
if (!Util.isValidIP(playerName)){
OfflinePlayer d = plugin.getServer().getOfflinePlayer(playerName);
if (d.isBanned()) {
d.setBanned(false);
}
}
Util.message(senderName, ChatColor.GREEN + _("unBanSuccess", I18n.PLAYER, playerName, I18n.SENDER, senderName));
plugin.getServer().getPluginManager().callEvent(new PlayerUnbannedEvent(playerName, senderName));
log.info(senderName + " unbanned " + playerName + "!");
return;
} else if (response.get("result").equals("e")) {
Util.message(senderName, ChatColor.RED + _("unBanError", I18n.PLAYER, playerName, I18n.SENDER, senderName));
} else if (response.get("result").equals("s")) {
Util.message(senderName, ChatColor.RED + _("unBanGroup", I18n.PLAYER, playerName, I18n.SENDER, senderName));
} else if (response.get("result").equals("n")) {
Util.message(senderName, ChatColor.RED + _("unBanNot", I18n.PLAYER, playerName, I18n.SENDER, senderName));
}
log.info(senderName + " tried to unban " + playerName + "!");
}
public void localBan() {
// Call PlayerLocalBanEvent
PlayerLocalBanEvent lBanEvent = new PlayerLocalBanEvent(playerName, playerIP, senderName, reason);
plugin.getServer().getPluginManager().callEvent(lBanEvent);
if (lBanEvent.isCancelled()){
return;
}
senderName = lBanEvent.getSenderName();
reason = lBanEvent.getReason();
JsonHandler webHandle = new JsonHandler(plugin);
HashMap<String, String> url_items = new HashMap<String, String>();
url_items.put("player", playerName);
url_items.put("playerip", playerIP);
url_items.put("reason", reason);
url_items.put("admin", senderName);
if (rollback) {
plugin.getRbHandler().rollback(senderName, playerName);
}
if (actionData != null) {
url_items.put("actionData", actionData.toString());
}
url_items.put("exec", "localBan");
HashMap<String, String> response = webHandle.mainRequest(url_items);
try {
if (response.containsKey("error")){
Util.message(senderName, ChatColor.RED + "Error: " + response.get("error"));
return;
}
if (!response.containsKey("result")) {
bukkitBan();
return;
}
if (response.get("result").equals("y")) {
this.kickPlayer(playerName, _("localBanPlayer", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
Util.broadcastMessage(ChatColor.GREEN + _("localBanSuccess", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
plugin.getServer().getPluginManager().callEvent(new PlayerBannedEvent(playerName, playerIP, senderName, reason, action_id, duration, measure));
log.info(playerName + " has been banned with a local type ban [" + reason + "] [" + senderName + "]!");
return;
} else if (response.get("result").equals("e")) {
Util.message(senderName,
ChatColor.RED + _("localBanError", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
} else if (response.get("result").equals("s")) {
Util.message(senderName,
ChatColor.RED + _("localBanGroup", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
} else if (response.get("result").equals("a")) {
Util.message(senderName,
ChatColor.RED + _("localBanAlready", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
}
log.info(senderName + " has tried to ban " + playerName + " with a local type ban [" + reason + "]!");
} catch (Exception ex) {
bukkitBan();
log.warning("Error occurred in localBan. Please report this!");
ex.printStackTrace();
}
}
public void globalBan() {
// Call PlayerGlobalBanEvent
PlayerGlobalBanEvent gBanEvent = new PlayerGlobalBanEvent(playerName, playerIP, senderName, reason);
plugin.getServer().getPluginManager().callEvent(gBanEvent);
if (gBanEvent.isCancelled()){
return;
}
senderName = gBanEvent.getSenderName();
reason = gBanEvent.getReason();
JsonHandler webHandle = new JsonHandler(plugin);
HashMap<String, String> url_items = new HashMap<String, String>();
url_items.put("player", playerName);
url_items.put("playerip", playerIP);
url_items.put("reason", reason);
url_items.put("admin", senderName);
// Put proof
try{
for (Map.Entry<String, JSONObject> proof : getProof().entrySet()){
actionData.put(proof.getKey(), proof.getValue());
}
}catch (JSONException ex){
if (plugin.getConfigs().isDebug()) {
ex.printStackTrace();
}
}
if (rollback) {
plugin.getRbHandler().rollback(senderName, playerName);
}
if (actionData.length() > 0) {
url_items.put("actionData", actionData.toString());
}
url_items.put("exec", "globalBan");
HashMap<String, String> response = webHandle.mainRequest(url_items);
try {
if (response.containsKey("error")){
Util.message(senderName, ChatColor.RED + "Error: " + response.get("error"));
return;
}
if (!response.containsKey("result")) {
bukkitBan();
return;
}
if (response.get("result").equals("y")) {
this.kickPlayer(playerName, _("globalBanPlayer", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
Util.broadcastMessage(ChatColor.GREEN + _("globalBanSuccess", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
plugin.getServer().getPluginManager().callEvent(new PlayerBannedEvent(playerName, playerIP, senderName, reason, action_id, duration, measure));
log.info(playerName + " has been banned with a global type ban [" + reason + "] [" + senderName + "]!");
return;
} else if (response.get("result").equals("e")) {
Util.message(senderName,
ChatColor.RED + _("globalBanError", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
} else if (response.get("result").equals("w")) {
badword = response.get("word");
Util.message(senderName,
ChatColor.RED + _("globalBanWarning", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP, I18n.BADWORD, badword));
} else if (response.get("result").equals("s")) {
Util.message(senderName,
ChatColor.RED + _("globalBanGroup", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
} else if (response.get("result").equals("a")) {
Util.message(senderName,
ChatColor.RED + _("globalBanAlready", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
}
log.info(senderName + " has tried to ban " + playerName + " with a global type ban [" + reason + "]!");
} catch (Exception ex) {
bukkitBan();
log.warning("Error occurred in globalBan. Please report this!");
ex.printStackTrace();
}
}
public void tempBan() {
// Call PlayerTempBanEvent
PlayerTempBanEvent tBanEvent = new PlayerTempBanEvent(playerName, playerIP, senderName, reason, duration, measure);
plugin.getServer().getPluginManager().callEvent(tBanEvent);
if (tBanEvent.isCancelled()){
return;
}
senderName = tBanEvent.getSenderName();
reason = tBanEvent.getReason();
duration = tBanEvent.getDuration();
measure = tBanEvent.getMeasure();
JsonHandler webHandle = new JsonHandler(plugin);
HashMap<String, String> url_items = new HashMap<String, String>();
url_items.put("player", playerName);
url_items.put("playerip", playerIP);
url_items.put("reason", reason);
url_items.put("admin", senderName);
url_items.put("duration", duration);
url_items.put("measure", measure);
if (actionData != null) {
url_items.put("actionData", actionData.toString());
}
url_items.put("exec", "tempBan");
HashMap<String, String> response = webHandle.mainRequest(url_items);
try {
if (response.containsKey("error")){
Util.message(senderName, ChatColor.RED + "Error: " + response.get("error"));
return;
}
if (!response.containsKey("result")) {
//bukkitBan(); // don't use default ban
Util.message(senderName, ChatColor.RED + " MCBans down, please try again later.");
return;
}
if (response.get("result").equals("y")) {
this.kickPlayer(playerName, _("tempBanPlayer", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
Util.broadcastMessage(ChatColor.GREEN + _("tempBanSuccess", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
plugin.getServer().getPluginManager().callEvent(new PlayerBannedEvent(playerName, playerIP, senderName, reason, action_id, duration, measure));
log.info(playerName + " has been banned with a temp type ban [" + reason + "] [" + senderName + "]!");
return;
} else if (response.get("result").equals("e")) {
Util.message(senderName,
ChatColor.RED + _("tempBanError", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
} else if (response.get("result").equals("s")) {
Util.message(senderName,
ChatColor.RED + _("tempBanGroup", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
} else if (response.get("result").equals("a")) {
Util.message(senderName,
ChatColor.RED + _("tempBanAlready", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
} else if (response.get("result").equals("n")){
if (response.get("msg") != null){
Util.message(senderName, ChatColor.RED + response.get("msg"));
}else{
Util.message(senderName,
ChatColor.RED + _("tempBanError", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
}
}
log.info(senderName + " has tried to ban " + playerName + " with a temp type ban [" + reason + "]!");
} catch (Exception ex) {
//bukkitBan();
log.warning("Error occurred in tempBan. Please report this!");
ex.printStackTrace();
}
}
private void bukkitBan(){
Util.message(senderName, ChatColor.RED + " MCBans down, adding bukkit default ban, unban with /pardon");
OfflinePlayer target = plugin.getServer().getOfflinePlayer(playerName);
if (!target.isBanned()) {
target.setBanned(true);
}
this.kickPlayer(playerName, _("localBanPlayer", I18n.PLAYER, playerName, I18n.SENDER, senderName, I18n.REASON, reason, I18n.IP, playerIP));
}
private Map<String, JSONObject> getProof() throws JSONException{
HashMap<String, JSONObject> ret = new HashMap<String, JSONObject>();
/* Hacked client */
// No catch PatternSyntaxException. This exception thrown when compiling invalid regex.
// In this case, regex is constant string. Next line is wrong if throw this. So should output full exception message.
Pattern regex = Pattern.compile("(fly|hack|nodus|glitch|exploit|NC|cheat|nuker|x-ray|xray)");
boolean foundMatch = regex.matcher(reason).find();
if (foundMatch) {
Player p = plugin.getServer().getPlayerExact(playerName);
if (p != null) playerName = p.getName();
// NoCheatPlus
if (plugin.isEnabledNCP()) {
ViolationHistory history = ViolationHistory.getHistory(playerName, false);
if (history != null){
// found player history
final ViolationLevel[] violations = history.getViolationLevels();
JSONObject tmp = new JSONObject();
for (ViolationLevel vl : violations){
tmp.put(vl.check, String.valueOf(Math.round(vl.sumVL)));
}
ret.put("nocheatplus", tmp);
//ActionData.put("nocheatplus", tmp); // don't put directly
}
}
// AntiCheat
if (plugin.isEnabledAC() && p.getPlayer() != null) {
JSONObject tmp = new JSONObject();
final int level = AnticheatAPI.getLevel(p);
final boolean xray = AnticheatAPI.isXrayer(p);
// TODO: Detail proof. Refer AntiCheat CommandHandler:
if (level > 0) tmp.put("hack level", String.valueOf(level));
if (xray) tmp.put("detected x-ray", "true");
if (tmp.length() > 0) ret.put("anticheat", tmp);
}
}
return ret;
}
}
|
package com.thesis.file;
import org.objectweb.asm.*;
import org.objectweb.asm.util.Printer;
public class DecompilerFieldVisitor extends FieldVisitor {
private final Printer printer;
public DecompilerFieldVisitor(FieldVisitor fieldVisitor, Printer printer) {
super(Opcodes.ASM5, fieldVisitor);
this.printer = printer;
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
Printer p = printer.visitFieldAnnotation(desc, visible);
AnnotationVisitor av = fv == null ? null : fv.visitAnnotation(desc, visible);
return new DecompilerAnnotationVisitor(av, p);
}
@Override
public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
Printer p = printer.visitFieldTypeAnnotation(typeRef, typePath, desc, visible);
AnnotationVisitor av = fv == null ? null : fv.visitTypeAnnotation(typeRef, typePath, desc, visible);
return new DecompilerAnnotationVisitor(av, p);
}
@Override
public void visitAttribute(Attribute attr) {
printer.visitFieldAttribute(attr);
super.visitAttribute(attr);
}
@Override
public void visitEnd() {
printer.visitFieldEnd();
super.visitEnd();
}
}
|
package com.valkryst.AsciiPanel;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import lombok.Getter;
import lombok.Setter;
public class AsciiCharacter {
/** The character. */
@Getter @Setter private char character;
/** The background color. Defaults to black. */
@Getter private Paint backgroundColor = Color.BLACK;
/** The foreground color. Defaults to white. */
@Getter private Paint foregroundColor = Color.WHITE;
/**
* Constructs a new AsciiCharacter.
*
* @param character
* The character.
*/
public AsciiCharacter(final char character) {
this.character = character;
}
@Override
public String toString() {
String string = "Character:\n";
string += "\tCharacter: '" + character + "'\n";
string += "\tBackground Color: " + backgroundColor + "\n";
string += "\tForeground Color: " + foregroundColor + "\n";
return string;
}
@Override
public boolean equals(final Object object) {
if (object instanceof AsciiCharacter == false) {
return false;
}
final AsciiCharacter otherCharacter = (AsciiCharacter) object;
if (character != otherCharacter.character) {
return false;
}
if (backgroundColor.equals(otherCharacter.backgroundColor) == false) {
return false;
}
if (foregroundColor.equals(otherCharacter.foregroundColor) == false) {
return false;
}
return true;
}
/**
* Draws the character onto the specified context.
*
* @param gc
* The context on which to draw.
*
* @param font
* The font to draw with.
*
* @param columnIndex
* The x-axis (column) coordinate where the character is to be drawn.
*
* @param rowIndex
* The y-axis (row) coordinate where the character is to be drawn.
*/
public void draw(final GraphicsContext gc, final AsciiFont font, double columnIndex, double rowIndex) {
final double fontWidth = font.getWidth();
final double fontHeight = font.getHeight();
columnIndex *= fontWidth;
rowIndex *= fontHeight;
gc.setFill(backgroundColor);
gc.fillRect(columnIndex, rowIndex, columnIndex + fontWidth, rowIndex + fontHeight);
gc.setFill(foregroundColor);
gc.fillText(String.valueOf(character), columnIndex, rowIndex + fontHeight, fontWidth);
}
/**
* Sets the new background color.
*
* Does nothing if the specified color is null.
*
* @param color
* The new background color.
*/
public void setBackgroundColor(final Paint color) {
boolean canProceed = color != null;
canProceed &= backgroundColor.equals(color) == false;
if (canProceed) {
this.backgroundColor = color;
}
}
/**
* Sets the new foreground color.
*
* Does nothing if the specified color is null.
*
* @param color
* The new foreground color.
*/
public void setForegroundColor(final Paint color) {
boolean canProceed = color != null;
canProceed &= foregroundColor.equals(color) == false;
if (canProceed) {
this.foregroundColor = color;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.