diff
stringlengths 164
2.11M
| is_single_chunk
bool 2
classes | is_single_function
bool 2
classes | buggy_function
stringlengths 0
335k
⌀ | fixed_function
stringlengths 23
335k
⌀ |
---|---|---|---|---|
diff --git a/RapidFTR-Blackberry/src/com/rapidftr/utilities/ImageUtility.java b/RapidFTR-Blackberry/src/com/rapidftr/utilities/ImageUtility.java
index 870fa7a..2b473a4 100755
--- a/RapidFTR-Blackberry/src/com/rapidftr/utilities/ImageUtility.java
+++ b/RapidFTR-Blackberry/src/com/rapidftr/utilities/ImageUtility.java
@@ -1,90 +1,94 @@
package com.rapidftr.utilities;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
public class ImageUtility {
public static Bitmap scaleImage(EncodedImage encodedImage,
int requiredWidth, int requiredHeight) {
int currentWidth = Fixed32.toFP(encodedImage.getWidth());
int currentHeight = Fixed32.toFP(encodedImage.getHeight());
int scaleXFixed32 = Fixed32.div(currentWidth, requiredWidth);
int scaleYFixed32 = Fixed32.div(currentHeight, requiredHeight);
EncodedImage image = encodedImage.scaleImage32(scaleXFixed32,
scaleYFixed32);
return image.getBitmap();
}
public static Bitmap resizeBitmap(Bitmap image, int width, int height) {
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
// Need an array (for RGB, with the size of original image)
int rgb[] = new int[imageWidth * imageHeight];
// Get the RGB array of image into "rgb"
image.getARGB(rgb, 0, imageWidth, 0, 0, imageWidth, imageHeight);
// Call to our function and obtain rgb2
int rgb2[] = rescaleArray(rgb, imageWidth, imageHeight, width, height);
// Create an image with that RGB array
Bitmap temp2 = new Bitmap(width, height);
temp2.setARGB(rgb2, 0, width, 0, 0, width, height);
return temp2;
}
private static int[] rescaleArray(int[] ini, int x, int y, int x2, int y2) {
int out[] = new int[x2 * y2];
for (int yy = 0; yy < y2; yy++) {
int dy = yy * y / y2;
for (int xx = 0; xx < x2; xx++) {
int dx = xx * x / x2;
out[(x2 * yy) + xx] = ini[(x * dy) + dx];
}
}
return out;
}
public static EncodedImage getBitmapImageForPath(String Path)
{
// String ImagePath = "file://"+ Path;
String ImagePath = Path;
FileConnection fconn;
try {
fconn = (FileConnection) Connector.open(ImagePath,
Connector.READ);
if (fconn.exists()) {
byte[] imageBytes = new byte[(int) fconn.fileSize()];
InputStream inStream = fconn.openInputStream();
inStream.read(imageBytes);
inStream.close();
EncodedImage eimg= EncodedImage.createEncodedImage(
imageBytes, 0, (int) fconn.fileSize());
fconn.close();
return eimg;
}
- } catch (IOException e) {
+ }catch (IllegalArgumentException e)
+ {
+ return EncodedImage.getEncodedImageResource("res\\head.png") ;
+ }
+ catch (IOException e) {
e.printStackTrace();
- return null ;
+ return EncodedImage.getEncodedImageResource("res\\head.png") ;
}
return null;
}
}
| false | true | public static EncodedImage getBitmapImageForPath(String Path)
{
// String ImagePath = "file://"+ Path;
String ImagePath = Path;
FileConnection fconn;
try {
fconn = (FileConnection) Connector.open(ImagePath,
Connector.READ);
if (fconn.exists()) {
byte[] imageBytes = new byte[(int) fconn.fileSize()];
InputStream inStream = fconn.openInputStream();
inStream.read(imageBytes);
inStream.close();
EncodedImage eimg= EncodedImage.createEncodedImage(
imageBytes, 0, (int) fconn.fileSize());
fconn.close();
return eimg;
}
} catch (IOException e) {
e.printStackTrace();
return null ;
}
return null;
}
| public static EncodedImage getBitmapImageForPath(String Path)
{
// String ImagePath = "file://"+ Path;
String ImagePath = Path;
FileConnection fconn;
try {
fconn = (FileConnection) Connector.open(ImagePath,
Connector.READ);
if (fconn.exists()) {
byte[] imageBytes = new byte[(int) fconn.fileSize()];
InputStream inStream = fconn.openInputStream();
inStream.read(imageBytes);
inStream.close();
EncodedImage eimg= EncodedImage.createEncodedImage(
imageBytes, 0, (int) fconn.fileSize());
fconn.close();
return eimg;
}
}catch (IllegalArgumentException e)
{
return EncodedImage.getEncodedImageResource("res\\head.png") ;
}
catch (IOException e) {
e.printStackTrace();
return EncodedImage.getEncodedImageResource("res\\head.png") ;
}
return null;
}
|
diff --git a/org.eclipse.symfony.core/src/org/eclipse/symfony/core/index/visitor/TemplateVariableVisitor.java b/org.eclipse.symfony.core/src/org/eclipse/symfony/core/index/visitor/TemplateVariableVisitor.java
index 545a99a5..a794c7c7 100644
--- a/org.eclipse.symfony.core/src/org/eclipse/symfony/core/index/visitor/TemplateVariableVisitor.java
+++ b/org.eclipse.symfony.core/src/org/eclipse/symfony/core/index/visitor/TemplateVariableVisitor.java
@@ -1,509 +1,516 @@
package org.eclipse.symfony.core.index.visitor;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.eclipse.dltk.ast.expressions.CallArgumentsList;
import org.eclipse.dltk.ast.expressions.Expression;
import org.eclipse.dltk.ast.references.SimpleReference;
import org.eclipse.dltk.ast.references.VariableReference;
import org.eclipse.php.internal.core.compiler.ast.nodes.ArrayCreation;
import org.eclipse.php.internal.core.compiler.ast.nodes.ArrayElement;
import org.eclipse.php.internal.core.compiler.ast.nodes.Assignment;
import org.eclipse.php.internal.core.compiler.ast.nodes.ClassInstanceCreation;
import org.eclipse.php.internal.core.compiler.ast.nodes.FullyQualifiedReference;
import org.eclipse.php.internal.core.compiler.ast.nodes.NamespaceDeclaration;
import org.eclipse.php.internal.core.compiler.ast.nodes.PHPCallExpression;
import org.eclipse.php.internal.core.compiler.ast.nodes.PHPDocBlock;
import org.eclipse.php.internal.core.compiler.ast.nodes.PHPMethodDeclaration;
import org.eclipse.php.internal.core.compiler.ast.nodes.ReturnStatement;
import org.eclipse.php.internal.core.compiler.ast.nodes.Scalar;
import org.eclipse.php.internal.core.compiler.ast.nodes.UsePart;
import org.eclipse.php.internal.core.compiler.ast.nodes.UseStatement;
import org.eclipse.php.internal.core.compiler.ast.visitor.PHPASTVisitor;
import org.eclipse.symfony.core.log.Logger;
import org.eclipse.symfony.core.model.Service;
import org.eclipse.symfony.core.model.SymfonyModelAccess;
import org.eclipse.symfony.core.model.TemplateVariable;
import org.eclipse.symfony.core.preferences.SymfonyCoreConstants;
import org.eclipse.symfony.core.util.AnnotationUtils;
import org.eclipse.symfony.core.util.ModelUtils;
import org.eclipse.symfony.core.util.PathUtils;
import org.eclipse.symfony.index.dao.Route;
/**
*
* The {@link TemplateVariableVisitor} indexes collects
* templateVariables in Symfony2 controller classes.
*
*
* @author Robert Gruendler <[email protected]>
*
*/
@SuppressWarnings("restriction")
public class TemplateVariableVisitor extends PHPASTVisitor {
// The templatevariables with their corresponding ViewPath
private Map<TemplateVariable, String> templateVariables = new HashMap<TemplateVariable, String>();
// The variables found during method parsing
private Stack<TemplateVariable> deferredVariables = new Stack<TemplateVariable>();
private PHPMethodDeclaration currentMethod;
final private List<UseStatement> useStatements;
final private NamespaceDeclaration namespace;
private boolean inAction = false;
private String currentAnnotationPath;
private Stack<Route> routes = new Stack<Route>();
final private String bundle;
private String controller;
public TemplateVariableVisitor(List<UseStatement> useStatements, NamespaceDeclaration namespace) {
this.namespace = namespace;
this.useStatements = useStatements;
bundle = ModelUtils.extractBundleName(namespace);
}
public Map<TemplateVariable, String> getTemplateVariables() {
return templateVariables;
}
/**
*
* Visit a {@link PHPMethodDeclaration} and check
* if it's an Action.
*
*/
@Override
public boolean visit(PHPMethodDeclaration method) throws Exception {
currentMethod = method;
deferredVariables = new Stack<TemplateVariable>();
controller = currentMethod.getDeclaringTypeName().replace(SymfonyCoreConstants.CONTROLLER_CLASS, "");
if (method.getName().endsWith(SymfonyCoreConstants.ACTION_SUFFIX)) {
inAction = true;
PHPDocBlock docs = method.getPHPDoc();
if (docs != null) {
//TODO: use the AnnotationParser for this instead
BufferedReader buffer = new BufferedReader(new StringReader(docs.getShortDescription()));
try {
String line;
while((line = buffer.readLine()) != null) {
if (line.startsWith(SymfonyCoreConstants.TEMPLATE_ANNOTATION)) {
parseTemplateAnnotation(line);
} else if (line.startsWith(SymfonyCoreConstants.ROUTE_ANNOTATION)) {
processRoute(line);
}
}
} catch (Exception e) {
Logger.logException(e);
}
}
}
return true;
}
/**
*
* Parse a route from the annotation and
* push it to the route stack for later indexing.
*
* @param annotation
*/
private void processRoute(String annotation) {
String action = currentMethod.getName().replace(SymfonyCoreConstants.ACTION_SUFFIX, "");
Route route = AnnotationUtils.getRoute(annotation, bundle, controller, action);
if (route != null) {
routes.push(route);
}
}
private void parseTemplateAnnotation(String annotation) {
int start = -1;
int end = -1;
if ((start = annotation.indexOf("\"")) > -1) {
end = annotation.lastIndexOf("\"");
} else if ( (start = annotation.indexOf("'")) > -1) {
end = annotation.lastIndexOf("'");
}
if (start > -1 && end > -1) {
String path = annotation.substring(start, end+1);
currentAnnotationPath = PathUtils.createViewPath(path);
}
}
@Override
public boolean endvisit(PHPMethodDeclaration s) throws Exception {
currentAnnotationPath = null;
deferredVariables = null;
currentMethod = null;
inAction = false;
return true;
}
/**
* Parse {@link ReturnStatement}s and try to evaluate
* the variables.
*
*/
@Override
@SuppressWarnings("unchecked")
public boolean visit(ReturnStatement statement) throws Exception {
// we're inside an action, find the template variables
if (inAction) {
// the simplest case:
// return array('foo' => $bar);
if (statement.getExpr().getClass() == ArrayCreation.class) {
if (namespace != null) {
String viewPath = null;
if (currentAnnotationPath != null) {
viewPath = currentAnnotationPath;
} else {
String template = currentMethod.getName().replace(SymfonyCoreConstants.ACTION_SUFFIX, "");
viewPath = String.format("%s:%s:%s", bundle, controller, template);
}
if (viewPath != null ) {
ArrayCreation array = (ArrayCreation) statement.getExpr();
parseVariablesFromArray(array, viewPath);
}
}
// a render call:
// return return $this->render("DemoBundle:Test:index.html.twig", array('foo' => $bar));
} else if (statement.getExpr().getClass() == PHPCallExpression.class) {
PHPCallExpression expression = (PHPCallExpression) statement.getExpr();
String callName = expression.getCallName().getName();
if (callName.startsWith(SymfonyCoreConstants.RENDER_PREFIX)) {
CallArgumentsList args = expression.getArgs();
List<Object> children = args.getChilds();
Scalar view = (Scalar) children.get(0);
if (children.size() >= 2 && children.get(1).getClass() == ArrayCreation.class) {
parseVariablesFromArray((ArrayCreation) children.get(1), PathUtils.createViewPath(view));
} else {
Logger.log(Logger.WARNING, "Unable to parse view variable from " + children.toString());
}
}
}
}
return true;
}
/**
*
* Parse the TemplateVariables from the given {@link ReturnStatement}
* @param viewPath
* @param statement
*/
private void parseVariablesFromArray(ArrayCreation array, String viewPath) {
for (ArrayElement element : array.getElements()) {
Expression key = element.getKey();
Expression value = element.getValue();
if (key.getClass() == Scalar.class) {
Scalar varName = (Scalar) key;
// something in the form: return array ('foo' => $bar);
// check the type of $bar:
if (value.getClass() == VariableReference.class) {
VariableReference ref = (VariableReference) value;
for (TemplateVariable variable : deferredVariables) {
// we got the variable, add it the the templateVariables
if (ref.getName().equals(variable.getName())) {
// alter the variable name
variable.setName(varName.getValue());
templateVariables.put(variable, viewPath);
break;
}
}
// this is more complicated, something like:
// return array('form' => $form->createView());
// we need to infer $form and then check the returntype of createView()
} else if(value.getClass() == PHPCallExpression.class) {
PHPCallExpression callExp = (PHPCallExpression) value;
VariableReference varRef = null;
try {
varRef = (VariableReference) callExp.getReceiver();
} catch (ClassCastException e) {
Logger.log(Logger.WARNING, callExp.getReceiver().getClass().toString()
+ " could not be cast to VariableReference in " + currentMethod.getName() );
}
if (varRef == null) {
continue;
}
SimpleReference callName = callExp.getCallName();
// we got the variable name (in this case $form)
// now search for the defferedVariable:
for (TemplateVariable deferred : deferredVariables) {
// we got it, find the returntype of the
// callExpression
if (deferred.getName().equals(varRef.getName())) {
TemplateVariable tempVar = SymfonyModelAccess.getDefault()
.createTemplateVariableByReturnType(currentMethod,
callName, deferred.getClassName(), deferred.getNamespace(),
varRef.getName());
templateVariables.put(tempVar, viewPath);
break;
}
}
// this is a direct ClassInstanceCreation, ie:
// return array('user' => new User());
} else if (value.getClass() == ClassInstanceCreation.class) {
ClassInstanceCreation instance = (ClassInstanceCreation) value;
if (instance.getClassName().getClass() == FullyQualifiedReference.class) {
FullyQualifiedReference fqcn = (FullyQualifiedReference) instance.getClassName();
NamespaceReference nsRef = createFromFQCN(fqcn);
if (nsRef != null) {
TemplateVariable variable = new TemplateVariable(currentMethod, varName.getValue(),
varName.sourceStart(), varName.sourceEnd(), nsRef.getNamespace(), nsRef.getClassName());
templateVariables.put(variable, viewPath);
}
}
} else {
Logger.debugMSG("array value: " + value.getClass());
}
}
}
}
/**
*
* Collect all Assignments inside a {@link PHPMethodDeclaration}
* to infer them in the ReturnStatements and add it to the
* templateVariables.
*
*/
@Override
public boolean visit(Assignment s) throws Exception {
if (inAction) {
Service service = null;
if (s.getVariable().getClass() == VariableReference.class) {
VariableReference var = (VariableReference) s.getVariable();
// A call expression like $foo = $this->get('bar');
//
if (s.getValue().getClass() == PHPCallExpression.class) {
PHPCallExpression exp = (PHPCallExpression) s.getValue();
// are we requesting a Service?
if (exp.getName().equals("get")) {
service = ModelUtils.extractServiceFromCall(exp);
- if (service != null) {
- TemplateVariable tempVar= new TemplateVariable(currentMethod, var.getName(), exp.sourceStart(), exp.sourceEnd(), service.getNamespace().getQualifiedName(), service.getClassName());
+ String fqsn = service.getNamespace() != null ? service.getNamespace().getQualifiedName() : null;
+
+ if (service != null && fqsn != null) {
+ TemplateVariable tempVar= new TemplateVariable(currentMethod, var.getName(), exp.sourceStart(), exp.sourceEnd(), fqsn, service.getClassName());
deferredVariables.push(tempVar);
}
// a more complex expression like
// $form = $this->get('form.factory')->create(new ContactType());
} else if (exp.getReceiver().getClass() == PHPCallExpression.class) {
// try to extract a service if it's a Servicecontainer call
service = ModelUtils.extractServiceFromCall((PHPCallExpression) exp.getReceiver());
// nothing found, return
if (service == null || exp.getCallName() == null) {
return true;
}
SimpleReference callName = exp.getCallName();
//TODO: this is a problematic case, as during a clean build
// it's possible that the SourceModule in which the
// called method was declared is not yet in the index, so
// the return type cannot be evaluated and therefore
// the templatevariable won't be created...
//
// Possible solution: check if there's an event fired when the
// build is completed and store those return types in a global
// singleton, evaluate them when the whole build process is finished.
- TemplateVariable tempVar = SymfonyModelAccess.getDefault()
- .createTemplateVariableByReturnType(currentMethod, callName,
- service.getClassName(), service.getNamespace().getQualifiedName(), var.getName());
+
+
+ String fqsn = service.getNamespace() != null ? service.getNamespace().getQualifiedName() : null;
+ TemplateVariable tempVar = null;
+
+ tempVar = SymfonyModelAccess.getDefault()
+ .createTemplateVariableByReturnType(currentMethod, callName,
+ service.getClassName(), fqsn, var.getName());
if (tempVar != null) {
deferredVariables.push(tempVar);
}
// something like $formView = $form->createView();
} else if (exp.getReceiver().getClass() == VariableReference.class) {
VariableReference varRef = (VariableReference) exp.getReceiver();
SimpleReference ref = exp.getCallName();
// check for a previosly declared variable
for (TemplateVariable tempVar : deferredVariables) {
if (tempVar.getName().equals(varRef.getName())) {
TemplateVariable tVar = SymfonyModelAccess.getDefault()
.createTemplateVariableByReturnType(currentMethod, ref, tempVar.getClassName(), tempVar.getNamespace(), var.getName());
if (tVar != null) {
deferredVariables.push(tVar);
break;
}
}
}
}
// a simple ClassInstanceCreation, ie. $contact = new ContactType();
} else if (s.getValue().getClass() == ClassInstanceCreation.class) {
ClassInstanceCreation instance = (ClassInstanceCreation) s.getValue();
if (instance.getClassName().getClass() == FullyQualifiedReference.class) {
FullyQualifiedReference fqcn = (FullyQualifiedReference) instance.getClassName();
NamespaceReference nsRef = createFromFQCN(fqcn);
if (nsRef != null) {
TemplateVariable variable = new TemplateVariable(currentMethod, var.getName(),
var.sourceStart(), var.sourceEnd(), nsRef.getNamespace(), nsRef.getClassName());
deferredVariables.push(variable);
}
}
}
}
}
return true;
}
/**
*
* Get the ClassName and Namespace from a {@link FullyQualifiedReference}
*
* @param fqcn
* @return
*/
private NamespaceReference createFromFQCN(FullyQualifiedReference fqcn) {
for (UseStatement use : useStatements) {
for (UsePart part : use.getParts()) {
if (part.getNamespace().getName().equals(fqcn.getName())) {
String name = fqcn.getName();
String qualifier = part.getNamespace().getNamespace().getName();
return new NamespaceReference(qualifier, name);
}
}
}
return null;
}
/**
* Simple helper class to pass around namespaces.
*/
private class NamespaceReference {
private String namespace;
private String className;
public NamespaceReference(String qualifier, String name) {
this.namespace = qualifier;
this.className = name;
}
public String getNamespace() {
return namespace;
}
public String getClassName() {
return className;
}
}
public Stack<Route> getRoutes() {
return routes;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/de.fu_berlin.inf.dpp/test/junit/de/fu_berlin/inf/dpp/test/fakes/EclipseResourceFake.java b/de.fu_berlin.inf.dpp/test/junit/de/fu_berlin/inf/dpp/test/fakes/EclipseResourceFake.java
index 11ce19e77..a48b85ea9 100644
--- a/de.fu_berlin.inf.dpp/test/junit/de/fu_berlin/inf/dpp/test/fakes/EclipseResourceFake.java
+++ b/de.fu_berlin.inf.dpp/test/junit/de/fu_berlin/inf/dpp/test/fakes/EclipseResourceFake.java
@@ -1,390 +1,388 @@
package de.fu_berlin.inf.dpp.test.fakes;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IPathVariableManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourceAttributes;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
/**
* Fake-Implementation of {@link org.eclipse.core.resources.IResource}.
*
* Wrappes a {@link java.io.File} to delegate the the most functionality.
*
* If you call a functionallity which is not implemented you will get a
* {@link UnsupportedOperationException}.
*
* @see de.fu_berlin.inf.dpp.test.util.EclipseWorkspaceFakeFacadeTest
* @author cordes
*/
public abstract class EclipseResourceFake implements IResource {
protected File wrappedFile;
protected EclipseProjectFake project;
protected EclipseResourceFake(File wrappedFile) {
this.wrappedFile = wrappedFile;
}
public void accept(IResourceProxyVisitor iResourceProxyVisitor, int i)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void accept(IResourceVisitor iResourceVisitor) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void accept(IResourceVisitor iResourceVisitor, int i, boolean b)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void accept(IResourceVisitor iResourceVisitor, int i, int i1)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void clearHistory(IProgressMonitor iProgressMonitor)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void copy(IPath iPath, boolean b, IProgressMonitor iProgressMonitor)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void copy(IPath iPath, int i, IProgressMonitor iProgressMonitor)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void copy(IProjectDescription iProjectDescription, boolean b,
IProgressMonitor iProgressMonitor) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void copy(IProjectDescription iProjectDescription, int i,
IProgressMonitor iProgressMonitor) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public IMarker createMarker(String s) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public IResourceProxy createProxy() {
throw new UnsupportedOperationException("not yet implemented");
}
public void delete(boolean b, IProgressMonitor iProgressMonitor)
throws CoreException {
FileUtils.deleteQuietly(wrappedFile);
}
public void delete(int i, IProgressMonitor iProgressMonitor)
throws CoreException {
FileUtils.deleteQuietly(wrappedFile);
}
public void deleteMarkers(String s, boolean b, int i) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean exists() {
return wrappedFile.exists();
}
public IMarker findMarker(long l) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public IMarker[] findMarkers(String s, boolean b, int i)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public int findMaxProblemSeverity(String s, boolean b, int i)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public String getFileExtension() {
throw new UnsupportedOperationException("not yet implemented");
}
public IPath getFullPath() {
return getProjectRelativePath();
}
public long getLocalTimeStamp() {
throw new UnsupportedOperationException("not yet implemented");
}
public IPath getLocation() {
return new Path(wrappedFile.getAbsolutePath());
}
public IMarker getMarker(long l) {
throw new UnsupportedOperationException("not yet implemented");
}
public long getModificationStamp() {
throw new UnsupportedOperationException("not yet implemented");
}
public String getName() {
return wrappedFile.getName();
}
public IContainer getParent() {
return new EclipseContainerFake(wrappedFile.getParentFile());
}
@SuppressWarnings("rawtypes")
public Map getPersistentProperties() throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public String getPersistentProperty(QualifiedName qualifiedName)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public IProject getProject() {
return project;
}
public IPath getProjectRelativePath() {
- String path = wrappedFile.getPath();
- path = path.replaceAll(project.getWrappedFile().getPath(), "");
- path = path.replaceFirst("/", "");
- return new Path(path);
+ return new Path(wrappedFile.getPath().substring(
+ project.getWrappedFile().getPath().length() + 1));
}
public IPath getRawLocation() {
throw new UnsupportedOperationException("not yet implemented");
}
public URI getRawLocationURI() {
throw new UnsupportedOperationException("not yet implemented");
}
public ResourceAttributes getResourceAttributes() {
return new ResourceAttributes();
}
@SuppressWarnings("rawtypes")
public Map getSessionProperties() throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public Object getSessionProperty(QualifiedName qualifiedName)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public int getType() {
int result = -1;
if (wrappedFile.isDirectory()) {
result = FOLDER;
} else if (wrappedFile.isFile()) {
result = FILE;
}
return result;
}
public IWorkspace getWorkspace() {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isAccessible() {
return true;
}
public boolean isDerived() {
return false;
}
public boolean isDerived(int i) {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isHidden() {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isHidden(int i) {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isLinked() {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isLinked(int i) {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isLocal(int i) {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isPhantom() {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isReadOnly() {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isSynchronized(int i) {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isTeamPrivateMember() {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isTeamPrivateMember(int i) {
throw new UnsupportedOperationException("not yet implemented");
}
public void move(IPath iPath, boolean b, IProgressMonitor iProgressMonitor)
throws CoreException {
IFile newFile = project.getFile(iPath);
File newIOFile = new File(newFile.getLocation().toPortableString());
if (wrappedFile.isDirectory() || newIOFile.isDirectory()) {
try {
FileUtils.moveDirectory(wrappedFile, newIOFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
FileUtils.moveFile(wrappedFile, newIOFile);
} catch (IOException e) {
e.printStackTrace();
}
}
wrappedFile = newIOFile;
}
public void move(IPath iPath, int i, IProgressMonitor iProgressMonitor)
throws CoreException {
move(iPath, false, iProgressMonitor);
}
public void move(IProjectDescription iProjectDescription, boolean b,
boolean b1, IProgressMonitor iProgressMonitor) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void move(IProjectDescription iProjectDescription, int i,
IProgressMonitor iProgressMonitor) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void refreshLocal(int i, IProgressMonitor iProgressMonitor)
throws CoreException {
// do nothing...
}
public void revertModificationStamp(long l) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void setDerived(boolean b) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void setHidden(boolean b) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void setLocal(boolean b, int i, IProgressMonitor iProgressMonitor)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public long setLocalTimeStamp(long l) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void setPersistentProperty(QualifiedName qualifiedName, String s)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void setReadOnly(boolean b) {
throw new UnsupportedOperationException("not yet implemented");
}
public void setResourceAttributes(ResourceAttributes resourceAttributes)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void setSessionProperty(QualifiedName qualifiedName, Object o)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void setTeamPrivateMember(boolean b) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
public void touch(IProgressMonitor iProgressMonitor) throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
@SuppressWarnings("rawtypes")
public Object getAdapter(Class aClass) {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean contains(ISchedulingRule iSchedulingRule) {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isConflicting(ISchedulingRule iSchedulingRule) {
throw new UnsupportedOperationException("not yet implemented");
}
public URI getLocationURI() {
throw new UnsupportedOperationException("not yet implemented");
}
public IPathVariableManager getPathVariableManager() {
throw new UnsupportedOperationException("not yet implemented");
}
public boolean isVirtual() {
throw new UnsupportedOperationException("not yet implemented");
}
public void setDerived(boolean isDerived, IProgressMonitor monitor)
throws CoreException {
throw new UnsupportedOperationException("not yet implemented");
}
}
| true | false | null | null |
diff --git a/java/uk/ac/mrc/hgu/SectionViewer/src/sectionViewer/SectionViewer.java b/java/uk/ac/mrc/hgu/SectionViewer/src/sectionViewer/SectionViewer.java
index cd38b7a7..0bccd942 100644
--- a/java/uk/ac/mrc/hgu/SectionViewer/src/sectionViewer/SectionViewer.java
+++ b/java/uk/ac/mrc/hgu/SectionViewer/src/sectionViewer/SectionViewer.java
@@ -1,3444 +1,3444 @@
package sectionViewer;
import sectionViewer.*;
import hguUntil.*;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.io.*;
import javax.help.*;
import java.net.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import wsetter.*;
import zoom.*;
import uk.ac.mrc.hgu.Wlz.*;
public class SectionViewer
extends SectionViewerGUI
implements Serializable, WlzObjectType, WSetterConstants {
private final boolean _debug = false;
private final boolean _NBdebug = false;
// allows SectionViewer to fire events when true
private boolean _enabled = true;
protected boolean _parentIsRoot = true;
/* parent class must implement the Utils interface */
protected Container _frame = null;
protected Object _parent = null;
protected Cursor xhairCursor = new Cursor(Cursor.CROSSHAIR_CURSOR);
protected Cursor defCursor = Cursor.getDefaultCursor();
protected WlzObjModel _OBJModel = null; // grey level
protected ViewStructModel _VSModel = null;
public WlzImgView _imgV = null;
private int _FPBounce = 0; // stops initial false event from PointEntry
private int _RABounce = 0;
private WlzObject _anatomyObj = null;
private WlzObject _constraintObj = null; // wlz obj from thresh constraint
private AnatomyBuilder _anatBuilder = null;
private Stack _embFileStack = null;
private Stack _embObjStack = null;
private Stack _xembFileStack = null;
private Stack _xembObjStack = null;
private Stack _maybeFil = null;
private Stack _maybeObj = null;
protected String viewType;
String _anatomyStr;
private boolean _anatomy; // for mouse click anatomy
private boolean _thresholding;
private boolean _threshConstraint;
private boolean _fixedPoint = false;
private boolean _setFixedPoint = false;
private boolean _showStdCntrls = false;
private boolean _showUsrCntrls = false;
private boolean _showIntersection = false;
private boolean _openingView = false;
fileMenuHandler handler_1 = null;
controlMenuHandler handler_2 = null;
showMenuHandler handler_3 = null;
helpMenuHandler handler_4 = null;
// temporarily disabled ... don't remove
thresholdMenuHandler handler_5 = null;
//--------------------------------------
planeColChooser colourHandler = null;;
private String SLASH = System.getProperty("file.separator");
//=========================================================
// constructor
//=========================================================
public SectionViewer(String viewstr, Container frame, Object parent) {
if (_debug) System.out.println("enter SectionViewer");
_frame = frame;
ExtFrameActivationHandler activationHandler1 = new ExtFrameActivationHandler();
IntFrameActivationHandler activationHandler2 = new IntFrameActivationHandler();
try {
Method M1 = _frame.getClass().getDeclaredMethod(
"setTitle",
new Class[]{viewstr.getClass( )});
M1.invoke(_frame, new Object[] {viewstr});
}
catch (NoSuchMethodException ne) {
}
catch (IllegalAccessException iae) {
}
catch (InvocationTargetException ite) {
}
try {
Method M1 = _frame.getClass().getMethod(
"addWindowListener",
new Class[]{activationHandler1.getClass().getInterfaces()[0]});
M1.invoke(_frame, new Object[] {activationHandler1});
}
catch (NoSuchMethodException ne) {
}
catch (IllegalAccessException iae) {
}
catch (InvocationTargetException ite) {
}
try {
Method M1 = _frame.getClass().getDeclaredMethod(
"addInternalFrameListener",
new Class[]{activationHandler2.getClass().getInterfaces()[0]});
M1.invoke(_frame, new Object[] {activationHandler2});
}
catch (NoSuchMethodException ne) {
}
catch (IllegalAccessException iae) {
}
catch (InvocationTargetException ite) {
}
_parent = parent;
try {
Method M1 = _parent.getClass().getDeclaredMethod("root", null);
}
catch (NoSuchMethodException ne) {
// System.out.println("SVParent sub-classed");
_parentIsRoot = false;
}
_anatomy = false;
_thresholding = false;
_threshConstraint = false;
setCursor(defCursor);
addFeedback();
/*
intersectionAdaptor IA = new intersectionAdaptor(this);
this.addChangeListener(IA);
*/
// instantiate the event handlers
handler_1 = new fileMenuHandler();
handler_2 = new controlMenuHandler();
handler_3 = new showMenuHandler();
handler_4 = new helpMenuHandler();
handler_5 = new thresholdMenuHandler();
// attach event handlers to menu items
fileMenu_1.addActionListener(handler_1);
fileMenu_2.addActionListener(handler_1);
fileMenu_3.addActionListener(handler_1);
fileMenu_4.addActionListener(handler_1);
controlMenu_1_1.addActionListener(handler_2);
controlMenu_1_2.addActionListener(handler_2);
controlMenu_2_1.addActionListener(handler_2);
controlMenu_2_2.addActionListener(handler_2);
controlMenu_3_1.addActionListener(handler_2);
controlMenu_3_2.addActionListener(handler_2);
controlMenu_3_3.addActionListener(handler_2);
controlMenu_4_1.addActionListener(handler_2);
controlMenu_4_2.addActionListener(handler_2);
controlMenu_4_3.addActionListener(handler_2);
controlMenu_5.addActionListener(handler_2);
showMenu_1.addActionListener(handler_3);
showMenu_2.addActionListener(handler_3);
showMenu_3.addActionListener(handler_3);
showMenu_4.addActionListener(handler_3);
showMenu_5.addActionListener(handler_3);
thresholdMenu_1.addActionListener(handler_5);
thresholdMenu_2.addActionListener(handler_5);
thresholdMenu_3.addActionListener(handler_5);
thresholdMenu_4.addActionListener(handler_5);
helpMenu_1.addActionListener(handler_4);
helpMenu_2.addActionListener(handler_4);
helpMenu_3.addActionListener(handler_4);
colourHandler = new planeColChooser();
secColorClt.addActionListener(colourHandler);
viewType = viewstr.substring(0, 2);
if (viewType.equals("XY")) {
if (pitchSetter != null) {
pitchSetter.setValue(0.0);
}
if (yawSetter != null) {
yawSetter.setValue(0.0);
}
if (rollSetter != null) {
if (rollSetter.isSliderEnabled() == true) {
rollSetter.setValue(0.0);
}
else {
rollSetter.setSliderEnabled(true);
rollSetter.setValue(0.0);
rollSetter.setSliderEnabled(false);
}
}
}
else if (viewType.equals("YZ")) {
if (pitchSetter != null) {
pitchSetter.setValue(90.0);
}
if (yawSetter != null) {
yawSetter.setValue(0.0);
}
if (rollSetter != null) {
if (rollSetter.isSliderEnabled() == true) {
rollSetter.setValue(90.0);
}
else {
rollSetter.setSliderEnabled(true);
rollSetter.setValue(90.0);
rollSetter.setSliderEnabled(false);
}
}
}
else if (viewType.equals("ZX")) {
if (pitchSetter != null) {
pitchSetter.setValue(90.0);
}
if (yawSetter != null) {
yawSetter.setValue(90.0);
}
if (rollSetter != null) {
if (rollSetter.isSliderEnabled() == true) {
rollSetter.setValue(90.0);
}
else {
rollSetter.setSliderEnabled(true);
rollSetter.setValue(90.0);
rollSetter.setSliderEnabled(false);
}
}
}
resetFeedbackText();
if (_debug)
System.out.println("exit SectionViewer");
} // constructor
//-------------------------------------------------------------
// methods for adding / removing panels from the gui
//-------------------------------------------------------------
protected void addStandardControls() {
Dimension dim;
if (_showUsrCntrls) {
dim = new Dimension(totalW, transH);
}
else {
dim = new Dimension(totalW, pyrH);
}
transientPanel.setPreferredSize(dim);
transientPanel.setMinimumSize(dim);
transientPanel.add(pitchYawRollPanel, BorderLayout.NORTH);
//_rootPane.validate();
revalidate();
repaint();
}
protected void removeStandardControls() {
Dimension dim;
if (_showUsrCntrls) {
dim = new Dimension(totalW, rotH);
}
else {
dim = new Dimension(totalW, pad);
}
transientPanel.setPreferredSize(dim);
transientPanel.setMinimumSize(dim);
transientPanel.remove(pitchYawRollPanel);
transientPanel.repaint();
//_rootPane.validate();
revalidate();
repaint();
}
//...............................
protected void addUserControls() {
Dimension dim;
if (_showStdCntrls) {
dim = new Dimension(totalW, transH);
}
else {
dim = new Dimension(totalW, rotH);
}
transientPanel.setPreferredSize(dim);
transientPanel.setMinimumSize(dim);
transientPanel.add(userDefinedRotPanel, BorderLayout.SOUTH);
//_rootPane.validate();
revalidate();
repaint();
}
protected void removeUserControls() {
Dimension dim;
if (_showStdCntrls) {
dim = new Dimension(totalW, pyrH);
}
else {
dim = new Dimension(totalW, pad);
}
transientPanel.setPreferredSize(dim);
transientPanel.setMinimumSize(dim);
transientPanel.remove(userDefinedRotPanel);
transientPanel.repaint();
//_rootPane.validate();
revalidate();
repaint();
}
//...............................
protected void addFeedback() {
feedbackImagePanel.add(feedbackPanel, BorderLayout.NORTH);
//_rootPane.validate();
revalidate();
repaint();
}
protected void removeFeedback() {
feedbackImagePanel.remove(feedbackPanel);
feedbackImagePanel.repaint();
//_rootPane.validate();
revalidate();
repaint();
}
//-------------------------------------------------------------
// methods for opening / closing views
//-------------------------------------------------------------
public void openView() {
if (null == _parent) {
System.out.println("There no object in system!!!");
return;
}
if (_imgV != null) {
_bigPanel.remove(_imgV);
_bigPanel.repaint();
_imageScrollPane.validate();
_imgV = null;
_anatBuilder = null;
_embFileStack = null;
_xembFileStack = null;
_embObjStack = null;
_xembObjStack = null;
resetFeedbackText();
}
_imgV = new WlzImgView();
_bigPanel.add(_imgV);
if (_OBJModel != null) {
_OBJModel = null;
}
if (_VSModel != null) {
_VSModel = null;
}
_openingView = true;
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod("getOBJModel", null);
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod("getOBJModel", null);
}
_OBJModel = (WlzObjModel) M1.invoke(_parent, null);
}
catch (InvocationTargetException e) {
System.out.println(e.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("getOBJModel: no such method");
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
_VSModel = new ViewStructModel(_OBJModel);
_OBJModel.makeSection(_VSModel.getViewStruct());
setDistLimits(0.0);
connectAdaptors_1();
// set WSetters according to which view is set
resetGUI();
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod("getTitleText", null);
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod(
"getTitleText", null);
}
setTitleText( (String) M1.invoke(_parent, null));
}
catch (InvocationTargetException e) {
System.out.println(e.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("getTitleText: no such method 1");
System.out.println(ne.getMessage());
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
//setTitleText(_parent.getTitleText());
setViewTitle();
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod("getAnatomyBuilder", null);
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod(
"getAnatomyBuilder", null);
}
_anatBuilder = (AnatomyBuilder) M1.invoke(_parent, null);
}
catch (InvocationTargetException e) {
System.out.println(e.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("getAnatomyBuilder: no such method 1");
System.out.println(ne.getMessage());
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
Thread t = new Thread(rStack);
t.start();
//printModelInfo();
/* to show intersection of this view on existing views */
_VSModel.fireChange();
_openingView = false;
} // openView()
//---------------------------------------
protected void closeView() {
if (WI2P_1 != null)
_imgV.removeChangeListener(WI2P_1);
if (WI2G_1 != null)
_imgV.removeChangeListener(WI2G_1);
_imgV = null;
_embFileStack = null;
_xembFileStack = null;
_embObjStack = null;
_xembObjStack = null;
_OBJModel = null;
} // closeView()
//-------------------------------------------------------------
// set max & min for distSetter
// (needs to be done when grey level file is opened &
// after every angle change)
//-------------------------------------------------------------
protected void setDistLimits(double val) {
double results[];
double min = 0.0;
double max = 0.0;
results = _OBJModel.getMaxMin(_VSModel.getViewStruct());
min = results[5];
max = results[2];
distSetter.setMin(min);
distSetter.setMax(max);
distSetter.setValue(val);
}
//-------------------------------------------------------------
// set the title text
//-------------------------------------------------------------
protected void setTitleText(String title) {
titleText.setText(title);
}
//-------------------------------------------------------------
// re-set Feedback text
//-------------------------------------------------------------
protected void resetFeedbackText() {
resetPosGreyText();
resetAnatomyText();
}
//-------------------------------------------------------------
// re-set pos & grey text
//-------------------------------------------------------------
protected void resetPosGreyText() {
xyzTextField.setText("-----");
valueTextField.setText("-");
}
//-------------------------------------------------------------
// re-set anatomy text
//-------------------------------------------------------------
protected void resetAnatomyText() {
anatomyTextField.setText("-----");
}
//-------------------------------------------------------------
// print model info
//-------------------------------------------------------------
protected void printModelInfo() {
if (_OBJModel != null) {
_OBJModel.printFacts();
_OBJModel.printBoundingBox();
if (_VSModel != null) {
_VSModel.printViewStructure();
}
}
}
//-------------------------------------------------------------
// print Woolz Facts
//---------------------------------------
public void printFacts(WlzObject obj) {
System.out.println("WLZ FACTS");
String facts[] = {
""};
try {
WlzObject.WlzObjectFacts(obj, null, facts, 1);
System.out.println(facts[0]);
}
catch (WlzException e) {
System.out.println("WlzException #6");
System.err.println(e);
}
System.out.println("*******************************");
}
//-------------------------------------------------------------
// get anatomy at mouse click
//-------------------------------------------------------------
protected String getAnatomyAt(double[] pt3d) {
_maybeFil = new Stack();
_maybeObj = new Stack();
File thisFile;
WlzObject obj = null;
WlzIBox3 bbox = null;
int plane = (int) pt3d[2];
int line = (int) pt3d[1];
int kol = (int) pt3d[0];
double smallestVol = 1000000000000000.0;
String ret = "";
int i = 0;
//look through embryo components
if (_embFileStack != null) {
int len = _embFileStack.size();
for (i = 0; i < len; i++) {
try {
obj = (WlzObject) _embObjStack.elementAt(i);
if (WlzObject.WlzInsideDomain(obj, plane, line, kol) != 0) {
thisFile = (File) _embFileStack.elementAt(i);
_maybeFil.push(thisFile);
_maybeObj.push(obj);
}
}
catch (WlzException e) {
System.out.println("WlzException #1");
System.out.println(e.getMessage());
}
}
}
//look through external components
if (_xembFileStack != null) {
int xlen = _xembFileStack.size();
for (i = 0; i < xlen; i++) {
try {
obj = (WlzObject) _xembObjStack.elementAt(i);
if (WlzObject.WlzInsideDomain(obj, plane, line, kol) != 0) {
thisFile = (File) _xembFileStack.elementAt(i);
_maybeFil.push(thisFile);
_maybeObj.push(obj);
}
}
catch (WlzException e) {
System.out.println("WlzException #2");
System.out.println(e.getMessage());
}
}
}
int indx = 0;
int len = _maybeObj.size();
//System.out.println(len+" possible anatomy objects");
double X = 0.0;
double Y = 0.0;
double Z = 0.0;
if (len > 0) {
// find the smallest wlz object
for (i = 0; i < len; i++) {
obj = (WlzObject) _maybeObj.elementAt(i);
try {
bbox = WlzObject.WlzBoundingBox3I(obj);
X = bbox.xMax - bbox.xMin;
Y = bbox.yMax - bbox.yMin;
Z = bbox.zMax - bbox.zMin;
}
catch (WlzException e) {
System.out.println("WlzException #?");
System.out.println(e.getMessage());
}
double vol = X * Y * Z;
if (vol < smallestVol) {
smallestVol = vol;
indx = i;
}
} // for
int end = 0;
StringBuffer temp = new StringBuffer(
( (File) _maybeFil.elementAt(indx)).getAbsolutePath());
// remove /net/... and '.wlz'
len = AnatomyBuilder._pathLengthToAnatomy;
temp.replace(0, len, "");
len = temp.lastIndexOf(SLASH);
temp.replace(len, temp.length(), "");
len = temp.lastIndexOf(SLASH);
if (len != -1) {
temp.replace(len, temp.length(), capitalise(temp.substring(len)));
ret = temp.toString();
}
else {
ret = capitalise(temp.toString());
}
}
return ret;
}
//-------------------------------------------------------------
protected boolean isValidName(String dir, String fil) {
if (fil.endsWith(".wlz")) {
return true;
}
else {
return false;
}
}
//-------------------------------------------------------------
protected String capitalise(String name) {
String endBit = "";
StringBuffer buf = new StringBuffer(name);
String ret = "";
int lastSlash = -1;
lastSlash = buf.lastIndexOf(SLASH);
if (lastSlash != -1) {
endBit = buf.substring(lastSlash);
buf.replace(lastSlash, buf.length(), endBit.toUpperCase());
ret = buf.toString();
}
else {
ret = (buf.toString()).toUpperCase();
}
return ret;
}
//-------------------------------------------------------------
// show anatomy selected from menu
//-------------------------------------------------------------
protected void anatomyFromMenu() {
AnatomyElement anatArr[] = null;
if (null != _parent) {
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod("getAnatomyArr", null);
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod(
"getAnatomyArr", null);
}
anatArr = (AnatomyElement[]) M1.invoke(_parent, null);
}
catch (InvocationTargetException e) {
System.out.println(e.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("getAnatomyArray: no such method 1");
System.out.println(ne.getMessage());
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
anatomyFromMenu(anatArr);
}
}
protected void anatomyFromMenu(AnatomyElement[] arr) {
int num = AnatKey._nrows;
WlzObject obj2D[] = new WlzObject[num];
boolean viz[] = new boolean[num];
for (int i = 0; i < num; i++) {
if ( (arr[i] != null) && (arr[i].isRemoved() == false)) {
viz[i] = arr[i].isVisible();
obj2D[i] = _OBJModel.makeSection(
arr[i].getObj(),
_VSModel.getViewStruct());
if (obj2D[i] != null) {
if (WlzObject.WlzObjGetType(obj2D[i]) ==
WlzObjectType.WLZ_EMPTY_OBJ) {
obj2D[i] = null;
}
}
}
else {
obj2D[i] = null;
viz[i] = false;
}
}
try {
_imgV.clearAnatomy();
_imgV.setAnatomyObj(obj2D, viz);
_imgV.repaint();
}
catch (WlzException err) {
System.out.println("WlzException #?");
System.out.println(err.getMessage());
}
}
//-------------------------------------------------------------
// get intersection array
//-------------------------------------------------------------
protected Line2D.Double[] getIntersectionArr() {
Line2D.Double intersectionArr[] = null;
SectionViewer SV = null;
Vector svVec = null;
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod("getOpenViews", null);
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod(
"getOpenViews", null);
}
svVec = (Vector) M1.invoke(_parent, null);
}
catch (InvocationTargetException e) {
System.out.println(e.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("getOpenViews: no such method 1");
System.out.println(ne.getMessage());
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
WlzThreeDViewStruct vs1 = _VSModel.getViewStruct();
WlzThreeDViewStruct vs2 = null;
WlzDVertex2 vtx = null;
int num = svVec.size();
// angles are in radians
// theta is the angle of intersection
double theta = 0.0;
double tan = 0.0;
double xmax[] = new double[1];
double ymax[] = new double[1];
double xmin[] = new double[1];
double ymin[] = new double[1];
double zarr[] = new double[1];
double x0 = 0.0;
double y0 = 0.0;
double x1 = 0.0;
double y1 = 0.0;
double xp = 0.0;
double yp = 0.0;
double xTotal = 0.0;
double yTotal = 0.0;
intersectionArr = new Line2D.Double[num - 1];
//..............................
// get max and min values from view struct
try {
WlzObject.Wlz3DViewGetMaxvals(vs1, xmax, ymax, zarr);
WlzObject.Wlz3DViewGetMinvals(vs1, xmin, ymin, zarr);
xTotal = xmax[0] - xmin[0];
yTotal = ymax[0] - ymin[0];
//printMaxMin(xmin[0],ymin[0],xmax[0],ymax[0]);
}
catch (WlzException e0) {
}
//..............................
int j = 0;
for (int i = 0; i < num; i++) {
SV = (SectionViewer) svVec.elementAt(i);
if (!this.equals(SV)) {
vs2 = SV.getViewStructModel().getViewStruct();
}
//..............................
if (vs2 != null) {
try {
// make sure view structs are presented in this order
// vs2, vs1
// or coords will be wrt the wrong view
vtx = WlzObject.Wlz3DViewGetIntersectionPoint(vs2, vs1);
}
catch (WlzException e1) {
/*
Woolz now gives WLZ_ERR_ALG if sections are parallel
*/
}
if (vtx != null) {
xp = vtx.vtX;
yp = vtx.vtY;
xp += xTotal/2.0;
yp += yTotal/2.0;
// assumes xp lies between 0 and xtotal
if ( (xp > 0) && (xp < xTotal)) {
try {
// make sure view structs are presented in this order
// or angle will be wrt the wrong view
theta = WlzObject.Wlz3DViewGetIntersectionAngle(vs2, vs1);
tan = Math.tan(theta);
}
catch (WlzException e2) {
System.out.println("getIntersectionArr()");
System.out.println(e2.getMessage());
}
if (Math.abs(tan) > 1.0) {
y0 = 0.0;
y1 = yTotal;
x0 = xp + (y0 - yp) / tan;
x1 = xp + (y1 - yp) / tan;
}
else {
x0 = 0.0;
x1 = xTotal;
y0 = yp + (x0 - xp) * tan;
y1 = yp + (x1 - xp) * tan;
}
} else {
x0 = 0.0;
y0 = 0.0;
x1 = 0.0;
y1 = 0.0;
}
intersectionArr[j] = new Line2D.Double(x0, y0, x1, y1);
j++;
}
}
vs2 = null;
vtx = null;
theta = 0.0;
SV = null;
x0 = 0.0;
y0 = 0.0;
x1 = 0.0;
y1 = 0.0;
} // for
return intersectionArr;
}
//-------------------------------------------------------------
// get interCol array
//-------------------------------------------------------------
protected Color[] getInterColArr() {
Color colarr[] = null;
SectionViewer SV = null;
Vector svVec = null;
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod("getOpenViews", null);
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod(
"getOpenViews", null);
}
svVec = (Vector) M1.invoke(_parent, null);
}
catch (InvocationTargetException e) {
System.out.println(e.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("getOpenViews: no such method 1");
System.out.println(ne.getMessage());
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
int num = svVec.size();
colarr = new Color[num - 1];
int j = 0;
for (int i = 0; i < num; i++) {
SV = (SectionViewer) svVec.elementAt(i);
if (!this.equals(SV)) {
colarr[j] = SV.getSecColorClt().getBackground();
j++;
}
}
return colarr;
}
//-------------------------
protected void doIntersection() {
if (_imgV == null) return;
if (_showIntersection) {
_imgV.setIntersectionVec(getIntersectionArr());
_imgV.setInterColVec(getInterColArr());
}
_imgV.repaint();
}
//-------------------------
protected void updateIntersections() {
SectionViewer SV = null;
Vector svVec = null;
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod("getOpenViews", null);
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod(
"getOpenViews", null);
}
svVec = (Vector) M1.invoke(_parent, null);
}
catch (InvocationTargetException e) {
System.out.println(e.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("getOpenViews: no such method 1");
System.out.println(ne.getMessage());
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
int num = svVec.size();
for (int i = 0; i < num; i++) {
SV = (SectionViewer) svVec.elementAt(i);
SV.doIntersection();
}
}
//-------------------------
protected void printIntersection(Line2D.Double line) {
String x1Str;
String y1Str;
String x2Str;
String y2Str;
if(line == null) return;
x1Str = Double.toString(line.getX1());
x2Str = Double.toString(line.getX2());
y1Str = Double.toString(line.getY1());
y2Str = Double.toString(line.getY2());
System.out.print("intersection line: "+x1Str+","+y1Str);
System.out.println(" --- "+x2Str+","+y2Str);
}
//-------------------------
protected void printMaxMin(double x1, double y1, double x2, double y2) {
String x1Str;
String y1Str;
String x2Str;
String y2Str;
x1Str = Double.toString(x1);
y1Str = Double.toString(y1);
x2Str = Double.toString(x2);
y2Str = Double.toString(y2);
System.out.print("x range: "+x1+","+x2);
System.out.println("y range: "+y1+","+y2);
}
//-------------------------
protected void doShowFixedPoint() {
double xa[] = new double[1];
double ya[] = new double[1];
double za[] = new double[1];
double pt3d[] = new double[3];
int intersect = -1;
if (_imgV == null)
return;
if (!_fixedPoint)
return;
_VSModel.getDist(za);
if (za[0] == 0.0) { // fixed point is in this plane
_VSModel.getFixedPoint(xa, ya, za);
pt3d[0] = xa[0];
pt3d[1] = ya[0];
pt3d[2] = za[0];
double vals[] = _OBJModel.get2DPoint(
pt3d,
_VSModel.getViewStruct());
try {
intersect = WlzObject.WlzInsideDomain(_OBJModel.getSection(),
0.0,
vals[1],
vals[0]);
}
catch (WlzException e) {
System.out.println("doShowFixedPoint");
System.out.println(e.getMessage());
}
if (intersect != 0) { // fixed point is in section
_imgV.setFixedPointVec(vals);
vals = null;
pt3d = null;
xa = null;
ya = null;
za = null;
}
}
else {
removeFixedPoint();
}
}
//-------------------------------------------------------------
// remove overlay
//-------------------------------------------------------------
protected void removeOverlay() {
_imgV.clearOverlay();
_maybeObj = null;
_maybeFil = null;
_imgV.repaint();
}
//-------------------------------------------------------------
// remove intersection
//-------------------------------------------------------------
protected void removeIntersection() {
_imgV.clearIntersection();
_imgV.repaint();
}
//-------------------------------------------------------------
// remove threshold
//-------------------------------------------------------------
protected void removeThreshold() {
_imgV.clearThreshold();
_imgV.repaint();
}
//-------------------------------------------------------------
// remove anatomy
//-------------------------------------------------------------
protected void removeAnatomy() {
_imgV.clearAnatomy();
_imgV.repaint();
}
//-------------------------------------------------------------
// remove threshConstraint
//-------------------------------------------------------------
protected void removeThreshConstraint() {
_imgV.clearThreshConstraint();
_imgV.repaint();
}
//-------------------------------------------------------------
// remove fixedPoint
//-------------------------------------------------------------
protected void removeFixedPoint() {
_imgV.enableFixedPoint(false);
_imgV.repaint();
}
//-------------------------------------------------------------
// set view title
//-------------------------------------------------------------
protected void setViewTitle() {
// assume all sliders are the same type (double etc)
int type = pitchSetter.getType();
Vector pVec = null;
Vector yVec = null;
Vector rVec = null;
String pitch = "";
String yaw = "";
String roll = "";
pVec = pitchSetter.getValue();
yVec = yawSetter.getValue();
rVec = rollSetter.getValue();
switch (type) {
case INTEGER:
pitch = ( (Integer) pVec.elementAt(0)).toString();
yaw = ( (Integer) yVec.elementAt(0)).toString();
roll = ( (Integer) rVec.elementAt(0)).toString();
break;
case FLOAT:
pitch = ( (Float) pVec.elementAt(0)).toString();
yaw = ( (Float) yVec.elementAt(0)).toString();
roll = ( (Float) rVec.elementAt(0)).toString();
break;
case DOUBLE:
pitch = ( (Double) pVec.elementAt(0)).toString();
yaw = ( (Double) yVec.elementAt(0)).toString();
roll = ( (Double) rVec.elementAt(0)).toString();
break;
default:
break;
}
String viewTitle = pitch + " | " + yaw + " | " + roll;
try {
Method M1 = _frame.getClass().getMethod(
"setTitle",
new Class[]{viewTitle.getClass( )});
M1.invoke(_frame, new Object[] {viewTitle});
}
catch (NoSuchMethodException ne) {
}
catch (IllegalAccessException iae) {
}
catch (InvocationTargetException ite) {
}
}
//-------------------------------------------------------------
// save image as jpeg
//-------------------------------------------------------------
protected void saveImage(String str) {
File fil = new File(str);
BufferedImage img = null;
img = _imgV.getComponentBufferedImage(1000d);
try {
FileOutputStream fout = new FileOutputStream(fil);
JPEGImageEncoder JIE = JPEGCodec.createJPEGEncoder(fout);
JIE.encode(img);
}
catch (FileNotFoundException e1) {
System.out.println(e1.getMessage());
}
catch (ImageFormatException e2) {
System.out.println(e2.getMessage());
}
catch (IOException e3) {
System.out.println(e3.getMessage());
}
}
//-------------------------------------------------------------
// save view settings
//-------------------------------------------------------------
protected void saveViewAsXML(String fil) {
String tab = " ";
String str = "";
double val1[] = new double[1];
double val2[] = new double[1];
double val3[] = new double[1];
double rtod = 180.0 / Math.PI;
try {
PrintWriter pout = new PrintWriter(
new FileWriter(fil));
pout.println("<?xml version=\"1.0\"?>");
pout.println("<view>");
//.......................
pout.print("<zoom>");
pout.print(Integer.toString(zoomSetter.getValue()));
pout.println("</zoom>");
//.......................
pout.println("<viewStruct>");
//.......................
val1[0] = 0.0;
_VSModel.getDist(val1);
pout.print(tab);
pout.print("<dist>");
str = Double.toString(val1[0]);
pout.print(str);
pout.println("</dist>");
//.......................
val1[0] = 0.0;
_VSModel.getTheta(val1);
pout.print(tab);
pout.print("<theta>");
str = Double.toString(val1[0] * rtod);
pout.print(str);
pout.println("</theta>");
//.......................
val1[0] = 0.0;
_VSModel.getPhi(val1);
pout.print(tab);
pout.print("<phi>");
str = Double.toString(val1[0] * rtod);
pout.print(str);
pout.println("</phi>");
//.......................
val1[0] = 0.0;
_VSModel.getZeta(val1);
pout.print(tab);
pout.print("<zeta>");
str = Double.toString(val1[0] * rtod);
pout.print(str);
pout.println("</zeta>");
//.......................
val1[0] = 0.0;
val2[0] = 0.0;
val3[0] = 0.0;
_VSModel.getFixedPoint(val1, val2, val3);
pout.print(tab);
pout.println("<fixed>");
pout.print(tab + tab);
pout.print("<x>");
str = Double.toString(val1[0]);
pout.print(str);
pout.println("</x>");
pout.print(tab + tab);
pout.print("<y>");
str = Double.toString(val2[0]);
pout.print(str);
pout.println("</y>");
pout.print(tab + tab);
pout.print("<z>");
str = Double.toString(val3[0]);
pout.print(str);
pout.println("</z>");
pout.print(tab);
pout.println("</fixed>");
//.......................
String str1 = _VSModel.getViewMode();
str = str1.substring(0, str1.length() - 1);
pout.print(tab);
pout.print("<mode>");
if (str.equals("WLZ_ZETA_MODE") == true) {
pout.print("absolute");
}
else {
pout.print("up_is_up");
}
pout.println("</mode>");
//.......................
pout.println("</viewStruct>");
pout.println("</view>");
if (pout.checkError() == true) {
System.out.println("error writing to xml file ");
}
}
catch (FileNotFoundException e1) {
System.out.println(e1.getMessage());
}
catch (IOException e3) {
System.out.println(e3.getMessage());
}
}
//-------------------------------------------------------------
// load view settings
//-------------------------------------------------------------
protected void loadViewFromXML(File fil) {
ParseXML parser = new ParseXML(this);
try {
parser.doParse(fil);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
//-------------------------------------------------------------
// convert from (slider) zoom factor to mag
//-------------------------------------------------------------
protected double zf2mag(double zf) {
//return (zf < 0.0) ? 1.0 + 0.001 * zf : 1.0 + 0.01 * zf;
return zf/100.0;
}
//-------------------------------------------------------------
// checkFilename for extension
//-------------------------------------------------------------
protected String checkFilename(String str, String ext) {
StringBuffer strbuf;
String lcaseStr = ext.toLowerCase();
String ucaseStr = ext.toUpperCase();
int len = 0;
if ( (str.endsWith(lcaseStr)) || (str.endsWith(ucaseStr))) {
return str;
}
else {
strbuf = new StringBuffer(str);
strbuf.append("." +lcaseStr);
return strbuf.toString();
}
}
//-------------------------------------------------------------
// set view mode
//-------------------------------------------------------------
public void setViewMode(String mode) {
if (_VSModel != null) {
_VSModel.setViewMode(mode);
if (mode.equals("absolute") == true) {
controlMenu_2_2.setSelected(true);
rollSetter.setSliderEnabled(true);
}
else {
controlMenu_2_1.setSelected(true);
rollSetter.setSliderEnabled(false);
}
}
}
//-------------------------------------------------------------
// get view structure model etc
//-------------------------------------------------------------
protected ViewStructModel getViewStructModel() {
return _VSModel;
}
protected WlzObjModel getWlzObjModel() {
return _OBJModel;
}
protected WlzImgView getImageView() {
return _imgV;
}
protected Zoom getZoomSetter() {
return zoomSetter;
}
protected WSetter getDistSetter() {
return distSetter;
}
protected WSetter getYawSetter() {
return yawSetter;
}
protected WSetter getPitchSetter() {
return pitchSetter;
}
protected WSetter getRollSetter() {
return rollSetter;
}
protected JButton getSecColorClt() {
return secColorClt;
}
//-------------------------------------------------------------
// enable / disable thresholding & threshConstraint
//-------------------------------------------------------------
protected void enableThresholding(boolean state) {
_thresholding = state;
}
//-------------------------------------------------------------
protected void enableThreshConstraint(boolean state) {
_threshConstraint = state;
if (state) {
if (!thresholdMenu_3state) {
thresholdMenu_3.doClick();
}
}
}
//-------------------------------------------------------------
protected void disableAnatomy() {
_anatomy = false;
}
protected void enableAnatomy() {
_anatomy = true;
}
//-------------------------------------------------------------
// set anatomy text field for menu selected anatomy
//-------------------------------------------------------------
protected void setAnatomyText(String str) {
resetAnatomyText();
anatomyTextField.setText(str);
}
//-------------------------------------------------------------
// reset fixed point
//-------------------------------------------------------------
protected void resetFixedPoint(boolean showFP) {
double vals[] = null;
// reset fixed point
vals = _VSModel.getInitialFixedPoint();
_VSModel.setFixedPoint(vals[0], vals[1], vals[2]);
vals = null;
setDistLimits(0.0);
if (showFP) {
Runnable fpClick = new Runnable() {
public void run() {
if (!showMenu_4state)
showMenu_4.doClick();
}
};
SwingUtilities.invokeLater(fpClick);
}
}
//-------------------------------------------------------------
// reset user interface controls
//-------------------------------------------------------------
protected void resetGUI() {
if (_debug)
System.out.println("enter resetGUI");
setSVEnabled(false);
zoomSetter.setEnabled(true);
distSetter.setEnabled(true);
pitchSetter.setEnabled(true);
yawSetter.setEnabled(true);
rollSetter.setEnabled(true);
rotSetter.setEnabled(true);
if (viewType.equals("XY")) {
pitchSetter.setValue(0.0);
yawSetter.setValue(0.0);
if (rollSetter.isSliderEnabled()) {
rollSetter.setValue(0.0);
}
else {
rollSetter.setSliderEnabled(true);
rollSetter.setValue(0.0);
rollSetter.setSliderEnabled(false);
}
}
else if (viewType.equals("YZ")) {
pitchSetter.setValue(90.0);
yawSetter.setValue(0.0);
if (rollSetter.isSliderEnabled()) {
rollSetter.setValue(90.0);
}
else {
rollSetter.setSliderEnabled(true);
rollSetter.setValue(90.0);
rollSetter.setSliderEnabled(false);
}
}
else if (viewType.equals("ZX")) {
pitchSetter.setValue(90.0);
yawSetter.setValue(90.0);
if (rollSetter.isSliderEnabled()) {
rollSetter.setValue(90.0);
}
else {
rollSetter.setSliderEnabled(true);
rollSetter.setValue(90.0);
rollSetter.setSliderEnabled(false);
}
}
else {
System.out.println("unknown view type in resetGUI(): " + viewType);
}
distSetter.setValue(0.0);
zoomSetter.setValue(100);
setViewMode("up_is_up");
removeThreshold();
removeThreshConstraint();
enableThresholding(false);
enableThreshConstraint(false);
disableAnatomy();
resetFeedbackText();
resetFixedPoint(false);
setSVEnabled(true);
if (_debug)
System.out.println("exit resetGUI");
}
//-------------------------------------------------------------
// constraint to Wlz
//-------------------------------------------------------------
protected void constraintToWlz(WlzIBox2 bbox2) {
GeneralPath GP = null;
PathIterator PI = null;
WlzIVertex2 vertArray[] = null;
int WLZ_POLYGON_INT = 1;
double ofsX = (bbox2.xMax - bbox2.xMin) / 2.0;
double ofsY = (bbox2.yMax - bbox2.yMin) / 2.0;
GP = _imgV.getThreshConstraint();
PI = GP.getPathIterator(null);
int tot = 0;
while (!PI.isDone()) {
PI.next();
tot++;
}
int maxv = tot - 1;
PI = null;
PI = GP.getPathIterator(null);
float segment[] = new float[6];
/* the first segment has coordinates 0,0 and is ignored */
vertArray = new WlzIVertex2[maxv];
int j = 0;
for (int i = 0; i < tot; i++) {
if ( (PI.currentSegment(segment) == PI.SEG_LINETO) ||
(PI.currentSegment(segment) == PI.SEG_CLOSE)) {
vertArray[j] = new WlzIVertex2(
(int) (segment[0] - ofsX),
(int) (segment[1] - ofsY));
j++;
}
PI.next();
}
if (!PI.isDone()) {
System.out.println("iterator not done");
System.out.println("array length " + vertArray.length);
}
int copy = 1; // allocate space and copy
int fillType = 0; // WLZ_SIMPLE_FILL
WlzPolygonDomain WPD = null;
int transformType = 2; // WLZ_TRANSFORM_2D_TRANS
try {
WPD = WlzObject.WlzMakePolygonDomain(
WLZ_POLYGON_INT,
maxv,
vertArray,
maxv,
copy);
_constraintObj = WlzObject.WlzPolyToObj(WPD, fillType);
}
catch (WlzException we) {
System.out.println("WlzMakePolygonDomain");
System.out.println(we.getMessage());
}
}
//-------------------------------------------------------------
// close
//-------------------------------------------------------------
protected void close() {
Object params[] = {this};
Vector openViews = null;
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod(
"removeView",
new Class[]{this.getClass( )});
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod(
"removeView",
- new Class[]{this.getClass( )});
+ new Class[]{this.getClass( ).getSuperclass()});
}
M1.invoke(_parent, new Object[] {this});
}
catch (InvocationTargetException e) {
System.out.println(e.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("removeView: no such method 2");
System.out.println(ne.getMessage());
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
closeView();
updateIntersections();
try {
Method M1 = _frame.getClass().getMethod(
"dispose", null);
M1.invoke(_frame, null);
}
catch (NoSuchMethodException ne) {
}
catch (IllegalAccessException iae) {
}
catch (InvocationTargetException ite) {
}
}
//-------------------------------------------------------------
// deal with container activation de-activation
//-------------------------------------------------------------
protected void thisFrameActivated() {
}
protected void thisFrameDeactivated() {
}
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
//-------------------------------------------------------------
// connect up the adaptors
//-------------------------------------------------------------
ZoomToZoomAdaptor Z2Z_1;
WSetterToDistAdaptor W2D_1;
WSetterToPitchAdaptor W2P_1;
WSetterToYawAdaptor W2Y_1;
WSetterToRollAdaptor W2R_1;
ViewStructModelToViewAdaptor WOM2V_1;
WlzImgViewToPosAdaptor WI2P_1;
WlzImgViewToGreyAdaptor WI2G_1;
WlzImgViewToAnatAdaptor WI2A_1;
WlzImgViewToFPAdaptor WI2FP_1;
MouseToFBAdaptor M2FB_1;
MouseToThresholdAdaptor M2T_1;
MouseToThreshConstraintAdaptor M2TC_1;
// adaptors for grey level
protected void connectAdaptors_1() {
if (_debug)
System.out.println("enter connectAdaptors_1");
setSVEnabled(false);
//...............................
// WSetter to model adaptors
//...............................
if (Z2Z_1 != null)
zoomSetter.removeChangeListener(Z2Z_1);
Z2Z_1 = new ZoomToZoomAdaptor(zoomSetter, _imgV);
zoomSetter.addChangeListener(Z2Z_1);
//...............................
if (distSetter == null)
System.out.println("distSetter = null");
if (_VSModel == null)
System.out.println("_VSModel = null");
if (_OBJModel == null)
System.out.println("_OBJModel = null");
if (W2D_1 != null)
distSetter.removeChangeListener(W2D_1);
W2D_1 = new WSetterToDistAdaptor(distSetter, _VSModel, _OBJModel);
if (W2D_1 == null)
System.out.println("W2D_1 = null");
distSetter.addChangeListener(W2D_1);
//...............................
if (W2P_1 != null)
pitchSetter.removeChangeListener(W2P_1);
W2P_1 = new WSetterToPitchAdaptor(pitchSetter, _VSModel, _OBJModel);
pitchSetter.addChangeListener(W2P_1);
//...............................
if (W2Y_1 != null)
yawSetter.removeChangeListener(W2Y_1);
W2Y_1 = new WSetterToYawAdaptor(yawSetter, _VSModel, _OBJModel);
yawSetter.addChangeListener(W2Y_1);
//...............................
if (W2R_1 != null)
rollSetter.removeChangeListener(W2R_1);
W2R_1 = new WSetterToRollAdaptor(rollSetter, _VSModel, _OBJModel);
rollSetter.addChangeListener(W2R_1);
//...............................
// View adaptors
//...............................
if (WOM2V_1 != null)
_VSModel.removeChangeListener(WOM2V_1);
WOM2V_1 = new ViewStructModelToViewAdaptor(_VSModel, _OBJModel, _imgV);
_VSModel.addChangeListener(WOM2V_1);
//...............................
if (WI2P_1 != null)
_imgV.removeChangeListener(WI2P_1);
WI2P_1 = new WlzImgViewToPosAdaptor(_imgV, _OBJModel, _VSModel,
xyzTextField);
_imgV.addChangeListener(WI2P_1);
//...............................
if (WI2G_1 != null)
_imgV.removeChangeListener(WI2G_1);
WI2G_1 = new WlzImgViewToGreyAdaptor(_imgV, valueTextField);
_imgV.addChangeListener(WI2G_1);
//...............................
if (WI2A_1 != null)
_imgV.removeChangeListener(WI2A_1);
WI2A_1 = new WlzImgViewToAnatAdaptor(_VSModel, _OBJModel, _imgV,
anatomyTextField);
_imgV.addChangeListener(WI2A_1);
//...............................
if (WI2FP_1 != null)
_imgV.removeChangeListener(WI2FP_1);
WI2FP_1 = new WlzImgViewToFPAdaptor(_imgV, _OBJModel, _VSModel);
_imgV.addChangeListener(WI2FP_1);
//...............................
if (M2FB_1 != null) {
_imgV.removeMouseListener(M2FB_1);
_imgV.removeMouseMotionListener(M2FB_1);
}
M2FB_1 = new MouseToFBAdaptor(_imgV);
_imgV.addMouseListener(M2FB_1);
_imgV.addMouseMotionListener(M2FB_1);
//...............................
if (M2T_1 != null) {
_imgV.removeMouseListener(M2T_1);
_imgV.removeMouseMotionListener(M2T_1);
}
M2T_1 = new MouseToThresholdAdaptor(_imgV, _OBJModel);
_imgV.addMouseListener(M2T_1);
_imgV.addMouseMotionListener(M2T_1);
//...............................
if (M2TC_1 != null) {
_imgV.removeMouseListener(M2TC_1);
_imgV.removeMouseMotionListener(M2TC_1);
}
M2TC_1 = new MouseToThreshConstraintAdaptor(_imgV,
_OBJModel);
_imgV.addMouseListener(M2TC_1);
_imgV.addMouseMotionListener(M2TC_1);
//--------------------------------------
setSVEnabled(true);
if (_debug)
System.out.println("exit connectAdaptors_1");
} //connectAdaptors_1()
protected void setSVEnabled(boolean state) {
_enabled = state;
}
protected boolean isSVEnabled() {
return _enabled;
}
//==========================================
// get and set methods
//==========================================
public double getDist() {
double ret = 0;
if(distSetter != null) {
ret = ((Double)distSetter.getValue().elementAt(0)).doubleValue();
}
return ret;
}
public void setDist(double val) {
if(distSetter != null) {
distSetter.setValue(val);
}
}
//......................................
public double getPitch() {
double ret = 0;
if(pitchSetter != null) {
ret = ((Double)pitchSetter.getValue().elementAt(0)).doubleValue();
}
return ret;
}
public void setPitch(double val) {
if(pitchSetter != null) {
pitchSetter.setValue(val);
}
}
//......................................
public double getYaw() {
double ret = 0;
if(yawSetter != null) {
ret = ((Double)yawSetter.getValue().elementAt(0)).doubleValue();
}
return ret;
}
public void setYaw(double val) {
if(yawSetter != null) {
yawSetter.setValue(val);
}
}
//......................................
public double getRoll() {
double ret = 0;
if(rollSetter != null) {
ret = ((Double)rollSetter.getValue().elementAt(0)).doubleValue();
}
return ret;
}
public void setRoll(double val) {
/* roll should not be adjusted if view mode is 'up_is_up' */
if((rollSetter != null)&&(controlMenu_2_2.isSelected())) {
rollSetter.setValue(val);
}
}
//......................................
public int getZoom() {
int ret = 0;
if(zoomSetter != null) {
ret = zoomSetter.getValue();
}
return ret;
}
public void setZoom(int val) {
if(zoomSetter != null) {
zoomSetter.setValue(val);
}
}
//......................................
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
//-------------------------------------------------------------
// inner classes for event handling
//-------------------------------------------------------------
public class fileMenuHandler
implements ActionListener {
String currentDirStr;
File currentDirFile;
File selectedFile;
JFileChooser chooser;
public fileMenuHandler() {
currentDirStr = System.getProperty("user.home");
currentDirFile = new File(currentDirStr);
}
public void actionPerformed(ActionEvent e) {
chooser = new JFileChooser(currentDirFile);
if (e.getActionCommand() == fileMenu_1str) {
// save image
gfFileFilter filter = new gfFileFilter();
filter.addExtension("jpg");
filter.setDescription("jpg image file");
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
currentDirFile = chooser.getCurrentDirectory();
saveImage(checkFilename(selectedFile.toString(), "jpg"));
}
}
else if (e.getActionCommand() == fileMenu_2str) {
// save view settings
int returnVal = chooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
currentDirFile = chooser.getCurrentDirectory();
saveViewAsXML(checkFilename(selectedFile.toString(), "xml"));
}
}
else if (e.getActionCommand() == fileMenu_3str) {
// load view settings
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
currentDirFile = chooser.getCurrentDirectory();
loadViewFromXML(selectedFile);
}
}
else if (e.getActionCommand() == fileMenu_4str) {
close();
}
} // actionPerformed()
} // class fileMenuHandler
//---------------------------------------
public class controlMenuHandler
implements ActionListener {
double xa[] = new double[1];
double ya[] = new double[1];
double za[] = new double[1];
double vals[] = null;
PointEntry pe = null;
JCheckBoxMenuItem src;
public controlMenuHandler() {
}
public void actionPerformed(ActionEvent e) {
// rotation ------------------------------
if (e.getActionCommand().equals(controlMenu_1_1str)) {
// see yaw pitch roll controls
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != controlMenu_1_1state) {
if (src.isSelected() == true) {
addStandardControls();
_showStdCntrls = true;
}
else {
removeStandardControls();
_showStdCntrls = false;
}
controlMenu_1_1state = src.isSelected();
}
}
else if (e.getActionCommand().equals(controlMenu_1_2str)) {
// see user defined rotation controls
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != controlMenu_1_2state) {
if (src.isSelected() == true) {
addUserControls();
_showUsrCntrls = true;
}
else {
removeUserControls();
_showUsrCntrls = false;
}
controlMenu_1_2state = src.isSelected();
}
}
// view mode ------------------------------
else if (e.getActionCommand().equals(controlMenu_2_1str)) {
// up is up mode => roll is fixed
setViewMode(controlMenu_2_1str);
rollSetter.setSliderEnabled(true);
rollSetter.setValue(0.0);
rollSetter.setSliderEnabled(false);
}
else if (e.getActionCommand().equals(controlMenu_2_2str)) {
setViewMode(controlMenu_2_2str);
}
// fixed point ------------------------------
else if (e.getActionCommand().equals(controlMenu_3_1str)) {
// change using mouse
_setFixedPoint = true;
setCursor(xhairCursor);
}
else if (e.getActionCommand().equals(controlMenu_3_2str)) {
// change by typing coordinates
_VSModel.getFixedPoint(xa, ya, za);
vals = new double[3];
vals[0] = xa[0];
vals[1] = ya[0];
vals[2] = za[0];
_FPBounce = 0;
pe = new PointEntry("Fixed Point Coordinates");
pe.setSize(250, 250);
pe.pack();
pe.setVisible(true);
pe.setInitVals(vals);
pe.addChangeListener(new FixedPointAdaptor(pe));
vals = null;
}
else if (e.getActionCommand().equals(controlMenu_3_3str)) {
// reset
resetFixedPoint(true);
}
// rotation axis ------------------------------
else if (e.getActionCommand().equals(controlMenu_4_2str)) {
// change by typing coordinates
_VSModel.getFixedPoint(xa, ya, za);
vals = new double[3];
vals[0] = xa[0];
vals[1] = ya[0];
vals[2] = za[0];
_RABounce = 0;
pe = new PointEntry("Rotation Axis Coordinates");
pe.setSize(250, 250);
pe.pack();
pe.setVisible(true);
pe.setInitVals(vals);
pe.addChangeListener(new RotationAxisAdaptor(pe));
vals = null;
}
// reset ------------------------------
else if (e.getActionCommand() == controlMenu_5str) {
// reset user interface controls
resetGUI();
_VSModel.fireChange();
}
} // actionPerformed()
} // class controlMenuHandler
//---------------------------------------
public class showMenuHandler
implements ActionListener {
JCheckBoxMenuItem src;
public showMenuHandler() {
}
public void actionPerformed(ActionEvent e) {
// cursor feedback ------------------------------
if (e.getActionCommand().equals(showMenu_1str)) {
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != showMenu_1state) {
if (src.isSelected()) {
addFeedback();
}
else {
removeFeedback();
}
showMenu_1state = src.isSelected();
}
}
// intersection of views ------------------------------
else if (e.getActionCommand().equals(showMenu_2str)) {
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != showMenu_2state) {
if (src.isSelected()) {
_showIntersection = true;
doIntersection();
}
else {
_showIntersection = false;
removeIntersection();
}
showMenu_2state = src.isSelected();
}
}
// mouse-click anatomy ------------------------------
else if (e.getActionCommand().equals(showMenu_3str)) {
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != showMenu_3state) {
if (src.isSelected()) {
enableAnatomy();
/* remove & disable thresholding */
if (thresholdMenu_1state) {
thresholdMenu_1.doClick();
}
if (thresholdMenu_2state) {
thresholdMenu_2.doClick();
}
if (thresholdMenu_3state) {
thresholdMenu_3.doClick();
}
thresholdMenu_4.doClick();
}
else {
disableAnatomy();
removeOverlay();
resetAnatomyText();
}
showMenu_3state = src.isSelected();
}
}
// fixed point ------------------------------
else if (e.getActionCommand().equals(showMenu_4str)) {
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != showMenu_4state) {
if (src.isSelected()) {
_fixedPoint = true;
doShowFixedPoint();
_imgV.repaint();
}
else {
_fixedPoint = false;
removeFixedPoint();
}
showMenu_4state = src.isSelected();
}
}
// rotation axis ------------------------------
else if (e.getActionCommand().equals(showMenu_5str)) {
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != showMenu_5state) {
if (src.isSelected()) {
}
else {
}
showMenu_5state = src.isSelected();
}
}
}
} // class showMenuHandler
//---------------------------------------
public class helpMenuHandler
implements ActionListener {
// help system belongs to SectionViewer Utils class
HelpBroker hb = null;
JMenuItem mi = null;
String IDStr = "";
String viewStr = "TOC";
public helpMenuHandler() {
}
public void actionPerformed(ActionEvent e) {
if (null != _parent) {
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod("getHelpBroker", null);
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod(
"getHelpBroker", null);
}
hb = (HelpBroker) M1.invoke(_parent, null);
}
catch (InvocationTargetException ie) {
System.out.println(ie.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("getHelpBroker: no such method");
System.out.println(ne.getMessage());
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
}
mi = (JMenuItem) e.getSource();
try {
if (mi.equals(helpMenu_1)) {
viewStr = "TOC";
}
else if (mi.equals(helpMenu_2)) {
viewStr = "Index";
}
else if (mi.equals(helpMenu_3)) {
viewStr = "Search";
}
hb.setCurrentView(viewStr);
hb.setDisplayed(true);
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
} // actionPerformed()
} // class helpMenuHandler
//---------------------------------------
public class thresholdMenuHandler
implements ActionListener {
/* the options are not part of a button group as they
are not mutually exclusive */
JCheckBoxMenuItem src;
JOptionPane jop;
String message;
int reply;
public thresholdMenuHandler() {
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == thresholdMenu_1str) {
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != thresholdMenu_1state) {
if (src.isSelected() == true) {
/* allow a 'polygonal' constraint to be drawn */
resetFeedbackText();
enableThreshConstraint(true);
enableThresholding(false);
if (thresholdMenu_2state) {
thresholdMenu_2state = false;
thresholdMenu_2.setSelected(false);
}
/* remove & disable mouse click anatomy */
if (showMenu_3state) {
showMenu_3.doClick();
}
}
else {
enableThreshConstraint(false);
}
thresholdMenu_1state = src.isSelected();
}
}
if (e.getActionCommand() == thresholdMenu_2str) {
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != thresholdMenu_2state) {
if (src.isSelected() == true) {
/* until bug is fixed vvvvvvvv */
message = new String(
"thresholding has a bug which may crash the program. Do you wish to proceed?");
reply = JOptionPane.showConfirmDialog(
null,
message,
"thresholding bug",
JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
/* threshold based on grey value of clicked point */
removeOverlay();
resetFeedbackText();
enableThresholding(true);
if (thresholdMenu_1state) {
thresholdMenu_1state = false;
thresholdMenu_1.setSelected(false);
}
/* remove & disable mouse click anatomy */
if (showMenu_3state) {
showMenu_3.doClick();
}
}
else {
enableThresholding(false);
}
/* until bug is fixed ^^^^^^^ */
}
else {
removeThreshold();
enableThresholding(false);
}
thresholdMenu_2state = src.isSelected();
}
}
if (e.getActionCommand() == thresholdMenu_3str) {
src = (JCheckBoxMenuItem) e.getSource();
if (src.isSelected() != thresholdMenu_3state) {
if (src.isSelected() == true) {
// show 'polygonal' constraint
_imgV.enableThreshConstraint(true);
_imgV.repaint();
}
else {
_imgV.enableThreshConstraint(false);
_imgV.repaint();
}
thresholdMenu_3state = src.isSelected();
}
}
if (e.getActionCommand() == thresholdMenu_4str) {
// remove 'polygonal' constraint
removeThreshConstraint();
enableThreshConstraint(false);
if (thresholdMenu_3state) {
thresholdMenu_3state = false;
thresholdMenu_3.setSelected(false);
}
}
} // actionPerformed()
} // class thresholdMenuHandler
//---------------------------------------
public class planeColChooser
implements ActionListener {
public planeColChooser() {}
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(null, "choose view colour",
secColorClt.getBackground());
if (null != c) {
secColorClt.setBackground(c);
updateIntersections();
}
}
}
//WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
//---------------------------------------
// Control ADAPTORS, wsetter to wlz object
//---------------------------------------
// change 'distance' using WSetter control
public class WSetterToDistAdaptor
implements ChangeListener {
WSetter control;
ViewStructModel VSmodel;
WlzObjModel OBJmodel;
Vector vec = null;
double val;
public WSetterToDistAdaptor(WSetter cntrl,
ViewStructModel mdl1,
WlzObjModel mdl2) {
VSmodel = mdl1;
OBJmodel = mdl2;
control = cntrl;
}
public void stateChanged(ChangeEvent e) {
vec = control.getValue();
switch (control.getType()) {
case INTEGER:
Integer iVal = (Integer) vec.elementAt(0);
val = (double) iVal.intValue();
break;
case FLOAT:
Float fVal = (Float) vec.elementAt(0);
val = (double) fVal.floatValue();
break;
case DOUBLE:
Double dVal = (Double) vec.elementAt(0);
val = dVal.doubleValue();
break;
default:
break;
}
VSmodel.setDist(val);
}
}
//---------------------------------------
// change 'pitch' using WSetter control
public class WSetterToPitchAdaptor
implements ChangeListener {
WSetter control;
ViewStructModel VSmodel;
WlzObjModel OBJmodel;
double valArr[] = new double[1];
Vector vec = null;
double val;
public WSetterToPitchAdaptor(WSetter cntrl, ViewStructModel mdl1,
WlzObjModel mdl2) {
VSmodel = mdl1;
OBJmodel = mdl2;
control = cntrl;
}
public void stateChanged(ChangeEvent e) {
vec = control.getValue();
switch (control.getType()) {
case INTEGER:
Integer iVal = (Integer) vec.elementAt(0);
val = (double) iVal.intValue();
break;
case FLOAT:
Float fVal = (Float) vec.elementAt(0);
val = (double) fVal.floatValue();
break;
case DOUBLE:
Double dVal = (Double) vec.elementAt(0);
val = dVal.doubleValue();
break;
default:
break;
}
VSmodel.setPhiDeg(val);
if (!control.isAdjusting()) {
VSmodel.getDist(valArr);
setDistLimits(valArr[0]);
}
}
}
//---------------------------------------
// change 'yaw' using WSetter control
public class WSetterToYawAdaptor
implements ChangeListener {
WSetter control;
ViewStructModel VSmodel;
WlzObjModel OBJmodel;
double valArr[] = new double[1];
Vector vec = null;
double val;
public WSetterToYawAdaptor(WSetter cntrl,
ViewStructModel mdl1,
WlzObjModel mdl2) {
VSmodel = mdl1;
OBJmodel = mdl2;
control = cntrl;
}
public void stateChanged(ChangeEvent e) {
vec = control.getValue();
switch (control.getType()) {
case INTEGER:
Integer iVal = (Integer) vec.elementAt(0);
val = (double) iVal.intValue();
break;
case FLOAT:
Float fVal = (Float) vec.elementAt(0);
val = (double) fVal.floatValue();
break;
case DOUBLE:
Double dVal = (Double) vec.elementAt(0);
val = dVal.doubleValue();
break;
default:
break;
}
VSmodel.setThetaDeg(val);
if (!control.isAdjusting()) {
VSmodel.getDist(valArr);
setDistLimits(valArr[0]);
}
}
}
//---------------------------------------
// change 'roll' using WSetter control
public class WSetterToRollAdaptor
implements ChangeListener {
WSetter control;
ViewStructModel VSmodel;
WlzObjModel OBJmodel;
double valArr[] = new double[1];
Vector vec = null;
double val;
public WSetterToRollAdaptor(WSetter cntrl,
ViewStructModel mdl1,
WlzObjModel mdl2) {
VSmodel = mdl1;
OBJmodel = mdl2;
control = cntrl;
}
public void stateChanged(ChangeEvent e) {
vec = control.getValue();
switch (control.getType()) {
case INTEGER:
Integer iVal = (Integer) vec.elementAt(0);
val = (double) iVal.intValue();
break;
case FLOAT:
Float fVal = (Float) vec.elementAt(0);
val = (double) fVal.floatValue();
break;
case DOUBLE:
Double dVal = (Double) vec.elementAt(0);
val = dVal.doubleValue();
break;
default:
break;
}
VSmodel.setZetaDeg(val);
if (!control.isAdjusting()) {
VSmodel.getDist(valArr);
setDistLimits(valArr[0]);
}
}
}
//---------------------------------------
// View ADAPTORS
//---------------------------------------
// change the displayed section when the view structure changes
public class ViewStructModelToViewAdaptor
implements ChangeListener {
ViewStructModel VSmodel;
WlzThreeDViewStruct VS;
WlzObjModel OBJmodel;
WlzImgView view;
Dimension imgSize;
Dimension newSize;
double mag;
WlzObject section;
WlzObject oSection;
WlzObject oObj;
WlzIBox2 bbox2;
AnatomyElement arr[];
WlzObject obj2D[];
public ViewStructModelToViewAdaptor(ViewStructModel mdl1,
WlzObjModel mdl2,
WlzImgView vw) {
VSmodel = mdl1;
OBJmodel = mdl2;
view = vw;
VS = VSmodel.getViewStruct();
}
public void stateChanged(ChangeEvent e) {
if (_debug) {
System.out.println("enter ViewStructModelToViewAdaptor");
}
if (_enabled == false) return;
section = null;
oObj = null;
oSection = null;
int num = AnatKey._nrows;
obj2D = new WlzObject[num];
boolean viz[] = new boolean[num];
for (int i = 0; i < num; i++) {
obj2D[i] = null;
viz[i] = false;
}
view.clearThreshold();
view.enableThreshConstraint(false);
resetPosGreyText();
section = OBJmodel.getSection();
//-------------------------
// draw the grey level
try {
view.setWlzObj(section);
}
catch (WlzException e1) {
System.out.println("ViewStructModelToViewAdaptor #1");
System.out.println(e1.getMessage());
}
//-------------------------
doShowFixedPoint();
//-------------------------
// draw the anatomy components
try {
if (null != _parent) {
try {
Method M1 = null;
if (_parentIsRoot) {
M1 = _parent.getClass().getDeclaredMethod("getAnatomyArr", null);
}
else {
M1 = _parent.getClass().getSuperclass().getDeclaredMethod(
"getAnatomyArr", null);
}
arr = (AnatomyElement[]) M1.invoke(_parent, null);
}
catch (InvocationTargetException ie) {
System.out.println(ie.getMessage());
}
catch (NoSuchMethodException ne) {
System.out.println("getAnatomyArr: no such method");
System.out.println(ne.getMessage());
}
catch (IllegalAccessException ae) {
System.out.println(ae.getMessage());
}
}
if ( (arr != null) && (viz != null) && (obj2D != null)) {
for (int i = 0; i < num; i++) {
if (arr[i] != null) {
viz[i] = (arr[i].isVisible() &&
!arr[i].isRemoved());
obj2D[i] = _OBJModel.makeSection(
arr[i].getObj(),
VS);
if (obj2D[i] != null) {
if (WlzObject.WlzObjGetType(obj2D[i]) ==
WlzObjectType.WLZ_EMPTY_OBJ) {
obj2D[i] = null;
}
}
}
else {
viz[i] = false;
obj2D[i] = null;
}
}
view.setAnatomyObj(obj2D, viz);
}
}
catch (WlzException e2) {
System.out.println("ViewStructModelToViewAdaptor #2");
System.out.println(e2.getMessage());
}
//-------------------------
// draw the 'mouse-click' anatomy
if (_thresholding != true) {
view.clearOverlay();
if ( (_maybeObj != null) && (_maybeObj.empty() == false)) {
oObj = (WlzObject) _maybeObj.peek();
if (oObj != null) {
oSection = OBJmodel.makeSection(oObj, VS);
}
if (oSection != null) {
// trap WLZ_ERR_OBJECT_TYPE to see
// if section 'misses' anatomy component
try {
view.setOverlayObj(oSection);
}
catch (WlzException e3) {
System.out.println("ViewStructModelToViewAdaptor #3");
System.out.println(e3.getMessage());
if ( (e3.getMessage()).equals("WLZ_ERR_OBJECT_TYPE")) {
System.out.println("oSection misses anatomy");
}
}
}
else {
//System.out.println("oSection == null");
}
} // if((_maybeObj != null) && ...
} // if(_thresholding != true)
//-------------------------
imgSize = view.getImgSize();
mag = view.getMag();
newSize = new Dimension(
(int) (imgSize.width * mag + 10),
(int) (imgSize.height * mag + 10));
setViewTitle();
_bigPanel.setPreferredSize(newSize);
//_rootPane.validate();
revalidate();
_bigPanel.repaint();
updateIntersections();
if (_debug) {
System.out.println("exit ViewStructModelToViewAdaptor");
}
} // stateChanged
} // ViewStructModelToViewAdaptor
//---------------------------------------
// connect mouse events to display of x-y position
public class WlzImgViewToPosAdaptor
implements ChangeListener {
WlzImgView ImgModel;
WlzObjModel ObjModel;
ViewStructModel VSModel;
WlzThreeDViewStruct VS;
JTextField view;
Point pos;
double pt3d[];
public WlzImgViewToPosAdaptor(WlzImgView mdl1,
WlzObjModel mdl2,
ViewStructModel mdl3,
JTextField tfpos) {
ImgModel = mdl1;
ObjModel = mdl2;
VSModel = mdl3;
view = tfpos;
VS = VSModel.getViewStruct();
}
public void stateChanged(ChangeEvent e) {
pos = ImgModel.getPos();
pt3d = ObjModel.get3DPoint(pos, VS);
view.setText(Math.round(pt3d[0]) + ", " +
Math.round(pt3d[1]) + ", " +
Math.round(pt3d[2]));
}
}
//---------------------------------------
// connects mouse events to display of grey level value
public class WlzImgViewToGreyAdaptor
implements ChangeListener {
WlzImgView model;
JTextField view;
int val;
public WlzImgViewToGreyAdaptor(WlzImgView mdl, JTextField pos) {
model = mdl;
view = pos;
}
public void stateChanged(ChangeEvent e) {
val = model.getGreyVal();
view.setText(Integer.toString(val));
}
}
//---------------------------------------
// connects mouse events to display of anatomy
public class WlzImgViewToAnatAdaptor
implements ChangeListener {
ViewStructModel VSmodel;
WlzThreeDViewStruct VS;
WlzObjModel OBJmodel;
WlzImgView IMGmodel;
JTextField view;
Point xypos;
WlzObject oSection = null;
WlzObject oObj = null;
double pt3d[];
public WlzImgViewToAnatAdaptor(ViewStructModel mdl1,
WlzObjModel mdl2,
WlzImgView mdl3,
ScrollableTextField anat) {
// JTextField anat) {
VSmodel = mdl1;
VS = VSmodel.getViewStruct();
OBJmodel = mdl2;
IMGmodel = mdl3;
view = anat;
}
public void stateChanged(ChangeEvent e) {
oObj = null;
oSection = null;
if ( (_thresholding == false) &&
(_threshConstraint == false) &&
(_anatomy == true)) {
xypos = IMGmodel.getPos();
pt3d = OBJmodel.get3DPoint(new Point(xypos.x, xypos.y), VS);
/*
System.out.println("2d pt: "+xypos.x+", "+xypos.y);
System.out.println("3d pt: "+pt3d[0]+", "+pt3d[1]+", "+pt3d[2]);
*/
_anatomyStr = getAnatomyAt(pt3d);
view.setText(_anatomyStr);
// overlay component onto greyscale image
if ( (_maybeObj != null) && (_maybeObj.empty() == false)) {
oObj = (WlzObject) _maybeObj.peek();
//printFacts(oObj);
if (oObj != null) {
oSection = OBJmodel.makeSection(oObj, VS);
}
else {
IMGmodel.clearOverlay();
}
if (oSection != null) {
//printFacts(oSection);
try {
IMGmodel.setOverlayObj(oSection);
}
catch (WlzException err) {
System.out.println("WlzException #5");
System.out.println(err.getMessage());
}
}
else {
IMGmodel.clearOverlay();
}
}
else {
view.setText("");
IMGmodel.clearOverlay();
}
}
else {
view.setText("");
IMGmodel.clearOverlay();
}
IMGmodel.repaint();
}
}
//---------------------------------------
// connect mouse events to setting of fixed point
public class WlzImgViewToFPAdaptor
implements ChangeListener {
WlzImgView ImgModel;
WlzObjModel ObjModel;
ViewStructModel VSModel;
WlzThreeDViewStruct VS;
Point pos;
double pt3d[];
public WlzImgViewToFPAdaptor(WlzImgView mdl1,
WlzObjModel mdl2,
ViewStructModel mdl3) {
ImgModel = mdl1;
ObjModel = mdl2;
VSModel = mdl3;
VS = VSModel.getViewStruct();
}
public void stateChanged(ChangeEvent e) {
if (!_setFixedPoint)
return;
pos = ImgModel.getPos();
pt3d = ObjModel.get3DPoint(pos, VS);
VSModel.setFixedPoint(pt3d[0],
pt3d[1],
pt3d[2]);
setDistLimits(0.0);
_setFixedPoint = false;
setCursor(defCursor);
Runnable fpClick = new Runnable() {
public void run() {
if (!showMenu_4state)
showMenu_4.doClick();
}
};
SwingUtilities.invokeLater(fpClick);
}
}
//---------------------------------------
// change 'zoom' using Zoom control
public class ZoomToZoomAdaptor
implements ChangeListener {
Zoom control;
WlzImgView view;
double zfactor;
double mag;
int zval;
int min, max, val, ext;
int imgW, imgH;
Dimension imgSize;
Dimension newSize;
BoundedRangeModel BRM = null;
public ZoomToZoomAdaptor(Zoom cntrl,
WlzImgView vw) {
control = cntrl;
view = vw;
}
public void stateChanged(ChangeEvent e) {
//System.out.println("ZoomToZoomAdaptor: stateChanged");
if (view != null) {
zval = control.getValue();
zfactor = (double)zval;
mag = zf2mag(zfactor);
imgSize = view.getImgSize();
view.setMag(mag);
imgW = (int) (imgSize.width * mag);
imgH = (int) (imgSize.height * mag);
newSize = new Dimension(imgW+10, imgH+10);
_bigPanel.setPreferredSize(newSize);
_bigPanel.revalidate();
_bigPanel.repaint();
}
}
}
//---------------------------------------
// connects mouse events to feedback display
public class MouseToFBAdaptor
implements MouseListener, MouseMotionListener {
WlzImgView model;
Point xypos;
double mag;
Point pt;
public MouseToFBAdaptor(WlzImgView mdl) {
model = mdl;
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
mag = model.getMag();
double xnorm = (e.getX()) / mag;
double ynorm = (e.getY()) / mag;
model.updateStats(xnorm, ynorm);
model.fireChange();
}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
if (e.getModifiers() == e.SHIFT_MASK) {
mag = model.getMag();
double xnorm = (e.getX()) / mag;
double ynorm = (e.getY()) / mag;
model.updateStats(xnorm, ynorm);
model.fireChange();
}
}
public void mouseDragged(MouseEvent e) {
mag = model.getMag();
double xnorm = (e.getX()) / mag;
double ynorm = (e.getY()) / mag;
model.updateStats(xnorm, ynorm);
model.fireChange();
}
}
//---------------------------------------
// connects mouse events to thresholding
public class MouseToThresholdAdaptor
implements MouseListener, MouseMotionListener {
WlzImgView view;
WlzObjModel model;
WlzObject section = null;
WlzObject section1 = null;
WlzObject section2 = null;
WlzObject section3 = null;
WlzObject section4 = null;
WlzObject selectedObj = null;
WlzDBox2 bbox2 = null;
Dimension imgSize;
Dimension newSize;
double mag;
int val;
int inc = 0;
int newval = 0;
int hi = WlzThresholdType.WLZ_THRESH_HIGH;
int lo = WlzThresholdType.WLZ_THRESH_LOW;
double xorg;
double yorg;
double xpt;
//Point pt2d = new Point();
Point.Double pt2d = new Point.Double();
public MouseToThresholdAdaptor(WlzImgView vw,
WlzObjModel mdl) {
view = vw;
model = mdl;
}
public void mousePressed(MouseEvent e) {
if ( (!_anatomy) && (_thresholding)) {
view.clearThreshold();
view.repaint();
section = model.getSection();
try {
bbox2 = section.WlzBoundingBox2D(section);
}
catch (WlzException we) {
System.out.println("WlzException #?");
System.out.println(we.getMessage());
}
section1 = model.smooth(section, 1.0, 1.0, 0, 0);
if (section1 != null) {
mag = view.getMag();
xorg = (e.getX()) / mag;
yorg = (e.getY()) / mag;
view.updateStats(xorg, yorg);
val = view.getGreyVal();
if (bbox2 != null) {
pt2d.setLocation(bbox2.xMin + xorg, bbox2.yMin + yorg);
}
if (_threshConstraint) {
section2 = model.constrain(section1, _constraintObj);
}
else {
section2 = section1;
}
}
}
}
public void mouseDragged(MouseEvent e) {
/*
if mouse dragged to right increase threshold window
if mouse dragged to left decrease threshold window to min = 0
*/
selectedObj = null;
if ( (!_anatomy) && (_thresholding)) {
if (section2 != null) {
mag = view.getMag();
xpt = (e.getX()) / mag;
/*
System.out.print("mouse at point: ");
System.out.println((e.getX())/mag+", "+(e.getY())/mag);
System.out.println("change = "+ (int)change(xpt));
*/
int ch = (int) change(xpt);
inc = ch > 0 ? ch : 0;
if (inc > 0) {
/* inc here is position not grey value !!!!!
it is just a handy way to increase threshold */
newval = (val + inc) > 255 ? 255 : (val + inc);
section3 = model.threshold(section2, newval, lo);
if (section3 != null) {
newval = (val - inc) > 0 ? (val - inc) : 0;
section4 = model.threshold(section3, newval, hi);
}
if (section4 != null) {
// call native method to select domain containing point
selectedObj = model.select(section4,
pt2d.getX(),
pt2d.getY());
if (selectedObj != null) {
try {
view.setThresholdObj(selectedObj);
}
catch (WlzException err) {
System.out.println("WlzException #7");
System.out.println(err.getMessage());
}
}
}
view.repaint();
}
else {
view.clearThreshold();
}
}
}
}
public void mouseReleased(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
protected double change(double x) {
return (x - xorg);
}
}
//---------------------------------------
// connects mouse events to threshConstraint
public class MouseToThreshConstraintAdaptor
implements MouseListener, MouseMotionListener {
WlzImgView view;
WlzObjModel model;
WlzObject section = null;
WlzIBox2 bbox2 = null;
Vector xpts;
Vector ypts;
int npts = 0;
double mag;
double xorg;
double yorg;
double x;
double y;
Point pt2d = new Point();
public MouseToThreshConstraintAdaptor(WlzImgView vw,
WlzObjModel mdl) {
view = vw;
model = mdl;
}
public void mousePressed(MouseEvent e) {
if ( (_anatomy == false) &&
(_thresholding == false) &&
(_threshConstraint == true)) {
xpts = new Vector(100, 10);
ypts = new Vector(100, 10);
section = model.getSection();
if (section != null) {
try {
bbox2 = section.WlzBoundingBox2I(section);
}
catch (WlzException we) {
System.out.println("WlzException #8");
System.out.println(we.getMessage());
}
mag = view.getMag();
xorg = (e.getX()) / mag;
yorg = (e.getY()) / mag;
view.updateStats(xorg, yorg);
view.clearThreshConstraint();
view.enableThreshConstraint(true);
view.setThreshConstraintOffsets(bbox2.xMin,
bbox2.yMin);
xpts.add(new Float(xorg));
ypts.add(new Float(yorg));
view.repaint();
/*
System.out.println("mouse pressed at");
System.out.print("xorg,yorg "+xorg+", "+yorg+" (");
System.out.println(pt2d.getX()+", "+pt2d.getY()+")");
*/
}
}
}
public void mouseDragged(MouseEvent e) {
if ( (_anatomy == false) &&
(_thresholding == false) &&
(_threshConstraint == true)) {
x = (e.getX()) / mag;
y = (e.getY()) / mag;
xpts.add(new Float(x));
ypts.add(new Float(y));
view.setThreshConstraint(xpts, ypts);
view.repaint();
}
}
public void mouseReleased(MouseEvent e) {
if ( (_anatomy == false) &&
(_thresholding == false) &&
(_threshConstraint == true)) {
view.closeThreshConstraint();
view.repaint();
constraintToWlz(bbox2);
}
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
//---------------------------------------
// connects window events to focus notification
public class WindowFocusHandler
implements WindowFocusListener {
ActionEvent event = null;
String actionCommand = "focus";
public WindowFocusHandler() {
}
public void windowLostFocus(WindowEvent e) {
}
public void windowGainedFocus(WindowEvent e) {
event = new ActionEvent(e.getSource(),
ActionEvent.ACTION_PERFORMED,
actionCommand);
fireEvent(event);
}
}
//---------------------------------------
// notifies window activation events
public class ExtFrameActivationHandler
implements WindowListener {
public ExtFrameActivationHandler() {
}
public void windowActivated(WindowEvent e) {
thisFrameActivated();
}
public void windowDeactivated(WindowEvent e) {
thisFrameDeactivated();
}
public void windowOpened(WindowEvent e) { }
public void windowClosing(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }
}
//---------------------------------------
// notifies internal frame activation events
public class IntFrameActivationHandler
implements InternalFrameListener {
public IntFrameActivationHandler() {
}
public void internalFrameActivated(InternalFrameEvent e) {
thisFrameActivated();
}
public void internalFrameDeactivated(InternalFrameEvent e) {
thisFrameDeactivated();
}
public void internalFrameOpened(InternalFrameEvent e) { }
public void internalFrameClosing(InternalFrameEvent e) { }
public void internalFrameClosed(InternalFrameEvent e) { }
public void internalFrameIconified(InternalFrameEvent e) { }
public void internalFrameDeiconified(InternalFrameEvent e) { }
}
//-------------------------------------------------------------
public class FixedPointAdaptor
implements ChangeListener {
double vals[];
PointEntry _pe;
public FixedPointAdaptor(PointEntry pe) {
_pe = pe;
}
public void stateChanged(ChangeEvent e) {
if (_FPBounce > 0) {
vals = _pe.getValues();
_VSModel.setFixedPoint(vals[0],
vals[1],
vals[2]);
setDistLimits(0.0);
Runnable fpClick = new Runnable() {
public void run() {
if (!showMenu_4state)
showMenu_4.doClick();
}
};
SwingUtilities.invokeLater(fpClick);
}
else {
_FPBounce++;
}
}
}
//-------------------------------------------------------------
public class RotationAxisAdaptor
implements ChangeListener {
double vals[];
PointEntry _pe;
public RotationAxisAdaptor(PointEntry pe) {
_pe = pe;
}
public void stateChanged(ChangeEvent e) {
}
}
//-------------------------------------------------------------
//=============================================================
//-------------------------------------------------------------
// thread stuff
//-------------------------------------------------------------
Object _lock = new Object();
//-------------------------------------------------------------
// stack
Runnable rStack = new Runnable() {
public void run() {
//System.out.println("stack thread started ");
synchronized (_anatBuilder._lock) {
while (_anatBuilder.getDone() == false) {
try {
_anatBuilder._lock.wait();
}
catch (InterruptedException iex2) {
System.out.println("Stack thread interrupted2 ");
System.out.println(iex2.getMessage());
}
}
try {
//System.out.println("stack thread working");
if (_anatBuilder != null) {
_embFileStack = (Stack) _anatBuilder.getEmbFileStack().clone();
_xembFileStack = (Stack) _anatBuilder.getXEmbFileStack().clone();
_embObjStack = (Stack) _anatBuilder.getEmbObjStack().clone();
_xembObjStack = (Stack) _anatBuilder.getXEmbObjStack().clone();
showMenu_3.setEnabled(true);
}
//System.out.println("stack thread finished");
}
catch (Exception ex) {
System.out.println("SectionViewer stack thread");
ex.printStackTrace();
}
} // sync1
}
};
//=============================================================
//-------------------------------------------------------------
// ChangeEvents
//-------------------------------------------------------------
//-------------------------------------------------------------
// handle all _objects that are interested in changes
//-------------------------------------------------------------
// keep track of all the listeners to this 'model'
protected EventListenerList changeListeners =
new EventListenerList();
//-------------------------------------------------------------
// add a listener to the register
public void addChangeListener(ChangeListener x) {
changeListeners.add(ChangeListener.class, x);
// bring it up to date with current state
x.stateChanged(new ChangeEvent(this));
}
//-------------------------------------------------------------
// remove a listener from the register
public void removeChangeListener(ChangeListener x) {
changeListeners.remove(ChangeListener.class, x);
}
//-------------------------------------------------------------
private ChangeEvent ce;
private Object[] listeners;
private ChangeListener cl;
protected void fireChange() {
if (_enabled == true) {
//System.out.println("firing an event from SectionViewer");
// Create the event:
ce = new ChangeEvent(this);
// Get the listener list
listeners = changeListeners.getListenerList();
// Process the listeners last to first
// List is in pairs, Class and instance
for (int i
= listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
cl = (ChangeListener) listeners[i + 1];
cl.stateChanged(ce);
}
}
}
} // fireChange
//=============================================================
//-------------------------------------------------------------
// ActionEvents
//-------------------------------------------------------------
//-------------------------------------------------------------
// keep track of all the listeners to this 'model'
protected EventListenerList actionListeners =
new EventListenerList();
//-------------------------------------------------------------
// add a listener to the register
public void addActionListener(ActionListener x) {
actionListeners.add(ActionListener.class, x);
}
//-------------------------------------------------------------
// remove a listener from the register
public void removeActionListener(ActionListener x) {
actionListeners.remove(ActionListener.class, x);
}
//-------------------------------------------------------------
private Object[] listeners2;
private ActionListener al;
protected void fireEvent(ActionEvent event) {
// Get the listener list
listeners2 = actionListeners.getListenerList();
// Process the listeners last to first
// List is in pairs, Class and instance
for (int i = listeners2.length - 2; i >= 0; i -= 2) {
if (listeners2[i] == ActionListener.class) {
al = (ActionListener) listeners2[i + 1];
al.actionPerformed(event);
}
}
} // fireEvent
} // class SectionViewer
| true | false | null | null |
diff --git a/src/com/github/andlyticsproject/AppInfoActivity.java b/src/com/github/andlyticsproject/AppInfoActivity.java
index f77c8e2..7caff0c 100644
--- a/src/com/github/andlyticsproject/AppInfoActivity.java
+++ b/src/com/github/andlyticsproject/AppInfoActivity.java
@@ -1,383 +1,383 @@
package com.github.andlyticsproject;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.github.andlyticsproject.cache.AppIconInMemoryCache;
import com.github.andlyticsproject.db.AndlyticsDb;
import com.github.andlyticsproject.dialog.AddEditLinkDialog;
import com.github.andlyticsproject.dialog.LongTextDialog;
import com.github.andlyticsproject.model.AppInfo;
import com.github.andlyticsproject.model.Link;
import com.github.andlyticsproject.util.DetachableAsyncTask;
import com.github.andlyticsproject.util.Utils;
public class AppInfoActivity extends SherlockFragmentActivity implements
AddEditLinkDialog.OnFinishAddEditLinkDialogListener, OnItemLongClickListener {
public static final String TAG = Main.class.getSimpleName();
private LinksListAdapter linksListAdapter;
private LoadLinksDb loadLinksDb;
private AppInfo appInfo;
private List<Link> links;
private ListView list;
private View linksListEmpty;
private AndlyticsDb db;
private String packageName;
private String iconFilePath;
private ActionMode currentActionMode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appinfo);
Bundle b = getIntent().getExtras();
if (b != null) {
packageName = b.getString(Constants.PACKAGE_NAME_PARCEL);
iconFilePath = b.getString(Constants.ICON_FILE_PARCEL);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String appName = getDbAdapter().getAppName(packageName);
if (appName != null) {
getSupportActionBar().setSubtitle(appName);
}
if (iconFilePath != null) {
Bitmap bm = BitmapFactory.decodeFile(iconFilePath);
BitmapDrawable icon = new BitmapDrawable(getResources(), bm);
getSupportActionBar().setIcon(icon);
}
LayoutInflater layoutInflater = getLayoutInflater();
list = (ListView) findViewById(R.id.appinfo_links_list);
list.addHeaderView(layoutInflater.inflate(R.layout.appinfo_header, null), null, false);
list.addFooterView(layoutInflater.inflate(R.layout.appinfo_links_list_empty, null), null,
false);
links = new ArrayList<Link>();
linksListAdapter = new LinksListAdapter(this);
list.setAdapter(linksListAdapter);
list.setOnItemLongClickListener(this);
linksListAdapter.setLinks(links);
linksListAdapter.notifyDataSetChanged();
View playStoreButton = findViewById(R.id.appinfo_playstore);
playStoreButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id="
+ packageName));
startActivity(intent);
}
});
View descriptionView = findViewById(R.id.appinfo_description);
descriptionView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showLongTextDialog(R.string.appinfo_description_label, ((TextView) v).getText()
.toString());
}
});
View changelogView = findViewById(R.id.appinfo_changelog);
changelogView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showLongTextDialog(R.string.appinfo_changelog_label, ((TextView) v).getText()
.toString());
}
});
db = AndlyticsDb.getInstance(this);
loadLinksDb = new LoadLinksDb(this);
Utils.execute(loadLinksDb);
registerForContextMenu(list);
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (currentActionMode != null) {
return false;
}
// skip header
if (position == 0) {
return false;
}
currentActionMode = startActionMode(new ContextCallback(position));
list.setItemChecked(position, true);
return true;
}
@SuppressLint("NewApi")
class ContextCallback implements ActionMode.Callback {
private int position;
ContextCallback(int position) {
this.position = position;
}
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.links_context_menu, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
if (menuItem.getItemId() == R.id.itemLinksmenuEdit) {
int pos = position - 1; // Subtract one for the header
Link link = links.get(pos);
showAddEditLinkDialog(link);
actionMode.finish();
return true;
} else if (menuItem.getItemId() == R.id.itemLinksmenuDelete) {
int pos = position - 1; // Subtract one for the header
Link link = links.get(pos);
db.deleteLink(link.getId().longValue());
loadLinksDb = new LoadLinksDb(AppInfoActivity.this);
Utils.execute(loadLinksDb);
actionMode.finish();
return true;
}
return false;
}
public void onDestroyActionMode(ActionMode actionMode) {
list.setItemChecked(position, false);
currentActionMode = null;
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
getSupportMenuInflater().inflate(R.menu.links_menu, menu);
return true;
}
/**
* Called if item in option menu is selected.
*
* @param item
* The chosen menu item
* @return boolean true/false
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
overridePendingTransition(R.anim.activity_prev_in, R.anim.activity_prev_out);
return true;
case R.id.itemLinksmenuAdd:
showAddEditLinkDialog(null);
return true;
default:
return (super.onOptionsItemSelected(item));
}
}
@Override
public void onBackPressed() {
finish();
overridePendingTransition(R.anim.activity_prev_in, R.anim.activity_prev_out);
}
public ContentAdapter getDbAdapter() {
return getAndlyticsApplication().getDbAdapter();
}
public AndlyticsApp getAndlyticsApplication() {
return (AndlyticsApp) getApplication();
}
private static class LoadLinksDb extends DetachableAsyncTask<Void, Void, Void, AppInfoActivity> {
LoadLinksDb(AppInfoActivity activity) {
super(activity);
}
@Override
protected Void doInBackground(Void... params) {
if (activity == null) {
return null;
}
activity.getLinksFromDb();
return null;
}
@Override
protected void onPostExecute(Void result) {
if (activity == null) {
return;
}
activity.refreshLinks();
}
}
private void getLinksFromDb() {
appInfo = db.findAppByPackageName(packageName);
- links = appInfo.getDetails().getLinks();
+ links = appInfo == null ? new ArrayList<Link>() : appInfo.getDetails().getLinks();
}
private void refreshLinks() {
linksListAdapter.setLinks(links);
linksListAdapter.notifyDataSetChanged();
linksListEmpty = findViewById(R.id.appinfo_links_list_empty);
if (links.size() == 0) {
linksListEmpty.setVisibility(View.VISIBLE);
} else {
linksListEmpty.setVisibility(View.GONE);
}
ImageView iconView = (ImageView) findViewById(R.id.appinfo_app_icon);
String packageName = appInfo.getPackageName();
// XXX hack? should be cached on main screen, so don't bother trying to load
// if (inMemoryCache.contains(packageName)) {
iconView.setImageBitmap(AppIconInMemoryCache.getInstance().get(packageName));
iconView.clearAnimation();
TextView appNameView = (TextView) findViewById(R.id.appinfo_app_name);
appNameView.setText(appInfo.getName());
TextView packageNameView = (TextView) findViewById(R.id.appinfo_package_name);
packageNameView.setText(packageName);
TextView developerView = (TextView) findViewById(R.id.appinfo_developer);
developerView.setText(String.format("%s / %s", appInfo.getDeveloperName(),
appInfo.getDeveloperId()));
TextView versionNameView = (TextView) findViewById(R.id.appinfo_version_name);
versionNameView.setText(appInfo.getVersionName());
TextView lastStoreUpdateView = (TextView) findViewById(R.id.appinfo_last_store_update);
lastStoreUpdateView.setText(DateFormat.getDateInstance().format(
appInfo.getDetails().getLastStoreUpdate()));
TextView descriptionView = (TextView) findViewById(R.id.appinfo_description);
descriptionView.setText(appInfo.getDetails().getDescription());
TextView changelogView = (TextView) findViewById(R.id.appinfo_changelog);
changelogView.setText(appInfo.getDetails().getChangelog());
}
@Override
public void onFinishAddEditLink(String url, String name, Long id) {
if (id == null) {
db.addLink(appInfo.getDetails(), url, name);
} else {
db.editLink(id, url, name);
}
loadLinksDb = new LoadLinksDb(this);
Utils.execute(loadLinksDb);
}
private void showAddEditLinkDialog(Link link) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("fragment_addedit_link");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
AddEditLinkDialog addEditLinkDialog = new AddEditLinkDialog();
Bundle arguments = new Bundle();
if (link != null) {
arguments.putLong("id", link.getId().longValue());
arguments.putString("name", link.getName());
arguments.putString("url", link.getURL());
}
addEditLinkDialog.setArguments(arguments);
addEditLinkDialog.setOnFinishAddEditLinkDialogListener(this);
addEditLinkDialog.show(ft, "fragment_addedit_link");
}
private void showLongTextDialog(int title, String longText) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("fragment_longtext");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
LongTextDialog longTextDialog = new LongTextDialog();
Bundle arguments = new Bundle();
arguments.putInt("title", title);
arguments.putString("longText", longText);
longTextDialog.setArguments(arguments);
longTextDialog.show(ft, "fragment_longtext");
}
}
diff --git a/src/com/github/andlyticsproject/CommentsActivity.java b/src/com/github/andlyticsproject/CommentsActivity.java
index b46e64c..934b083 100644
--- a/src/com/github/andlyticsproject/CommentsActivity.java
+++ b/src/com/github/andlyticsproject/CommentsActivity.java
@@ -1,628 +1,636 @@
package com.github.andlyticsproject;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.github.andlyticsproject.console.v2.DevConsoleRegistry;
import com.github.andlyticsproject.console.v2.DevConsoleV2;
import com.github.andlyticsproject.db.AndlyticsDb;
import com.github.andlyticsproject.model.AppStats;
import com.github.andlyticsproject.model.Comment;
import com.github.andlyticsproject.model.CommentGroup;
import com.github.andlyticsproject.util.DetachableAsyncTask;
import com.github.andlyticsproject.util.Utils;
public class CommentsActivity extends BaseDetailsActivity {
private static final String TAG = Main.class.getSimpleName();
private static final String REPLY_DIALOG_FRAGMENT = "reply_dialog_fragment";
private static final int MAX_LOAD_COMMENTS = 20;
private CommentsListAdapter commentsListAdapter;
private ExpandableListView list;
private View footer;
private int maxAvailableComments;
private ArrayList<CommentGroup> commentGroups;
private List<Comment> comments;
public int nextCommentIndex;
private View nocomments;
public boolean hasMoreComments;
private ContentAdapter db;
private DevConsoleV2 devConsole;
private static class State {
LoadCommentsCache loadCommentsCache;
LoadCommentsData loadCommentsData;
List<Comment> comments;
void detachAll() {
if (loadCommentsCache != null) {
loadCommentsCache.detach();
}
if (loadCommentsData != null) {
loadCommentsData.detach();
}
}
void attachAll(CommentsActivity activity) {
if (loadCommentsCache != null) {
loadCommentsCache.attach(activity);
}
if (loadCommentsData != null) {
loadCommentsData.attach(activity);
}
}
void setLoadCommentsCache(LoadCommentsCache task) {
if (loadCommentsCache != null) {
loadCommentsCache.detach();
}
loadCommentsCache = task;
}
void setLoadCommentsData(LoadCommentsData task) {
if (loadCommentsData != null) {
loadCommentsData.detach();
}
loadCommentsData = task;
}
}
private State state = new State();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.comments);
list = (ExpandableListView) findViewById(R.id.comments_list);
// TODO Use ListView.setEmptyView
nocomments = (View) findViewById(R.id.comments_nocomments);
// footer
View inflate = getLayoutInflater().inflate(R.layout.comments_list_footer, null);
footer = (View) inflate.findViewById(R.id.comments_list_footer);
list.addFooterView(inflate, null, false);
View header = getLayoutInflater().inflate(R.layout.comments_list_header, null);
list.addHeaderView(header, null, false);
list.setGroupIndicator(null);
devConsole = DevConsoleRegistry.getInstance().get(accountName);
commentsListAdapter = new CommentsListAdapter(this);
if (devConsole.hasSessionCredentials()) {
commentsListAdapter.setCanReplyToComments(devConsole.canReplyToComments());
}
list.setAdapter(commentsListAdapter);
maxAvailableComments = -1;
commentGroups = new ArrayList<CommentGroup>();
comments = new ArrayList<Comment>();
footer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
fetchNextComments();
}
});
hideFooter();
db = getDbAdapter();
State lastState = (State) getLastCustomNonConfigurationInstance();
if (lastState != null) {
state = lastState;
state.attachAll(this);
if (state.comments != null) {
comments = state.comments;
rebuildCommentGroups();
expandCommentGroups();
refreshCommentsIfNecessary();
}
} else {
state.setLoadCommentsCache(new LoadCommentsCache(this));
Utils.execute(state.loadCommentsCache);
}
}
@Override
public Object onRetainCustomNonConfigurationInstance() {
state.comments = comments;
state.detachAll();
return state;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
getSupportMenuInflater().inflate(R.menu.comments_menu, menu);
if (isRefreshing()) {
menu.findItem(R.id.itemCommentsmenuRefresh).setActionView(
R.layout.action_bar_indeterminate_progress);
}
return true;
}
/**
* Called if item in option menu is selected.
*
* @param item
* The chosen menu item
* @return boolean true/false
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemCommentsmenuRefresh:
refreshComments();
return true;
default:
return (super.onOptionsItemSelected(item));
}
}
private static class LoadCommentsCache extends
DetachableAsyncTask<Void, Void, Void, CommentsActivity> {
LoadCommentsCache(CommentsActivity activity) {
super(activity);
}
@Override
protected Void doInBackground(Void... params) {
if (activity == null) {
return null;
}
activity.getCommentsFromCache();
activity.rebuildCommentGroups();
return null;
}
@Override
protected void onPostExecute(Void result) {
if (activity == null) {
return;
}
activity.expandCommentGroups();
activity.showFooterIfNecessary();
activity.refreshCommentsIfNecessary();
}
}
private void getCommentsFromCache() {
comments = db.getCommentsFromCache(packageName);
nextCommentIndex = comments.size();
AppStats appInfo = db.getLatestForApp(packageName);
if (appInfo != null) {
maxAvailableComments = appInfo.getNumberOfComments();
} else {
maxAvailableComments = comments.size();
}
hasMoreComments = nextCommentIndex < maxAvailableComments;
}
protected boolean shouldRemoteUpdateComments() {
if (comments == null || comments.isEmpty()) {
return true;
}
long now = System.currentTimeMillis();
long lastUpdate = AndlyticsDb.getInstance(this)
.getLastCommentsRemoteUpdateTime(packageName);
// never updated
if (lastUpdate == 0) {
return true;
}
return (now - lastUpdate) >= Preferences.COMMENTS_REMOTE_UPDATE_INTERVAL;
}
private void expandCommentGroups() {
if (comments.size() > 0) {
commentsListAdapter.setCommentGroups(commentGroups);
for (int i = 0; i < commentGroups.size(); i++) {
list.expandGroup(i);
}
commentsListAdapter.notifyDataSetChanged();
}
}
private static class LoadCommentsData extends
DetachableAsyncTask<Void, Void, Exception, CommentsActivity> {
LoadCommentsData(CommentsActivity activity) {
super(activity);
}
@Override
protected void onPreExecute() {
if (activity == null) {
return;
}
activity.refreshStarted();
activity.disableFooter();
}
@Override
protected Exception doInBackground(Void... params) {
if (activity == null) {
return null;
}
Exception exception = null;
if (activity.maxAvailableComments == -1) {
ContentAdapter db = activity.getDbAdapter();
AppStats appInfo = db.getLatestForApp(activity.packageName);
if (appInfo != null) {
activity.maxAvailableComments = appInfo.getNumberOfComments();
} else {
activity.maxAvailableComments = MAX_LOAD_COMMENTS;
}
}
if (activity.maxAvailableComments != 0) {
DevConsoleV2 console = DevConsoleRegistry.getInstance().get(activity.accountName);
try {
List<Comment> result = console.getComments(activity, activity.packageName,
activity.developerId, activity.nextCommentIndex, MAX_LOAD_COMMENTS,
Utils.getDisplayLocale());
activity.updateCommentsCacheIfNecessary(result);
// we can only do this after we authenticate at least once,
// which may not happen before refreshing if we are loading
// from cache
activity.commentsListAdapter
.setCanReplyToComments(console.canReplyToComments());
activity.incrementNextCommentIndex(result.size());
activity.rebuildCommentGroups();
} catch (Exception e) {
exception = e;
}
}
return exception;
}
@Override
protected void onPostExecute(Exception exception) {
if (activity == null) {
return;
}
activity.refreshFinished();
activity.enableFooter();
if (exception != null) {
Log.e(TAG, "Error fetching comments: " + exception.getMessage(), exception);
activity.handleUserVisibleException(exception);
activity.hideFooter();
return;
}
if (activity.comments != null && activity.comments.size() > 0) {
activity.nocomments.setVisibility(View.GONE);
activity.commentsListAdapter.setCommentGroups(activity.commentGroups);
for (int i = 0; i < activity.commentGroups.size(); i++) {
activity.list.expandGroup(i);
}
activity.commentsListAdapter.notifyDataSetChanged();
} else {
activity.nocomments.setVisibility(View.VISIBLE);
}
activity.showFooterIfNecessary();
AndlyticsDb.getInstance(activity).saveLastCommentsRemoteUpdateTime(
activity.packageName, System.currentTimeMillis());
}
}
private void incrementNextCommentIndex(int increment) {
nextCommentIndex += increment;
if (nextCommentIndex >= maxAvailableComments) {
hasMoreComments = false;
} else {
hasMoreComments = true;
}
}
private void resetNextCommentIndex() {
maxAvailableComments = -1;
nextCommentIndex = 0;
hasMoreComments = true;
}
private void updateCommentsCacheIfNecessary(List<Comment> newComments) {
if (newComments == null || newComments.isEmpty()) {
return;
}
if (comments == null || comments.isEmpty()) {
updateCommentsCache(newComments);
comments.addAll(newComments);
return;
}
// if refreshing, clear and rebuild cache
if (nextCommentIndex == 0) {
updateCommentsCache(newComments);
}
// otherwise add to adapter and display
comments.addAll(newComments);
}
private void updateCommentsCache(List<Comment> commentsToCache) {
db.updateCommentsCache(commentsToCache, packageName);
comments = new ArrayList<Comment>();
}
public void rebuildCommentGroups() {
commentGroups = new ArrayList<CommentGroup>();
Comment prevComment = null;
for (Comment comment : Comment.expandReplies(comments)) {
if (prevComment != null) {
CommentGroup group = new CommentGroup();
group.setDate(comment.isReply() ? comment.getOriginalCommentDate() : comment
.getDate());
if (commentGroups.contains(group)) {
int index = commentGroups.indexOf(group);
group = commentGroups.get(index);
group.addComment(comment);
} else {
addNewCommentGroup(comment);
}
} else {
addNewCommentGroup(comment);
}
prevComment = comment;
}
}
private void addNewCommentGroup(Comment comment) {
CommentGroup group = new CommentGroup();
group.setDate(comment.getDate());
List<Comment> groupComments = new ArrayList<Comment>();
groupComments.add(comment);
group.setComments(groupComments);
commentGroups.add(group);
}
private void refreshCommentsIfNecessary() {
if (shouldRemoteUpdateComments()) {
resetNextCommentIndex();
fetchNextComments();
}
}
private void refreshComments() {
resetNextCommentIndex();
fetchNextComments();
}
private void fetchNextComments() {
state.setLoadCommentsData(new LoadCommentsData(this));
Utils.execute(state.loadCommentsData);
}
private void enableFooter() {
footer.setEnabled(true);
}
private void disableFooter() {
footer.setEnabled(false);
}
private void hideFooter() {
footer.setVisibility(View.GONE);
}
private void showFooterIfNecessary() {
footer.setVisibility(hasMoreComments ? View.VISIBLE : View.GONE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_AUTHENTICATE) {
if (resultCode == RESULT_OK) {
// user entered credentials, etc, try to get data again
refreshCommentsIfNecessary();
} else {
Toast.makeText(this, getString(R.string.auth_error, accountName), Toast.LENGTH_LONG)
.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public static class ReplyDialog extends SherlockDialogFragment {
String commentUniqueId;
public ReplyDialog() {
setStyle(DialogFragment.STYLE_NORMAL, R.style.Dialog);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.comment_reply_dialog, container);
final EditText replyText = (EditText) view.findViewById(R.id.comment_reply_dialog_text);
replyText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showKeyboard();
}
}
});
Bundle args = getArguments();
if (args.containsKey("uniqueId")) {
commentUniqueId = args.getString("uniqueId");
}
if (args.containsKey("reply")) {
replyText.setText(args.getString("reply"));
}
view.findViewById(R.id.comment_reply_dialog_negative_button).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
view.findViewById(R.id.comment_reply_dialog_positive_button).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
String reply = replyText.getText().toString();
CommentsActivity activity = (CommentsActivity) getActivity();
if (activity != null) {
activity.replyToComment(commentUniqueId, reply);
}
dismiss();
}
});
replyText.requestFocus();
showKeyboard();
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
super.onViewCreated(view, savedInstanceState);
}
private void showKeyboard() {
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}
}
void showReplyDialog(Comment comment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag(REPLY_DIALOG_FRAGMENT);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
ReplyDialog replyDialog = new ReplyDialog();
Bundle args = new Bundle();
args.putString("uniqueId", comment.getUniqueId());
args.putString("reply", comment.getReply() == null ? "" : comment.getReply().getText());
replyDialog.setArguments(args);
replyDialog.show(ft, REPLY_DIALOG_FRAGMENT);
}
void hideReplyDialog() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment dialog = getSupportFragmentManager().findFragmentByTag(REPLY_DIALOG_FRAGMENT);
if (dialog != null) {
ft.remove(dialog);
ft.commit();
}
}
public void replyToComment(final String commentUniqueId, final String replyText) {
Utils.execute(new DetachableAsyncTask<Void, Void, Comment, CommentsActivity>(this) {
Exception error;
@Override
+ protected void onPreExecute() {
+ if (activity == null) {
+ return;
+ }
+
+ activity.refreshStarted();
+ }
+
+ @Override
protected Comment doInBackground(Void... arg0) {
if (activity == null) {
return null;
}
- activity.refreshStarted();
try {
return devConsole.replyToComment(CommentsActivity.this, packageName,
developerId, commentUniqueId, replyText);
} catch (Exception e) {
error = e;
return null;
}
}
@Override
protected void onPostExecute(Comment reply) {
if (activity == null) {
return;
}
activity.refreshFinished();
if (error != null) {
Log.e(TAG, "Error replying to comment: " + error.getMessage(), error);
activity.hideReplyDialog();
activity.handleUserVisibleException(error);
return;
}
refreshComments();
}
});
}
}
| false | false | null | null |
diff --git a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/MeasurementView.java b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/MeasurementView.java
index fcf703a6..5de680d0 100644
--- a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/MeasurementView.java
+++ b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/MeasurementView.java
@@ -1,364 +1,367 @@
package ch.cern.atlas.apvs.client.ui;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.cern.atlas.apvs.client.ClientFactory;
import ch.cern.atlas.apvs.client.widget.ClickableHtmlColumn;
import ch.cern.atlas.apvs.client.widget.ClickableTextCell;
import ch.cern.atlas.apvs.client.widget.ClickableTextColumn;
import ch.cern.atlas.apvs.domain.Measurement;
import ch.cern.atlas.apvs.ptu.shared.PtuClientConstants;
import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.CellTable;
+import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.Header;
import com.google.gwt.user.cellview.client.TextHeader;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.view.client.SelectionChangeEvent;
public class MeasurementView extends AbstractMeasurementView {
private Logger log = LoggerFactory.getLogger(getClass().getName());
private CellTable<String> table = new CellTable<String>();
private ListHandler<String> columnSortHandler;
private ClickableHtmlColumn<String> name;
private boolean sortable = true;
public MeasurementView() {
}
@Override
public boolean configure(Element element, ClientFactory clientFactory,
Arguments args) {
super.configure(element, clientFactory, args);
sortable = !options.contains("NoSort");
table.setWidth("100%");
add(table, CENTER);
name = new ClickableHtmlColumn<String>() {
@Override
public String getValue(String name) {
return historyMap.getDisplayName(name);
}
@Override
public void render(Context context, String name, SafeHtmlBuilder sb) {
String s = getValue(name);
Measurement m = historyMap.getMeasurement(ptuId, name);
if (m == null) {
return;
}
((ClickableTextCell) getCell()).render(context, decorate(s, m),
sb);
}
};
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(sortable);
if (selectable) {
name.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
selectMeasurement(object);
}
});
}
table.addColumn(name, showHeader ? new TextHeader("") {
@Override
public String getValue() {
if (!showName)
return null;
return ptuId;
}
public void render(Context context, SafeHtmlBuilder sb) {
String s = getValue();
if (s != null) {
s = "PTU Id: " + ptuId;
if (interventions != null) {
String realName = interventions.get(ptuId) != null ? interventions
.get(ptuId).getName() : null;
if (realName != null) {
s = "<div title=\"" + s + "\">" + realName
+ "</div>";
}
}
sb.append(SafeHtmlUtils.fromSafeConstant(s));
}
};
}
: null);
// ClickableTextColumn<String> gauge = new ClickableTextColumn<String>()
// {
// @Override
// public String getValue(String name) {
// if ((name == null) || (historyMap == null) || (ptuId == null)) {
// return "";
// }
// Measurement m = historyMap.getMeasurement(ptuId, name);
// return m != null ? m.getLowLimit()+" "+m.getHighLimit() : "";
// }
//
// @Override
// public void render(Context context, String name, SafeHtmlBuilder sb)
// {
// Measurement m = historyMap != null ? historyMap.getMeasurement(ptuId,
// name) : null;
// if (m == null) {
// return;
// }
// gaugeWidget.setValue(m.getValue(), m.getLowLimit(),
// m.getHighLimit());
// sb.appendEscaped(gaugeWidget.getElement().getInnerHTML());
// Window.alert(gaugeWidget.getElement().getInnerHTML());
// }
//
// };
// gauge.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
// if (selectable) {
// gauge.setFieldUpdater(new FieldUpdater<String, String>() {
//
// @Override
// public void update(int index, String object, String value) {
// selectMeasurement(object);
// }
// });
// }
// table.addColumn(gauge, showHeader ? new TextHeader("Limits")
// : (Header<?>) null);
ClickableTextColumn<String> value = new ClickableTextColumn<String>() {
@Override
public String getValue(String name) {
if ((name == null) || (historyMap == null) || (ptuId == null)) {
return "";
}
Measurement m = historyMap.getMeasurement(ptuId, name);
return m != null ? format.format(m.getValue()) : "";
}
@Override
public void render(Context context, String name, SafeHtmlBuilder sb) {
String s = getValue(name);
Measurement m = historyMap != null ? historyMap.getMeasurement(
ptuId, name) : null;
if (m == null) {
return;
}
double c = m.getValue().doubleValue();
double lo = m.getLowLimit().doubleValue();
double hi = m.getHighLimit().doubleValue();
String status = lo >= hi ? "in_range" : c < lo ? "lo-limit"
: c > hi ? "hi-limit" : "in-range";
sb.append(SafeHtmlUtils.fromSafeConstant("<div class=\""
+ status + "\">"));
((ClickableTextCell) getCell()).render(context,
decorate(s, m, last), sb);
sb.append(SafeHtmlUtils.fromSafeConstant("</div>"));
}
};
value.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
if (selectable) {
value.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
selectMeasurement(object);
}
});
}
table.addColumn(value, showHeader ? new TextHeader("Value")
: (Header<?>) null);
ClickableHtmlColumn<String> unit = new ClickableHtmlColumn<String>() {
@Override
public String getValue(String name) {
Measurement m = historyMap != null ? historyMap.getMeasurement(
ptuId, name) : null;
return m != null ? m.getUnit() : "";
}
@Override
public void render(Context context, String name, SafeHtmlBuilder sb) {
String s = getValue(name);
Measurement m = historyMap != null ? historyMap.getMeasurement(
ptuId, name) : null;
if (m == null) {
return;
}
((ClickableTextCell) getCell()).render(context, decorate(s, m),
sb);
}
};
unit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
unit.setSortable(sortable);
if (selectable) {
unit.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
selectMeasurement(object);
}
});
}
table.addColumn(unit, showHeader ? new TextHeader("Unit")
: (Header<?>) null);
ClickableHtmlColumn<String> date = new ClickableHtmlColumn<String>() {
@Override
public String getValue(String name) {
Measurement measurement = historyMap.getMeasurement(ptuId, name);
return measurement != null ? PtuClientConstants.dateFormat.format(measurement
.getDate()) : "";
}
@Override
public void render(Context context, String name, SafeHtmlBuilder sb) {
String s = getValue(name);
Measurement m = historyMap.getMeasurement(ptuId, name);
if (m == null) {
return;
}
((ClickableTextCell) getCell()).render(context, decorate(s, m),
sb);
}
};
unit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
unit.setSortable(sortable);
if (selectable) {
unit.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
selectMeasurement(object);
}
});
}
if (showDate) {
table.addColumn(date, showHeader ? new TextHeader("Date")
: (Header<?>) null);
}
List<String> list = new ArrayList<String>();
dataProvider.addDataDisplay(table);
dataProvider.setList(list);
columnSortHandler = new ListHandler<String>(dataProvider.getList());
columnSortHandler.setComparator(name, new Comparator<String>() {
public int compare(String s1, String s2) {
if (s1 == s2) {
return 0;
}
if (s1 != null) {
return s1.compareTo(s2);
}
return -1;
}
});
columnSortHandler.setComparator(value, new Comparator<String>() {
public int compare(String s1, String s2) {
Measurement o1 = historyMap.getMeasurement(ptuId, s1);
Measurement o2 = historyMap.getMeasurement(ptuId, s2);
if (o1 == o2) {
return 0;
}
if ((o1 != null) && (o1.getValue() != null)) {
if ((o2 != null) && (o2.getValue() != null)) {
double d1 = o1.getValue().doubleValue();
double d2 = o2.getValue().doubleValue();
return d1 < d2 ? -1 : d1 == d2 ? 0 : 1;
}
return 1;
}
return -1;
}
});
columnSortHandler.setComparator(unit, new Comparator<String>() {
public int compare(String s1, String s2) {
Measurement o1 = historyMap.getMeasurement(ptuId, s1);
Measurement o2 = historyMap.getMeasurement(ptuId, s2);
if (o1 == o2) {
return 0;
}
if (o1 != null) {
return (o2 != null) ? o1.getUnit().compareTo(o2.getUnit())
: 1;
}
return -1;
}
});
columnSortHandler.setComparator(date, new Comparator<String>() {
public int compare(String s1, String s2) {
Measurement o1 = historyMap.getMeasurement(ptuId, s1);
Measurement o2 = historyMap.getMeasurement(ptuId, s2);
if (o1 == o2) {
return 0;
}
if (o1 != null) {
return (o2 != null) ? o1.getDate().compareTo(o2.getDate())
: 1;
}
return -1;
}
});
table.addColumnSortHandler(columnSortHandler);
table.getColumnSortList().push(name);
if (selectable) {
table.setSelectionModel(selectionModel);
selectionModel
.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
String s = selectionModel.getSelectedObject();
log.info(s + " " + event.getSource());
}
});
}
return true;
}
@Override
public boolean update() {
boolean result = super.update();
+ // resort the table
+ ColumnSortEvent.fire(table, table.getColumnSortList());
table.redraw();
return result;
}
}
| false | false | null | null |
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReviewers.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReviewers.java
index 0441fd3f7..5a6d44163 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReviewers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReviewers.java
@@ -1,305 +1,313 @@
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.change;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.gerrit.common.ChangeHooks;
import com.google.gerrit.common.data.GroupDescription;
import com.google.gerrit.common.errors.EmailException;
import com.google.gerrit.common.errors.NoSuchGroupException;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.DefaultInput;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.extensions.restapi.UnprocessableEntityException;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.reviewdb.client.PatchSetApproval.LabelId;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.account.AccountInfo;
import com.google.gerrit.server.account.AccountsCollection;
import com.google.gerrit.server.account.GroupMembers;
import com.google.gerrit.server.change.PostReviewers.Input;
import com.google.gerrit.server.change.ReviewerJson.PostResult;
import com.google.gerrit.server.change.ReviewerJson.ReviewerInfo;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.group.GroupsCollection;
import com.google.gerrit.server.mail.AddReviewerSender;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.NoSuchProjectException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Set;
public class PostReviewers implements RestModifyView<ChangeResource, Input> {
+ private static final Logger log = LoggerFactory
+ .getLogger(PostReviewers.class);
+
public static final int DEFAULT_MAX_REVIEWERS_WITHOUT_CHECK = 10;
public static final int DEFAULT_MAX_REVIEWERS = 20;
public static class Input {
@DefaultInput
public String reviewer;
Boolean confirmed;
boolean confirmed() {
return Objects.firstNonNull(confirmed, false);
}
}
private final AccountsCollection accounts;
private final ReviewerResource.Factory reviewerFactory;
private final AddReviewerSender.Factory addReviewerSenderFactory;
private final Provider<GroupsCollection> groupsCollection;
private final GroupMembers.Factory groupMembersFactory;
private final AccountInfo.Loader.Factory accountLoaderFactory;
private final Provider<ReviewDb> dbProvider;
private final IdentifiedUser currentUser;
private final IdentifiedUser.GenericFactory identifiedUserFactory;
private final Config cfg;
private final ChangeHooks hooks;
private final AccountCache accountCache;
private final ReviewerJson json;
@Inject
PostReviewers(AccountsCollection accounts,
ReviewerResource.Factory reviewerFactory,
AddReviewerSender.Factory addReviewerSenderFactory,
Provider<GroupsCollection> groupsCollection,
GroupMembers.Factory groupMembersFactory,
AccountInfo.Loader.Factory accountLoaderFactory,
Provider<ReviewDb> db,
IdentifiedUser currentUser,
IdentifiedUser.GenericFactory identifiedUserFactory,
@GerritServerConfig Config cfg,
ChangeHooks hooks,
AccountCache accountCache,
ReviewerJson json) {
this.accounts = accounts;
this.reviewerFactory = reviewerFactory;
this.addReviewerSenderFactory = addReviewerSenderFactory;
this.groupsCollection = groupsCollection;
this.groupMembersFactory = groupMembersFactory;
this.accountLoaderFactory = accountLoaderFactory;
this.dbProvider = db;
this.currentUser = currentUser;
this.identifiedUserFactory = identifiedUserFactory;
this.cfg = cfg;
this.hooks = hooks;
this.accountCache = accountCache;
this.json = json;
}
@Override
public PostResult apply(ChangeResource rsrc, Input input)
throws BadRequestException, ResourceNotFoundException, AuthException,
UnprocessableEntityException, OrmException, EmailException, IOException {
if (input.reviewer == null) {
throw new BadRequestException("missing reviewer field");
}
try {
Account.Id accountId = accounts.parse(input.reviewer).getAccountId();
return putAccount(reviewerFactory.create(rsrc, accountId));
} catch (UnprocessableEntityException e) {
try {
return putGroup(rsrc, input);
} catch (UnprocessableEntityException e2) {
throw new UnprocessableEntityException(MessageFormat.format(
ChangeMessages.get().reviewerNotFound,
input.reviewer));
}
}
}
private PostResult putAccount(ReviewerResource rsrc) throws OrmException,
EmailException {
PostResult result = new PostResult();
addReviewers(rsrc, result, ImmutableSet.of(rsrc.getUser()));
return result;
}
private PostResult putGroup(ChangeResource rsrc, Input input)
throws BadRequestException,
UnprocessableEntityException, OrmException, EmailException, IOException {
GroupDescription.Basic group = groupsCollection.get().parseInternal(input.reviewer);
PostResult result = new PostResult();
if (!isLegalReviewerGroup(group.getGroupUUID())) {
result.error = MessageFormat.format(
ChangeMessages.get().groupIsNotAllowed, group.getName());
return result;
}
Set<IdentifiedUser> reviewers = Sets.newLinkedHashSet();
ChangeControl control = rsrc.getControl();
Set<Account> members;
try {
members = groupMembersFactory.create(control.getCurrentUser()).listAccounts(
group.getGroupUUID(), control.getProject().getNameKey());
} catch (NoSuchGroupException e) {
throw new UnprocessableEntityException(e.getMessage());
} catch (NoSuchProjectException e) {
throw new BadRequestException(e.getMessage());
}
// if maxAllowed is set to 0, it is allowed to add any number of
// reviewers
int maxAllowed =
cfg.getInt("addreviewer", "maxAllowed", DEFAULT_MAX_REVIEWERS);
if (maxAllowed > 0 && members.size() > maxAllowed) {
result.error = MessageFormat.format(
ChangeMessages.get().groupHasTooManyMembers, group.getName());
return result;
}
// if maxWithoutCheck is set to 0, we never ask for confirmation
int maxWithoutConfirmation =
cfg.getInt("addreviewer", "maxWithoutConfirmation",
DEFAULT_MAX_REVIEWERS_WITHOUT_CHECK);
if (!input.confirmed() && maxWithoutConfirmation > 0
&& members.size() > maxWithoutConfirmation) {
result.confirm = true;
result.error = MessageFormat.format(
ChangeMessages.get().groupManyMembersConfirmation,
group.getName(), members.size());
return result;
}
for (Account member : members) {
if (member.isActive()) {
IdentifiedUser user = identifiedUserFactory.create(member.getId());
// Does not account for draft status as a user might want to let a
// reviewer see a draft.
if (control.forUser(user).isRefVisible()) {
reviewers.add(user);
}
}
}
addReviewers(rsrc, result, reviewers);
return result;
}
private void addReviewers(ChangeResource rsrc, PostResult result,
Set<IdentifiedUser> reviewers) throws OrmException, EmailException {
if (reviewers.isEmpty()) {
result.reviewers = ImmutableList.of();
return;
}
ReviewDb db = dbProvider.get();
PatchSet.Id psid = rsrc.getChange().currentPatchSetId();
Set<Account.Id> existing = Sets.newHashSet();
for (PatchSetApproval psa : db.patchSetApprovals().byPatchSet(psid)) {
existing.add(psa.getAccountId());
}
result.reviewers = Lists.newArrayListWithCapacity(reviewers.size());
List<PatchSetApproval> toInsert =
Lists.newArrayListWithCapacity(reviewers.size());
for (IdentifiedUser user : reviewers) {
Account.Id id = user.getAccountId();
if (existing.contains(id)) {
continue;
}
ChangeControl control = rsrc.getControl().forUser(user);
PatchSetApproval psa = dummyApproval(control, psid, id);
result.reviewers.add(json.format(
new ReviewerInfo(id), control, ImmutableList.of(psa)));
toInsert.add(psa);
}
if (toInsert.isEmpty()) {
return;
}
db.changes().beginTransaction(rsrc.getChange().getId());
try {
ChangeUtil.bumpRowVersionNotLastUpdatedOn(rsrc.getChange().getId(), db);
db.patchSetApprovals().insert(toInsert);
db.commit();
} finally {
db.rollback();
}
accountLoaderFactory.create(true).fill(result.reviewers);
postAdd(rsrc.getChange(), result);
}
private void postAdd(Change change, PostResult result)
throws OrmException, EmailException {
if (result.reviewers.isEmpty()) {
return;
}
// Execute hook for added reviewers
//
PatchSet patchSet = dbProvider.get().patchSets().get(change.currentPatchSetId());
for (AccountInfo info : result.reviewers) {
Account account = accountCache.get(info._id).getAccount();
hooks.doReviewerAddedHook(change, account, patchSet, dbProvider.get());
}
// Email the reviewers
//
// The user knows they added themselves, don't bother emailing them.
List<Account.Id> added =
Lists.newArrayListWithCapacity(result.reviewers.size());
for (AccountInfo info : result.reviewers) {
if (!info._id.equals(currentUser.getAccountId())) {
added.add(info._id);
}
}
if (!added.isEmpty()) {
- AddReviewerSender cm;
-
- cm = addReviewerSenderFactory.create(change);
- cm.setFrom(currentUser.getAccountId());
- cm.addReviewers(added);
- cm.send();
+ try {
+ AddReviewerSender cm = addReviewerSenderFactory.create(change);
+ cm.setFrom(currentUser.getAccountId());
+ cm.addReviewers(added);
+ cm.send();
+ } catch (Exception err) {
+ log.error("Cannot send email to new reviewers of change "
+ + change.getId(), err);
+ }
}
}
public static boolean isLegalReviewerGroup(AccountGroup.UUID groupUUID) {
return !(AccountGroup.ANONYMOUS_USERS.equals(groupUUID)
|| AccountGroup.REGISTERED_USERS.equals(groupUUID));
}
private PatchSetApproval dummyApproval(ChangeControl ctl,
PatchSet.Id patchSetId, Account.Id reviewerId) {
LabelId id =
Iterables.getLast(ctl.getLabelTypes().getLabelTypes()).getLabelId();
PatchSetApproval dummyApproval = new PatchSetApproval(
new PatchSetApproval.Key(patchSetId, reviewerId, id), (short) 0);
dummyApproval.cache(ctl.getChange());
return dummyApproval;
}
}
| false | false | null | null |
diff --git a/tests/tests/text/src/android/text/method/cts/CharacterPickerDialogTest.java b/tests/tests/text/src/android/text/method/cts/CharacterPickerDialogTest.java
index fe9400e8..5ad230c2 100644
--- a/tests/tests/text/src/android/text/method/cts/CharacterPickerDialogTest.java
+++ b/tests/tests/text/src/android/text/method/cts/CharacterPickerDialogTest.java
@@ -1,146 +1,147 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.text.method.cts;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.ToBeFixed;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.test.ActivityInstrumentationTestCase2;
import android.text.Editable;
import android.text.Selection;
import android.text.method.CharacterPickerDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.TextView;
@TestTargetClass(CharacterPickerDialog.class)
public class CharacterPickerDialogTest extends
ActivityInstrumentationTestCase2<StubActivity> {
private Activity mActivity;
public CharacterPickerDialogTest() {
super("com.android.cts.stub", StubActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mActivity = getActivity();
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "CharacterPickerDialog",
args = {Context.class, View.class, Editable.class, String.class, boolean.class}
)
@ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete, " +
"should add @throw in the javadoc.")
public void testConstructor() {
final CharSequence str = "123456";
final Editable content = Editable.Factory.getInstance().newEditable(str);
final View view = new TextView(mActivity);
new CharacterPickerDialog(view.getContext(), view, content, "\u00A1", false);
try {
new CharacterPickerDialog(null, view, content, "\u00A1", false);
fail("should throw NullPointerException.");
} catch (NullPointerException e) {
// expected.
}
}
@TestTargetNew(
level = TestLevel.NOT_NECESSARY,
method = "onCreate",
args = {Bundle.class}
)
public void testOnCreate() {
// Do not test. Implementation details.
}
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "only position is read in this method",
method = "onItemClick",
args = {AdapterView.class, View.class, int.class, long.class}
)
public void testOnItemClick() {
final Gallery parent = new Gallery(mActivity);
final CharSequence str = "123456";
Editable text = Editable.Factory.getInstance().newEditable(str);
final View view = new TextView(mActivity);
CharacterPickerDialog replacePickerDialog =
new CharacterPickerDialog(view.getContext(), view, text, "abc", false);
// insert 'a' to the beginning of text
replacePickerDialog.show();
Selection.setSelection(text, 0, 0);
assertEquals(str, text.toString());
assertTrue(replacePickerDialog.isShowing());
replacePickerDialog.onItemClick(parent, view, 0, 0);
assertEquals("a123456", text.toString());
assertFalse(replacePickerDialog.isShowing());
// replace the second character '1' with 'c'
replacePickerDialog.show();
Selection.setSelection(text, 2, 2);
assertTrue(replacePickerDialog.isShowing());
replacePickerDialog.onItemClick(parent, view, 2, 0);
assertEquals("ac23456", text.toString());
assertFalse(replacePickerDialog.isShowing());
// insert character 'c' between '2' and '3'
text = Editable.Factory.getInstance().newEditable(str);
CharacterPickerDialog insertPickerDialog =
new CharacterPickerDialog(view.getContext(), view, text, "abc", true);
Selection.setSelection(text, 2, 2);
assertEquals(str, text.toString());
insertPickerDialog.show();
assertTrue(insertPickerDialog.isShowing());
insertPickerDialog.onItemClick(parent, view, 2, 0);
assertEquals("12c3456", text.toString());
assertFalse(insertPickerDialog.isShowing());
}
@TestTargetNew(
level = TestLevel.COMPLETE,
method = "onClick",
args = {View.class}
)
public void testOnClick() {
final CharSequence str = "123456";
final Editable content = Editable.Factory.getInstance().newEditable(str);
final View view = new TextView(mActivity);
CharacterPickerDialog characterPickerDialog =
new CharacterPickerDialog(view.getContext(), view, content, "\u00A1", false);
characterPickerDialog.show();
assertTrue(characterPickerDialog.isShowing());
+ // nothing to test here, just make sure onClick does not throw exception
characterPickerDialog.onClick(view);
- assertFalse(characterPickerDialog.isShowing());
+
}
}
| false | false | null | null |
diff --git a/simulator/code/simulator/elevatorcontrol/DriveControl.java b/simulator/code/simulator/elevatorcontrol/DriveControl.java
index 3990420..7e8b7ac 100644
--- a/simulator/code/simulator/elevatorcontrol/DriveControl.java
+++ b/simulator/code/simulator/elevatorcontrol/DriveControl.java
@@ -1,388 +1,387 @@
/* 18649 Fall 2012
* (Group 17)
* Jesse Salazar (jessesal)
* Rajeev Sharma (rdsharma)
* Collin Buchan (cbuchan)
* Jessica Tiu (jtiu) - Author
*/
package simulator.elevatorcontrol;
import jSimPack.SimTime;
import simulator.elevatorcontrol.Utility.AtFloorArray;
import simulator.elevatorcontrol.Utility.DoorClosedHallwayArray;
import simulator.elevatormodules.CarWeightCanPayloadTranslator;
import simulator.elevatormodules.LevelingCanPayloadTranslator;
import simulator.framework.Controller;
import simulator.framework.Direction;
import simulator.framework.Elevator;
import simulator.framework.Hallway;
import simulator.framework.ReplicationComputer;
import simulator.framework.Speed;
import simulator.payloads.CanMailbox;
import simulator.payloads.CanMailbox.ReadableCanMailbox;
import simulator.payloads.CanMailbox.WriteableCanMailbox;
import simulator.payloads.DrivePayload;
import simulator.payloads.DrivePayload.WriteableDrivePayload;
import simulator.payloads.translators.BooleanCanPayloadTranslator;
/**
* There is one DriveControl, which controls the elevator Drive
* (the main motor moving Car Up and Down). For simplicity we will assume
* this node never fails, although the system could be implemented with
* two such nodes, one per each of the Drive windings.
*
* @author Jessica Tiu
*/
public class DriveControl extends Controller {
/**
* ************************************************************************
* Declarations
* ************************************************************************
*/
//note that inputs are Readable objects, while outputs are Writeable objects
//local physical state
private WriteableDrivePayload localDrive;
//output network messages
private WriteableCanMailbox networkDriveOut;
private WriteableCanMailbox networkDriveSpeedOut;
//translators for output network messages
private DriveCommandCanPayloadTranslator mDrive;
private DriveSpeedCanPayloadTranslator mDriveSpeed;
//input network messages
private ReadableCanMailbox networkLevelUp;
private ReadableCanMailbox networkLevelDown;
private ReadableCanMailbox networkEmergencyBrake;
private ReadableCanMailbox networkCarWeight;
private ReadableCanMailbox networkDesiredFloor;
private DoorClosedHallwayArray networkDoorClosedFront;
private DoorClosedHallwayArray networkDoorClosedBack;
private AtFloorArray networkAtFloorArray;
//translators for input network messages
private LevelingCanPayloadTranslator mLevelUp;
private LevelingCanPayloadTranslator mLevelDown;
private BooleanCanPayloadTranslator mEmergencyBrake;
private CarWeightCanPayloadTranslator mCarWeight;
private DesiredFloorCanPayloadTranslator mDesiredFloor;
//store the period for the controller
private SimTime period;
//enumerate states
private enum State {
STATE_DRIVE_STOPPED,
STATE_DRIVE_LEVEL_UP,
STATE_DRIVE_LEVEL_DOWN,
STATE_DRIVE_SLOW,
}
//state variable initialized to the initial state DRIVE_STOPPED
private State state = State.STATE_DRIVE_STOPPED;
- private Direction desiredDir;
+ private Direction desiredDir = Direction.UP;
//returns the desired direction based on current floor and desired floor by dispatcher
private Direction getDesiredDir(Direction curDirection) {
Direction desiredDirection = curDirection;
int currentFloor = networkAtFloorArray.getCurrentFloor();
int desiredFloor = mDesiredFloor.getFloor();
//check car is not between floors
if (currentFloor != MessageDictionary.NONE){
//current floor below desired floor
if (currentFloor < desiredFloor) {
desiredDirection = Direction.UP;
}
//current floor above desired floor
else if (currentFloor > desiredFloor) {
desiredDirection = Direction.DOWN;
}
//current floor is desired floor
else {
desiredDirection = Direction.STOP;
}
}
return desiredDirection;
}
/**
* The arguments listed in the .cf configuration file should match the order and
* type given here.
* <p/>
* For your elevator controllers, you should make sure that the constructor matches
* the method signatures in ControllerBuilder.makeAll().
* <p/>
* controllers.add(createControllerObject("DriveControl",
* MessageDictionary.DRIVE_CONTROL_PERIOD, verbose));
*/
public DriveControl(SimTime period, boolean verbose) {
//call to the Controller superclass constructor is required
super("DriveControl", verbose);
this.period = period;
/*
* The log() method is inherited from the Controller class. It takes an
* array of objects which will be converted to strings and concatenated
* only if the log message is actually written.
*
* For performance reasons, call with comma-separated lists, e.g.:
* log("object=",object);
* Do NOT call with concatenated objects like:
* log("object=" + object);
*/
log("Created DriveControl with period = ", period);
//create an output payload
localDrive = DrivePayload.getWriteablePayload();
//register the payload to be sent periodically
physicalInterface.sendTimeTriggered(localDrive, period);
//create CAN mailbox for output network messages
networkDriveOut = CanMailbox.getWriteableCanMailbox(MessageDictionary.DRIVE_COMMAND_CAN_ID);
networkDriveSpeedOut = CanMailbox.getWriteableCanMailbox(MessageDictionary.DRIVE_SPEED_CAN_ID);
/*
* Create a translator with a reference to the CanMailbox. Use the
* translator to read and write values to the mailbox
*/
mDrive = new DriveCommandCanPayloadTranslator(networkDriveOut);
mDriveSpeed = new DriveSpeedCanPayloadTranslator(networkDriveSpeedOut);
//register the mailbox to have its value broadcast on the network periodically
//with a period specified by the period parameter.
canInterface.sendTimeTriggered(networkDriveOut, period);
canInterface.sendTimeTriggered(networkDriveSpeedOut, period);
/*
* To register for network messages from the smart sensors or other objects
* defined in elevator modules, use the translators already defined in
* elevatormodules package. These translators are specific to one type
* of message.
*/
networkLevelUp =
CanMailbox.getReadableCanMailbox(MessageDictionary.LEVELING_BASE_CAN_ID +
ReplicationComputer.computeReplicationId(Direction.UP));
networkLevelDown =
CanMailbox.getReadableCanMailbox(MessageDictionary.LEVELING_BASE_CAN_ID +
ReplicationComputer.computeReplicationId(Direction.DOWN));
networkEmergencyBrake =
CanMailbox.getReadableCanMailbox(MessageDictionary.EMERGENCY_BRAKE_CAN_ID);
networkCarWeight =
CanMailbox.getReadableCanMailbox(MessageDictionary.CAR_WEIGHT_CAN_ID);
networkDesiredFloor =
CanMailbox.getReadableCanMailbox(MessageDictionary.DESIRED_FLOOR_CAN_ID);
networkDoorClosedFront = new Utility.DoorClosedHallwayArray(Hallway.FRONT, canInterface);
networkDoorClosedBack = new Utility.DoorClosedHallwayArray(Hallway.BACK, canInterface);
networkAtFloorArray = new Utility.AtFloorArray(canInterface);
mLevelUp =
new LevelingCanPayloadTranslator(networkLevelUp, Direction.UP);
mLevelDown =
new LevelingCanPayloadTranslator(networkLevelDown, Direction.DOWN);
mEmergencyBrake =
new BooleanCanPayloadTranslator(networkEmergencyBrake);
mCarWeight =
new CarWeightCanPayloadTranslator(networkCarWeight);
// used to calculate desiredDir
mDesiredFloor =
new DesiredFloorCanPayloadTranslator(networkDesiredFloor);
//register to receive periodic updates to the mailbox via the CAN network
//the period of updates will be determined by the sender of the message
canInterface.registerTimeTriggered(networkLevelUp);
canInterface.registerTimeTriggered(networkLevelDown);
canInterface.registerTimeTriggered(networkEmergencyBrake);
canInterface.registerTimeTriggered(networkCarWeight);
canInterface.registerTimeTriggered(networkDesiredFloor);
/* issuing the timer start method with no callback data means a NULL value
* will be passed to the callback later. Use the callback data to distinguish
* callbacks from multiple calls to timer.start() (e.g. if you have multiple
* timers.
*/
timer.start(period);
}
/*
* The timer callback is where the main controller code is executed. For time
* triggered design, this consists mainly of a switch block with a case blcok for
* each state. Each case block executes actions for that state, then executes
* a transition to the next state if the transition conditions are met.
*/
public void timerExpired(Object callbackData) {
State newState = state;
- desiredDir = Direction.UP;
switch (state) {
case STATE_DRIVE_STOPPED:
desiredDir = getDesiredDir(desiredDir);
//state actions for DRIVE_STOPPED
localDrive.set(Speed.STOP, Direction.STOP);
mDrive.set(Speed.STOP, Direction.STOP);
mDriveSpeed.set(Speed.STOP, desiredDir);
//transitions
//#transition 'T6.1'
if (desiredDir.equals(Direction.STOP) &&
!mLevelUp.getValue() && mLevelDown.getValue()){
log("T6.1");
newState = State.STATE_DRIVE_LEVEL_UP;
}
//#transition 'T6.3'
else if (desiredDir.equals(Direction.STOP) &&
!mLevelDown.getValue() && mLevelUp.getValue()){
log("T6.3");
newState = State.STATE_DRIVE_LEVEL_DOWN;
}
//#transition 'T6.9'
else if (networkDoorClosedFront.getAllClosed() && networkDoorClosedBack.getAllClosed() &&
!desiredDir.equals(Direction.STOP) &&
mCarWeight.getWeight() < Elevator.MaxCarCapacity &&
!mEmergencyBrake.getValue()){
log("T6.9");
newState = State.STATE_DRIVE_SLOW;
} else {
newState = state;
}
break;
case STATE_DRIVE_LEVEL_UP:
desiredDir = getDesiredDir(desiredDir);
//state actions for DRIVE_LEVEL_UP
localDrive.set(Speed.LEVEL, Direction.UP);
mDrive.set(Speed.LEVEL, Direction.UP);
mDriveSpeed.set(Speed.LEVEL, Direction.UP);
//transitions
//#transition 'T6.2'
if (mCarWeight.getWeight() >= Elevator.MaxCarCapacity ||
mEmergencyBrake.getValue() ||
!networkDoorClosedFront.getAllClosed() || !networkDoorClosedBack.getAllClosed() ||
(mLevelUp.getValue() && mLevelDown.getValue() &&
desiredDir.equals(Direction.STOP))){
newState = State.STATE_DRIVE_STOPPED;
}
//#transition 'T6.5'
else if (desiredDir.equals(Direction.STOP) &&
!mLevelDown.getValue() && mLevelUp.getValue()){
newState = State.STATE_DRIVE_LEVEL_DOWN;
} else {
newState = state;
}
break;
case STATE_DRIVE_LEVEL_DOWN:
desiredDir = getDesiredDir(desiredDir);
//state actions for DRIVE_LEVEL_DOWN
localDrive.set(Speed.LEVEL, Direction.DOWN);
mDrive.set(Speed.LEVEL, Direction.DOWN);
mDriveSpeed.set(Speed.LEVEL, Direction.DOWN);
//transitions
//#transition 'T6.4'
if (mCarWeight.getWeight() >= Elevator.MaxCarCapacity ||
mEmergencyBrake.getValue() ||
!networkDoorClosedFront.getAllClosed() || !networkDoorClosedBack.getAllClosed() ||
(mLevelUp.getValue() && mLevelDown.getValue() &&
desiredDir.equals(Direction.STOP))){
newState = State.STATE_DRIVE_STOPPED;
}
//#transition 'T6.6'
else if (desiredDir.equals(Direction.STOP) &&
!mLevelUp.getValue() && mLevelDown.getValue()){
newState = State.STATE_DRIVE_LEVEL_UP;
} else {
newState = state;
}
break;
case STATE_DRIVE_SLOW:
desiredDir = getDesiredDir(desiredDir);
//state actions for DRIVE_SLOW
localDrive.set(Speed.SLOW, desiredDir);
mDrive.set(Speed.SLOW, desiredDir);
mDriveSpeed.set(Speed.SLOW, desiredDir);
//transitions
//#transition 'T6.7'
if (desiredDir.equals(Direction.STOP) &&
!mLevelUp.getValue() && mLevelDown.getValue()){
newState = State.STATE_DRIVE_LEVEL_UP;
}
//#transition 'T6.8'
else if (desiredDir.equals(Direction.STOP) &&
!mLevelDown.getValue() && mLevelUp.getValue()){
newState = State.STATE_DRIVE_LEVEL_DOWN;
}
//#transition 'T6.10'
else if (mCarWeight.getWeight() >= Elevator.MaxCarCapacity ||
mEmergencyBrake.getValue()){
newState = State.STATE_DRIVE_STOPPED;
} else {
newState = state;
}
break;
default:
throw new RuntimeException("State " + state + " was not recognized.");
}
//log the results of this iteration
if (state == newState) {
log("remains in state: ", state);
} else {
log("Transition:", state, "->", newState);
}
//update the state variable
state = newState;
//report the current state
setState(STATE_KEY, newState.toString());
//schedule the next iteration of the controller
//you must do this at the end of the timer callback in order to restart
//the timer
timer.start(period);
}
}
| false | false | null | null |
diff --git a/izpack-compiler/src/test/java/com/izforge/izpack/compiler/container/provider/IzpackProjectProviderTest.java b/izpack-compiler/src/test/java/com/izforge/izpack/compiler/container/provider/IzpackProjectProviderTest.java
index 87fefc01b..ce7bc523c 100644
--- a/izpack-compiler/src/test/java/com/izforge/izpack/compiler/container/provider/IzpackProjectProviderTest.java
+++ b/izpack-compiler/src/test/java/com/izforge/izpack/compiler/container/provider/IzpackProjectProviderTest.java
@@ -1,102 +1,110 @@
package com.izforge.izpack.compiler.container.provider;
import com.izforge.izpack.api.data.Panel;
import com.izforge.izpack.api.data.binding.*;
import org.hamcrest.beans.HasPropertyWithValue;
import org.hamcrest.collection.IsCollectionContaining;
import org.hamcrest.core.AllOf;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Test for provider
*
* @author Anthonin Bonnefoy
*/
public class IzpackProjectProviderTest
{
private IzpackProjectProvider izpackProjectProvider;
private IzpackProjectInstaller izpackProjectInstaller;
@Before
public void setUp() throws Exception
{
izpackProjectProvider = new IzpackProjectProvider();
izpackProjectInstaller = izpackProjectProvider.provide(
"bindingTest.xml");
assertThat(izpackProjectInstaller, Is.is(IzpackProjectInstaller.class));
}
@Test
+ public void bindingWithXInclude() throws Exception
+ {
+ // TODO : find why this test fails
+ izpackProjectInstaller = izpackProjectProvider.provide(
+ "bindingXInclude/main.xml");
+ }
+
+ @Test
public void bindingListener() throws Exception
{
List<Listener> listenerList = izpackProjectInstaller.getListeners();
assertThat(listenerList, IsCollectionContaining.hasItem(
AllOf.allOf(
HasPropertyWithValue.<Listener>hasProperty("classname", Is.is("SummaryLoggerInstallerListener")),
HasPropertyWithValue.<Listener>hasProperty("stage", Is.is(Stage.install))
)
));
assertThat(listenerList, IsCollectionContaining.hasItem(
AllOf.allOf(
HasPropertyWithValue.<Listener>hasProperty("classname", Is.is("RegistryInstallerListener")),
HasPropertyWithValue.<Listener>hasProperty("stage", Is.is(Stage.install)),
HasPropertyWithValue.<Listener>hasProperty("os",
IsCollectionContaining.hasItems(
HasPropertyWithValue.<OsModel>hasProperty("family", Is.is("windows")),
HasPropertyWithValue.<OsModel>hasProperty("arch", Is.is("ppc"))
)))));
}
@Test
public void bindingSimplePanel() throws Exception
{
List<Panel> panelList = izpackProjectInstaller.getPanels();
assertThat(panelList, IsCollectionContaining.hasItem(
AllOf.allOf(
HasPropertyWithValue.<Panel>hasProperty("className", Is.is("CheckedHelloPanel")),
HasPropertyWithValue.<Panel>hasProperty("panelid", Is.is("hellopanel")),
HasPropertyWithValue.<Panel>hasProperty("condition", Is.is("test.cond"))
)
));
}
@Test
public void bindingPanelWithOsConstraint() throws Exception
{
List<Panel> panelList = izpackProjectInstaller.getPanels();
assertThat(panelList, IsCollectionContaining.hasItem(
AllOf.allOf(
HasPropertyWithValue.<Panel>hasProperty("className", Is.is("HTMLInfoPanel")),
HasPropertyWithValue.<Panel>hasProperty("panelid", Is.is("infopanel")),
HasPropertyWithValue.<Panel>hasProperty("osConstraints",
IsCollectionContaining.hasItems(
HasPropertyWithValue.<OsModel>hasProperty("family", Is.is("BSD")),
HasPropertyWithValue.<OsModel>hasProperty("arch", Is.is("x666"))
))
)));
}
@Test
public void bindingPanelWithHelp() throws Exception
{
List<Panel> panelList = izpackProjectInstaller.getPanels();
assertThat(panelList, IsCollectionContaining.hasItem(
HasPropertyWithValue.<Panel>hasProperty("helps",
IsCollectionContaining.hasItem(
AllOf.allOf(
HasPropertyWithValue.<Help>hasProperty("src", Is.is("HelloPanelHelp_deu.html")),
HasPropertyWithValue.<Help>hasProperty("iso3", Is.is("deu"))
)
))
));
}
}
| true | false | null | null |
diff --git a/errai-bus/src/main/java/org/jboss/errai/bus/server/security/auth/rules/RolesRequiredRule.java b/errai-bus/src/main/java/org/jboss/errai/bus/server/security/auth/rules/RolesRequiredRule.java
index 91568bf2b..a3e6175d6 100644
--- a/errai-bus/src/main/java/org/jboss/errai/bus/server/security/auth/rules/RolesRequiredRule.java
+++ b/errai-bus/src/main/java/org/jboss/errai/bus/server/security/auth/rules/RolesRequiredRule.java
@@ -1,128 +1,137 @@
/*
* Copyright 2009 JBoss, a divison Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.errai.bus.server.security.auth.rules;
import org.jboss.errai.bus.client.framework.BooleanRoutingRule;
import org.jboss.errai.bus.client.api.ErrorCallback;
import org.jboss.errai.bus.client.api.Message;
import org.jboss.errai.bus.client.protocols.MessageParts;
import org.jboss.errai.bus.client.protocols.SecurityCommands;
import org.jboss.errai.bus.client.protocols.SecurityParts;
import org.jboss.errai.bus.server.api.QueueSession;
import org.jboss.errai.bus.server.api.ServerMessageBus;
import org.jboss.errai.bus.server.security.auth.AuthSubject;
import org.jboss.errai.bus.server.service.ErraiService;
import org.jboss.errai.bus.client.util.ErrorHelper;
import org.jboss.errai.bus.server.util.ServerBusUtils;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import static org.jboss.errai.bus.client.api.base.MessageBuilder.createConversation;
import static org.jboss.errai.bus.client.api.base.MessageBuilder.createMessage;
/**
* This routing rule specifies a set of required roles that a message must posess in order for this routing rule
* to return true.
*/
public class RolesRequiredRule implements BooleanRoutingRule {
private Set<Object> requiredRoles;
private ServerMessageBus bus;
public RolesRequiredRule(String[] requiredRoles, ServerMessageBus bus) {
this.requiredRoles = new HashSet<Object>();
for (String role : requiredRoles) {
this.requiredRoles.add(role.trim());
}
this.bus = bus;
}
public RolesRequiredRule(Set<Object> requiredRoles, ServerMessageBus bus) {
this.requiredRoles = requiredRoles;
this.bus = bus;
}
public boolean decision(final Message message) {
if (!message.hasResource("Session")) return false;
else {
+
AuthSubject subject = getSession(message).getAttribute(AuthSubject.class, ErraiService.SESSION_AUTH_DATA);
if (subject == null) {
/**
* Inform the client they must login.
*/
+ if ("LoginClient".equals(message.getSubject())) {
+ /**
+ * Make an exception for the LoginClient ...
+ */
+ return true;
+ }
+
+
// TODO: This reside with the "AuthenticationService" listener, no
// i.e. by forwarding to that subject. See ErraiServiceImpl
createMessage()
.toSubject("LoginClient")
.command(SecurityCommands.SecurityChallenge)
.with(SecurityParts.CredentialsRequired, "Name,Password")
.with(MessageParts.ReplyTo, ErraiService.AUTHORIZATION_SVC_SUBJECT)
.with(SecurityParts.RejectedMessage, ServerBusUtils.encodeJSON(message.getParts()))
.copyResource("Session", message)
.errorsHandledBy(new ErrorCallback() {
public boolean error(Message message, Throwable throwable) {
ErrorHelper.sendClientError(bus, message, "Could not contact LoginClient to handle access denial, due to insufficient privileges for: " + message.getSubject(), throwable);
return false;
}
})
.sendNowWith(bus, false);
return false;
}
if (!subject.getRoles().containsAll(requiredRoles)) {
createConversation(message)
.toSubject("ClientErrorService")
.signalling()
.with(MessageParts.ErrorMessage, "Access denied to service: "
+ message.get(String.class, MessageParts.ToSubject) +
" (Required Roles: [" + getRequiredRolesString() + "])")
.noErrorHandling().sendNowWith(bus);
return false;
} else {
return true;
}
}
}
public String getRequiredRolesString() {
StringBuilder builder = new StringBuilder();
Iterator<Object> iter = requiredRoles.iterator();
while (iter.hasNext()) {
builder.append(String.valueOf(iter.next()));
if (iter.hasNext()) builder.append(", ");
}
return builder.toString();
}
public Set<Object> getRoles() {
return requiredRoles;
}
private static QueueSession getSession(Message message) {
return message.getResource(QueueSession.class, "Session");
}
}
| false | false | null | null |
diff --git a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/classifier/AbstractExpressionEvaluator.java b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/classifier/AbstractExpressionEvaluator.java
index bda97a710..74c963c7f 100644
--- a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/classifier/AbstractExpressionEvaluator.java
+++ b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/classifier/AbstractExpressionEvaluator.java
@@ -1,81 +1,84 @@
/*
* Copyright (c) 2009-2010, IETR/INSA of Rennes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the IETR/INSA of Rennes nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.orcc.tools.classifier;
import net.sf.orcc.OrccRuntimeException;
import net.sf.orcc.ir.ExprBinary;
import net.sf.orcc.ir.ExprUnary;
import net.sf.orcc.ir.util.ExpressionEvaluator;
+import net.sf.orcc.ir.util.ExpressionPrinter;
/**
* This class defines a partial expression evaluator.
*
* @author Matthieu Wipliez
*
*/
public class AbstractExpressionEvaluator extends ExpressionEvaluator {
private boolean schedulableMode;
@Override
public Object caseExprBinary(ExprBinary expr) {
Object val1 = doSwitch(expr.getE1());
Object val2 = doSwitch(expr.getE2());
Object result = interpretBinaryExpr(val1, expr.getOp(), val2);
// only throws an exception if we are in schedulable mode and the result
// is null
if (schedulableMode && result == null) {
- throw new OrccRuntimeException("Runtime binary expression");
+ throw new OrccRuntimeException("Expression \""
+ + new ExpressionPrinter().doSwitch(expr) + "\" is null");
}
return result;
}
@Override
public Object caseExprUnary(ExprUnary expr) {
Object value = doSwitch(expr.getExpr());
Object result = interpretUnaryExpr(expr.getOp(), value);
if (schedulableMode && value == null) {
- throw new OrccRuntimeException("Runtime unary expression");
+ throw new OrccRuntimeException("Expression \""
+ + new ExpressionPrinter().doSwitch(expr) + "\" is null");
}
return result;
}
/**
* Sets schedulable mode. When in schedulable mode, evaluations of null
* expressions is forbidden. Otherwise it is allowed.
*
* @param schedulableMode
*/
public void setSchedulableMode(boolean schedulableMode) {
this.schedulableMode = schedulableMode;
}
}
| false | false | null | null |
diff --git a/user/src/com/google/gwt/user/client/ui/DecoratedPopupPanel.java b/user/src/com/google/gwt/user/client/ui/DecoratedPopupPanel.java
index e8b73a447..275daa554 100644
--- a/user/src/com/google/gwt/user/client/ui/DecoratedPopupPanel.java
+++ b/user/src/com/google/gwt/user/client/ui/DecoratedPopupPanel.java
@@ -1,192 +1,192 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.client.ui;
import com.google.gwt.user.client.Element;
import java.util.Iterator;
/**
* <p>
* A {@link PopupPanel} that wraps its content in a 3x3 grid, which allows users
* to add rounded corners.
* </p>
*
* <h3>Setting the Size:</h3>
* <p>
* If you set the width or height of the {@link DecoratedPopupPanel}, you need
* to set the height and width of the middleCenter cell to 100% so that the
* middleCenter cell takes up all of the available space. If you do not set the
* width and height of the {@link DecoratedPopupPanel}, it will wrap its
* contents tightly.
* </p>
*
* <pre>
* .gwt-DecoratedPopupPanel .popupMiddleCenter {
* height: 100%;
* width: 100%;
* }
* </pre>
*
* <h3>CSS Style Rules</h3>
* <ul class='css'>
* <li>.gwt-DecoratedPopupPanel { the outside of the popup }</li>
* <li>.gwt-DecoratedPopupPanel .popupContent { the wrapper around the content }</li>
* <li>.gwt-DecoratedPopupPanel .popupTopLeft { the top left cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupTopLeftInner { the inner element of the
* cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupTopCenter { the top center cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupTopCenterInner { the inner element of the
* cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupTopRight { the top right cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupTopRightInner { the inner element of the
* cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupMiddleLeft { the middle left cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupMiddleLeftInner { the inner element of
* the cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupMiddleCenter { the middle center cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupMiddleCenterInner { the inner element of
* the cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupMiddleRight { the middle right cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupMiddleRightInner { the inner element of
* the cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupBottomLeft { the bottom left cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupBottomLeftInner { the inner element of
* the cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupBottomCenter { the bottom center cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupBottomCenterInner { the inner element of
* the cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupBottomRight { the bottom right cell }</li>
* <li>.gwt-DecoratedPopupPanel .popupBottomRightInner { the inner element of
* the cell }</li>
* </ul>
*/
public class DecoratedPopupPanel extends PopupPanel {
private static final String DEFAULT_STYLENAME = "gwt-DecoratedPopupPanel";
/**
* The panel used to nine box the contents.
*/
private DecoratorPanel decPanel;
/**
* Creates an empty decorated popup panel. A child widget must be added to it
* before it is shown.
*/
public DecoratedPopupPanel() {
this(false);
}
/**
* Creates an empty decorated popup panel, specifying its "auto-hide"
* property.
*
* @param autoHide <code>true</code> if the popup should be automatically
* hidden when the user clicks outside of it
*/
public DecoratedPopupPanel(boolean autoHide) {
this(autoHide, false);
}
/**
* Creates an empty decorated popup panel, specifying its "auto-hide" and
* "modal" properties.
*
* @param autoHide <code>true</code> if the popup should be automatically
* hidden when the user clicks outside of it
* @param modal <code>true</code> if keyboard or mouse events that do not
* target the PopupPanel or its children should be ignored
*/
public DecoratedPopupPanel(boolean autoHide, boolean modal) {
this(autoHide, modal, "popup");
}
/**
* Creates an empty decorated popup panel using the specified style names.
*
* @param autoHide <code>true</code> if the popup should be automatically
* hidden when the user clicks outside of it
* @param modal <code>true</code> if keyboard or mouse events that do not
* target the PopupPanel or its children should be ignored
* @param prefix the prefix applied to child style names
*/
DecoratedPopupPanel(boolean autoHide, boolean modal, String prefix) {
super(autoHide, modal);
String[] rowStyles = new String[] {
prefix + "Top", prefix + "Middle", prefix + "Bottom"};
decPanel = new DecoratorPanel(rowStyles, 1);
decPanel.setStyleName("");
setStylePrimaryName(DEFAULT_STYLENAME);
- setWidget(decPanel);
+ super.setWidget(decPanel);
setStyleName(getContainerElement(), "popupContent", false);
setStyleName(decPanel.getContainerElement(), prefix + "Content", true);
}
@Override
public void clear() {
decPanel.clear();
}
@Override
public Widget getWidget() {
return decPanel.getWidget();
}
@Override
public Iterator<Widget> iterator() {
return decPanel.iterator();
}
@Override
public boolean remove(Widget w) {
return decPanel.remove(w);
}
@Override
public void setWidget(Widget w) {
decPanel.setWidget(w);
maybeUpdateSize();
}
@Override
protected void doAttachChildren() {
// See comment in doDetachChildren for an explanation of this call
decPanel.onAttach();
}
@Override
protected void doDetachChildren() {
// We need to detach the decPanel because it is not part of the iterator of
// Widgets that this class returns (see the iterator() method override).
// Detaching the decPanel detaches both itself and its children. We do not
// call super.onDetachChildren() because that would detach the decPanel's
// children (redundantly) without detaching the decPanel itself.
// This is similar to a {@link ComplexPanel}, but we do not want to expose
// the decPanel widget, as its just an internal implementation.
decPanel.onDetach();
}
/**
* Get a specific Element from the panel.
*
* @param row the row index
* @param cell the cell index
* @return the Element at the given row and cell
*/
protected Element getCellElement(int row, int cell) {
return decPanel.getCellElement(row, cell);
}
}
diff --git a/user/test/com/google/gwt/dom/client/StyleTest.java b/user/test/com/google/gwt/dom/client/StyleTest.java
index eff425975..8ea8c3088 100644
--- a/user/test/com/google/gwt/dom/client/StyleTest.java
+++ b/user/test/com/google/gwt/dom/client/StyleTest.java
@@ -1,258 +1,268 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.dom.client;
import static com.google.gwt.dom.client.Style.Unit.CM;
import static com.google.gwt.dom.client.Style.Unit.EM;
import static com.google.gwt.dom.client.Style.Unit.EX;
import static com.google.gwt.dom.client.Style.Unit.IN;
import static com.google.gwt.dom.client.Style.Unit.MM;
import static com.google.gwt.dom.client.Style.Unit.PC;
import static com.google.gwt.dom.client.Style.Unit.PCT;
import static com.google.gwt.dom.client.Style.Unit.PT;
import static com.google.gwt.dom.client.Style.Unit.PX;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.FontStyle;
import com.google.gwt.dom.client.Style.FontWeight;
import com.google.gwt.dom.client.Style.HasCssName;
import com.google.gwt.dom.client.Style.ListStyleType;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.TextDecoration;
import com.google.gwt.dom.client.Style.VerticalAlign;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Tests the native {@link Style} class.
*/
public class StyleTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.dom.DOMTest";
}
public void testCursor() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setCursor(Cursor.DEFAULT);
assertEquals(Cursor.DEFAULT, style.getCursor());
style.setCursor(Cursor.AUTO);
assertEquals(Cursor.AUTO, style.getCursor());
style.setCursor(Cursor.CROSSHAIR);
assertEquals(Cursor.CROSSHAIR, style.getCursor());
style.setCursor(Cursor.POINTER);
assertEquals(Cursor.POINTER, style.getCursor());
style.setCursor(Cursor.MOVE);
assertEquals(Cursor.MOVE, style.getCursor());
style.setCursor(Cursor.E_RESIZE);
assertEquals(Cursor.E_RESIZE, style.getCursor());
style.setCursor(Cursor.NE_RESIZE);
assertEquals(Cursor.NE_RESIZE, style.getCursor());
style.setCursor(Cursor.NW_RESIZE);
assertEquals(Cursor.NW_RESIZE, style.getCursor());
style.setCursor(Cursor.N_RESIZE);
assertEquals(Cursor.N_RESIZE, style.getCursor());
style.setCursor(Cursor.SE_RESIZE);
assertEquals(Cursor.SE_RESIZE, style.getCursor());
style.setCursor(Cursor.SW_RESIZE);
assertEquals(Cursor.SW_RESIZE, style.getCursor());
style.setCursor(Cursor.S_RESIZE);
assertEquals(Cursor.S_RESIZE, style.getCursor());
style.setCursor(Cursor.W_RESIZE);
assertEquals(Cursor.W_RESIZE, style.getCursor());
style.setCursor(Cursor.TEXT);
assertEquals(Cursor.TEXT, style.getCursor());
style.setCursor(Cursor.WAIT);
assertEquals(Cursor.WAIT, style.getCursor());
style.setCursor(Cursor.HELP);
assertEquals(Cursor.HELP, style.getCursor());
+
+ // These aren't supported on old mozilla, so testing them will break.
+ // TODO: re-enable these cases when we finally drop linux hosted mode.
+ /*
style.setCursor(Cursor.COL_RESIZE);
assertEquals(Cursor.COL_RESIZE, style.getCursor());
style.setCursor(Cursor.ROW_RESIZE);
assertEquals(Cursor.ROW_RESIZE, style.getCursor());
+ */
}
public void testDisplay() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setDisplay(Display.NONE);
assertEquals(Display.NONE, style.getDisplay());
style.setDisplay(Display.BLOCK);
assertEquals(Display.BLOCK, style.getDisplay());
style.setDisplay(Display.INLINE);
assertEquals(Display.INLINE, style.getDisplay());
+
+ // Not supported on old mozilla, so testing it will break.
+ // TODO: re-enable these cases when we finally drop linux hosted mode.
+ /*
style.setDisplay(Display.INLINE_BLOCK);
assertEquals(Display.INLINE_BLOCK, style.getDisplay());
+ */
}
public void testFontStyle() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setFontStyle(FontStyle.NORMAL);
assertEquals(FontStyle.NORMAL, style.getFontStyle());
style.setFontStyle(FontStyle.ITALIC);
assertEquals(FontStyle.ITALIC, style.getFontStyle());
style.setFontStyle(FontStyle.OBLIQUE);
assertEquals(FontStyle.OBLIQUE, style.getFontStyle());
}
public void testFontWeight() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setFontWeight(FontWeight.NORMAL);
assertEquals(FontWeight.NORMAL, style.getFontWeight());
style.setFontWeight(FontWeight.BOLD);
assertEquals(FontWeight.BOLD, style.getFontWeight());
style.setFontWeight(FontWeight.BOLDER);
assertEquals(FontWeight.BOLDER, style.getFontWeight());
style.setFontWeight(FontWeight.LIGHTER);
assertEquals(FontWeight.LIGHTER, style.getFontWeight());
}
public void testListStyleType() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setListStyleType(ListStyleType.NONE);
assertEquals(ListStyleType.NONE, style.getListStyleType());
style.setListStyleType(ListStyleType.DISC);
assertEquals(ListStyleType.DISC, style.getListStyleType());
style.setListStyleType(ListStyleType.CIRCLE);
assertEquals(ListStyleType.CIRCLE, style.getListStyleType());
style.setListStyleType(ListStyleType.SQUARE);
assertEquals(ListStyleType.SQUARE, style.getListStyleType());
style.setListStyleType(ListStyleType.DECIMAL);
assertEquals(ListStyleType.DECIMAL, style.getListStyleType());
style.setListStyleType(ListStyleType.LOWER_ALPHA);
assertEquals(ListStyleType.LOWER_ALPHA, style.getListStyleType());
style.setListStyleType(ListStyleType.UPPER_ALPHA);
assertEquals(ListStyleType.UPPER_ALPHA, style.getListStyleType());
style.setListStyleType(ListStyleType.LOWER_ROMAN);
assertEquals(ListStyleType.LOWER_ROMAN, style.getListStyleType());
style.setListStyleType(ListStyleType.UPPER_ROMAN);
assertEquals(ListStyleType.UPPER_ROMAN, style.getListStyleType());
}
public void testOverflow() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setOverflow(Overflow.VISIBLE);
assertEquals(Overflow.VISIBLE, style.getOverflow());
style.setOverflow(Overflow.HIDDEN);
assertEquals(Overflow.HIDDEN, style.getOverflow());
style.setOverflow(Overflow.SCROLL);
assertEquals(Overflow.SCROLL, style.getOverflow());
style.setOverflow(Overflow.AUTO);
assertEquals(Overflow.AUTO, style.getOverflow());
}
public void testPosition() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setPosition(Position.STATIC);
assertEquals(Position.STATIC, style.getPosition());
style.setPosition(Position.RELATIVE);
assertEquals(Position.RELATIVE, style.getPosition());
style.setPosition(Position.ABSOLUTE);
assertEquals(Position.ABSOLUTE, style.getPosition());
style.setPosition(Position.FIXED);
assertEquals(Position.FIXED, style.getPosition());
}
public void testTextDecoration() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setTextDecoration(TextDecoration.NONE);
assertEquals(TextDecoration.NONE, style.getTextDecoration());
style.setTextDecoration(TextDecoration.UNDERLINE);
assertEquals(TextDecoration.UNDERLINE, style.getTextDecoration());
style.setTextDecoration(TextDecoration.OVERLINE);
assertEquals(TextDecoration.OVERLINE, style.getTextDecoration());
style.setTextDecoration(TextDecoration.LINE_THROUGH);
assertEquals(TextDecoration.LINE_THROUGH, style.getTextDecoration());
}
public void testVerticalAlign() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setVerticalAlign(VerticalAlign.BASELINE);
assertEquals(VerticalAlign.BASELINE, style.getVerticalAlign());
style.setVerticalAlign(VerticalAlign.SUB);
assertEquals(VerticalAlign.SUB, style.getVerticalAlign());
style.setVerticalAlign(VerticalAlign.SUPER);
assertEquals(VerticalAlign.SUPER, style.getVerticalAlign());
style.setVerticalAlign(VerticalAlign.TOP);
assertEquals(VerticalAlign.TOP, style.getVerticalAlign());
style.setVerticalAlign(VerticalAlign.TEXT_TOP);
assertEquals(VerticalAlign.TEXT_TOP, style.getVerticalAlign());
style.setVerticalAlign(VerticalAlign.MIDDLE);
assertEquals(VerticalAlign.MIDDLE, style.getVerticalAlign());
style.setVerticalAlign(VerticalAlign.BOTTOM);
assertEquals(VerticalAlign.BOTTOM, style.getVerticalAlign());
style.setVerticalAlign(VerticalAlign.TEXT_BOTTOM);
assertEquals(VerticalAlign.TEXT_BOTTOM, style.getVerticalAlign());
}
public void testVisibility() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setVisibility(Visibility.VISIBLE);
assertEquals(Visibility.VISIBLE, style.getVisibility());
style.setVisibility(Visibility.HIDDEN);
assertEquals(Visibility.HIDDEN, style.getVisibility());
}
public void testUnits() {
DivElement div = Document.get().createDivElement();
Style style = div.getStyle();
style.setWidth(1, PX);
assertEquals("1px", style.getWidth());
style.setWidth(1, PCT);
assertEquals("1%", style.getWidth());
style.setWidth(1, EM);
assertEquals("1em", style.getWidth());
style.setWidth(1, EX);
assertEquals("1ex", style.getWidth());
style.setWidth(1, PT);
assertEquals("1pt", style.getWidth());
style.setWidth(1, PC);
assertEquals("1pc", style.getWidth());
style.setWidth(1, CM);
assertEquals("1cm", style.getWidth());
style.setWidth(1, IN);
assertEquals("1in", style.getWidth());
style.setWidth(1, MM);
assertEquals("1mm", style.getWidth());
}
private void assertEquals(HasCssName enumValue, String cssValue) {
assertEquals(enumValue.getCssName(), cssValue);
}
}
| false | false | null | null |
diff --git a/compiler/org/sugarj/driver/Driver.java b/compiler/org/sugarj/driver/Driver.java
index a7bfd64a..4fd192ab 100644
--- a/compiler/org/sugarj/driver/Driver.java
+++ b/compiler/org/sugarj/driver/Driver.java
@@ -1,1424 +1,1424 @@
package org.sugarj.driver;
import static org.sugarj.driver.ATermCommands.extractSDF;
import static org.sugarj.driver.ATermCommands.extractSTR;
import static org.sugarj.driver.ATermCommands.fixSDF;
import static org.sugarj.driver.ATermCommands.getApplicationSubterm;
import static org.sugarj.driver.ATermCommands.getList;
import static org.sugarj.driver.ATermCommands.getString;
import static org.sugarj.driver.ATermCommands.isApplication;
import static org.sugarj.driver.Environment.bin;
import static org.sugarj.driver.Environment.sep;
import static org.sugarj.driver.Log.log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.collections.map.LRUMap;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.jsglr.client.InvalidParseTableException;
import org.spoofax.jsglr.client.ParseTable;
import org.spoofax.jsglr.client.imploder.ImploderAttachment;
import org.spoofax.jsglr.shared.BadTokenException;
import org.spoofax.jsglr.shared.SGLRException;
import org.spoofax.jsglr.shared.TokenExpectedException;
import org.spoofax.terms.Term;
import org.strategoxt.HybridInterpreter;
import org.strategoxt.imp.runtime.parser.JSGLRI;
import org.strategoxt.lang.Context;
import org.strategoxt.lang.StrategoException;
import org.strategoxt.permissivegrammars.make_permissive;
import org.strategoxt.tools.tools;
import org.sugarj.driver.caching.ModuleKeyCache;
import org.sugarj.driver.transformations.extraction.extraction;
import org.sugarj.stdlib.StdLib;
/**
* @author Sebastian Erdweg <seba at informatik uni-marburg de>
*/
public class Driver{
- public final static String CACHE_VERSION = "editor-base-0.7";
+ public final static String CACHE_VERSION = "editor-base-0.7a";
private static class Key {
private String source;
private String moduleName;
private Key(String source, String moduleName) {
this.source = source;
this.moduleName = moduleName;
}
public int hashCode() {
return source.hashCode() + moduleName.hashCode();
}
public boolean equals(Object o) {
return o instanceof Key
&& ((Key) o).source.equals(source)
&& ((Key) o).moduleName.equals(moduleName);
}
}
private final static int PENDING_TIMEOUT = 120000;
private static LRUMap resultCache = new LRUMap(50);
private static List<URI> allInputFiles;
private static List<URI> pendingInputFiles;
private static List<URI> currentlyProcessing;
private Result driverResult = new Result();
private String moduleName;
private String javaOutDir;
private String javaOutFile;
private String relPackageName;
private String mainModuleName;
private String currentGrammarSDF;
private String currentGrammarModule;
private String currentTransSTR;
private String currentTransModule;
private String remainingInput;
// private Collection<String> dependentFiles;
private List<String> availableSDFImports;
private List<String> availableSTRImports;
private IStrategoTerm sugaredPackageDecl;
private List<IStrategoTerm> sugaredImportDecls = new ArrayList<IStrategoTerm>();
private List<IStrategoTerm> sugaredTypeOrSugarDecls = new ArrayList<IStrategoTerm>();
private IStrategoTerm lastSugaredToplevelDecl;
private RetractableTreeBuilder inputTreeBuilder;
private JSGLRI sdfParser;
private JSGLRI strParser;
private JSGLRI editorServicesParser;
private HybridInterpreter interp;
private JSGLRI parser;
private Context sdfContext;
private Context makePermissiveContext;
private Context extractionContext;
private Context strjContext;
private String currentTransProg;
private boolean interrupt = false;
/**
* the next parsing and desugaring uses no cache lookup if skipCache.
*/
private boolean skipCache = false;
private List<String> generatedJavaClasses = new ArrayList<String>();
private static synchronized Result getResult(String source, String moduleName) {
return (Result) resultCache.get(new Key(source, moduleName));
}
private static Result getNonPendingResult(String source, String moduleName) {
Key key = new Key(source, moduleName);
Result r;
int count = 0;
synchronized (key) {
while (true) {
synchronized (resultCache) {
r = (Result) resultCache.get(key);
}
if (r != null && !(r instanceof PendingResult))
return r;
if (count > PENDING_TIMEOUT)
throw new IllegalStateException("pending result timed out for module " + moduleName);
count += 100;
try {
key.wait(100);
} catch (InterruptedException e) {
}
}
}
}
private static synchronized void putResult(String source, String moduleName, Result result) {
resultCache.put(new Key(source, moduleName), result);
System.out.println(resultCache.size());
}
public static Result compile(URI sourceFile) throws IOException, TokenExpectedException, BadTokenException, ParseException, InvalidParseTableException, SGLRException, InterruptedException {
synchronized (currentlyProcessing) {
// TODO we need better circular dependency handling
if (currentlyProcessing.contains(sourceFile))
throw new IllegalStateException("circular processing");
currentlyProcessing.add(sourceFile);
}
String source = FileCommands.readFileAsString(sourceFile.getPath());
String moduleName = FileCommands.fileName(sourceFile);
Result res = compile(source, moduleName, sourceFile.getPath());
synchronized (currentlyProcessing) {
currentlyProcessing.remove(sourceFile);
}
pendingInputFiles.remove(sourceFile);
return res;
}
public static Result compile(String source, String moduleName, String file) throws IOException, TokenExpectedException, BadTokenException, ParseException, InvalidParseTableException, SGLRException, InterruptedException {
Driver driver = new Driver();
boolean isPending = false;
synchronized (Driver.class) {
Result result = getResult(source, moduleName);
if (result != null && result instanceof PendingResult)
isPending = true;
else if (result != null && result.isUpToDate())
return result;
// mark this module as pending
if (!isPending)
putResult(source, moduleName, new PendingResult(driver));
}
if (isPending && getNonPendingResult(source, moduleName) != null)
return compile(source, moduleName, file);
try {
initialize();
driver.process(source, moduleName);
storeCaches();
} finally {
putResult(source, moduleName, driver == null || driver.driverResult.getSugaredSyntaxTree() == null ? null : driver.driverResult);
}
return driver.driverResult;
}
/**
* Process the given Extensible Java file.
*
* @param moduleFileName
* the file to process.
* @param outdir
* the directory to write the output into.
* @throws IOException
* @throws SGLRException
* @throws InvalidParseTableException
* @throws ParseException
* @throws BadTokenException
* @throws TokenExpectedException
* @throws InterruptedException
*/
private void process(String source, String moduleName) throws IOException, TokenExpectedException, BadTokenException, ParseException, InvalidParseTableException, SGLRException, InterruptedException {
log.beginTask("processing", "BEGIN PROCESSING " + moduleName);
boolean success = false;
try {
init(moduleName);
remainingInput = source;
initEditorServices();
boolean done = false;
while (!done) {
boolean wocache = Environment.wocache;
Environment.wocache |= skipCache;
if (interrupt) throw new InterruptedException();
// PARSE the next top-level declaration
IncrementalParseResult parseResult =
parseNextToplevelDeclaration(remainingInput, true);
lastSugaredToplevelDecl = parseResult.getToplevelDecl();
remainingInput = parseResult.getRest();
if (interrupt) throw new InterruptedException();
// DESUGAR the parsed top-level declaration
IStrategoTerm desugared = currentDesugar(lastSugaredToplevelDecl);
// reset cache skipping
Environment.wocache = wocache;
if (interrupt) throw new InterruptedException();
// PROCESS the assimilated top-level declaration
processToplevelDeclaration(desugared);
done = parseResult.parsingFinished();
}
if (interrupt) throw new InterruptedException();
if (Environment.generateJavaFile && !generatedJavaClasses.isEmpty()) {
String f = Environment.bin + sep + relPackageNameSep() + mainModuleName + ".java";
driverResult.generateFile(f, FileCommands.readFileAsString(javaOutFile));
log.log("Wrote generated Java file to " + f);
}
try {
// check final grammar and transformation for errors
if (!Environment.noChecking) {
checkCurrentGrammar();
}
if (interrupt) throw new InterruptedException();
// need to build current transformation program for editor services
checkCurrentTransformation();
} catch (Exception e) {
e.printStackTrace();
}
if (interrupt) throw new InterruptedException();
// COMPILE the generated java file
compileGeneratedJavaFile();
driverResult.setSugaredSyntaxTree(makeSugaredSyntaxTree());
if (currentTransProg != null)
driverResult.registerEditorDesugarings(currentTransProg);
success = true;
}
catch (CommandExecution.ExecutionError e) {
// TODO do something more sensible
e.printStackTrace();
success = false;
}
finally {
log.endTask(success, "done processing " + moduleName, "failed processing " + moduleName);
}
}
private void compileGeneratedJavaFile() throws IOException {
log.beginTask("compilation", "COMPILE the generated java file");
try {
List<String> path = new ArrayList<String>(Environment.includePath);
path.add(StdLib.stdLibDir.getPath());
path.add(javaOutDir);
driverResult.compileJava(javaOutFile, bin, path, generatedJavaClasses);
} finally {
log.endTask();
}
}
private IncrementalParseResult parseNextToplevelDeclaration(String input, boolean recovery)
throws IOException, ParseException, InvalidParseTableException, TokenExpectedException, BadTokenException, SGLRException {
log.beginTask("parsing", "PARSE the next toplevel declaration.");
try {
IStrategoTerm remainingInputTerm = currentParse(input, recovery);
if (remainingInputTerm == null)
throw new ParseException("could not parse toplevel declaration in:\n"
+ input, -1);
IStrategoTerm toplevelDecl = getApplicationSubterm(remainingInputTerm, "NextToplevelDeclaration", 0);
IStrategoTerm restTerm = getApplicationSubterm(remainingInputTerm, "NextToplevelDeclaration", 1);
String rest = getString(restTerm);
if (input.equals(rest))
throw new RuntimeException("empty toplevel declaration parse rule");
try {
if (!rest.isEmpty())
inputTreeBuilder.retract(restTerm);
} catch (Throwable t) {
t.printStackTrace();
}
if (toplevelDecl == null || rest == null)
throw new ParseException(
"could not parse next toplevel declaration in:\n"
+ remainingInputTerm.toString(),
-1);
String tmpFile = FileCommands.newTempFile("aterm");
FileCommands.writeToFile(tmpFile, toplevelDecl.toString());
log.log("next toplevel declaration parsed: " + tmpFile);
return new IncrementalParseResult(toplevelDecl, rest);
} finally {
log.endTask();
}
}
private void processEditorServicesDec(IStrategoTerm toplevelDecl) throws IOException {
log.beginTask(
"processing",
"PROCESS the desugared editor services declaration.");
try {
if (!sugaredTypeOrSugarDecls.contains(lastSugaredToplevelDecl))
sugaredTypeOrSugarDecls.add(lastSugaredToplevelDecl);
String extName = null;
String fullExtName = null;
boolean isPublic = false;
IStrategoTerm head = getApplicationSubterm(toplevelDecl, "EditorServicesDec", 0);
IStrategoTerm body= getApplicationSubterm(toplevelDecl, "EditorServicesDec", 1);
log.beginTask("Extracting name and accessibility of the editor services.");
try {
extName =
SDFCommands.prettyPrintJava(
getApplicationSubterm(head, "EditorServicesDecHead", 1), interp);
IStrategoTerm mods = getApplicationSubterm(head, "EditorServicesDecHead", 0);
for (IStrategoTerm t : getList(mods))
if (isApplication(t, "Public"))
{
isPublic = true;
break;
}
fullExtName = relPackageNameSep() + extName;
log.log("The name of the editor services is '" + extName + "'.");
log.log("The full name of the editor services is '" + fullExtName + "'.");
if (isPublic)
log.log("The editor services is public.");
else
log.log("The editor services is not public.");
IStrategoTerm services = ATermCommands.getApplicationSubterm(body, "EditorServicesBody", 0);
if (!ATermCommands.isList(services))
throw new IllegalStateException("editor services are not a list: " + services);
List<IStrategoTerm> editorServices = ATermCommands.getList(services);
// XXX if (currentTransProg != null)
editorServices = ATermCommands.registerSemanticProvider(editorServices, currentTransProg);
String editorServicesFile = bin + sep + relPackageNameSep() + extName + ".serv";
FileCommands.createFile(editorServicesFile);
log.log("writing editor services to " + editorServicesFile);
StringBuffer buf = new StringBuffer();
for (IStrategoTerm service : driverResult.getEditorServices())
buf.append(service).append('\n');
for (IStrategoTerm service : editorServices) {
driverResult.addEditorService(service);
buf.append(service).append('\n');
}
driverResult.generateFile(editorServicesFile, buf.toString());
} finally {
log.endTask();
}
} finally {
log.endTask();
}
}
private void processPlainDec(IStrategoTerm toplevelDecl) throws IOException {
log.beginTask(
"processing",
"PROCESS the desugared plain declaration.");
try {
if (!sugaredTypeOrSugarDecls.contains(lastSugaredToplevelDecl))
sugaredTypeOrSugarDecls.add(lastSugaredToplevelDecl);
String extName = null;
String fullExtName = null;
boolean isPublic = false;
IStrategoTerm head = getApplicationSubterm(toplevelDecl, "PlainDec", 0);
IStrategoTerm body= getApplicationSubterm(toplevelDecl, "PlainDec", 1);
log.beginTask("Extracting name and accessibility.");
try {
extName =
SDFCommands.prettyPrintJava(
getApplicationSubterm(head, "PlainDecHead", 1), interp);
String extension = null;
if (head.getSubtermCount() >= 3 && isApplication(getApplicationSubterm(head, "PlainDecHead", 2), "Some"))
extension = Term.asJavaString(
getApplicationSubterm(getApplicationSubterm(head, "PlainDecHead", 2), "Some", 0));
IStrategoTerm mods = getApplicationSubterm(head, "PlainDecHead", 0);
for (IStrategoTerm t : getList(mods))
if (isApplication(t, "Public"))
{
isPublic = true;
break;
}
fullExtName = relPackageNameSep() + extName + (extension == null ? "" : ("." + extension));
log.log("The name is '" + extName + "'.");
log.log("The full name is '" + fullExtName + "'.");
if (isPublic)
log.log("The plain file is public.");
else
log.log("The plain file is not public.");
String plainContent = Term.asJavaString(ATermCommands.getApplicationSubterm(body, "PlainBody", 0));
String plainFile = bin + sep + relPackageNameSep() + extName + (extension == null ? "" : ("." + extension));
FileCommands.createFile(plainFile);
log.log("writing plain content to " + plainFile);
driverResult.generateFile(plainFile, plainContent);
} finally {
log.endTask();
}
} finally {
log.endTask();
}
}
private void processToplevelDeclaration(IStrategoTerm toplevelDecl)
throws IOException, TokenExpectedException, BadTokenException, ParseException, InvalidParseTableException, SGLRException {
if (isApplication(toplevelDecl, "PackageDec"))
processPackageDec(toplevelDecl);
else {
if (javaOutFile == null)
javaOutFile = javaOutDir + sep + relPackageNameSep() + mainModuleName + ".java";
try {
if (isApplication(toplevelDecl, "TypeImportDec") || isApplication(toplevelDecl, "TypeImportOnDemandDec")) {
if (!Environment.atomicImportParsing)
processImportDec(toplevelDecl);
else
processImportDecs(toplevelDecl);
}
else if (isApplication(toplevelDecl, "JavaTypeDec") || //XXX remove this branch
isApplication(toplevelDecl, "ClassDec") ||
isApplication(toplevelDecl, "InterfaceDec") ||
isApplication(toplevelDecl, "EnumDec") ||
isApplication(toplevelDecl, "AnnoDec"))
processJavaTypeDec(toplevelDecl);
else if (isApplication(toplevelDecl, "SugarDec"))
processSugarDec(toplevelDecl);
else if (isApplication(toplevelDecl, "EditorServicesDec"))
processEditorServicesDec(toplevelDecl);
else if (isApplication(toplevelDecl, "PlainDec"))
processPlainDec(toplevelDecl);
else if (ATermCommands.isList(toplevelDecl))
/*
* Desugarings may generate lists of toplevel declarations. These declarations,
* however, may not depend on one another.
*/
for (IStrategoTerm term : ATermCommands.getList(toplevelDecl))
processToplevelDeclaration(term);
else
throw new IllegalArgumentException("unexpected toplevel declaration, desugaring probably failed: " + toplevelDecl.toString(5));
} catch (Exception e) {
String msg = e.getClass().getName() + " " + e.getLocalizedMessage() != null ? e.getLocalizedMessage() : e.toString();
if (!(e instanceof StrategoException))
e.printStackTrace();
else
log.logErr(msg);
ATermCommands.setErrorMessage(toplevelDecl, msg);
if (!sugaredTypeOrSugarDecls.contains(lastSugaredToplevelDecl))
sugaredTypeOrSugarDecls.add(lastSugaredToplevelDecl);
}
}
}
private IStrategoTerm currentParse(String remainingInput, boolean recovery) throws IOException,
InvalidParseTableException, TokenExpectedException, BadTokenException, SGLRException {
// recompile the current grammar definition
ParseTable currentGrammarTBL;
currentGrammarTBL = SDFCommands.compile(currentGrammarSDF, currentGrammarModule, driverResult.getFileDependencies(), sdfParser, sdfContext, makePermissiveContext);
IStrategoTerm parseResult = null;
parser.setUseRecovery(recovery);
// read next toplevel decl and stop if that fails
try {
parseResult = SDFCommands.parseImplode(
currentGrammarTBL,
remainingInput,
"NextToplevelDeclaration",
false,
inputTreeBuilder,
parser);
} finally {
if (recovery)
driverResult.addBadTokenExceptions(parser.getCollectedErrors());
}
return parseResult;
}
private IStrategoTerm currentDesugar(IStrategoTerm term) throws IOException,
InvalidParseTableException, TokenExpectedException, BadTokenException, SGLRException {
// assimilate toplevelDec using current transformation
log.beginTask(
"desugaring",
"DESUGAR the current toplevel declaration.");
try {
currentTransProg = STRCommands.compile(currentTransSTR, "main", driverResult.getFileDependencies(), strParser, strjContext);
return STRCommands.assimilate(currentTransProg, term, interp);
} finally {
log.endTask();
}
}
private void processPackageDec(IStrategoTerm toplevelDecl) throws IOException {
log.beginTask("processing", "PROCESS the desugared package declaration.");
try {
sugaredPackageDecl = lastSugaredToplevelDecl;
String packageName =
SDFCommands.prettyPrintJava(
getApplicationSubterm(toplevelDecl, "PackageDec", 1), interp);
log.log("The Java package name is '" + packageName + "'.");
relPackageName = FileCommands.getRelativeModulePath(packageName);
log.log("The SDF / Stratego package name is '" + relPackageName + "'.");
javaOutFile =
javaOutDir + sep + relPackageNameSep() + mainModuleName + ".java";
driverResult.generateFile(javaOutFile, SDFCommands.prettyPrintJava(toplevelDecl, interp) + "\n");
} finally {
log.endTask();
}
}
private void processImportDecs(IStrategoTerm toplevelDecl) throws IOException, TokenExpectedException, BadTokenException, ParseException, InvalidParseTableException, SGLRException {
List<IStrategoTerm> pendingImports = new ArrayList<IStrategoTerm>();
pendingImports.add(toplevelDecl);
while (true) {
IncrementalParseResult res = null;
IStrategoTerm term = null;
try {
log.beginSilent();
res = parseNextToplevelDeclaration(remainingInput, false);
term = res.getToplevelDecl();
}
catch (Throwable t) { }
finally {
log.endSilent();
}
if (res != null &&
term != null &&
(isApplication(term, "TypeImportDec") ||
isApplication(term, "TypeImportOnDemandDec"))) {
remainingInput = res.getRest();
pendingImports.add(term);
}
else {
if (term != null)
inputTreeBuilder.retract(term);
break;
}
}
for (IStrategoTerm pendingImport : pendingImports) {
lastSugaredToplevelDecl = pendingImport;
processImportDec(pendingImport);
}
}
private void processImportDec(IStrategoTerm toplevelDecl) {
sugaredImportDecls.add(lastSugaredToplevelDecl);
if (javaOutFile == null)
javaOutFile = javaOutDir + sep + mainModuleName + ".java";
log.beginTask("processing", "PROCESS the desugared import declaration.");
try {
String importModule = ModuleSystemCommands.extractImportedModuleName(toplevelDecl, interp);
// TODO handle import declarations with asterisks, e.g. import foo.*;
String modulePath = FileCommands.getRelativeModulePath(importModule);
boolean success = processImport(modulePath, toplevelDecl);
URI sourceFile = ModuleSystemCommands.locateSourceFile(modulePath);
if (sourceFile != null &&
!modulePath.startsWith("org/sugarj") &&
!modulePath.endsWith("*")) {
URI classUri = ModuleSystemCommands.searchFile(modulePath, ".class");
if (!success ||
pendingInputFiles.contains(sourceFile) ||
(classUri != null && new File(sourceFile).lastModified() > new File(classUri).lastModified())) {
log.log("Need to compile the imported module first ; processing it now.");
compile(sourceFile);
log.log("CONTINUE PROCESSING'" + moduleName + "'.");
// try again
success = processImport(modulePath, toplevelDecl);
}
}
if (!success)
ATermCommands.setErrorMessage(toplevelDecl, "module not found " + importModule);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
log.endTask();
}
}
private boolean processImport(String modulePath, IStrategoTerm importTerm) throws IOException {
boolean success = false;
success |= ModuleSystemCommands.importClass(
modulePath,
importTerm,
javaOutFile,
interp,
driverResult);
String grammarModule = ModuleSystemCommands.importSdf(
modulePath,
currentGrammarModule,
availableSDFImports,
driverResult);
if (grammarModule != null) {
success = true;
currentGrammarSDF = grammarModule;
currentGrammarModule = FileCommands.fileName(grammarModule);
}
String transModule = ModuleSystemCommands.importStratego(
modulePath,
currentTransModule,
availableSTRImports,
driverResult);
if (transModule != null) {
success = true;
currentTransSTR = transModule;
currentTransModule = FileCommands.fileName(transModule);
}
success |= ModuleSystemCommands.importEditorServices(modulePath, driverResult);
return success;
}
private void processJavaTypeDec(IStrategoTerm toplevelDecl) throws IOException {
log.beginTask(
"processing",
"PROCESS the desugared Java type declaration.");
try {
if (!sugaredTypeOrSugarDecls.contains(lastSugaredToplevelDecl))
sugaredTypeOrSugarDecls.add(lastSugaredToplevelDecl);
log.beginTask("Generate Java code.");
try {
IStrategoTerm dec = isApplication(toplevelDecl, "JavaTypeDec") ? getApplicationSubterm(toplevelDecl, "JavaTypeDec", 0) : toplevelDecl;
String decName = Term.asJavaString(dec.getSubterm(0).getSubterm(1).getSubterm(0));
generatedJavaClasses.add(
bin + sep
+ (relPackageName == null || relPackageName.isEmpty() ? "" : (relPackageName + sep))
+ decName + ".class");
driverResult.appendToFile(javaOutFile, SDFCommands.prettyPrintJava(dec, interp) + "\n");
} finally {
log.endTask();
}
} finally {
log.endTask();
}
}
private void processSugarDec(IStrategoTerm toplevelDecl) throws IOException,
InvalidParseTableException, TokenExpectedException, BadTokenException, SGLRException {
log.beginTask(
"processing",
"PROCESS the desugared sugar declaration.");
try {
if (!sugaredTypeOrSugarDecls.contains(lastSugaredToplevelDecl))
sugaredTypeOrSugarDecls.add(lastSugaredToplevelDecl);
boolean isNative;
String extName = null;
String fullExtName = null;
boolean isPublic = false;
IStrategoTerm head = getApplicationSubterm(toplevelDecl, "SugarDec", 0);
IStrategoTerm body= getApplicationSubterm(toplevelDecl, "SugarDec", 1);
log.beginTask("Extracting name and accessibility of the sugar.");
try {
isNative = isApplication(head, "NativeSugarDecHead");
if (isNative) {
extName =
SDFCommands.prettyPrintJava(
getApplicationSubterm(head, "NativeSugarDecHead", 2), interp);
IStrategoTerm mods = getApplicationSubterm(head, "NativeSugarDecHead", 0);
for (IStrategoTerm t : getList(mods))
if (isApplication(t, "Public"))
{
isPublic = true;
break;
}
}
else {
extName =
SDFCommands.prettyPrintJava(
getApplicationSubterm(head, "SugarDecHead", 1), interp);
IStrategoTerm mods = getApplicationSubterm(head, "SugarDecHead", 0);
for (IStrategoTerm t : getList(mods))
if (isApplication(t, "Public"))
{
isPublic = true;
break;
}
}
fullExtName = relPackageNameSep() + extName;
log.log("The name of the sugar is '" + extName + "'.");
log.log("The full name of the sugar is '" + fullExtName + "'.");
if (isPublic)
log.log("The sugar is public.");
else
log.log("The sugar is not public.");
if (isNative)
log.log("The sugar is native.");
else
log.log("The sugar is not native.");
} finally {
log.endTask();
}
String sdfExtension =
bin + sep + relPackageNameSep()
+ extName + ".sdf";
String strExtension =
bin + sep + relPackageNameSep()
+ extName + ".str";
FileCommands.delete(sdfExtension);
FileCommands.delete(strExtension);
String sdfImports = " imports " + StringCommands.printListSeparated(availableSDFImports, " ") + "\n";
String strImports = " imports " + StringCommands.printListSeparated(availableSTRImports, " ") + "\n";
if (isNative) {
String nativeModule = getString(getApplicationSubterm(body, "NativeSugarBody", 0));
if (nativeModule.length() > 1)
// remove quotes
nativeModule = nativeModule.substring(1, nativeModule.length() - 1);
if (FileCommands.exists(ModuleSystemCommands.searchFile(nativeModule, ".sdf"))) {
availableSDFImports.add(nativeModule);
driverResult.generateFile(
sdfExtension,
"module " + fullExtName + "\n"
+ sdfImports
+ "imports " + nativeModule);
}
if (FileCommands.exists(ModuleSystemCommands.searchFile(nativeModule, ".str"))) {
availableSTRImports.add(nativeModule);
driverResult.generateFile(
strExtension,
"module " + fullExtName + "\n"
+ strImports
+ "imports " + nativeModule);
}
}
else {
// this is a list of SDF and Stratego statements
IStrategoTerm sugarBody = getApplicationSubterm(body, "SugarBody", 0);
IStrategoTerm sdfExtract = fixSDF(extractSDF(sugarBody, extractionContext), interp);
IStrategoTerm strExtract = extractSTR(sugarBody, extractionContext);
String sdfExtensionHead =
"module " + fullExtName + "\n"
+ sdfImports
+ (isPublic ? "exports " : "hiddens ") + "\n"
+ " (/)" + "\n";
String sdfExtensionContent = SDFCommands.prettyPrintSDF(sdfExtract, interp);
String sdfSource = SDFCommands.makePermissiveSdf(sdfExtensionHead + sdfExtensionContent, makePermissiveContext);
driverResult.generateFile(sdfExtension, sdfSource);
availableSDFImports.add(fullExtName);
if (CommandExecution.FULL_COMMAND_LINE)
log.log("Wrote SDF file to '" + new File(sdfExtension).getAbsolutePath() + "'.");
String strExtensionTerm =
"Module(" + "\"" + fullExtName+ "\"" + ", "
+ strExtract + ")" + "\n";
String strExtensionContent = SDFCommands.prettyPrintSTR(ATermCommands.atermFromString(strExtensionTerm), interp);
int index = strExtensionContent.indexOf('\n');
if (index >= 0)
strExtensionContent =
strExtensionContent.substring(0, index + 1) + "\n"
+ strImports + "\n"
+ strExtensionContent.substring(index + 1);
else
strExtensionContent += strImports;
driverResult.generateFile(strExtension, strExtensionContent);
availableSTRImports.add(fullExtName);
if (CommandExecution.FULL_COMMAND_LINE)
log.log("Wrote Stratego file to '" + new File(strExtension).getAbsolutePath() + "'.");
}
if (FileCommands.exists(sdfExtension)) {
String currentGrammarName =
FileCommands.hashFileName("sugarj", currentGrammarModule + fullExtName);
currentGrammarSDF =
Environment.tmpDir + sep + currentGrammarName + ".sdf";
driverResult.generateFile(currentGrammarSDF,
"module " + currentGrammarName + "\n"
+ "imports " + currentGrammarModule + "\n"
+ " " + fullExtName);
currentGrammarModule = currentGrammarName;
driverResult.addFileDependency(sdfExtension);
}
if (FileCommands.exists(strExtension)) {
String currentTransName =
FileCommands.hashFileName("sugarj", currentTransModule + fullExtName);
currentTransSTR = Environment.tmpDir + sep + currentTransName + ".str";
driverResult.generateFile(currentTransSTR,
"module " + currentTransName + "\n"
+ "imports " + currentTransModule + "\n"
+ " " + fullExtName);
currentTransModule = currentTransName;
driverResult.addFileDependency(strExtension);
}
} finally {
log.endTask();
}
}
private void checkCurrentGrammar() throws IOException, InvalidParseTableException, TokenExpectedException, BadTokenException, SGLRException {
log.beginTask("checking grammar", "CHECK current grammar");
try {
SDFCommands.compile(currentGrammarSDF, currentGrammarModule, driverResult.getFileDependencies(), sdfParser, sdfContext, makePermissiveContext);
} finally {
log.endTask();
}
}
private void checkCurrentTransformation() throws IOException, InvalidParseTableException, TokenExpectedException, BadTokenException, SGLRException{
log.beginTask("checking transformation", "CHECK current transformation");
try {
currentTransProg = STRCommands.compile(currentTransSTR, "main", driverResult.getFileDependencies(), strParser, strjContext);
} finally {
log.endTask();
}
}
private void initEditorServices() throws IOException, TokenExpectedException, BadTokenException, SGLRException {
driverResult.addEditorService(
ATermCommands.atermFromString(
"Builders(\"sugarj checking\", [SemanticObserver(Strategy(\"sugarj-analyze\"))])"));
IStrategoTerm initEditor = editorServicesParser.parse(new FileInputStream(StdLib.initEditor.getPath()), StdLib.initEditor.getPath());
IStrategoTerm services = ATermCommands.getApplicationSubterm(initEditor, "Module", 2);
if (!ATermCommands.isList(services))
throw new IllegalStateException("initial editor ill-formed");
for (IStrategoTerm service : ATermCommands.getList(services))
driverResult.addEditorService(service);
}
private static void initialize() throws IOException {
Environment.init();
if (Environment.cacheDir != null)
FileCommands.createDir(Environment.cacheDir);
FileCommands.createDir(Environment.bin);
initializeCaches();
allInputFiles = new ArrayList<URI>();
pendingInputFiles = new ArrayList<URI>();
currentlyProcessing = new ArrayList<URI>();
}
private void init(String moduleName) throws FileNotFoundException, IOException, InvalidParseTableException {
this.moduleName = moduleName;
javaOutDir = FileCommands.newTempDir();
javaOutFile = null;
// FileCommands.createFile(tmpOutdir, relModulePath + ".java");
mainModuleName = moduleName;
currentGrammarSDF = StdLib.initGrammar.getPath();
currentGrammarModule = StdLib.initGrammarModule;
currentTransSTR = StdLib.initTrans.getPath();
currentTransModule = StdLib.initTransModule;
// list of imports that contain SDF extensions
availableSDFImports = new ArrayList<String>();
// list of imports that contain Stratego extensions
availableSTRImports = new ArrayList<String>();
inputTreeBuilder = new RetractableTreeBuilder();
// XXX need to load ANY parse table, preferably an empty one.
parser = new JSGLRI(org.strategoxt.imp.runtime.Environment.loadParseTable(StdLib.sdfTbl.getPath()), "Sdf2Module");
sdfParser = new JSGLRI(org.strategoxt.imp.runtime.Environment.loadParseTable(StdLib.sdfTbl.getPath()), "Sdf2Module");
strParser = new JSGLRI(org.strategoxt.imp.runtime.Environment.loadParseTable(StdLib.strategoTbl.getPath()), "StrategoModule");
editorServicesParser = new JSGLRI(org.strategoxt.imp.runtime.Environment.loadParseTable(StdLib.editorServicesTbl.getPath()), "Module");
interp = new HybridInterpreter(); //TODO (ATermCommands.factory);
sdfContext = tools.init();
makePermissiveContext = make_permissive.init();
extractionContext = extraction.init();
strjContext = org.strategoxt.strj.strj.init();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
// log.log("This is the extensible java compiler.");
try {
initialize();
String[] sources = handleOptions(args);
ClassLoader loader = new URLClassLoader(new URL[] {new File(Environment.src).toURI().toURL()});
for (String source : sources)
{
URL url = loader.getResource(source);
if (url == null)
throw new FileNotFoundException(source);
URI uri = url.toURI();
allInputFiles.add(uri);
pendingInputFiles.add(uri);
}
for (URI source : allInputFiles) {
Result res = compile(source);
if (!DriverCLI.processResultCLI(res, source.getPath(), new File(".").getAbsolutePath()))
throw new RuntimeException("compilation of " + source.getPath() + " failed");
}
} catch (Exception e) {
e.printStackTrace();
} catch (CLIError e) {
System.out.println(e.getMessage());
System.out.println();
e.showUsage();
}
// kills all remaining subprocesses, if any
// log.log("The extensible java compiler has done its job and says 'good bye'.");
System.exit(0);
}
/**
* This is thrown when a problem during option processing
* occurs.
*
* @author [email protected]
*/
public static class CLIError extends Error {
private static final long serialVersionUID = -918505242287737113L;
private final Options options;
public CLIError(String message, Options options) {
super(message);
this.options = options;
}
public void showUsage() {
showUsageMessage(options);
}
}
/**
* Parses and processes command line options. This method may
* set paths and flags in {@link CommandExecution} and
* {@link Environment} in the process.
*
* @param args
* the command line arguments to be parsed
* @return the source file to be processed
* @throws CLIError
* when the command line is not correct
*/
private static String[] handleOptions(String[] args) {
Options options = specifyOptions();
try {
CommandLine line = parseOptions(options, args);
return processOptions(options, line);
} catch (org.apache.commons.cli.ParseException e) {
throw new CLIError(e.getMessage(), options);
}
}
private static void showUsageMessage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(
"java -java sugarj.jar [options] source-files",
options,
false);
}
private static String[] processOptions(Options options, CommandLine line) throws org.apache.commons.cli.ParseException {
if (line.hasOption("help")) {
// TODO This is not exactly an error ...
throw new CLIError("help requested", options);
}
if (line.hasOption("verbose")) {
CommandExecution.SILENT_EXECUTION = false;
CommandExecution.SUB_SILENT_EXECUTION = false;
CommandExecution.FULL_COMMAND_LINE = true;
}
if (line.hasOption("silent-execution"))
CommandExecution.SILENT_EXECUTION = true;
if (line.hasOption("sub-silent-execution"))
CommandExecution.SUB_SILENT_EXECUTION = true;
if (line.hasOption("full-command-line"))
CommandExecution.FULL_COMMAND_LINE = true;
if (line.hasOption("cache-info"))
CommandExecution.CACHE_INFO = true;
if (line.hasOption("buildpath"))
for (String path : line.getOptionValue("buildpath").split(Environment.classpathsep))
Environment.includePath.add(path);
if (line.hasOption("sourcepath"))
for (String path : line.getOptionValue("sourcepath").split(Environment.classpathsep))
Environment.src = path;
if (line.hasOption("d"))
Environment.bin = line.getOptionValue("d");
if (line.hasOption("cache"))
Environment.cacheDir = line.getOptionValue("cache");
if (line.hasOption("read-only-cache"))
Environment.rocache = true;
if (line.hasOption("write-only-cache"))
Environment.wocache = true;
if (line.hasOption("gen-java"))
Environment.generateJavaFile = true;
if (line.hasOption("atomic-imports"))
Environment.atomicImportParsing = true;
if (line.hasOption("no-checking"))
Environment.noChecking = true;
String[] sources = line.getArgs();
if (sources.length < 1)
throw new CLIError("No source files specified.", options);
return sources;
}
private static CommandLine parseOptions(Options options, String[] args) throws org.apache.commons.cli.ParseException {
CommandLineParser parser = new GnuParser();
return parser.parse(options, args);
}
private static Options specifyOptions() {
Options options = new Options();
options.addOption(
"v",
"verbose",
false,
"show verbose output");
options.addOption(
null,
"silent-execution",
false,
"try to be silent");
options.addOption(
null,
"sub-silent-execution",
false,
"do not display output of subprocesses");
options.addOption(
null,
"full-command-line",
false,
"show all arguments to subprocesses");
options.addOption(
null,
"cache-info",
false,
"show where files are cached");
options.addOption(
null,
"buildpath",
true,
"Specify where to find compiled files. Multiple paths can be given separated by \'" + Environment.classpathsep + "\'.");
options.addOption(
null,
"sourcepath",
true,
"Specify where to find source files. Multiple paths can be given separated by \'" + Environment.classpathsep + "\'.");
options.addOption(
"d",
null,
true,
"Specify where to place compiled files");
options.addOption(
null,
"help",
false,
"Print this synopsis of options");
options.addOption(
null,
"cache",
true,
"Specifiy a directory for caching.");
options.addOption(
null,
"read-only-cache",
false,
"Specify the cache to be read-only.");
options.addOption(
null,
"write-only-cache",
false,
"Specify the cache to be write-only.");
options.addOption(
null,
"imports-changed",
false,
"Declare that the imported modules have changed since last compilation.");
options.addOption(
null,
"gen-java",
false,
"Generate the resulting Java file in the source folder.");
options.addOption(
null,
"atomic-imports",
false,
"Parse all import statements simultaneously.");
options.addOption(
null,
"no-checking",
false,
"Do not check resulting SDF and Stratego files.");
return options;
}
@SuppressWarnings("unchecked")
private static synchronized void initializeCaches() throws IOException {
if (Environment.cacheDir == null)
return;
String sdfCache = FileCommands.findFile("sdfCache" + "-" + CACHE_VERSION, Environment.cacheDir);
String strCache = FileCommands.findFile("strCache" + "-" + CACHE_VERSION, Environment.cacheDir);
if (SDFCommands.sdfCache == null && sdfCache != null)
try {
log.log("load sdf cache from " + sdfCache);
SDFCommands.sdfCache =
(ModuleKeyCache<String>) new ObjectInputStream(new FileInputStream(
sdfCache)).readObject();
}
catch (Exception e) {
SDFCommands.sdfCache = new ModuleKeyCache<String>();
e.printStackTrace();
}
else if (SDFCommands.sdfCache == null)
SDFCommands.sdfCache = new ModuleKeyCache<String>();
if (STRCommands.strCache == null && strCache != null)
try {
log.log("load str cache from " + strCache);
STRCommands.strCache =
(ModuleKeyCache<String>) new ObjectInputStream(new FileInputStream(
strCache)).readObject();
}
catch (Exception e) {
STRCommands.strCache = new ModuleKeyCache<String>();
e.printStackTrace();
}
else if (STRCommands.strCache == null)
STRCommands.strCache = new ModuleKeyCache<String>();
}
private static synchronized void storeCaches() throws IOException {
if (Environment.cacheDir == null || Environment.rocache)
return;
String sdfCache = FileCommands.findFile("sdfCache" + "-" + CACHE_VERSION , Environment.cacheDir);
String strCache = FileCommands.findFile("strCache" + "-" + CACHE_VERSION, Environment.cacheDir);
if (sdfCache == null) {
sdfCache = Environment.cacheDir + sep + "sdfCache" + "-" + CACHE_VERSION;
FileCommands.createFile(sdfCache);
}
if (strCache == null) {
strCache = Environment.cacheDir + sep + "strCache" + "-" + CACHE_VERSION;
FileCommands.createFile(strCache);
}
if (SDFCommands.sdfCache != null) {
log.log("store sdf cache in " + sdfCache);
log.log("sdf cache size: " + SDFCommands.sdfCache.size());
new ObjectOutputStream(new FileOutputStream(sdfCache)).writeObject(SDFCommands.sdfCache);
}
if (STRCommands.strCache != null) {
log.log("store str cache in " + strCache);
log.log("str cache size: " + STRCommands.strCache.size());
new ObjectOutputStream(new FileOutputStream(strCache)).writeObject(STRCommands.strCache);
}
}
private String relPackageNameSep() {
if (relPackageName == null || relPackageName.isEmpty())
return "";
return relPackageName + sep;
}
/**
* @return the non-desugared syntax tree of the complete file.
*/
private IStrategoTerm makeSugaredSyntaxTree() {
// XXX empty lists => no tokens
IStrategoTerm packageDecl = ATermCommands.makeSome(sugaredPackageDecl, inputTreeBuilder.getTokenizer().getTokenAt(0));
IStrategoTerm imports =
ATermCommands.makeList("JavaImportDec*", ImploderAttachment.getRightToken(packageDecl), sugaredImportDecls);
IStrategoTerm body =
ATermCommands.makeList("TypeOrSugarDec*", ImploderAttachment.getRightToken(imports), sugaredTypeOrSugarDecls);
IStrategoTerm term =
ATermCommands.makeAppl("SugarCompilationUnit", "SugarCompilationUnit", 3,
packageDecl,
imports,
body);
ImploderAttachment.getTokenizer(term).setAst(term);
ImploderAttachment.getTokenizer(term).initAstNodeBinding();
return term;
}
public synchronized void interrupt() {
this.interrupt = true;
}
}
| true | false | null | null |
diff --git a/edu/cmu/sphinx/decoder/LivePretendDecoder.java b/edu/cmu/sphinx/decoder/LivePretendDecoder.java
index d5e3ce6e..15e5516c 100644
--- a/edu/cmu/sphinx/decoder/LivePretendDecoder.java
+++ b/edu/cmu/sphinx/decoder/LivePretendDecoder.java
@@ -1,252 +1,270 @@
/*
* Copyright 1999-2002 Carnegie Mellon University.
* Portions Copyright 2002 Sun Microsystems, Inc.
* Portions Copyright 2002 Mitsubishi Electronic Research Laboratories.
* All Rights Reserved. Use is subject to license terms.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.cmu.sphinx.decoder;
import edu.cmu.sphinx.frontend.util.ConcatFileAudioSource;
import edu.cmu.sphinx.frontend.DataSource;
import edu.cmu.sphinx.frontend.FrontEnd;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.BatchFile;
+import edu.cmu.sphinx.util.GapInsertionDetector;
import edu.cmu.sphinx.util.SphinxProperties;
import edu.cmu.sphinx.util.Timer;
import edu.cmu.sphinx.util.NISTAlign;
import edu.cmu.sphinx.util.Utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.FileWriter;
import java.net.URL;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.StringTokenizer;
/**
* Decodes a batch file containing a list of files to decode.
* The files can be either audio files or cepstral files, but defaults
* to audio files. To decode cepstral files, set the Sphinx property
* <code> edu.cmu.sphinx.decoder.LiveDecoder.inputDataType = cepstrum </code>
*/
public class LivePretendDecoder {
/**
* Prefix for the properties of this class.
*/
public final static String PROP_PREFIX =
"edu.cmu.sphinx.decoder.LivePretendDecoder.";
/**
* SphinxProperty specifying the transcript file. If a transcript file
* is specified, it will be created. Otherwise, it is not created.
*/
public final static String PROP_HYPOTHESIS_TRANSCRIPT =
PROP_PREFIX + "hypothesisTranscript";
/**
* The default value of PROP_TRANSCRIPT.
*/
public final static String PROP_HYPOTHESIS_TRANSCRIPT_DEFAULT = null;
private int sampleRate;
private String context;
private String batchFile;
+ private String hypothesisFile;
private Decoder decoder;
private FileWriter hypothesisTranscript;
private SphinxProperties props;
private ConcatFileAudioSource dataSource;
+ private GapInsertionDetector gapInsertionDetector;
/**
* Constructs a LivePretendDecoder.
*
* @param context the context of this LivePretendDecoder
* @param batchFile the file that contains a list of files to decode
*/
public LivePretendDecoder(String context, String batchFile)
throws IOException {
SphinxProperties props = SphinxProperties.getSphinxProperties(context);
this.context = context;
init(props, batchFile);
}
/**
* Common intialization code
*
* @param props the sphinx properties
*
* @param batchFile the batch file
*/
private void init(SphinxProperties props, String batchFile)
throws IOException {
this.batchFile = batchFile;
dataSource = new ConcatFileAudioSource
("ConcatFileAudioSource", context, props, batchFile);
decoder = new Decoder(context, dataSource);
- String transcriptFile
+ hypothesisFile
= props.getString(PROP_HYPOTHESIS_TRANSCRIPT,
PROP_HYPOTHESIS_TRANSCRIPT_DEFAULT);
- if (transcriptFile != null) {
+ if (hypothesisFile != null) {
sampleRate = props.getInt(FrontEnd.PROP_SAMPLE_RATE,
FrontEnd.PROP_SAMPLE_RATE_DEFAULT);
- hypothesisTranscript = new FileWriter(transcriptFile);
+ hypothesisTranscript = new FileWriter(hypothesisFile);
}
}
/**
* Decodes the batch of audio files
*/
public void decode() throws IOException {
int numUtterances = 0;
List resultList = new LinkedList();
Result result = null;
while ((result = decoder.decode()) != null) {
numUtterances++;
decoder.calculateTimes(result);
String resultText = result.getBestResultNoFiller();
System.out.println("\nHYP: " + resultText);
System.out.println(" Sentences: " + numUtterances);
decoder.showAudioUsage();
decoder.showMemoryUsage();
resultList.add(resultText);
if (hypothesisTranscript != null) {
hypothesisTranscript.write
- (result.getTimedBestResult(false, true) + "\n");
+ (result.getTimedBestResult(false, true, sampleRate) +"\n");
hypothesisTranscript.flush();
}
}
alignResults(resultList, dataSource.getReferences());
+
+ Timer gapTimer = Timer.getTimer(context, "GapInsertionDetector");
+ gapTimer.start();
+ GapInsertionDetector gid = new GapInsertionDetector
+ (dataSource.getTranscriptFile(), hypothesisFile);
+ System.out.println("# of gap insertion errors: " + gid.detect());
+ gapTimer.stop();
+
Timer.dumpAll(context);
decoder.showSummary();
}
/**
* Align the list of results with reference text.
*/
private void alignResults(List hypothesisList, List referenceList) {
System.out.println("Aligning results...");
System.out.println(" Actual utterances: " + referenceList.size());
String hypothesis = listToString(hypothesisList);
String reference = listToString(referenceList);
saveAlignedText(hypothesis, reference);
getAlignTimer().start();
NISTAlign aligner = decoder.getNISTAlign();
aligner.align(reference, hypothesis);
getAlignTimer().stop();
System.out.println("...done aligning");
aligner.printTotalSummary();
}
+ /**
+ * Saves the aligned hypothesis and reference text to the aligned
+ * text file.
+ *
+ * @param hypothesis the aligned hypothesis text
+ * @param reference the aligned reference text
+ */
private void saveAlignedText(String hypothesis, String reference) {
try {
FileWriter writer = new FileWriter("align.txt");
writer.write(hypothesis);
writer.write("\n");
writer.write(reference);
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Converts the given list of strings into one string, putting a space
* character in between the strings.
*
* @param resultList the list of strings
*
* @return a string which is a concatenation of the strings in the list,
* separated by a space character
*/
private String listToString(List resultList) {
StringBuffer sb = new StringBuffer();
for (Iterator i = resultList.iterator(); i.hasNext(); ) {
String result = (String) i.next();
sb.append(result + " ");
}
return sb.toString();
}
/**
* Return the timer for alignment.
*/
private Timer getAlignTimer() {
return Timer.getTimer(context, "Align");
}
/**
* Returns the time in seconds given the sample number and sample rate.
*
* @param sampleNumber the sample number
* @param sampleRate the sample rate
*
* @return the time in seconds
*/
private static float getSeconds(long sampleNumber, int sampleRate) {
return ((float) (sampleNumber / sampleRate));
}
/**
* Do clean up
*/
public void close() throws IOException {
if (hypothesisTranscript != null) {
hypothesisTranscript.close();
}
}
/**
* Main method of this LivePretendDecoder.
*
* @param argv argv[0] : SphinxProperties file
* argv[1] : a file listing all the audio files to decode
*/
public static void main(String[] argv) {
if (argv.length < 2) {
System.out.println
("Usage: LivePretendDecoder propertiesFile batchFile");
System.exit(1);
}
String context = "batch";
String propertiesFile = argv[0];
String batchFile = argv[1];
try {
URL url = new File(propertiesFile).toURI().toURL();
SphinxProperties.initContext (context, url);
LivePretendDecoder decoder =
new LivePretendDecoder(context, batchFile);
decoder.decode();
decoder.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
| false | false | null | null |
diff --git a/src/lang/psi/impl/LuaPsiFileImpl.java b/src/lang/psi/impl/LuaPsiFileImpl.java
index cfb2873c..f4259412 100644
--- a/src/lang/psi/impl/LuaPsiFileImpl.java
+++ b/src/lang/psi/impl/LuaPsiFileImpl.java
@@ -1,330 +1,330 @@
/*
* Copyright 2010 Jon S Akhtar (Sylvanaar)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sylvanaar.idea.Lua.lang.psi.impl;
import com.intellij.openapi.diagnostic.*;
import com.intellij.openapi.fileTypes.*;
import com.intellij.psi.*;
import com.intellij.psi.impl.*;
import com.intellij.psi.impl.source.*;
import com.intellij.psi.scope.*;
import com.intellij.psi.util.*;
import com.intellij.util.*;
import com.sylvanaar.idea.Lua.*;
import com.sylvanaar.idea.Lua.lang.*;
import com.sylvanaar.idea.Lua.lang.psi.*;
import com.sylvanaar.idea.Lua.lang.psi.controlFlow.*;
import com.sylvanaar.idea.Lua.lang.psi.controlFlow.impl.*;
import com.sylvanaar.idea.Lua.lang.psi.expressions.*;
import com.sylvanaar.idea.Lua.lang.psi.statements.*;
import com.sylvanaar.idea.Lua.lang.psi.symbols.*;
import com.sylvanaar.idea.Lua.lang.psi.visitor.*;
import com.sylvanaar.idea.Lua.util.*;
import org.jetbrains.annotations.*;
import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: Apr 10, 2010
* Time: 12:19:03 PM
*/
public class LuaPsiFileImpl extends LuaPsiFileBaseImpl implements LuaPsiFile, PsiFileWithStubSupport, PsiFileEx, LuaPsiFileBase, LuaExpressionCodeFragment {
private boolean sdkFile;
private static final Logger log = Logger.getInstance("Lua.LuaPsiFileImp");
private PsiElement myContext = null;
public LuaPsiFileImpl(FileViewProvider viewProvider) {
super(viewProvider, LuaFileType.LUA_LANGUAGE);
}
@NotNull
@Override
public FileType getFileType() {
return LuaFileType.LUA_FILE_TYPE;
}
@Override
public String toString() {
return "Lua script: " + getName();
}
@Override
public LuaStatementElement addStatementBefore(@NotNull LuaStatementElement statement, LuaStatementElement anchor) throws IncorrectOperationException {
return (LuaStatementElement) addBefore(statement, anchor);
}
Modules moduleStatements = new Modules();
public LuaModuleExpression getModuleAtOffset(final int offset) {
final List<LuaModuleExpression> modules = moduleStatements.getValue();
if (modules.size() == 0) return null;
LuaModuleExpression module = null;
for (LuaModuleExpression m : modules) {
if (m.getIncludedTextRange().contains(offset)) module = module == null ? m :
m.getIncludedTextRange().getStartOffset() >
module.getIncludedTextRange().getStartOffset() ? m : module;
}
return module;
}
@Override
public void setContext(PsiElement e) {
myContext = e;
}
@Override
public PsiElement getContext() {
if (myContext != null)
return myContext;
return super.getContext();
}
@Override
@Nullable
public String getModuleNameAtOffset(final int offset) {
LuaModuleExpression module = getModuleAtOffset(offset);
return module == null ? null : module.getGlobalEnvironmentName();
}
@Override
public void clearCaches() {
super.clearCaches();
moduleStatements.drop();
functionDefs.drop();
putUserData(CONTROL_FLOW, null);
}
@Override
public LuaExpression getReturnedValue() {
// This only works for the last statement in the file
LuaStatementElement[] stmts = getStatements();
if (stmts.length==0) return null;
LuaStatementElement s = stmts[stmts.length-1];
if (! (s instanceof LuaReturnStatement)) return null;
return ((LuaReturnStatement) s).getReturnValue();
}
@Override
public boolean processDeclarations(PsiScopeProcessor processor,
ResolveState state, PsiElement lastParent,
PsiElement place) {
PsiElement run = lastParent == null ? getLastChild() : lastParent.getPrevSibling();
if (run != null && run.getParent() != this) run = null;
while (run != null) {
if (!run.processDeclarations(processor, state, null, place)) return false;
run = run.getPrevSibling();
}
return true;
}
public void accept(LuaElementVisitor visitor) {
visitor.visitLuaFile(this);
}
public void acceptChildren(LuaElementVisitor visitor) {
PsiElement child = getFirstChild();
while (child != null) {
if (child instanceof LuaPsiElement) {
((LuaPsiElement) child).accept(visitor);
}
child = child.getNextSibling();
}
}
@Override
public String getPresentationText() {
return getName();
}
@Override
public Assignable[] getSymbolDefs() {
final Set<Assignable> decls =
new HashSet<Assignable>();
LuaElementVisitor v = new LuaRecursiveElementVisitor() {
public void visitDeclarationExpression(LuaDeclarationExpression e) {
super.visitDeclarationExpression(e);
if (!(e instanceof LuaLocalIdentifier))
decls.add(e);
}
@Override
public void visitCompoundIdentifier(LuaCompoundIdentifier e) {
super.visitCompoundIdentifier(e);
if (e.isAssignedTo())
decls.add(e);
}
};
v.visitLuaElement(this);
return decls.toArray(new Assignable[decls.size()]);
}
@Override
public LuaStatementElement[] getAllStatements() {
final List<LuaStatementElement> stats =
new ArrayList<LuaStatementElement>();
LuaElementVisitor v = new LuaRecursiveElementVisitor() {
public void visitLuaElement(LuaPsiElement e) {
super.visitLuaElement(e);
if (e instanceof LuaStatementElement)
stats.add((LuaStatementElement) e);
}
};
v.visitLuaElement(this);
return stats.toArray(new LuaStatementElement[stats.size()]);
}
@Override
public LuaStatementElement[] getStatements() {
return findChildrenByClass(LuaStatementElement.class);
}
LuaFunctionDefinitionNotNullLazyValue functionDefs = new LuaFunctionDefinitionNotNullLazyValue();
@Override
public LuaFunctionDefinition[] getFunctionDefs() {
return functionDefs.getValue();
}
@Override
public synchronized Instruction[] getControlFlow() {
assert isValid();
if (getStub() != null)
return EMPTY_CONTROL_FLOW;
return CachedValuesManager.getManager(getProject()).getCachedValue(this, CONTROL_FLOW,
new CachedValueProvider<Instruction[]>() {
@Override
public Result<Instruction[]> compute() {
Instruction[] value =
new ControlFlowBuilder(getProject()).buildControlFlow(LuaPsiFileImpl.this);
if (value == null || value.length > MAX_CONTROL_FLOW_LEN)
value = EMPTY_CONTROL_FLOW;
- return Result.create(value, value == EMPTY_CONTROL_FLOW ? null : PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
+ return Result.create(value, PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
}
},
false);
}
@Override
public void removeVariable(LuaIdentifier variable) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public LuaDeclarationStatement addVariableDeclarationBefore(LuaDeclarationStatement declaration, LuaStatementElement anchor) throws IncorrectOperationException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void inferTypes() {
log.debug("start infer "+getName());
final LuaPsiManager m = LuaPsiManager.getInstance(getProject());
LuaElementVisitor v = new LuaRecursiveElementVisitor() {
@Override
public void visitLuaElement(LuaPsiElement element) {
super.visitLuaElement(element);
if (element instanceof InferenceCapable && element != LuaPsiFileImpl.this)
m.queueInferences((InferenceCapable) element);
}
};
acceptChildren(v);
log.debug("end infer " + getName());
}
private class LuaFunctionDefinitionNotNullLazyValue extends LuaAtomicNotNullLazyValue<LuaFunctionDefinition[]> {
@NotNull
@Override
protected LuaFunctionDefinition[] compute() {
final List<LuaFunctionDefinition> funcs =
new ArrayList<LuaFunctionDefinition>();
LuaElementVisitor v = new LuaRecursiveElementVisitor() {
public void visitFunctionDef(LuaFunctionDefinitionStatement e) {
super.visitFunctionDef(e);
funcs.add(e);
}
@Override
public void visitAnonymousFunction(LuaAnonymousFunctionExpression e) {
super.visitAnonymousFunction(e);
if (e.getName() != null)
funcs.add(e);
}
};
v.visitLuaElement(LuaPsiFileImpl.this);
return funcs.toArray(new LuaFunctionDefinition[funcs.size()]);
}
}
// Only looks at the current block
private class LuaModuleVisitor extends LuaElementVisitor {
private final Collection<LuaModuleExpression> list;
public LuaModuleVisitor(Collection<LuaModuleExpression> list) {this.list = list;}
@Override
public void visitFunctionCallStatement(LuaFunctionCallStatement e) {
super.visitFunctionCallStatement(e);
e.acceptChildren(this);
}
@Override
public void visitModuleExpression(LuaModuleExpression e) {
super.visitModuleExpression(e);
list.add(e);
}
}
private class Modules extends LuaAtomicNotNullLazyValue<List<LuaModuleExpression>> {
@NotNull
@Override
protected List<LuaModuleExpression> compute() {
List<LuaModuleExpression> val = new ArrayList<LuaModuleExpression>();
acceptChildren(new LuaModuleVisitor(val));
return val;
}
}
}
| true | false | null | null |
diff --git a/parser/org/eclipse/cdt/internal/core/parser/scanner/Scanner.java b/parser/org/eclipse/cdt/internal/core/parser/scanner/Scanner.java
index 0bb0674a7..f12e764d2 100644
--- a/parser/org/eclipse/cdt/internal/core/parser/scanner/Scanner.java
+++ b/parser/org/eclipse/cdt/internal/core/parser/scanner/Scanner.java
@@ -1,3217 +1,3224 @@
/*******************************************************************************
* Copyright (c) 2001 Rational Software Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Rational Software - initial implementation
******************************************************************************/
package org.eclipse.cdt.internal.core.parser.scanner;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import org.eclipse.cdt.core.parser.BacktrackException;
import org.eclipse.cdt.core.parser.CodeReader;
import org.eclipse.cdt.core.parser.Directives;
import org.eclipse.cdt.core.parser.EndOfFileException;
import org.eclipse.cdt.core.parser.IMacroDescriptor;
import org.eclipse.cdt.core.parser.IParserLogService;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.core.parser.Keywords;
import org.eclipse.cdt.core.parser.NullLogService;
import org.eclipse.cdt.core.parser.NullSourceElementRequestor;
import org.eclipse.cdt.core.parser.OffsetLimitReachedException;
import org.eclipse.cdt.core.parser.ParserFactory;
import org.eclipse.cdt.core.parser.ParserFactoryError;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ScannerException;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.cdt.core.parser.IMacroDescriptor.MacroType;
import org.eclipse.cdt.core.parser.ast.ASTExpressionEvaluationException;
import org.eclipse.cdt.core.parser.ast.IASTCompletionNode;
import org.eclipse.cdt.core.parser.ast.IASTExpression;
import org.eclipse.cdt.core.parser.ast.IASTFactory;
import org.eclipse.cdt.core.parser.ast.IASTInclusion;
import org.eclipse.cdt.core.parser.extension.IScannerExtension;
import org.eclipse.cdt.internal.core.parser.IExpressionParser;
import org.eclipse.cdt.internal.core.parser.InternalParserUtil;
import org.eclipse.cdt.internal.core.parser.ast.ASTCompletionNode;
import org.eclipse.cdt.internal.core.parser.token.KeywordSets;
import org.eclipse.cdt.internal.core.parser.token.SimpleToken;
import org.eclipse.cdt.internal.core.parser.token.TokenFactory;
import org.eclipse.cdt.internal.core.parser.util.TraceUtil;
/**
* @author jcamelon
*
*/
public class Scanner implements IScanner {
private static final NullSourceElementRequestor NULL_REQUESTOR = new NullSourceElementRequestor();
private final static String SCRATCH = "<scratch>"; //$NON-NLS-1$
protected final IScannerData scannerData;
private boolean initialContextInitialized = false;
protected IToken finalToken;
private final IScannerExtension scannerExtension;
private static final int NO_OFFSET_LIMIT = -1;
private int offsetLimit = NO_OFFSET_LIMIT;
private boolean limitReached = false;
protected void handleProblem( int problemID, String argument, int beginningOffset, boolean warning, boolean error ) throws ScannerException
{
handleProblem( problemID, argument, beginningOffset, warning, error, true );
}
protected void handleProblem( int problemID, String argument, int beginningOffset, boolean warning, boolean error, boolean extra ) throws ScannerException
{
IProblem problem = scannerData.getProblemFactory().createProblem(
problemID,
beginningOffset,
getCurrentOffset(),
scannerData.getContextStack().getCurrentLineNumber(),
getCurrentFile().toCharArray(),
argument,
warning,
error );
// trace log
TraceUtil.outputTrace(scannerData.getLogService(), "Scanner problem encountered: ", problem, null, null, null ); //$NON-NLS-1$
if( (! scannerData.getClientRequestor().acceptProblem( problem )) && extra )
throw new ScannerException( problem );
}
Scanner( Reader reader, String filename, Map definitions, List includePaths, ISourceElementRequestor requestor, ParserMode mode, ParserLanguage language, IParserLogService log, IScannerExtension extension )
{
String [] incs = (String [])includePaths.toArray(STRING_ARRAY);
scannerData = new ScannerData( this, log, requestor, mode, filename, reader, language, new ScannerInfo( definitions, incs ), new ContextStack( this, log ), null );
scannerExtension = extension;
if( scannerExtension instanceof GCCScannerExtension )
((GCCScannerExtension)scannerExtension).setScannerData( scannerData );
scannerData.setDefinitions( definitions );
scannerData.setIncludePathNames( includePaths );
scannerData.setASTFactory( ParserFactory.createASTFactory( this, scannerData.getParserMode(), language ) );
try {
//this is a hack to get around a sudden EOF experience
scannerData.getContextStack().push(
new ScannerContext(
new StringReader("\n"), //$NON-NLS-1$
START,
ScannerContext.ContextKind.SENTINEL, null), requestor);
} catch( ContextException ce ) {
//won't happen since we aren't adding an include or a macro
}
}
public Scanner(Reader reader, String filename, IScannerInfo info, ISourceElementRequestor requestor, ParserMode parserMode, ParserLanguage language, IParserLogService log, IScannerExtension extension, List workingCopies ) {
scannerData = new ScannerData( this, log, requestor, parserMode, filename, reader, language, info, new ContextStack( this, log ), workingCopies );
scannerExtension = extension;
if( scannerExtension instanceof GCCScannerExtension )
((GCCScannerExtension)scannerExtension).setScannerData( scannerData );
scannerData.setASTFactory( ParserFactory.createASTFactory( this, scannerData.getParserMode(), language ) );
try {
//this is a hack to get around a sudden EOF experience
scannerData.getContextStack().push(
new ScannerContext(
new StringReader("\n"), //$NON-NLS-1$
START,
ScannerContext.ContextKind.SENTINEL, null), requestor);
} catch( ContextException ce ) {
//won't happen since we aren't adding an include or a macro
// assert false
}
TraceUtil.outputTrace(log, "Scanner constructed with the following configuration:"); //$NON-NLS-1$
TraceUtil.outputTrace(log, "\tPreprocessor definitions from IScannerInfo: "); //$NON-NLS-1$
if( info.getDefinedSymbols() != null )
{
Iterator i = info.getDefinedSymbols().keySet().iterator();
Map m = info.getDefinedSymbols();
int numberOfSymbolsLogged = 0;
while( i.hasNext() )
{
String symbolName = (String) i.next();
Object value = m.get( symbolName );
if( value instanceof String )
{
addDefinition( symbolName, scannerExtension.initializeMacroValue((String) value));
TraceUtil.outputTrace(log, "\t\tNAME = ", symbolName, " VALUE = ", value.toString() ); //$NON-NLS-1$ //$NON-NLS-2$
++numberOfSymbolsLogged;
}
else if( value instanceof IMacroDescriptor )
addDefinition( symbolName, (IMacroDescriptor)value);
}
if( numberOfSymbolsLogged == 0 )
TraceUtil.outputTrace(log, "\t\tNo definitions specified."); //$NON-NLS-1$
}
else
TraceUtil.outputTrace(log, "\t\tNo definitions specified."); //$NON-NLS-1$
TraceUtil.outputTrace( log, "\tInclude paths from IScannerInfo: "); //$NON-NLS-1$
if( info.getIncludePaths() != null )
{
overwriteIncludePath( info.getIncludePaths() );
for( int i = 0; i < info.getIncludePaths().length; ++i )
TraceUtil.outputTrace( log, "\t\tPATH: ", info.getIncludePaths()[i], null, null); //$NON-NLS-1$
}
else
TraceUtil.outputTrace(log, "\t\tNo include paths specified."); //$NON-NLS-1$
setupBuiltInMacros();
}
/**
*
*/
protected void setupBuiltInMacros() {
scannerExtension.setupBuiltInMacros(scannerData.getLanguage());
if( getDefinition(__STDC__) == null )
addDefinition( __STDC__, new ObjectMacroDescriptor( __STDC__, "1") ); //$NON-NLS-1$
if( scannerData.getLanguage() == ParserLanguage.C )
{
if( getDefinition(__STDC_HOSTED__) == null )
addDefinition( __STDC_HOSTED__, new ObjectMacroDescriptor( __STDC_HOSTED__, "0")); //$NON-NLS-1$
if( getDefinition( __STDC_VERSION__) == null )
addDefinition( __STDC_VERSION__, new ObjectMacroDescriptor( __STDC_VERSION__, "199001L")); //$NON-NLS-1$
}
else
if( getDefinition( __CPLUSPLUS ) == null )
addDefinition( __CPLUSPLUS, new ObjectMacroDescriptor( __CPLUSPLUS, "199711L")); //$NON-NLS-1$
if( getDefinition(__FILE__) == null )
addDefinition( __FILE__,
new DynamicMacroDescriptor( __FILE__, new DynamicMacroEvaluator() {
public String execute() {
return scannerData.getContextStack().getMostRelevantFileContext().getFilename();
}
} ) );
if( getDefinition( __LINE__) == null )
addDefinition( __LINE__,
new DynamicMacroDescriptor( __LINE__, new DynamicMacroEvaluator() {
public String execute() {
return new Integer( scannerData.getContextStack().getCurrentLineNumber() ).toString();
}
} ) );
if( getDefinition( __DATE__ ) == null )
addDefinition( __DATE__,
new DynamicMacroDescriptor( __DATE__, new DynamicMacroEvaluator() {
public String getMonth()
{
if( Calendar.MONTH == Calendar.JANUARY ) return "Jan" ; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.FEBRUARY) return "Feb"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.MARCH) return "Mar"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.APRIL) return "Apr"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.MAY) return "May"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.JUNE) return "Jun"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.JULY) return "Jul"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.AUGUST) return "Aug"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.SEPTEMBER) return "Sep"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.OCTOBER) return "Oct"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.NOVEMBER) return "Nov"; //$NON-NLS-1$
if( Calendar.MONTH == Calendar.DECEMBER) return "Dec"; //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
public String execute() {
StringBuffer result = new StringBuffer();
result.append( getMonth() );
result.append(" "); //$NON-NLS-1$
if( Calendar.DAY_OF_MONTH < 10 )
result.append(" "); //$NON-NLS-1$
result.append(Calendar.DAY_OF_MONTH);
result.append(" "); //$NON-NLS-1$
result.append( Calendar.YEAR );
return result.toString();
}
} ) );
if( getDefinition( __TIME__) == null )
addDefinition( __TIME__,
new DynamicMacroDescriptor( __TIME__, new DynamicMacroEvaluator() {
public String execute() {
StringBuffer result = new StringBuffer();
if( Calendar.AM_PM == Calendar.PM )
result.append( Calendar.HOUR + 12 );
else
{
if( Calendar.HOUR < 10 )
result.append( '0');
result.append(Calendar.HOUR);
}
result.append(':');
if( Calendar.MINUTE < 10 )
result.append( '0');
result.append(Calendar.MINUTE);
result.append(':');
if( Calendar.SECOND < 10 )
result.append( '0');
result.append(Calendar.SECOND);
return result.toString();
}
} ) );
}
private void setupInitialContext()
{
String resolvedFilename = scannerData.getInitialFilename() == null ? TEXT : scannerData.getInitialFilename();
IScannerContext context = null;
try
{
if( offsetLimit == NO_OFFSET_LIMIT )
context = new ScannerContext(scannerData.getInitialReader(), resolvedFilename, ScannerContext.ContextKind.TOP, null );
else
context = new LimitedScannerContext( this, scannerData.getInitialReader(), resolvedFilename, ScannerContext.ContextKind.TOP, offsetLimit );
scannerData.getContextStack().push( context, scannerData.getClientRequestor() );
} catch( ContextException ce )
{
handleInternalError();
}
initialContextInitialized = true;
}
public void addIncludePath(String includePath) {
scannerData.getIncludePathNames().add(includePath);
}
public void overwriteIncludePath(String [] newIncludePaths) {
if( newIncludePaths == null ) return;
scannerData.setIncludePathNames(new ArrayList());
for( int i = 0; i < newIncludePaths.length; ++i )
{
String path = newIncludePaths[i];
File file = new File( path );
if( !file.exists() && path.indexOf('\"') != -1 )
{
StringTokenizer tokenizer = new StringTokenizer(path, "\"" ); //$NON-NLS-1$
StringBuffer buffer = new StringBuffer(path.length() );
while( tokenizer.hasMoreTokens() ){
buffer.append( tokenizer.nextToken() );
}
file = new File( buffer.toString() );
}
if( file.exists() && file.isDirectory() )
scannerData.getIncludePathNames().add( path );
}
}
public void addDefinition(String key, IMacroDescriptor macro) {
scannerData.getDefinitions().put(key, macro);
}
public void addDefinition(String key, String value) {
addDefinition(key,
new ObjectMacroDescriptor( key,
value ));
}
public final IMacroDescriptor getDefinition(String key) {
return (IMacroDescriptor) scannerData.getDefinitions().get(key);
}
public final String[] getIncludePaths() {
return (String[])scannerData.getIncludePathNames().toArray();
}
protected boolean skipOverWhitespace() throws ScannerException {
int c = getChar();
boolean result = false;
while ((c != NOCHAR) && ((c == ' ') || (c == '\t')))
{
c = getChar();
result = true;
}
if (c != NOCHAR)
ungetChar(c);
return result;
}
protected String getRestOfPreprocessorLine() throws ScannerException, EndOfFileException {
skipOverWhitespace();
int c = getChar();
if (c == '\n')
return ""; //$NON-NLS-1$
StringBuffer buffer = new StringBuffer();
boolean inString = false;
boolean inChar = false;
while (true) {
while ((c != '\n')
&& (c != '\r')
&& (c != '\\')
&& (c != '/')
&& (c != '"' || ( c == '"' && inChar ) )
&& (c != '\'' || ( c == '\'' && inString ) )
&& (c != NOCHAR)) {
buffer.append((char) c);
c = getChar( true );
}
if (c == '/') {
//only care about comments outside of a quote
if( inString || inChar ){
buffer.append( (char) c );
c = getChar( true );
continue;
}
// we need to peek ahead at the next character to see if
// this is a comment or not
int next = getChar();
if (next == '/') {
// single line comment
skipOverSinglelineComment();
break;
} else if (next == '*') {
// multiline comment
if (skipOverMultilineComment())
break;
else
c = getChar( true );
continue;
} else {
// we are not in a comment
buffer.append((char) c);
c = next;
continue;
}
} else if( c == '"' ){
inString = !inString;
buffer.append((char) c);
c = getChar( true );
continue;
} else if( c == '\'' ){
inChar = !inChar;
buffer.append((char) c);
c = getChar( true );
continue;
} else if( c == '\\' ){
c = getChar(true);
if( c == '\r' ){
c = getChar(true);
if( c == '\n' ){
c = getChar(true);
}
} else if( c == '\n' ){
c = getChar(true);
} else {
buffer.append('\\');
if( c == '"' || c == '\'' ){
buffer.append((char)c);
c = getChar( true );
}
}
continue;
} else {
ungetChar(c);
break;
}
}
return buffer.toString();
}
protected void skipOverTextUntilNewline() throws ScannerException {
for (;;) {
switch (getChar()) {
case NOCHAR :
case '\n' :
return;
case '\\' :
getChar();
}
}
}
private void setCurrentToken(IToken t) {
if (currentToken != null)
currentToken.setNext(t);
finalToken = t;
currentToken = t;
}
protected void resetStorageBuffer()
{
if( storageBuffer != null )
storageBuffer = null;
}
protected IToken newToken(int t, String i) {
IToken theToken = TokenFactory.createToken( t, i, scannerData );
setCurrentToken(theToken);
return currentToken;
}
protected IToken newConstantToken(int t) {
setCurrentToken( TokenFactory.createToken(t,scannerData));
return currentToken;
}
protected String getNextIdentifier() throws ScannerException {
StringBuffer buffer = new StringBuffer();
skipOverWhitespace();
int c = getChar();
if (((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z')) | (c == '_')) {
buffer.append((char) c);
c = getChar();
while (((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z'))
|| ((c >= '0') && (c <= '9'))
|| (c == '_')) {
buffer.append((char) c);
c = getChar();
}
}
ungetChar(c);
return buffer.toString();
}
protected void handleInclusion(String fileName, boolean useIncludePaths, int beginOffset, int startLine, int nameOffset, int nameLine, int endOffset, int endLine ) throws ScannerException {
CodeReader duple = null;
totalLoop: for( int i = 0; i < 2; ++i )
{
if( useIncludePaths ) // search include paths for this file
{
// iterate through the include paths
Iterator iter = scannerData.getIncludePathNames().iterator();
while (iter.hasNext()) {
String path = (String)iter.next();
duple = ScannerUtility.createReaderDuple( path, fileName, scannerData.getClientRequestor(), scannerData.getWorkingCopies() );
if( duple != null )
break totalLoop;
}
if (duple == null )
handleProblem( IProblem.PREPROCESSOR_INCLUSION_NOT_FOUND, fileName, beginOffset, false, true );
}
else // local inclusion
{
duple = ScannerUtility.createReaderDuple( new File( scannerData.getContextStack().getCurrentContext().getFilename() ).getParentFile().getAbsolutePath(), fileName, scannerData.getClientRequestor(), scannerData.getWorkingCopies() );
if( duple != null )
break totalLoop;
useIncludePaths = true;
continue totalLoop;
}
}
if (duple!= null) {
IASTInclusion inclusion = null;
try
{
inclusion =
scannerData.getASTFactory().createInclusion(
fileName,
duple.getFilename(),
!useIncludePaths,
beginOffset,
startLine,
nameOffset,
nameOffset + fileName.length(), nameLine, endOffset, endLine);
}
catch (Exception e)
{
/* do nothing */
}
try
{
scannerData.getContextStack().updateContext(
duple.getUnderlyingReader(),
duple.getFilename(),
ScannerContext.ContextKind.INCLUSION,
inclusion,
scannerData.getClientRequestor() );
}
catch (ContextException e1)
{
handleProblem( e1.getId(), fileName, beginOffset, false, true );
}
}
}
/* protected void handleInclusion(String fileName, boolean useIncludePaths, int beginOffset, int startLine, int nameOffset, int nameLine, int endOffset, int endLine ) throws ScannerException {
// if useIncludePaths is true then
// #include <foo.h>
// else
// #include "foo.h"
Reader inclusionReader = null;
File includeFile = null;
if( !useIncludePaths ) { // local inclusion is checked first
String currentFilename = scannerData.getContextStack().getCurrentContext().getFilename();
File currentIncludeFile = new File( currentFilename );
String parentDirectory = currentIncludeFile.getParentFile().getAbsolutePath();
currentIncludeFile = null;
//TODO remove ".." and "." segments
includeFile = new File( parentDirectory, fileName );
if (includeFile.exists() && includeFile.isFile()) {
try {
inclusionReader = new BufferedReader(new FileReader(includeFile));
} catch (FileNotFoundException fnf) {
inclusionReader = null;
}
}
}
// search include paths for this file
// iterate through the include paths
Iterator iter = scannerData.getIncludePathNames().iterator();
while ((inclusionReader == null) && iter.hasNext()) {
String path = (String)iter.next();
//TODO remove ".." and "." segments
includeFile = new File (path, fileName);
if (includeFile.exists() && includeFile.isFile()) {
try {
inclusionReader = new BufferedReader(new FileReader(includeFile));
} catch (FileNotFoundException fnf) {
inclusionReader = null;
}
}
}
if (inclusionReader == null )
handleProblem( IProblem.PREPROCESSOR_INCLUSION_NOT_FOUND, fileName, beginOffset, false, true );
else {
IASTInclusion inclusion = null;
try
{
inclusion =
scannerData.getASTFactory().createInclusion(
fileName,
includeFile.getPath(),
!useIncludePaths,
beginOffset,
startLine,
nameOffset,
nameOffset + fileName.length(), nameLine, endOffset, endLine);
}
catch (Exception e)
{
do nothing
}
try
{
scannerData.getContextStack().updateContext(inclusionReader, includeFile.getPath(), ScannerContext.ContextKind.INCLUSION, inclusion, scannerData.getClientRequestor() );
}
catch (ContextException e1)
{
handleProblem( e1.getId(), fileName, beginOffset, false, true );
}
}
}
*/
// constants
private static final int NOCHAR = -1;
private static final String TEXT = "<text>"; //$NON-NLS-1$
private static final String START = "<initial reader>"; //$NON-NLS-1$
private static final String EXPRESSION = "<expression>"; //$NON-NLS-1$
private static final String PASTING = "<pasting>"; //$NON-NLS-1$
private static final String DEFINED = "defined"; //$NON-NLS-1$
private static final String _PRAGMA = "_Pragma"; //$NON-NLS-1$
private static final String POUND_DEFINE = "#define "; //$NON-NLS-1$
private IScannerContext lastContext = null;
private StringBuffer storageBuffer = null;
private int count = 0;
private static HashMap cppKeywords = new HashMap();
private static HashMap cKeywords = new HashMap();
private static HashMap ppDirectives = new HashMap();
private IToken currentToken = null;
private IToken cachedToken = null;
private boolean passOnToClient = true;
// these are scanner configuration aspects that we perhaps want to tweak
// eventually, these should be configurable by the client, but for now
// we can just leave it internal
private boolean enableDigraphReplacement = true;
private boolean enableTrigraphReplacement = true;
private boolean enableTrigraphReplacementInStrings = true;
private boolean throwExceptionOnBadCharacterRead = false;
private boolean atEOF = false;
private boolean tokenizingMacroReplacementList = false;
protected static final String EMPTY_STRING = ""; //$NON-NLS-1$
public void setTokenizingMacroReplacementList( boolean mr ){
tokenizingMacroReplacementList = mr;
}
public int getCharacter() throws ScannerException
{
if( ! initialContextInitialized )
setupInitialContext();
return getChar();
}
final int getChar() throws ScannerException
{
return getChar( false );
}
private int getChar( boolean insideString ) throws ScannerException {
int c = NOCHAR;
lastContext = scannerData.getContextStack().getCurrentContext();
if (lastContext == null)
// past the end of file
return c;
if (lastContext.undoStackSize() != 0 )
c = lastContext.popUndo();
else
c = readFromStream();
if (enableTrigraphReplacement && (!insideString || enableTrigraphReplacementInStrings)) {
// Trigraph processing
enableTrigraphReplacement = false;
if (c == '?') {
c = getChar(insideString);
if (c == '?') {
c = getChar(insideString);
switch (c) {
case '(':
expandDefinition("??(", "[", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(insideString);
break;
case ')':
expandDefinition("??)", "]", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(insideString);
break;
case '<':
expandDefinition("??<", "{", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(insideString);
break;
case '>':
expandDefinition("??>", "}", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(insideString);
break;
case '=':
expandDefinition("??=", "#", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(insideString);
break;
case '/':
expandDefinition("??/", "\\", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(insideString);
break;
case '\'':
expandDefinition("??\'", "^", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(insideString);
break;
case '!':
expandDefinition("??!", "|", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(insideString);
break;
case '-':
expandDefinition("??-", "~", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(insideString);
break;
default:
// Not a trigraph
ungetChar(c);
ungetChar('?');
c = '?';
}
} else {
// Not a trigraph
ungetChar(c);
c = '?';
}
}
enableTrigraphReplacement = true;
}
if (!insideString)
{
if (enableDigraphReplacement) {
enableDigraphReplacement = false;
// Digraph processing
if (c == '<') {
c = getChar(false);
if (c == '%') {
expandDefinition("<%", "{", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(false);
} else if (c == ':') {
expandDefinition("<:", "[", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(false);
} else {
// Not a digraph
ungetChar(c);
c = '<';
}
} else if (c == ':') {
c = getChar(false);
if (c == '>') {
expandDefinition(":>", "]", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(false);
} else {
// Not a digraph
ungetChar(c);
c = ':';
}
} else if (c == '%') {
c = getChar(false);
if (c == '>') {
expandDefinition("%>", "}", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(false);
} else if (c == ':') {
expandDefinition("%:", "#", lastContext.getOffset() - lastContext.undoStackSize() - 1); //$NON-NLS-1$ //$NON-NLS-2$
c = getChar(false);
} else {
// Not a digraph
ungetChar(c);
c = '%';
}
}
enableDigraphReplacement = true;
}
}
return c;
}
protected int readFromStream()
{
int c;
try {
c = scannerData.getContextStack().getCurrentContext().read();
}
catch (IOException e) {
c = NOCHAR;
}
if (c != NOCHAR)
return c;
if (scannerData.getContextStack().rollbackContext(scannerData.getClientRequestor()) == false)
return NOCHAR;
if (scannerData.getContextStack().getCurrentContext().undoStackSize() != 0 )
return scannerData.getContextStack().getCurrentContext().popUndo();
return readFromStream();
}
final void ungetChar(int c) throws ScannerException{
scannerData.getContextStack().getCurrentContext().pushUndo(c);
try
{
scannerData.getContextStack().undoRollback( lastContext, scannerData.getClientRequestor() );
}
catch (ContextException e)
{
handleProblem( e.getId(), scannerData.getContextStack().getCurrentContext().getFilename(), getCurrentOffset(), false, true );
}
}
protected boolean lookAheadForTokenPasting() throws ScannerException
{
int c = getChar();
if( c == '#' )
{
c = getChar();
if( c == '#' )
{
return true;
}
else
{
ungetChar( c );
}
}
ungetChar( c );
return false;
}
protected void consumeUntilOutOfMacroExpansion() throws ScannerException
{
while( scannerData.getContextStack().getCurrentContext().getKind() == IScannerContext.ContextKind.MACROEXPANSION )
getChar();
}
public IToken nextToken() throws ScannerException, EndOfFileException {
return nextToken( true );
}
public boolean pasteIntoInputStream(StringBuffer buff) throws ScannerException, EndOfFileException
{
// we have found ## in the input stream -- so save the results
if( lookAheadForTokenPasting() )
{
if( storageBuffer == null )
storageBuffer = buff;
else
storageBuffer.append( buff.toString() );
return true;
}
// a previous call has stored information, so we will add to it
if( storageBuffer != null )
{
storageBuffer.append( buff.toString() );
try
{
scannerData.getContextStack().updateContext(
new StringReader( storageBuffer.toString()),
PASTING,
IScannerContext.ContextKind.MACROEXPANSION,
null,
scannerData.getClientRequestor() );
}
catch (ContextException e)
{
handleProblem( e.getId(), scannerData.getContextStack().getCurrentContext().getFilename(), getCurrentOffset(), false, true );
}
storageBuffer = null;
return true;
}
// there is no need to save the results -- we will not concatenate
return false;
}
public int consumeNewlineAfterSlash() throws ScannerException
{
int c;
c = getChar(false);
if (c == '\r')
{
c = getChar(false);
if (c == '\n')
{
// consume \ \r \n and then continue
return getChar(true);
}
else
{
// consume the \ \r and then continue
return c;
}
}
if (c == '\n')
{
// consume \ \n and then continue
return getChar(true);
}
// '\' is not the last character on the line
ungetChar(c);
return '\\';
}
public IToken processStringLiteral(boolean wideLiteral) throws ScannerException, EndOfFileException
{
int beginOffset = getCurrentOffset();
StringBuffer buff = new StringBuffer();
int beforePrevious = NOCHAR;
int previous = '"';
int c = getChar(true);
for( ; ; ) {
if (c == '\\')
c = consumeNewlineAfterSlash();
if ( ( c == '"' ) && ( previous != '\\' || beforePrevious == '\\') ) break;
if ( ( c == NOCHAR ) || (( c == '\n' ) && ( previous != '\\' || beforePrevious == '\\')) )
{
// TODO : we could probably return the partial string -- it might cause
// the parse to get by...
handleProblem( IProblem.SCANNER_UNBOUNDED_STRING, null, beginOffset, false, true );
return null;
}
buff.append((char) c);
beforePrevious = previous;
previous = c;
c = getChar(true);
}
int type = wideLiteral ? IToken.tLSTRING : IToken.tSTRING;
//If the next token is going to be a string as well, we need to concatenate
//it with this token. This will be recursive for as many strings as need to be concatenated
IToken returnToken = newToken( type, buff.toString());
IToken next = null;
try{
next = nextToken( true );
if ( next != null &&
(next.getType() == IToken.tSTRING ||
next.getType() == IToken.tLSTRING )) {
buff.append( next.getImage() );
}
else
cachedToken = next;
} catch( EndOfFileException e ){
next = null;
}
returnToken.setImage(buff.toString());
currentToken = returnToken;
returnToken.setNext( null );
return returnToken;
}
public IToken processNumber(int c, boolean pasting) throws ScannerException, EndOfFileException
{
// pasting happens when a macro appears in the middle of a number
// we will "store" the first part of the number in the "pasting" buffer
// until we have the full monty to evaluate
// for example
// #define F1 3
// #define F2 F1##F1
// int x = F2;
int beginOffset = getCurrentOffset();
StringBuffer buff = new StringBuffer();
boolean hex = false;
boolean floatingPoint = ( c == '.' ) ? true : false;
boolean firstCharZero = ( c== '0' )? true : false;
buff.append((char) c);
c = getChar();
if( ! firstCharZero && floatingPoint && !(c >= '0' && c <= '9') ){
//if pasting, there could actually be a float here instead of just a .
if( buff.toString().equals( "." ) ){ //$NON-NLS-1$
if( c == '*' ){
return newConstantToken( IToken.tDOTSTAR );
} else if( c == '.' ){
if( getChar() == '.' )
return newConstantToken( IToken.tELLIPSIS );
else
handleProblem( IProblem.SCANNER_BAD_FLOATING_POINT, null, beginOffset, false, true );
} else {
ungetChar( c );
return newConstantToken( IToken.tDOT );
}
}
} else if (c == 'x') {
if( ! firstCharZero )
{
handleProblem( IProblem.SCANNER_BAD_HEX_FORMAT, null, beginOffset, false, true );
return null;
// c = getChar();
// continue;
}
buff.append( (char)c );
hex = true;
c = getChar();
}
while ((c >= '0' && c <= '9')
|| (hex
&& ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')))) {
buff.append((char) c);
c = getChar();
}
if( c == '.' )
{
buff.append( (char)c);
floatingPoint = true;
c= getChar();
while ((c >= '0' && c <= '9')
|| (hex
&& ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))))
{
buff.append((char) c);
c = getChar();
}
}
if (c == 'e' || c == 'E' || (hex && (c == 'p' || c == 'P')))
{
if( ! floatingPoint ) floatingPoint = true;
// exponent type for floating point
buff.append((char)c);
c = getChar();
// optional + or -
if( c == '+' || c == '-' )
{
buff.append( (char)c );
c = getChar();
}
// digit sequence of exponent part
while ((c >= '0' && c <= '9') )
{
buff.append((char) c);
c = getChar();
}
// optional suffix
if( c == 'l' || c == 'L' || c == 'f' || c == 'F' )
{
buff.append( (char)c );
c = getChar();
}
} else {
if( floatingPoint ){
//floating-suffix
if( c == 'l' || c == 'L' || c == 'f' || c == 'F' ){
c = getChar();
}
} else {
//integer suffix
if( c == 'u' || c == 'U' ){
c = getChar();
if( c == 'l' || c == 'L')
c = getChar();
if( c == 'l' || c == 'L')
c = getChar();
} else if( c == 'l' || c == 'L' ){
c = getChar();
if( c == 'l' || c == 'L')
c = getChar();
if( c == 'u' || c == 'U' )
c = getChar();
}
}
}
ungetChar( c );
if( pasting && pasteIntoInputStream(buff))
return null;
int tokenType;
String result = buff.toString();
if( floatingPoint && result.equals(".") ) //$NON-NLS-1$
tokenType = IToken.tDOT;
else
tokenType = floatingPoint ? IToken.tFLOATINGPT : IToken.tINTEGER;
return newToken(
tokenType,
result);
}
public IToken processPreprocessor() throws ScannerException, EndOfFileException
{
int c;
int beginningOffset = scannerData.getContextStack().getCurrentContext().getOffset() - 1;
int beginningLine = scannerData.getContextStack().getCurrentLineNumber();
// we are allowed arbitrary whitespace after the '#' and before the rest of the text
boolean skipped = skipOverWhitespace();
c = getChar();
if( c == '#' )
{
if( skipped )
handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, "# #", beginningOffset, false, true ); //$NON-NLS-1$
else
return newConstantToken( tPOUNDPOUND ); //$NON-NLS-1$
} else if( tokenizingMacroReplacementList ) {
ungetChar( c );
return newConstantToken( tPOUND ); //$NON-NLS-1$
}
StringBuffer buff = new StringBuffer();
buff.append('#');
while (((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z')) || (c == '_') ) {
buff.append((char) c);
c = getChar();
}
ungetChar(c);
String token = buff.toString();
if( isLimitReached() )
handleCompletionOnPreprocessorDirective(token);
Object directive = ppDirectives.get(token);
if (directive == null) {
if( scannerExtension.canHandlePreprocessorDirective( token ) )
scannerExtension.handlePreprocessorDirective( token, getRestOfPreprocessorLine() );
else
{
if( passOnToClient )
handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, token, beginningOffset, false, true );
}
return null;
}
int type = ((Integer) directive).intValue();
switch (type) {
case PreprocessorDirectives.DEFINE :
if ( ! passOnToClient ) {
skipOverTextUntilNewline();
if( isLimitReached() )
handleInvalidCompletion();
return null;
}
poundDefine(beginningOffset, beginningLine);
return null;
case PreprocessorDirectives.INCLUDE :
if (! passOnToClient ) {
skipOverTextUntilNewline();
if( isLimitReached() )
handleInvalidCompletion();
return null;
}
poundInclude( beginningOffset, beginningLine );
return null;
case PreprocessorDirectives.UNDEFINE :
if (! passOnToClient) {
skipOverTextUntilNewline();
if( isLimitReached() )
handleInvalidCompletion();
return null;
}
removeSymbol(getNextIdentifier());
skipOverTextUntilNewline();
return null;
case PreprocessorDirectives.IF :
//TODO add in content assist stuff here
// get the rest of the line
int currentOffset = getCurrentOffset();
String expression = getRestOfPreprocessorLine();
if( isLimitReached() )
handleCompletionOnExpression( expression );
if (expression.trim().equals("")) //$NON-NLS-1$
handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, "#if", beginningOffset, false, true ); //$NON-NLS-1$
boolean expressionEvalResult = false;
if( scannerData.getBranchTracker().queryCurrentBranchForIf() )
expressionEvalResult = evaluateExpression(expression, currentOffset);
passOnToClient = scannerData.getBranchTracker().poundIf( expressionEvalResult );
return null;
case PreprocessorDirectives.IFDEF :
//TODO add in content assist stuff here
String definition = getNextIdentifier();
if( isLimitReached() )
handleCompletionOnDefinition( definition );
if (getDefinition(definition) == null) {
// not defined
passOnToClient = scannerData.getBranchTracker().poundIf( false );
skipOverTextUntilNewline();
} else
// continue along, act like nothing is wrong :-)
passOnToClient = scannerData.getBranchTracker().poundIf( true );
return null;
case PreprocessorDirectives.ENDIF :
String restOfLine = getRestOfPreprocessorLine().trim();
if( isLimitReached() )
handleInvalidCompletion();
if( ! restOfLine.equals( "" ) ) //$NON-NLS-1$
{
StringBuffer buffer = new StringBuffer("#endif "); //$NON-NLS-1$
buffer.append( restOfLine );
handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, buffer.toString(), beginningOffset, false, true );
}
try{
passOnToClient = scannerData.getBranchTracker().poundEndif();
}
catch( EmptyStackException ese )
{
handleProblem( IProblem.PREPROCESSOR_UNBALANCE_CONDITION,
token,
beginningOffset,
false, true );
}
return null;
case PreprocessorDirectives.IFNDEF :
//TODO add in content assist stuff here
String definition2 = getNextIdentifier();
if( isLimitReached() )
handleCompletionOnDefinition( definition2 );
if (getDefinition(definition2) != null) {
// not defined
skipOverTextUntilNewline();
passOnToClient = scannerData.getBranchTracker().poundIf( false );
if( isLimitReached() )
handleInvalidCompletion();
} else
// continue along, act like nothing is wrong :-)
passOnToClient = scannerData.getBranchTracker().poundIf( true );
return null;
case PreprocessorDirectives.ELSE :
try
{
passOnToClient = scannerData.getBranchTracker().poundElse();
}
catch( EmptyStackException ese )
{
handleProblem( IProblem.PREPROCESSOR_UNBALANCE_CONDITION,
token,
beginningOffset,
false, true );
}
skipOverTextUntilNewline();
if( isLimitReached() )
handleInvalidCompletion();
return null;
case PreprocessorDirectives.ELIF :
//TODO add in content assist stuff here
int co = getCurrentOffset();
String elifExpression = getRestOfPreprocessorLine();
if( isLimitReached() )
handleCompletionOnExpression( elifExpression );
if (elifExpression.equals("")) //$NON-NLS-1$
handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, "#elif", beginningOffset, false, true ); //$NON-NLS-1$
boolean elsifResult = false;
if( scannerData.getBranchTracker().queryCurrentBranchForElif() )
elsifResult = evaluateExpression(elifExpression, co );
try
{
passOnToClient = scannerData.getBranchTracker().poundElif( elsifResult );
}
catch( EmptyStackException ese )
{
StringBuffer buffer = new StringBuffer( token );
buffer.append( ' ' );
buffer.append( elifExpression );
handleProblem( IProblem.PREPROCESSOR_UNBALANCE_CONDITION,
buffer.toString(),
beginningOffset,
false, true );
}
return null;
case PreprocessorDirectives.LINE :
skipOverTextUntilNewline();
if( isLimitReached() )
handleInvalidCompletion();
return null;
case PreprocessorDirectives.ERROR :
if (! passOnToClient) {
skipOverTextUntilNewline();
if( isLimitReached() )
handleInvalidCompletion();
return null;
}
- handleProblem( IProblem.PREPROCESSOR_POUND_ERROR, getRestOfPreprocessorLine(), beginningOffset, false, true );
+ String restOfErrorLine = getRestOfPreprocessorLine();
+ if( isLimitReached() )
+ handleInvalidCompletion();
+
+ handleProblem( IProblem.PREPROCESSOR_POUND_ERROR, restOfErrorLine, beginningOffset, false, true );
return null;
case PreprocessorDirectives.PRAGMA :
skipOverTextUntilNewline();
if( isLimitReached() )
handleInvalidCompletion();
return null;
case PreprocessorDirectives.BLANK :
String remainderOfLine =
getRestOfPreprocessorLine().trim();
if (!remainderOfLine.equals("")) { //$NON-NLS-1$
StringBuffer buffer = new StringBuffer( "# "); //$NON-NLS-1$
buffer.append( remainderOfLine );
handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, buffer.toString(), beginningOffset, false, true);
}
return null;
default :
StringBuffer buffer = new StringBuffer( "# "); //$NON-NLS-1$
buffer.append( token );
handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, buffer.toString(), beginningOffset, false, true );
return null;
}
}
// buff contains \\u or \\U
protected StringBuffer processUniversalCharacterName( StringBuffer buff ) throws ScannerException
{
// first octet is mandatory
for( int i = 0; i < 4; ++i )
{
int c = getChar();
if( ! isHex( c ))
return null;
buff.append( (char) c );
}
Vector v = new Vector();
Overall: for( int i = 0; i < 4; ++i )
{
int c = getChar();
if( ! isHex( c ))
{
ungetChar( c );
break;
}
v.add( new Character((char) c ));
}
if( v.size() == 4 )
{
for( int i = 0; i < 4; ++i )
buff.append( ((Character)v.get(i)).charValue());
}
else
{
for( int i = v.size() - 1; i >= 0; --i )
ungetChar( ((Character)v.get(i)).charValue() );
}
return buff;
}
/**
* @param c
* @return
*/
private boolean isHex(int c) {
switch( c )
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return true;
default:
return false;
}
}
protected IToken processKeywordOrIdentifier(StringBuffer buff, boolean pasting) throws ScannerException, EndOfFileException
{
int baseOffset = lastContext.getOffset() - lastContext.undoStackSize() - 1;
// String buffer is slow, we need a better way such as memory mapped files
int c = getChar();
for( ; ; )
{
// do the least expensive tests first!
while ( ( scannerExtension.offersDifferentIdentifierCharacters() &&
scannerExtension.isValidIdentifierCharacter(c) ) ||
isValidIdentifierCharacter(c) ) {
buff.append((char) c);
c = getChar();
if (c == '\\') {
c = consumeNewlineAfterSlash();
}
}
if( c == '\\')
{
int next = getChar();
if( next == 'u' || next == 'U')
{
buff.append( '\\');
buff.append( (char)next );
buff = processUniversalCharacterName(buff);
if( buff == null ) return null;
continue; // back to top of loop
}
else
ungetChar( next );
}
break;
}
ungetChar(c);
String ident = buff. toString();
if (ident.equals(DEFINED))
return newToken(IToken.tINTEGER, handleDefinedMacro());
if( ident.equals(_PRAGMA) && scannerData.getLanguage() == ParserLanguage.C )
{
handlePragmaOperator();
return null;
}
IMacroDescriptor mapping = getDefinition(ident);
if (mapping != null && !isLimitReached())
if( scannerData.getContextStack().shouldExpandDefinition( ident ) ) {
expandDefinition(ident, mapping, baseOffset);
return null;
}
if( pasting && pasteIntoInputStream(buff))
return null;
Object tokenTypeObject;
if( scannerData.getLanguage() == ParserLanguage.CPP )
tokenTypeObject = cppKeywords.get(ident);
else
tokenTypeObject = cKeywords.get(ident);
if (tokenTypeObject != null)
return newConstantToken(((Integer) tokenTypeObject).intValue());
else
return newToken(IToken.tIDENTIFIER, ident);
}
/**
* @param c
* @return
*/
protected boolean isValidIdentifierCharacter(int c) {
return ((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z'))
|| ((c >= '0') && (c <= '9'))
|| (c == '_') || Character.isUnicodeIdentifierPart( (char)c);
}
public IToken nextToken( boolean pasting ) throws ScannerException, EndOfFileException
{
if( ! initialContextInitialized )
setupInitialContext();
if( cachedToken != null ){
setCurrentToken( cachedToken );
cachedToken = null;
return currentToken;
}
IToken token;
count++;
int c = getChar();
while (c != NOCHAR) {
if ( ! passOnToClient ) {
while (c != NOCHAR && c != '#' )
{
c = getChar();
if( c == '/' )
{
c = getChar();
if( c == '/' )
{
skipOverSinglelineComment();
c = getChar();
continue;
}
else if( c == '*' )
{
skipOverMultilineComment();
c = getChar();
continue;
}
}
}
if( c == NOCHAR )
{
if( isLimitReached() )
handleInvalidCompletion();
continue;
}
}
switch (c) {
case ' ' :
case '\r' :
case '\t' :
case '\n' :
c = getChar();
continue;
case ':' :
c = getChar();
switch (c) {
case ':' : return newConstantToken(IToken.tCOLONCOLON);
// Diagraph
case '>' : return newConstantToken(IToken.tRBRACKET);
default :
ungetChar(c);
return newConstantToken(IToken.tCOLON);
}
case ';' : return newConstantToken(IToken.tSEMI);
case ',' : return newConstantToken(IToken.tCOMMA);
case '?' :
c = getChar();
if (c == '?')
{
// trigraph
c = getChar();
switch (c) {
case '=':
// this is the same as the # case
token = processPreprocessor();
if (token == null)
{
c = getChar();
continue;
}
return token;
default:
// Not a trigraph
ungetChar(c);
ungetChar('?');
return newConstantToken(IToken.tQUESTION);
}
}
ungetChar(c);
return newConstantToken(IToken.tQUESTION);
case '(' : return newConstantToken(IToken.tLPAREN);
case ')' : return newConstantToken(IToken.tRPAREN);
case '[' : return newConstantToken(IToken.tLBRACKET);
case ']' : return newConstantToken(IToken.tRBRACKET);
case '{' : return newConstantToken(IToken.tLBRACE);
case '}' : return newConstantToken(IToken.tRBRACE);
case '+' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tPLUSASSIGN);
case '+' : return newConstantToken(IToken.tINCR);
default :
ungetChar(c);
return newConstantToken(IToken.tPLUS);
}
case '-' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tMINUSASSIGN);
case '-' : return newConstantToken(IToken.tDECR);
case '>' :
c = getChar();
switch (c) {
case '*' : return newConstantToken(IToken.tARROWSTAR);
default :
ungetChar(c);
return newConstantToken(IToken.tARROW);
}
default :
ungetChar(c);
return newConstantToken(IToken.tMINUS);
}
case '*' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tSTARASSIGN);
default :
ungetChar(c);
return newConstantToken(IToken.tSTAR);
}
case '%' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tMODASSIGN);
// Diagraph
case '>' : return newConstantToken(IToken.tRBRACE);
case ':' :
// this is the same as the # case
token = processPreprocessor();
if (token == null)
{
c = getChar();
continue;
}
return token;
default :
ungetChar(c);
return newConstantToken(IToken.tMOD);
}
case '^' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tXORASSIGN);
default :
ungetChar(c);
return newConstantToken(IToken.tXOR);
}
case '&' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tAMPERASSIGN);
case '&' : return newConstantToken(IToken.tAND);
default :
ungetChar(c);
return newConstantToken(IToken.tAMPER);
}
case '|' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tBITORASSIGN);
case '|' : return newConstantToken(IToken.tOR);
default :
ungetChar(c);
return newConstantToken(IToken.tBITOR);
}
case '~' : return newConstantToken(IToken.tCOMPL);
case '!' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tNOTEQUAL);
default :
ungetChar(c);
return newConstantToken(IToken.tNOT);
}
case '=' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tEQUAL);
default :
ungetChar(c);
return newConstantToken(IToken.tASSIGN);
}
case '<' :
c = getChar();
switch (c) {
case '<' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tSHIFTLASSIGN);
default :
ungetChar(c);
return newConstantToken(IToken.tSHIFTL);
}
case '=' : return newConstantToken(IToken.tLTEQUAL);
// Diagraphs
case '%' : return newConstantToken(IToken.tLBRACE);
case ':' : return newConstantToken(IToken.tLBRACKET);
default :
ungetChar(c);
if( forInclusion )
temporarilyReplaceDefinitionsMap();
return newConstantToken(IToken.tLT);
}
case '>' :
c = getChar();
switch (c) {
case '>' :
c = getChar();
switch (c) {
case '=' : return newConstantToken(IToken.tSHIFTRASSIGN);
default :
ungetChar(c);
return newConstantToken(IToken.tSHIFTR);
}
case '=' : return newConstantToken(IToken.tGTEQUAL);
default :
ungetChar(c);
if( forInclusion )
restoreDefinitionsMap();
return newConstantToken(IToken.tGT);
}
case '.' :
c = getChar();
switch (c) {
case '.' :
c = getChar();
switch (c) {
case '.' : return newConstantToken(IToken.tELLIPSIS);
default :
// TODO : there is something missing here!
break;
}
break;
case '*' : return newConstantToken(IToken.tDOTSTAR);
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
ungetChar(c);
return processNumber('.', pasting);
default :
ungetChar(c);
return newConstantToken(IToken.tDOT);
}
break;
// The logic around the escape \ is fuzzy. There is code in getChar(boolean) and
// in consumeNewLineAfterSlash(). It currently works, but is fragile.
// case '\\' :
// c = consumeNewlineAfterSlash();
//
// // if we are left with the \ we can skip it.
// if (c == '\\')
// c = getChar();
// continue;
case '/' :
c = getChar();
switch (c) {
case '/' :
skipOverSinglelineComment();
c = getChar();
continue;
case '*' :
skipOverMultilineComment();
c = getChar();
continue;
case '=' : return newConstantToken(IToken.tDIVASSIGN);
default :
ungetChar(c);
return newConstantToken(IToken.tDIV);
}
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
token = processNumber(c, pasting);
if (token == null)
{
c = getChar();
continue;
}
return token;
case 'L' :
// check for wide literal
c = getChar();
if (c == '"')
token = processStringLiteral(true);
else if (c == '\'')
return processCharacterLiteral( c, true );
else
{
// This is not a wide literal -- it must be a token or keyword
ungetChar(c);
token = processKeywordOrIdentifier(new StringBuffer( "L"), pasting);
}
if (token == null)
{
c = getChar();
continue;
}
return token;
case '"' :
token = processStringLiteral(false);
if (token == null)
{
c = getChar();
continue;
}
return token;
case '\'' : return processCharacterLiteral( c, false );
case '#':
// This is a special case -- the preprocessor is integrated into
// the scanner. If we get a null token, it means that everything
// was handled correctly and we can go on to the next characgter.
token = processPreprocessor();
if (token == null)
{
c = getChar();
continue;
}
return token;
default:
if ( ( scannerExtension.offersDifferentIdentifierCharacters() &&
scannerExtension.isValidIdentifierStartCharacter(c) ) ||
isValidIdentifierStartCharacter(c) )
{
StringBuffer startBuffer = new StringBuffer( );
startBuffer.append( (char) c );
token = processKeywordOrIdentifier(startBuffer, pasting);
if (token == null)
{
c = getChar();
continue;
}
return token;
}
else if( c == '\\' )
{
int next = getChar();
StringBuffer ucnBuffer = new StringBuffer( "\\");
ucnBuffer.append( (char) next );
if( next == 'u' || next =='U' )
{
StringBuffer secondBuffer = processUniversalCharacterName(ucnBuffer);
if( secondBuffer == null )
{
handleProblem( IProblem.SCANNER_BAD_CHARACTER, ucnBuffer.toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead );
c = getChar();
continue;
}
else
{
token = processKeywordOrIdentifier( secondBuffer, pasting );
if (token == null)
{
c = getChar();
continue;
}
return token;
}
}
else
{
ungetChar( next );
handleProblem( IProblem.SCANNER_BAD_CHARACTER, ucnBuffer.toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead );
}
}
handleProblem( IProblem.SCANNER_BAD_CHARACTER, new Character( (char)c ).toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead );
c = getChar();
continue;
}
}
if (( getDepth() != 0) && !atEOF )
{
atEOF = true;
handleProblem( IProblem.SCANNER_UNEXPECTED_EOF, null, getCurrentOffset(), false, true );
}
// we're done
throwEOF(null);
return null;
}
/**
* @param c
* @return
*/
protected boolean isValidIdentifierStartCharacter(int c) {
return Character.isLetter((char)c) || ( c == '_');
}
/**
* @param definition
*/
protected void handleCompletionOnDefinition(String definition) throws EndOfFileException {
IASTCompletionNode node = new ASTCompletionNode( IASTCompletionNode.CompletionKind.MACRO_REFERENCE,
null, null, definition, KeywordSets.getKeywords(KeywordSets.Key.EMPTY, scannerData.getLanguage()), EMPTY_STRING );
throwEOF( node );
}
/**
* @param expression2
*/
protected void handleCompletionOnExpression(String expression) throws EndOfFileException {
int completionPoint = expression.length() + 2;
IASTCompletionNode.CompletionKind kind = IASTCompletionNode.CompletionKind.MACRO_REFERENCE;
String prefix = ""; //$NON-NLS-1$
if( ! expression.trim().equals("")) //$NON-NLS-1$
{
IScanner subScanner = new Scanner(
new StringReader(expression),
SCRATCH,
EMPTY_MAP,
EMPTY_LIST,
NULL_REQUESTOR,
ParserMode.QUICK_PARSE,
scannerData.getLanguage(),
NULL_LOG_SERVICE,
scannerExtension );
IToken lastToken = null;
while( true )
{
try
{
lastToken = subScanner.nextToken();
}
catch( EndOfFileException eof )
{
// ok
break;
} catch (ScannerException e) {
handleInternalError();
break;
}
}
if( ( lastToken != null ))
{
if( ( lastToken.getType() == IToken.tIDENTIFIER )
&& ( lastToken.getEndOffset() == completionPoint ) )
prefix = lastToken.getImage();
else if( ( lastToken.getEndOffset() == completionPoint ) &&
( lastToken.getType() != IToken.tIDENTIFIER ) )
kind = IASTCompletionNode.CompletionKind.NO_SUCH_KIND;
}
}
IASTCompletionNode node = new ASTCompletionNode( kind,
null, null, prefix,
KeywordSets.getKeywords(((kind == IASTCompletionNode.CompletionKind.NO_SUCH_KIND )? KeywordSets.Key.EMPTY : KeywordSets.Key.MACRO), scannerData.getLanguage()), EMPTY_STRING );
throwEOF( node );
}
protected void handleInvalidCompletion() throws EndOfFileException
{
throwEOF( new ASTCompletionNode( IASTCompletionNode.CompletionKind.UNREACHABLE_CODE, null, null, EMPTY_STRING, KeywordSets.getKeywords(KeywordSets.Key.EMPTY, scannerData.getLanguage()) , EMPTY_STRING));
}
protected void handleCompletionOnPreprocessorDirective( String prefix ) throws EndOfFileException
{
throwEOF( new ASTCompletionNode( IASTCompletionNode.CompletionKind.NO_SUCH_KIND, null, null, prefix, KeywordSets.getKeywords(KeywordSets.Key.PP_DIRECTIVE, scannerData.getLanguage() ), EMPTY_STRING));
}
/**
* @param key
*/
protected void removeSymbol(String key) {
scannerData.getDefinitions().remove(key);
}
/**
*
*/
protected void handlePragmaOperator() throws ScannerException, EndOfFileException
{
// until we know what to do with pragmas, do the equivalent as
// to what we do for #pragma blah blah blah (ignore it)
getRestOfPreprocessorLine();
}
/**
* @param c
* @param wideLiteral
*/
protected IToken processCharacterLiteral(int c, boolean wideLiteral)
throws ScannerException
{
int beginOffset = getCurrentOffset();
int type = wideLiteral ? IToken.tLCHAR : IToken.tCHAR;
StringBuffer buffer = new StringBuffer();
int prev = c;
int prevPrev = c;
c = getChar(true);
for( ; ; )
{
// error conditions
if( ( c == '\n' ) ||
( ( c == '\\' || c =='\'' )&& prev == '\\' ) ||
( c == NOCHAR ) )
{
handleProblem( IProblem.SCANNER_BAD_CHARACTER, new Character( (char)c ).toString(),beginOffset, false, true, throwExceptionOnBadCharacterRead );
c = '\'';
}
// exit condition
if ( ( c =='\'' ) && ( prev != '\\' || prevPrev == '\\' ) ) break;
buffer.append( (char)c);
prevPrev = prev;
prev = c;
c = getChar(true);
}
return newToken( type, buffer.toString());
}
protected String getCurrentFile()
{
return scannerData.getContextStack().getMostRelevantFileContext() != null ? scannerData.getContextStack().getMostRelevantFileContext().getFilename() : ""; //$NON-NLS-1$
}
protected int getCurrentOffset()
{
return scannerData.getContextStack().getMostRelevantFileContext() != null ? scannerData.getContextStack().getMostRelevantFileContext().getOffset() : -1;
}
protected static class endOfMacroTokenException extends Exception {}
// the static instance we always use
protected static endOfMacroTokenException endOfMacroToken = new endOfMacroTokenException();
public IToken nextTokenForStringizing() throws ScannerException, EndOfFileException
{
int beginOffset = getCurrentOffset();
int c = getChar();
StringBuffer tokenImage = new StringBuffer();
try {
while (c != NOCHAR) {
if ((c == ' ') || (c == '\r') || (c == '\t') || (c == '\n')) {
if (tokenImage.length() > 0) throw endOfMacroToken;
c = getChar();
continue;
} else if (c == '"') {
if (tokenImage.length() > 0) throw endOfMacroToken;
// string
StringBuffer buff = new StringBuffer();
c = getChar(true);
for( ; ; )
{
if ( c =='"' ) break;
if( c == NOCHAR) break;
buff.append((char) c);
c = getChar(true);
}
if (c != NOCHAR )
{
return newToken( IToken.tSTRING, buff.toString());
} else {
handleProblem( IProblem.SCANNER_UNBOUNDED_STRING, null, beginOffset, false, true );
c = getChar();
continue;
}
} else {
switch (c) {
case '\'' :
if (tokenImage.length() > 0) throw endOfMacroToken;
return processCharacterLiteral( c, false );
case ',' :
if (tokenImage.length() > 0) throw endOfMacroToken;
return newToken(IToken.tCOMMA, ","); //$NON-NLS-1$
case '(' :
if (tokenImage.length() > 0) throw endOfMacroToken;
return newToken(IToken.tLPAREN, "("); //$NON-NLS-1$
case ')' :
if (tokenImage.length() > 0) throw endOfMacroToken;
return newToken(IToken.tRPAREN, ")"); //$NON-NLS-1$
case '/' :
if (tokenImage.length() > 0) throw endOfMacroToken;
c = getChar();
switch (c) {
case '/' :
skipOverSinglelineComment();
c = getChar();
continue;
case '*' :
skipOverMultilineComment();
c = getChar();
continue;
default:
tokenImage.append('/');
continue;
}
default :
tokenImage.append((char)c);
c = getChar();
}
}
}
} catch (endOfMacroTokenException e) {
// unget the first character after the end of token
ungetChar(c);
}
// return completed token
if (tokenImage.length() > 0) {
return newToken(IToken.tIDENTIFIER, tokenImage.toString());
}
// we're done
throwEOF(null);
return null;
}
/**
*
*/
protected void throwEOF(IASTCompletionNode node) throws EndOfFileException, OffsetLimitReachedException {
if( node == null )
{
if( offsetLimit == NO_OFFSET_LIMIT )
throw new EndOfFileException();
if( finalToken != null && finalToken.getEndOffset() == offsetLimit )
throw new OffsetLimitReachedException(finalToken);
throw new OffsetLimitReachedException( (IToken)null );
}
throw new OffsetLimitReachedException( node );
}
static {
cppKeywords.put( Keywords.AND, new Integer(IToken.t_and));
cppKeywords.put( Keywords.AND_EQ, new Integer(IToken.t_and_eq));
cppKeywords.put( Keywords.ASM, new Integer(IToken.t_asm));
cppKeywords.put( Keywords.AUTO, new Integer(IToken.t_auto));
cppKeywords.put( Keywords.BITAND, new Integer(IToken.t_bitand));
cppKeywords.put( Keywords.BITOR, new Integer(IToken.t_bitor));
cppKeywords.put( Keywords.BOOL, new Integer(IToken.t_bool));
cppKeywords.put( Keywords.BREAK, new Integer(IToken.t_break));
cppKeywords.put( Keywords.CASE, new Integer(IToken.t_case));
cppKeywords.put( Keywords.CATCH, new Integer(IToken.t_catch));
cppKeywords.put( Keywords.CHAR, new Integer(IToken.t_char));
cppKeywords.put( Keywords.CLASS, new Integer(IToken.t_class));
cppKeywords.put( Keywords.COMPL, new Integer(IToken.t_compl));
cppKeywords.put( Keywords.CONST, new Integer(IToken.t_const));
cppKeywords.put( Keywords.CONST_CAST, new Integer(IToken.t_const_cast));
cppKeywords.put( Keywords.CONTINUE, new Integer(IToken.t_continue));
cppKeywords.put( Keywords.DEFAULT, new Integer(IToken.t_default));
cppKeywords.put( Keywords.DELETE, new Integer(IToken.t_delete));
cppKeywords.put( Keywords.DO, new Integer(IToken.t_do));
cppKeywords.put( Keywords.DOUBLE, new Integer(IToken.t_double));
cppKeywords.put( Keywords.DYNAMIC_CAST, new Integer(IToken.t_dynamic_cast));
cppKeywords.put( Keywords.ELSE, new Integer(IToken.t_else));
cppKeywords.put( Keywords.ENUM, new Integer(IToken.t_enum));
cppKeywords.put( Keywords.EXPLICIT, new Integer(IToken.t_explicit));
cppKeywords.put( Keywords.EXPORT, new Integer(IToken.t_export));
cppKeywords.put( Keywords.EXTERN, new Integer(IToken.t_extern));
cppKeywords.put( Keywords.FALSE, new Integer(IToken.t_false));
cppKeywords.put( Keywords.FLOAT, new Integer(IToken.t_float));
cppKeywords.put( Keywords.FOR, new Integer(IToken.t_for));
cppKeywords.put( Keywords.FRIEND, new Integer(IToken.t_friend));
cppKeywords.put( Keywords.GOTO, new Integer(IToken.t_goto));
cppKeywords.put( Keywords.IF, new Integer(IToken.t_if));
cppKeywords.put( Keywords.INLINE, new Integer(IToken.t_inline));
cppKeywords.put( Keywords.INT, new Integer(IToken.t_int));
cppKeywords.put( Keywords.LONG, new Integer(IToken.t_long));
cppKeywords.put( Keywords.MUTABLE, new Integer(IToken.t_mutable));
cppKeywords.put( Keywords.NAMESPACE, new Integer(IToken.t_namespace));
cppKeywords.put( Keywords.NEW, new Integer(IToken.t_new));
cppKeywords.put( Keywords.NOT, new Integer(IToken.t_not));
cppKeywords.put( Keywords.NOT_EQ, new Integer(IToken.t_not_eq));
cppKeywords.put( Keywords.OPERATOR, new Integer(IToken.t_operator));
cppKeywords.put( Keywords.OR, new Integer(IToken.t_or));
cppKeywords.put( Keywords.OR_EQ, new Integer(IToken.t_or_eq));
cppKeywords.put( Keywords.PRIVATE, new Integer(IToken.t_private));
cppKeywords.put( Keywords.PROTECTED, new Integer(IToken.t_protected));
cppKeywords.put( Keywords.PUBLIC, new Integer(IToken.t_public));
cppKeywords.put( Keywords.REGISTER, new Integer(IToken.t_register));
cppKeywords.put( Keywords.REINTERPRET_CAST, new Integer(IToken.t_reinterpret_cast));
cppKeywords.put( Keywords.RETURN, new Integer(IToken.t_return));
cppKeywords.put( Keywords.SHORT, new Integer(IToken.t_short));
cppKeywords.put( Keywords.SIGNED, new Integer(IToken.t_signed));
cppKeywords.put( Keywords.SIZEOF, new Integer(IToken.t_sizeof));
cppKeywords.put( Keywords.STATIC, new Integer(IToken.t_static));
cppKeywords.put( Keywords.STATIC_CAST, new Integer(IToken.t_static_cast));
cppKeywords.put( Keywords.STRUCT, new Integer(IToken.t_struct));
cppKeywords.put( Keywords.SWITCH, new Integer(IToken.t_switch));
cppKeywords.put( Keywords.TEMPLATE, new Integer(IToken.t_template));
cppKeywords.put( Keywords.THIS, new Integer(IToken.t_this));
cppKeywords.put( Keywords.THROW, new Integer(IToken.t_throw));
cppKeywords.put( Keywords.TRUE, new Integer(IToken.t_true));
cppKeywords.put( Keywords.TRY, new Integer(IToken.t_try));
cppKeywords.put( Keywords.TYPEDEF, new Integer(IToken.t_typedef));
cppKeywords.put( Keywords.TYPEID, new Integer(IToken.t_typeid));
cppKeywords.put( Keywords.TYPENAME, new Integer(IToken.t_typename));
cppKeywords.put( Keywords.UNION, new Integer(IToken.t_union));
cppKeywords.put( Keywords.UNSIGNED, new Integer(IToken.t_unsigned));
cppKeywords.put( Keywords.USING, new Integer(IToken.t_using));
cppKeywords.put( Keywords.VIRTUAL, new Integer(IToken.t_virtual));
cppKeywords.put( Keywords.VOID, new Integer(IToken.t_void));
cppKeywords.put( Keywords.VOLATILE, new Integer(IToken.t_volatile));
cppKeywords.put( Keywords.WCHAR_T, new Integer(IToken.t_wchar_t));
cppKeywords.put( Keywords.WHILE, new Integer(IToken.t_while));
cppKeywords.put( Keywords.XOR, new Integer(IToken.t_xor));
cppKeywords.put( Keywords.XOR_EQ, new Integer(IToken.t_xor_eq));
ppDirectives.put(Directives.POUND_DEFINE, new Integer(PreprocessorDirectives.DEFINE));
ppDirectives.put(Directives.POUND_UNDEF,new Integer(PreprocessorDirectives.UNDEFINE));
ppDirectives.put(Directives.POUND_IF, new Integer(PreprocessorDirectives.IF));
ppDirectives.put(Directives.POUND_IFDEF, new Integer(PreprocessorDirectives.IFDEF));
ppDirectives.put(Directives.POUND_IFNDEF, new Integer(PreprocessorDirectives.IFNDEF));
ppDirectives.put(Directives.POUND_ELSE, new Integer(PreprocessorDirectives.ELSE));
ppDirectives.put(Directives.POUND_ENDIF, new Integer(PreprocessorDirectives.ENDIF));
ppDirectives.put(Directives.POUND_INCLUDE, new Integer(PreprocessorDirectives.INCLUDE));
ppDirectives.put(Directives.POUND_LINE, new Integer(PreprocessorDirectives.LINE));
ppDirectives.put(Directives.POUND_ERROR, new Integer(PreprocessorDirectives.ERROR));
ppDirectives.put(Directives.POUND_PRAGMA, new Integer(PreprocessorDirectives.PRAGMA));
ppDirectives.put(Directives.POUND_ELIF, new Integer(PreprocessorDirectives.ELIF));
ppDirectives.put(Directives.POUND_BLANK, new Integer(PreprocessorDirectives.BLANK));
cKeywords.put( Keywords.AUTO, new Integer(IToken.t_auto));
cKeywords.put( Keywords.BREAK, new Integer(IToken.t_break));
cKeywords.put( Keywords.CASE, new Integer(IToken.t_case));
cKeywords.put( Keywords.CHAR, new Integer(IToken.t_char));
cKeywords.put( Keywords.CONST, new Integer(IToken.t_const));
cKeywords.put( Keywords.CONTINUE, new Integer(IToken.t_continue));
cKeywords.put( Keywords.DEFAULT, new Integer(IToken.t_default));
cKeywords.put( Keywords.DELETE, new Integer(IToken.t_delete));
cKeywords.put( Keywords.DO, new Integer(IToken.t_do));
cKeywords.put( Keywords.DOUBLE, new Integer(IToken.t_double));
cKeywords.put( Keywords.ELSE, new Integer(IToken.t_else));
cKeywords.put( Keywords.ENUM, new Integer(IToken.t_enum));
cKeywords.put( Keywords.EXTERN, new Integer(IToken.t_extern));
cKeywords.put( Keywords.FLOAT, new Integer(IToken.t_float));
cKeywords.put( Keywords.FOR, new Integer(IToken.t_for));
cKeywords.put( Keywords.GOTO, new Integer(IToken.t_goto));
cKeywords.put( Keywords.IF, new Integer(IToken.t_if));
cKeywords.put( Keywords.INLINE, new Integer(IToken.t_inline));
cKeywords.put( Keywords.INT, new Integer(IToken.t_int));
cKeywords.put( Keywords.LONG, new Integer(IToken.t_long));
cKeywords.put( Keywords.REGISTER, new Integer(IToken.t_register));
cKeywords.put( Keywords.RESTRICT, new Integer(IToken.t_restrict));
cKeywords.put( Keywords.RETURN, new Integer(IToken.t_return));
cKeywords.put( Keywords.SHORT, new Integer(IToken.t_short));
cKeywords.put( Keywords.SIGNED, new Integer(IToken.t_signed));
cKeywords.put( Keywords.SIZEOF, new Integer(IToken.t_sizeof));
cKeywords.put( Keywords.STATIC, new Integer(IToken.t_static));
cKeywords.put( Keywords.STRUCT, new Integer(IToken.t_struct));
cKeywords.put( Keywords.SWITCH, new Integer(IToken.t_switch));
cKeywords.put( Keywords.TYPEDEF, new Integer(IToken.t_typedef));
cKeywords.put( Keywords.UNION, new Integer(IToken.t_union));
cKeywords.put( Keywords.UNSIGNED, new Integer(IToken.t_unsigned));
cKeywords.put( Keywords.VOID, new Integer(IToken.t_void));
cKeywords.put( Keywords.VOLATILE, new Integer(IToken.t_volatile));
cKeywords.put( Keywords.WHILE, new Integer(IToken.t_while));
cKeywords.put( Keywords._BOOL, new Integer(IToken.t__Bool));
cKeywords.put( Keywords._COMPLEX, new Integer(IToken.t__Complex));
cKeywords.put( Keywords._IMAGINARY, new Integer(IToken.t__Imaginary));
}
static public class PreprocessorDirectives {
static public final int DEFINE = 0;
static public final int UNDEFINE = 1;
static public final int IF = 2;
static public final int IFDEF = 3;
static public final int IFNDEF = 4;
static public final int ELSE = 5;
static public final int ENDIF = 6;
static public final int INCLUDE = 7;
static public final int LINE = 8;
static public final int ERROR = 9;
static public final int PRAGMA = 10;
static public final int BLANK = 11;
static public final int ELIF = 12;
}
public final int getCount() {
return count;
}
public final int getDepth() {
return scannerData.getBranchTracker().getDepth();
}
protected boolean evaluateExpression(String expression, int beginningOffset )
throws ScannerException {
IExpressionParser parser = null;
StringBuffer expressionBuffer = new StringBuffer( expression );
expressionBuffer.append( ';');
IScanner trial = new Scanner(
new StringReader(expressionBuffer.toString()),
EXPRESSION,
scannerData.getDefinitions(),
scannerData.getIncludePathNames(),
NULL_REQUESTOR,
ParserMode.QUICK_PARSE,
scannerData.getLanguage(),
NULL_LOG_SERVICE,
scannerExtension );
parser = InternalParserUtil.createExpressionParser(trial, scannerData.getLanguage(), NULL_LOG_SERVICE);
try {
IASTExpression exp = parser.expression(null, null);
if( exp.evaluateExpression() == 0 )
return false;
return true;
} catch( BacktrackException backtrack )
{
if( scannerData.getParserMode() == ParserMode.QUICK_PARSE )
return false;
handleProblem( IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR, expression, beginningOffset, false, true );
}
catch (ASTExpressionEvaluationException e) {
if( scannerData.getParserMode() == ParserMode.QUICK_PARSE )
return false;
handleProblem( IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR, expression, beginningOffset, false, true );
} catch (EndOfFileException e) {
if( scannerData.getParserMode() == ParserMode.QUICK_PARSE )
return false;
handleProblem( IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR, expression, beginningOffset, false, true );
}
return true;
}
protected void skipOverSinglelineComment() throws ScannerException, EndOfFileException {
int c;
loop:
for (;;) {
c = getChar();
switch (c) {
case NOCHAR :
case '\n' :
break loop;
default :
break;
}
}
if( c== NOCHAR && isLimitReached() )
handleInvalidCompletion();
}
protected boolean skipOverMultilineComment() throws ScannerException, EndOfFileException {
int state = 0;
boolean encounteredNewline = false;
// simple state machine to handle multi-line comments
// state 0 == no end of comment in site
// state 1 == encountered *, expecting /
// state 2 == we are no longer in a comment
int c = getChar();
while (state != 2 && c != NOCHAR) {
if (c == '\n')
encounteredNewline = true;
switch (state) {
case 0 :
if (c == '*')
state = 1;
break;
case 1 :
if (c == '/')
state = 2;
else if (c != '*')
state = 0;
break;
}
c = getChar();
}
if (c == NOCHAR && !isLimitReached() )
handleProblem( IProblem.SCANNER_UNEXPECTED_EOF, null, getCurrentOffset(), false, true );
else if( c== NOCHAR ) // limit reached
handleInvalidCompletion();
ungetChar(c);
return encounteredNewline;
}
protected void poundInclude( int beginningOffset, int startLine ) throws ScannerException, EndOfFileException {
skipOverWhitespace();
int baseOffset = lastContext.getOffset() - lastContext.undoStackSize();
int nameLine = scannerData.getContextStack().getCurrentLineNumber();
String includeLine = getRestOfPreprocessorLine();
+ if( isLimitReached() )
+ handleInvalidCompletion();
+
int endLine = scannerData.getContextStack().getCurrentLineNumber();
ScannerUtility.InclusionDirective directive = null;
try
{
directive = ScannerUtility.parseInclusionDirective( scannerData, scannerExtension, includeLine, baseOffset );
}
catch( ScannerUtility.InclusionParseException ipe )
{
StringBuffer potentialErrorLine = new StringBuffer( "#include "); //$NON-NLS-1$
potentialErrorLine.append( includeLine );
handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, potentialErrorLine.toString(), beginningOffset, false, true );
return;
}
if( scannerData.getParserMode() == ParserMode.QUICK_PARSE )
{
if( scannerData.getClientRequestor() != null )
{
IASTInclusion i = null;
try
{
i =
scannerData.getASTFactory().createInclusion(
directive.getFilename(),
"", //$NON-NLS-1$
!directive.useIncludePaths(),
beginningOffset,
startLine,
directive.getStartOffset(),
directive.getStartOffset() + directive.getFilename().length(), nameLine, directive.getEndOffset(), endLine);
}
catch (Exception e)
{
/* do nothing */
}
if( i != null )
{
i.enterScope( scannerData.getClientRequestor() );
i.exitScope( scannerData.getClientRequestor() );
}
}
}
else
handleInclusion(directive.getFilename().trim(), directive.useIncludePaths(), beginningOffset, startLine, directive.getStartOffset(), nameLine, directive.getEndOffset(), endLine);
}
protected static final Hashtable EMPTY_MAP = new Hashtable();
protected static final List EMPTY_LIST = new ArrayList();
protected Map definitionsBackupMap = null;
protected void temporarilyReplaceDefinitionsMap()
{
definitionsBackupMap = scannerData.getDefinitions();
scannerData.setDefinitions( EMPTY_MAP );
}
protected void restoreDefinitionsMap()
{
scannerData.setDefinitions( definitionsBackupMap );
definitionsBackupMap = null;
}
protected boolean forInclusion = false;
private final static IParserLogService NULL_LOG_SERVICE = new NullLogService();
private static final String [] STRING_ARRAY = new String[0];
/**
* @param b
*/
protected void setForInclusion(boolean b)
{
forInclusion = b;
}
protected List tokenizeReplacementString( int beginning, String key, String replacementString, List parameterIdentifiers )
{
List macroReplacementTokens = new ArrayList();
if( replacementString.trim().equals( "" ) ) //$NON-NLS-1$
return macroReplacementTokens;
IScanner helperScanner=null;
try {
helperScanner = new Scanner(
new StringReader(replacementString),
SCRATCH,
EMPTY_MAP, EMPTY_LIST,
NULL_REQUESTOR,
scannerData.getParserMode(),
scannerData.getLanguage(),
NULL_LOG_SERVICE, scannerExtension);
} catch (ParserFactoryError e1) {
}
helperScanner.setTokenizingMacroReplacementList( true );
IToken t = null;
try {
t = helperScanner.nextToken(false);
} catch (ScannerException e) {
} catch (EndOfFileException e) {
}
if( t == null )
return macroReplacementTokens;
try {
while (true) {
//each # preprocessing token in the replacement list shall be followed
//by a parameter as the next reprocessing token in the list
if( t.getType() == tPOUND ){
macroReplacementTokens.add( t );
t = helperScanner.nextToken(false);
if( parameterIdentifiers != null )
{
int index = parameterIdentifiers.indexOf(t.getImage());
if (index == -1 ) {
//not found
if( beginning != NO_OFFSET_LIMIT )
{
StringBuffer buffer = new StringBuffer( POUND_DEFINE );
buffer.append( key );
buffer.append( ' ' );
buffer.append( replacementString );
handleProblem( IProblem.PREPROCESSOR_MACRO_PASTING_ERROR, buffer.toString(),
beginning, false, true );
return null;
}
}
}
}
macroReplacementTokens.add(t);
t = helperScanner.nextToken(false);
}
}
catch( EndOfFileException eof )
{
}
catch( ScannerException sc )
{
}
return macroReplacementTokens;
}
protected IMacroDescriptor createObjectMacroDescriptor(String key, String value ) {
IToken t = null;
if( !value.trim().equals( "" ) ) //$NON-NLS-1$
t = TokenFactory.createToken( IToken.tIDENTIFIER, value, scannerData );
return new ObjectMacroDescriptor( key,
t,
value);
}
protected void poundDefine(int beginning, int beginningLine ) throws ScannerException, EndOfFileException {
// definition
String key = getNextIdentifier();
int offset = scannerData.getContextStack().getCurrentContext().getOffset() - key.length() - scannerData.getContextStack().getCurrentContext().undoStackSize();
int nameLine = scannerData.getContextStack().getCurrentLineNumber();
// store the previous definition to check against later
IMacroDescriptor previousDefinition = getDefinition( key );
IMacroDescriptor descriptor = null;
// get the next character
// the C++ standard says that macros must not put
// whitespace between the end of the definition
// identifier and the opening parenthesis
int c = getChar();
if (c == '(') {
StringBuffer buffer = new StringBuffer();
c = getChar(true);
while (c != ')') {
if( c == '\\' ){
c = getChar();
if( c == '\r' )
c = getChar();
if( c == '\n' ){
c = getChar();
continue;
} else {
StringBuffer potentialErrorMessage = new StringBuffer( POUND_DEFINE );
ungetChar( c );
potentialErrorMessage.append( buffer );
potentialErrorMessage.append( '\\');
potentialErrorMessage.append( (char)c );
handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_DEFN, potentialErrorMessage.toString(), beginning, false, true);
return;
}
} else if( c == '\r' || c == '\n' ){
StringBuffer potentialErrorMessage = new StringBuffer( POUND_DEFINE );
potentialErrorMessage.append( buffer );
potentialErrorMessage.append( '\\');
potentialErrorMessage.append( (char)c );
handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_DEFN, potentialErrorMessage.toString(), beginning, false, true );
return;
} else if( c == NOCHAR ){
handleProblem( IProblem.SCANNER_UNEXPECTED_EOF, null, beginning, false, true );
return;
}
buffer.append((char) c);
c = getChar(true);
}
String parameters = buffer.toString();
// replace StringTokenizer later -- not performant
StringTokenizer tokenizer = new StringTokenizer(parameters, ","); //$NON-NLS-1$
ArrayList parameterIdentifiers =
new ArrayList(tokenizer.countTokens());
while (tokenizer.hasMoreTokens()) {
parameterIdentifiers.add(tokenizer.nextToken().trim());
}
skipOverWhitespace();
List macroReplacementTokens = null;
String replacementString = getRestOfPreprocessorLine();
// TODO: This tokenization could be done live, instead of using a sub-scanner.
macroReplacementTokens = ( ! replacementString.equals( "" ) ) ? //$NON-NLS-1$
tokenizeReplacementString( beginning, key, replacementString, parameterIdentifiers ) :
EMPTY_LIST;
descriptor = new FunctionMacroDescriptor(
key,
parameterIdentifiers,
macroReplacementTokens,
replacementString);
checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning);
addDefinition(key, descriptor);
}
else if ((c == '\n') || (c == '\r'))
{
descriptor = createObjectMacroDescriptor(key, ""); //$NON-NLS-1$
checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning);
addDefinition( key, descriptor );
}
else if ((c == ' ') || (c == '\t') ) {
// this is a simple definition
skipOverWhitespace();
// get what we are to map the name to and add it to the definitions list
String value = getRestOfPreprocessorLine();
descriptor = createObjectMacroDescriptor(key, value);
checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning);
addDefinition( key, descriptor );
} else if (c == '/') {
// this could be a comment
c = getChar();
if (c == '/') // one line comment
{
skipOverSinglelineComment();
descriptor = createObjectMacroDescriptor(key, ""); //$NON-NLS-1$
checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning);
addDefinition(key, descriptor);
} else if (c == '*') // multi-line comment
{
if (skipOverMultilineComment()) {
// we have gone over a newline
// therefore, this symbol was defined to an empty string
descriptor = createObjectMacroDescriptor(key, ""); //$NON-NLS-1$
checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning);
addDefinition(key, descriptor);
} else {
String value = getRestOfPreprocessorLine();
descriptor = createObjectMacroDescriptor(key, value);
checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning);
addDefinition(key, descriptor);
}
} else {
// this is not a comment
// it is a bad statement
StringBuffer potentialErrorMessage = new StringBuffer( POUND_DEFINE );
potentialErrorMessage.append( key );
potentialErrorMessage.append( " /"); //$NON-NLS-1$
potentialErrorMessage.append( getRestOfPreprocessorLine() );
handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_DEFN, potentialErrorMessage.toString(), beginning, false, true );
return;
}
} else {
StringBuffer potentialErrorMessage = new StringBuffer( POUND_DEFINE );
potentialErrorMessage.append( key );
potentialErrorMessage.append( (char)c );
potentialErrorMessage.append( getRestOfPreprocessorLine() );
handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_DEFN, potentialErrorMessage.toString(), beginning, false, true );
return;
}
try
{
scannerData.getASTFactory().createMacro( key, beginning, beginningLine, offset, offset + key.length(), nameLine, scannerData.getContextStack().getCurrentContext().getOffset(), scannerData.getContextStack().getCurrentLineNumber(), descriptor ).acceptElement( scannerData.getClientRequestor() );
}
catch (Exception e)
{
/* do nothing */
}
}
protected void checkValidMacroRedefinition(
String key,
IMacroDescriptor previousDefinition,
IMacroDescriptor newDefinition, int beginningOffset )
throws ScannerException
{
if( scannerData.getParserMode() != ParserMode.QUICK_PARSE && previousDefinition != null )
{
if( previousDefinition.compatible( newDefinition ) )
return;
handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_REDEFN, key, beginningOffset, false, true );
}
}
/**
*
*/
protected void handleInternalError() {
// TODO Auto-generated method stub
}
protected Vector getMacroParameters (String params, boolean forStringizing) throws ScannerException {
Scanner tokenizer = new Scanner(
new StringReader(params),
TEXT,
scannerData.getDefinitions(),
scannerData.getIncludePathNames(),
NULL_REQUESTOR,
scannerData.getParserMode(),
scannerData.getLanguage(),
NULL_LOG_SERVICE,
(IScannerExtension)scannerExtension.clone() );
tokenizer.setThrowExceptionOnBadCharacterRead(false);
Vector parameterValues = new Vector();
SimpleToken t = null;
StringBuffer buffer = new StringBuffer();
boolean space = false;
int nParen = 0;
try {
while (true) {
int c = tokenizer.getCharacter();
if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n')) {
space = false;
}
if (c != NOCHAR) tokenizer.ungetChar(c);
t = (SimpleToken)(forStringizing ? tokenizer.nextTokenForStringizing() : tokenizer.nextToken(false));
if (t.getType() == IToken.tLPAREN) {
nParen++;
} else if (t.getType() == IToken.tRPAREN) {
nParen--;
} else if (t.getType() == IToken.tCOMMA && nParen == 0) {
parameterValues.add(buffer.toString());
buffer = new StringBuffer();
space = false;
continue;
}
if (space)
buffer.append( ' ' );
switch (t.getType()) {
case IToken.tSTRING :
buffer.append('\"');
buffer.append(t.getImage());
buffer.append('\"');
break;
case IToken.tLSTRING :
buffer.append( "L\""); //$NON-NLS-1$
buffer.append(t.getImage());
buffer.append('\"');
break;
case IToken.tCHAR :
buffer.append('\'');
buffer.append(t.getImage());
buffer.append('\'');
break;
default :
buffer.append( t.getImage());
break;
}
space = true;
}
}
catch (EndOfFileException e) {
// Good
parameterValues.add(buffer.toString());
}
return parameterValues;
}
protected void expandDefinition(String symbol, String expansion, int symbolOffset ) throws ScannerException
{
expandDefinition( symbol,
new ObjectMacroDescriptor( symbol,
expansion ),
symbolOffset);
}
protected void expandDefinition(String symbol, IMacroDescriptor expansion, int symbolOffset)
throws ScannerException
{
// All the tokens generated by the macro expansion
// will have dimensions (offset and length) equal to the expanding symbol.
if ( expansion.getMacroType() == MacroType.OBJECT_LIKE || expansion.getMacroType() == MacroType.INTERNAL_LIKE ) {
String replacementValue = expansion.getExpansionSignature();
try
{
scannerData.getContextStack().updateContext(
new StringReader(replacementValue),
symbol, ScannerContext.ContextKind.MACROEXPANSION,
null,
scannerData.getClientRequestor(),
symbolOffset,
symbol.length());
}
catch (ContextException e)
{
handleProblem( e.getId(), scannerData.getContextStack().getCurrentContext().getFilename(), getCurrentOffset(), false, true );
consumeUntilOutOfMacroExpansion();
return;
}
} else if (expansion.getMacroType() == MacroType.FUNCTION_LIKE ) {
skipOverWhitespace();
int c = getChar();
if (c == '(') {
StringBuffer buffer = new StringBuffer();
int bracketCount = 1;
c = getChar();
while (true) {
if (c == '(')
++bracketCount;
else if (c == ')')
--bracketCount;
if(bracketCount == 0 || c == NOCHAR)
break;
buffer.append((char) c);
c = getChar( true );
}
// Position of the closing ')'
int endMacroOffset = lastContext.getOffset() - lastContext.undoStackSize() - 1;
String betweenTheBrackets = buffer.toString().trim();
Vector parameterValues = getMacroParameters(betweenTheBrackets, false);
Vector parameterValuesForStringizing = getMacroParameters(betweenTheBrackets, true);
SimpleToken t = null;
// create a string that represents what needs to be tokenized
buffer = new StringBuffer();
List tokens = expansion.getTokenizedExpansion();
List parameterNames = expansion.getParameters();
if (parameterNames.size() != parameterValues.size())
{
handleProblem( IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, symbol, getCurrentOffset(), false, true );
consumeUntilOutOfMacroExpansion();
return;
}
int numberOfTokens = tokens.size();
for (int i = 0; i < numberOfTokens; ++i) {
t = (SimpleToken) tokens.get(i);
if (t.getType() == IToken.tIDENTIFIER) {
// is this identifier in the parameterNames
// list?
int index = parameterNames.indexOf(t.getImage());
if (index == -1 ) {
// not found
// just add image to buffer
buffer.append(t.getImage() );
} else {
buffer.append(
(String) parameterValues.elementAt(index) );
}
} else if (t.getType() == tPOUND) {
//next token should be a parameter which needs to be turned into
//a string literal
t = (SimpleToken) tokens.get( ++i );
int index = parameterNames.indexOf(t.getImage());
if( index == -1 ){
handleProblem( IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, expansion.getName(), getCurrentOffset(), false, true );
return;
} else {
buffer.append('\"');
String value = (String)parameterValuesForStringizing.elementAt(index);
char val [] = value.toCharArray();
char ch;
int length = value.length();
for( int j = 0; j < length; j++ ){
ch = val[j];
if( ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' ){
//Each occurance of whitespace becomes a single space character
while( ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' ){
ch = val[++j];
}
buffer.append(' ');
}
//a \ character is inserted before each " and \
if( ch == '\"' || ch == '\\' ){
buffer.append('\\');
buffer.append(ch);
} else {
buffer.append(ch);
}
}
buffer.append('\"');
}
} else {
switch( t.getType() )
{
case IToken.tSTRING:
buffer.append('\"');
buffer.append(t.getImage());
buffer.append('\"');
break;
case IToken.tLSTRING:
buffer.append("L\""); //$NON-NLS-1$
buffer.append(t.getImage());
buffer.append('\"');
break;
case IToken.tCHAR:
buffer.append('\'');
buffer.append(t.getImage());
buffer.append('\'');
break;
default:
buffer.append(t.getImage());
break;
}
}
boolean pastingNext = false;
if( i != numberOfTokens - 1)
{
IToken t2 = (IToken) tokens.get(i+1);
if( t2.getType() == tPOUNDPOUND ) {
pastingNext = true;
i++;
}
}
if( t.getType() != tPOUNDPOUND && ! pastingNext )
if (i < (numberOfTokens-1)) // Do not append to the last one
buffer.append( " " ); //$NON-NLS-1$
}
String finalString = buffer.toString();
try
{
scannerData.getContextStack().updateContext(
new StringReader(finalString),
expansion.getName(),
ScannerContext.ContextKind.MACROEXPANSION,
null,
scannerData.getClientRequestor(),
symbolOffset,
endMacroOffset - symbolOffset + 1 );
}
catch (ContextException e)
{
handleProblem( e.getId(), scannerData.getContextStack().getCurrentContext().getFilename(), getCurrentOffset(), false, true );
consumeUntilOutOfMacroExpansion();
return;
}
} else
{
handleProblem( IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, symbol, getCurrentOffset(), false, true );
consumeUntilOutOfMacroExpansion();
return;
}
}
else {
TraceUtil.outputTrace(scannerData.getLogService(), "Unexpected type of MacroDescriptor stored in definitions table: ", null, expansion.getMacroType().toString(), null, null); //$NON-NLS-1$
}
}
protected String handleDefinedMacro() throws ScannerException {
int o = getCurrentOffset();
skipOverWhitespace();
int c = getChar();
String definitionIdentifier = null;
if (c == '(') {
definitionIdentifier = getNextIdentifier();
skipOverWhitespace();
c = getChar();
if (c != ')')
{
handleProblem( IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, "defined()", o, false, true ); //$NON-NLS-1$
return "0"; //$NON-NLS-1$
}
}
else
{
ungetChar(c);
definitionIdentifier = getNextIdentifier();
}
if (getDefinition(definitionIdentifier) != null)
return "1"; //$NON-NLS-1$
return "0"; //$NON-NLS-1$
}
public void setThrowExceptionOnBadCharacterRead( boolean throwOnBad ){
throwExceptionOnBadCharacterRead = throwOnBad;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IScanner#setASTFactory(org.eclipse.cdt.internal.core.parser.ast.IASTFactory)
*/
public void setASTFactory(IASTFactory f) {
scannerData.setASTFactory(f);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IScanner#setOffsetBoundary(int)
*/
public void setOffsetBoundary(int offset) {
offsetLimit = offset;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IScanner#getDefinitions()
*/
public Map getDefinitions() {
return Collections.unmodifiableMap(scannerData.getDefinitions());
}
/**
* @param b
*/
public void setOffsetLimitReached(boolean b) {
limitReached = b;
}
protected boolean isLimitReached()
{
if( offsetLimit == NO_OFFSET_LIMIT ) return false;
return limitReached;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IScanner#isOnTopContext()
*/
public boolean isOnTopContext() {
return ( scannerData.getContextStack().getCurrentContext() == scannerData.getContextStack().getTopContext() );
} /* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.IFilenameProvider#getCurrentFilename()
*/
public char[] getCurrentFilename() {
return getCurrentFile().toCharArray();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append( "Scanner @"); //$NON-NLS-1$
if( scannerData.getContextStack().getCurrentContext() != null )
buffer.append( scannerData.getContextStack().getCurrentContext().toString());
else
buffer.append( "EOF"); //$NON-NLS-1$
return buffer.toString();
}
}
| false | false | null | null |
diff --git a/src/test/java/org/bouncycastle/jce/provider/test/ECNRTest.java b/src/test/java/org/bouncycastle/jce/provider/test/ECNRTest.java
index 17357c826..dc60a5c7d 100644
--- a/src/test/java/org/bouncycastle/jce/provider/test/ECNRTest.java
+++ b/src/test/java/org/bouncycastle/jce/provider/test/ECNRTest.java
@@ -1,247 +1,247 @@
package org.bouncycastle.jce.provider.test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.util.BigIntegers;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.FixedSecureRandom;
import org.bouncycastle.util.test.SimpleTest;
public class ECNRTest
extends SimpleTest
{
byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3");
byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded");
SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 });
/**
* X9.62 - 1998,<br>
* J.3.2, Page 155, ECDSA over the field Fp<br>
* an example with 239 bit prime
*/
private void testECNR239bitPrime()
throws Exception
{
BigInteger r = new BigInteger("308636143175167811492623515537541734843573549327605293463169625072911693");
BigInteger s = new BigInteger("852401710738814635664888632022555967400445256405412579597015412971797143");
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));
SecureRandom k = new FixedSecureRandom(kData);
ECCurve curve = new ECCurve.Fp(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
ECParameterSpec spec = new ECParameterSpec(
curve,
curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
spec);
ECPublicKeySpec pubKey = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
spec);
Signature sgr = Signature.getInstance("SHA1withECNR", "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
checkSignature(239, priKey, pubKey, sgr, k, message, r, s);
}
// -------------------------------------------------------------------------
/**
* X9.62 - 1998,<br>
* Page 104-105, ECDSA over the field Fp<br>
* an example with 192 bit prime
*/
private void testECNR192bitPrime()
throws Exception
{
BigInteger r = new BigInteger("2474388605162950674935076940284692598330235697454145648371");
BigInteger s = new BigInteger("2997192822503471356158280167065034437828486078932532073836");
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("dcc5d1f1020906df2782360d36b2de7a17ece37d503784af", 16));
SecureRandom k = new FixedSecureRandom(kData);
ECCurve.Fp curve = new ECCurve.Fp(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q (or p)
new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", 16), // a
new BigInteger("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", 16)); // b
ECParameterSpec spec = new ECParameterSpec(
curve,
curve.decodePoint(Hex.decode("03188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012")), // G
new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
spec);
ECPublicKeySpec pubKey = new ECPublicKeySpec(
curve.decodePoint(Hex.decode("0262B12D60690CDCF330BABAB6E69763B471F994DD702D16A5")), // Q
spec);
Signature sgr = Signature.getInstance("SHA1withECNR", "BC");
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
checkSignature(192, priKey, pubKey, sgr, k, message, r, s);
}
// -------------------------------------------------------------------------
/**
* SEC 2: Recommended Elliptic Curve Domain Parameters - September 2000,<br>
* Page 17-19, Recommended 521-bit Elliptic Curve Domain Parameters over Fp<br>
* an ECC example with a 521 bit prime and a 512 bit hash
*/
private void testECNR521bitPrime()
throws Exception
{
BigInteger r = new BigInteger("1820641608112320695747745915744708800944302281118541146383656165330049339564439316345159057453301092391897040509935100825960342573871340486684575368150970954");
BigInteger s = new BigInteger("6358277176448326821136601602749690343031826490505780896013143436153111780706227024847359990383467115737705919410755190867632280059161174165591324242446800763");
byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("cdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", 16));
SecureRandom k = new FixedSecureRandom(kData);
ECCurve.Fp curve = new ECCurve.Fp(
new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p)
new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), // a
new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); // b
ECParameterSpec spec = new ECParameterSpec(
curve,
- curve.decodePoint(Hex.decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
+ curve.decodePoint(Hex.decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d
spec);
ECPublicKeySpec pubKey = new ECPublicKeySpec(
- curve.decodePoint(Hex.decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
+ curve.decodePoint(Hex.decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
spec);
Signature sgr = Signature.getInstance("SHA512withECNR", "BC");
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
checkSignature(521, priKey, pubKey, sgr, k, message, r, s);
}
private void checkSignature(
int size,
ECPrivateKeySpec priKey,
ECPublicKeySpec pubKey,
Signature sgr,
SecureRandom k,
byte[] message,
BigInteger r,
BigInteger s)
throws Exception
{
KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
PrivateKey sKey = f.generatePrivate(priKey);
PublicKey vKey = f.generatePublic(pubKey);
sgr.initSign(sKey, k);
sgr.update(message);
byte[] sigBytes = sgr.sign();
sgr.initVerify(vKey);
sgr.update(message);
if (!sgr.verify(sigBytes))
{
fail(size + " bit EC verification failed");
}
BigInteger[] sig = derDecode(sigBytes);
if (!r.equals(sig[0]))
{
fail(size + "bit"
+ ": r component wrong." + System.getProperty("line.separator")
+ " expecting: " + r + System.getProperty("line.separator")
+ " got : " + sig[0]);
}
if (!s.equals(sig[1]))
{
fail(size + "bit"
+ ": s component wrong." + System.getProperty("line.separator")
+ " expecting: " + s + System.getProperty("line.separator")
+ " got : " + sig[1]);
}
}
protected BigInteger[] derDecode(
byte[] encoding)
throws IOException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);
ASN1InputStream aIn = new ASN1InputStream(bIn);
ASN1Sequence s = (ASN1Sequence)aIn.readObject();
BigInteger[] sig = new BigInteger[2];
sig[0] = ((DERInteger)s.getObjectAt(0)).getValue();
sig[1] = ((DERInteger)s.getObjectAt(1)).getValue();
return sig;
}
public String getName()
{
return "ECNR";
}
public void performTest()
throws Exception
{
testECNR192bitPrime();
testECNR239bitPrime();
testECNR521bitPrime();
}
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new ECNRTest());
}
}
| false | false | null | null |
diff --git a/Neljansuora/src/datas/GUI.java b/Neljansuora/src/datas/GUI.java
index 21668f1..4c49a5e 100644
--- a/Neljansuora/src/datas/GUI.java
+++ b/Neljansuora/src/datas/GUI.java
@@ -1,112 +1,112 @@
package datas;
import javax.swing.*;
import java.awt.*;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map;
import java.util.Map.Entry;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.io.*;
public class GUI extends JFrame {
private Controller control;
private int move = 1;
private JPanel panel;
private JPanel frame;
private LinkedHashMap<Integer, JButton> images;
private Image cross;
private Image empty;
private Image circle;
private JButton restart;
private CrossListener listener = new CrossListener();
private JLabel info;
public void registerController(Controller inControl) {
this.control = inControl;
}
public GUI() {
setUp();
}
public void setUp() {
setTitle("Ristinolla");
panel = new JPanel(new GridLayout(10, 10));
try {
empty = ImageIO.read(new File("Blank.gif"));
cross = ImageIO.read(new File("Cross.gif"));
circle = ImageIO.read(new File("Circle.gif"));
} catch (IOException e) {
e.printStackTrace();
}
images = new LinkedHashMap<Integer, JButton>();
for (int i = 0; i < 100; i++) {
JButton b = new JButton(new ImageIcon(empty));
b.setContentAreaFilled(false);
b.addActionListener(listener);
b.setSize(20, 20);
images.put(i, b);
panel.add(b);
}
- info = new JLabel("Nollan Vuoro");
+ info = new JLabel("Ristin Vuoro");
frame = new JPanel(new BorderLayout());
frame.add(panel, BorderLayout.NORTH);
frame.add(info, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(frame);
setSize(500, 500);
setVisible(true);
}
public void makeCross(JButton button) {
if (move % 2 == 0) {
int newCircle = control.getAiMove();
images.put(newCircle,new JButton(new ImageIcon(circle)));
control.makeMove(newCircle,2);
info = new JLabel("Ristin vuoro");
refresh();
move++;
} else {
Set<Entry<Integer, JButton>> es = images.entrySet();
Iterator<Entry<Integer, JButton>> ei = es.iterator();
Map.Entry entry;
while (ei.hasNext()) {
entry = ei.next();
if (entry.getValue().equals(button)) {
int newCross = (Integer) entry.getKey();
images.put(newCross, new JButton(new ImageIcon(cross)));
control.makeMove(newCross,1);
info = new JLabel("Nollan vuoro");
refresh();
move++;
}
}
}
}
public void refresh() {
panel = new JPanel(new GridLayout(10, 10));
Set<Entry<Integer, JButton>> es = images.entrySet();
Iterator<Entry<Integer, JButton>> ei = es.iterator();
while (ei.hasNext()) {
panel.add(ei.next().getValue());
}
frame = new JPanel(new BorderLayout());
frame.add(panel, BorderLayout.NORTH);
frame.add(info, BorderLayout.SOUTH);
setContentPane(frame);
setVisible(true);
}
private class CrossListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
makeCross((JButton) e.getSource());
}
}
}
| true | true | public void setUp() {
setTitle("Ristinolla");
panel = new JPanel(new GridLayout(10, 10));
try {
empty = ImageIO.read(new File("Blank.gif"));
cross = ImageIO.read(new File("Cross.gif"));
circle = ImageIO.read(new File("Circle.gif"));
} catch (IOException e) {
e.printStackTrace();
}
images = new LinkedHashMap<Integer, JButton>();
for (int i = 0; i < 100; i++) {
JButton b = new JButton(new ImageIcon(empty));
b.setContentAreaFilled(false);
b.addActionListener(listener);
b.setSize(20, 20);
images.put(i, b);
panel.add(b);
}
info = new JLabel("Nollan Vuoro");
frame = new JPanel(new BorderLayout());
frame.add(panel, BorderLayout.NORTH);
frame.add(info, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(frame);
setSize(500, 500);
setVisible(true);
}
| public void setUp() {
setTitle("Ristinolla");
panel = new JPanel(new GridLayout(10, 10));
try {
empty = ImageIO.read(new File("Blank.gif"));
cross = ImageIO.read(new File("Cross.gif"));
circle = ImageIO.read(new File("Circle.gif"));
} catch (IOException e) {
e.printStackTrace();
}
images = new LinkedHashMap<Integer, JButton>();
for (int i = 0; i < 100; i++) {
JButton b = new JButton(new ImageIcon(empty));
b.setContentAreaFilled(false);
b.addActionListener(listener);
b.setSize(20, 20);
images.put(i, b);
panel.add(b);
}
info = new JLabel("Ristin Vuoro");
frame = new JPanel(new BorderLayout());
frame.add(panel, BorderLayout.NORTH);
frame.add(info, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(frame);
setSize(500, 500);
setVisible(true);
}
|
diff --git a/java/target/src/test/testrt/PeriodicUnrel.java b/java/target/src/test/testrt/PeriodicUnrel.java
index 89001151..ea4bb3bb 100644
--- a/java/target/src/test/testrt/PeriodicUnrel.java
+++ b/java/target/src/test/testrt/PeriodicUnrel.java
@@ -1,63 +1,61 @@
package testrt;
import util.*;
import joprt.*;
import com.jopdesign.sys.*;
// use differnet (unrelated) period to find WC Jitter
public class PeriodicUnrel {
static class Busy extends RtThread {
private int c;
Busy(int per, int ch) {
super(5, per);
c = ch;
}
public void run() {
for (;;) {
// Dbg.wr(c);
waitForNextPeriod();
}
}
}
public static void main(String[] args) {
Dbg.initSer(); // use serial line for debug output
RtThread rt = new RtThread(10, 100000) {
public void run() {
waitForNextPeriod();
int ts_old = Native.rd(Const.IO_US_CNT);
for (;;) {
waitForNextPeriod();
int ts = Native.rd(Const.IO_US_CNT);
Result.printPeriod(ts_old, ts);
ts_old = ts;
}
}
};
int i;
for (i=0; i<10; ++i) {
new Busy(2345+456*i, i+'a');
}
RtThread.startMission();
-RtThread.debug();
// sleep
for (;;) {
-// RtThread.debug();
-Dbg.wr('M');
+ Dbg.wr('M');
Timer.wd();
-for (;;) ;
+ for (;;) ;
// try { Thread.sleep(1200); } catch (Exception e) {}
}
}
}
| false | true | public static void main(String[] args) {
Dbg.initSer(); // use serial line for debug output
RtThread rt = new RtThread(10, 100000) {
public void run() {
waitForNextPeriod();
int ts_old = Native.rd(Const.IO_US_CNT);
for (;;) {
waitForNextPeriod();
int ts = Native.rd(Const.IO_US_CNT);
Result.printPeriod(ts_old, ts);
ts_old = ts;
}
}
};
int i;
for (i=0; i<10; ++i) {
new Busy(2345+456*i, i+'a');
}
RtThread.startMission();
RtThread.debug();
// sleep
for (;;) {
// RtThread.debug();
Dbg.wr('M');
Timer.wd();
for (;;) ;
// try { Thread.sleep(1200); } catch (Exception e) {}
}
}
| public static void main(String[] args) {
Dbg.initSer(); // use serial line for debug output
RtThread rt = new RtThread(10, 100000) {
public void run() {
waitForNextPeriod();
int ts_old = Native.rd(Const.IO_US_CNT);
for (;;) {
waitForNextPeriod();
int ts = Native.rd(Const.IO_US_CNT);
Result.printPeriod(ts_old, ts);
ts_old = ts;
}
}
};
int i;
for (i=0; i<10; ++i) {
new Busy(2345+456*i, i+'a');
}
RtThread.startMission();
// sleep
for (;;) {
Dbg.wr('M');
Timer.wd();
for (;;) ;
// try { Thread.sleep(1200); } catch (Exception e) {}
}
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/evaluator/costmodel/DefaultCostModel.java b/src/de/uni_koblenz/jgralab/greql2/evaluator/costmodel/DefaultCostModel.java
index 6e27ec6d2..591e77c1c 100644
--- a/src/de/uni_koblenz/jgralab/greql2/evaluator/costmodel/DefaultCostModel.java
+++ b/src/de/uni_koblenz/jgralab/greql2/evaluator/costmodel/DefaultCostModel.java
@@ -1,1760 +1,1762 @@
/*
* JGraLab - The Java graph laboratory
* (c) 2006-2009 Institute for Software Technology
* University of Koblenz-Landau, Germany
*
* [email protected]
*
* Please report bugs to http://serres.uni-koblenz.de/bugzilla
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package de.uni_koblenz.jgralab.greql2.evaluator.costmodel;
import java.util.ArrayList;
import java.util.logging.Logger;
import de.uni_koblenz.jgralab.EdgeDirection;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.greql2.evaluator.GreqlEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.AggregationPathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.AlternativePathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.BackwardVertexSetEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.BagComprehensionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.BagConstructionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.ConditionalExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.DeclarationEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.DefinitionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.EdgePathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.EdgeRestrictionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.EdgeSetExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.EdgeSubgraphExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.ExponentiatedPathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.ForwardVertexSetEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.FunctionApplicationEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.Greql2ExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.IntLiteralEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.IntermediateVertexPathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.IteratedPathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.LetExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.ListConstructionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.ListRangeConstructionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.MapComprehensionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.MapConstructionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.OptionalPathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.PathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.PathExistenceEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.QuantifiedExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.RecordConstructionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.RecordElementEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.RestrictedExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.SequentialPathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.SetComprehensionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.SetConstructionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.SimpleDeclarationEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.SimplePathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.TableComprehensionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.TransposedPathDescriptionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.TupleConstructionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.TypeIdEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.VariableEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.VertexEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.VertexSetExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.VertexSubgraphExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.WhereExpressionEvaluator;
import de.uni_koblenz.jgralab.greql2.funlib.Greql2Function;
import de.uni_koblenz.jgralab.greql2.schema.AlternativePathDescription;
import de.uni_koblenz.jgralab.greql2.schema.BackwardVertexSet;
import de.uni_koblenz.jgralab.greql2.schema.BagComprehension;
import de.uni_koblenz.jgralab.greql2.schema.BagConstruction;
import de.uni_koblenz.jgralab.greql2.schema.ConditionalExpression;
import de.uni_koblenz.jgralab.greql2.schema.Declaration;
import de.uni_koblenz.jgralab.greql2.schema.Definition;
import de.uni_koblenz.jgralab.greql2.schema.EdgePathDescription;
import de.uni_koblenz.jgralab.greql2.schema.EdgeRestriction;
import de.uni_koblenz.jgralab.greql2.schema.EdgeSetExpression;
import de.uni_koblenz.jgralab.greql2.schema.EdgeSubgraphExpression;
import de.uni_koblenz.jgralab.greql2.schema.ExponentiatedPathDescription;
import de.uni_koblenz.jgralab.greql2.schema.Expression;
import de.uni_koblenz.jgralab.greql2.schema.ForwardVertexSet;
import de.uni_koblenz.jgralab.greql2.schema.FunctionApplication;
import de.uni_koblenz.jgralab.greql2.schema.Greql2Expression;
import de.uni_koblenz.jgralab.greql2.schema.IntermediateVertexPathDescription;
import de.uni_koblenz.jgralab.greql2.schema.IsAlternativePathOf;
import de.uni_koblenz.jgralab.greql2.schema.IsArgumentOf;
import de.uni_koblenz.jgralab.greql2.schema.IsBoundVarOf;
import de.uni_koblenz.jgralab.greql2.schema.IsConstraintOf;
import de.uni_koblenz.jgralab.greql2.schema.IsDeclaredVarOf;
import de.uni_koblenz.jgralab.greql2.schema.IsDefinitionOf;
import de.uni_koblenz.jgralab.greql2.schema.IsFalseExprOf;
import de.uni_koblenz.jgralab.greql2.schema.IsKeyExprOfConstruction;
import de.uni_koblenz.jgralab.greql2.schema.IsNullExprOf;
import de.uni_koblenz.jgralab.greql2.schema.IsPartOf;
import de.uni_koblenz.jgralab.greql2.schema.IsRecordElementOf;
import de.uni_koblenz.jgralab.greql2.schema.IsRecordExprOf;
import de.uni_koblenz.jgralab.greql2.schema.IsSequenceElementOf;
import de.uni_koblenz.jgralab.greql2.schema.IsSimpleDeclOf;
import de.uni_koblenz.jgralab.greql2.schema.IsSubPathOf;
import de.uni_koblenz.jgralab.greql2.schema.IsTrueExprOf;
import de.uni_koblenz.jgralab.greql2.schema.IsTypeRestrOf;
import de.uni_koblenz.jgralab.greql2.schema.IsValueExprOfConstruction;
import de.uni_koblenz.jgralab.greql2.schema.IteratedPathDescription;
import de.uni_koblenz.jgralab.greql2.schema.LetExpression;
import de.uni_koblenz.jgralab.greql2.schema.ListConstruction;
import de.uni_koblenz.jgralab.greql2.schema.ListRangeConstruction;
import de.uni_koblenz.jgralab.greql2.schema.MapComprehension;
import de.uni_koblenz.jgralab.greql2.schema.MapConstruction;
import de.uni_koblenz.jgralab.greql2.schema.OptionalPathDescription;
import de.uni_koblenz.jgralab.greql2.schema.PathDescription;
import de.uni_koblenz.jgralab.greql2.schema.PathExistence;
import de.uni_koblenz.jgralab.greql2.schema.QuantifiedExpression;
import de.uni_koblenz.jgralab.greql2.schema.RecordConstruction;
import de.uni_koblenz.jgralab.greql2.schema.RecordElement;
import de.uni_koblenz.jgralab.greql2.schema.RestrictedExpression;
import de.uni_koblenz.jgralab.greql2.schema.SequentialPathDescription;
import de.uni_koblenz.jgralab.greql2.schema.SetComprehension;
import de.uni_koblenz.jgralab.greql2.schema.SetConstruction;
import de.uni_koblenz.jgralab.greql2.schema.SimpleDeclaration;
import de.uni_koblenz.jgralab.greql2.schema.TableComprehension;
import de.uni_koblenz.jgralab.greql2.schema.TransposedPathDescription;
import de.uni_koblenz.jgralab.greql2.schema.TupleConstruction;
import de.uni_koblenz.jgralab.greql2.schema.TypeId;
import de.uni_koblenz.jgralab.greql2.schema.Variable;
import de.uni_koblenz.jgralab.greql2.schema.VertexSetExpression;
import de.uni_koblenz.jgralab.greql2.schema.VertexSubgraphExpression;
import de.uni_koblenz.jgralab.greql2.schema.WhereExpression;
/**
* This is the default costmodel the evaluator uses if no other costmodel is
* set.
*
* @author [email protected]
*
*/
public class DefaultCostModel extends CostModelBase implements CostModel {
private static Logger logger = Logger.getLogger(DefaultCostModel.class
.getName());
/**
* Nullary constructor needed for reflective instantiation. Creates a
* non-functional CostModel.
*/
public DefaultCostModel() {
}
/**
* Creates a new CostModel for a graph whose {@link GreqlEvaluator} is given
* here.
*
* @param eval
* a {@link GreqlEvaluator}
*/
public DefaultCostModel(GreqlEvaluator eval) {
greqlEvaluator = eval;
}
@Override
public long calculateCardinalityBackwardVertexSet(
BackwardVertexSetEvaluator e, GraphSize graphSize) {
// TODO Auto-generated method stub
return 5;
}
@Override
public long calculateCardinalityBagComprehension(
BagComprehensionEvaluator e, GraphSize graphSize) {
BagComprehension bagComp = (BagComprehension) e.getVertex();
Declaration decl = (Declaration) bagComp.getFirstIsCompDeclOf()
.getAlpha();
DeclarationEvaluator declEval = (DeclarationEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(decl);
return declEval.getEstimatedCardinality(graphSize);
}
@Override
public long calculateCardinalityBagConstruction(BagConstructionEvaluator e,
GraphSize graphSize) {
BagConstruction bagCons = (BagConstruction) e.getVertex();
IsPartOf inc = bagCons.getFirstIsPartOf();
long parts = 0;
while (inc != null) {
parts++;
inc = inc.getNextIsPartOf();
}
return parts;
}
@Override
public long calculateCardinalityConditionalExpression(
ConditionalExpressionEvaluator e, GraphSize graphSize) {
ConditionalExpression condExp = (ConditionalExpression) e.getVertex();
IsTrueExprOf trueInc = condExp.getFirstIsTrueExprOf();
long trueCard = 0;
if (trueInc != null) {
VertexEvaluator trueEval = greqlEvaluator
.getVertexEvaluatorGraphMarker()
.getMark(trueInc.getAlpha());
trueCard = trueEval.getEstimatedCardinality(graphSize);
}
IsFalseExprOf falseInc = condExp.getFirstIsFalseExprOf();
long falseCard = 0;
if (falseInc != null) {
VertexEvaluator falseEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
falseInc.getAlpha());
falseCard = falseEval.getEstimatedCardinality(graphSize);
}
IsNullExprOf nullInc = condExp.getFirstIsNullExprOf();
long nullCard = 0;
if (falseInc != null) {
VertexEvaluator nullEval = greqlEvaluator
.getVertexEvaluatorGraphMarker()
.getMark(nullInc.getAlpha());
nullCard = nullEval.getEstimatedCardinality(graphSize);
}
long maxCard = trueCard;
if (falseCard > maxCard) {
maxCard = falseCard;
}
if (nullCard > maxCard) {
maxCard = nullCard;
}
return maxCard;
}
@Override
public long calculateCardinalityDeclaration(DeclarationEvaluator e,
GraphSize graphSize) {
Declaration decl = (Declaration) e.getVertex();
IsConstraintOf inc = decl.getFirstIsConstraintOf(EdgeDirection.IN);
double selectivity = 1.0;
while (inc != null) {
VertexEvaluator constEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
selectivity *= constEval.getEstimatedSelectivity(graphSize);
inc = inc.getNextIsConstraintOf(EdgeDirection.IN);
}
return Math.round(e.getDefinedVariableCombinations(graphSize)
* selectivity);
}
@Override
public long calculateCardinalityEdgeSetExpression(
EdgeSetExpressionEvaluator e, GraphSize graphSize) {
EdgeSetExpression exp = (EdgeSetExpression) e.getVertex();
IsTypeRestrOf inc = exp.getFirstIsTypeRestrOf();
double selectivity = 1.0;
if (inc != null) {
TypeIdEvaluator typeIdEval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
selectivity = typeIdEval.getEstimatedSelectivity(graphSize);
}
return Math.round(graphSize.getEdgeCount() * selectivity);
}
@Override
public long calculateCardinalityEdgeSubgraphExpression(
EdgeSubgraphExpressionEvaluator e, GraphSize graphSize) {
EdgeSubgraphExpression exp = (EdgeSubgraphExpression) e.getVertex();
IsTypeRestrOf inc = exp.getFirstIsTypeRestrOf();
double selectivity = 1.0;
if (inc != null) {
TypeIdEvaluator typeIdEval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
selectivity = typeIdEval.getEstimatedSelectivity(graphSize);
}
return Math.round((graphSize.getEdgeCount() + graphSize
.getVertexCount())
* selectivity);
}
@Override
public long calculateCardinalityForwardVertexSet(
ForwardVertexSetEvaluator e, GraphSize graphSize) {
// TODO Auto-generated method stub
return 5;
}
@Override
public long calculateCardinalityFunctionApplication(
FunctionApplicationEvaluator e, GraphSize graphSize) {
FunctionApplication funApp = (FunctionApplication) e.getVertex();
IsArgumentOf inc = funApp.getFirstIsArgumentOf(EdgeDirection.IN);
int elements = 0;
while (inc != null) {
VertexEvaluator argEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
elements += argEval.getEstimatedCardinality(graphSize);
inc = inc.getNextIsArgumentOf(EdgeDirection.IN);
}
Greql2Function func = e.getGreql2Function();
if (func != null) {
return func.getEstimatedCardinality(elements);
} else {
return 1;
}
}
@Override
public long calculateCardinalityListConstruction(
ListConstructionEvaluator e, GraphSize graphSize) {
ListConstruction listCons = (ListConstruction) e.getVertex();
IsPartOf inc = listCons.getFirstIsPartOf();
long parts = 0;
while (inc != null) {
parts++;
inc = inc.getNextIsPartOf();
}
return parts;
}
@Override
public long calculateCardinalityListRangeConstruction(
ListRangeConstructionEvaluator e, GraphSize graphSize) {
ListRangeConstruction exp = (ListRangeConstruction) e.getVertex();
VertexEvaluator startExpEval = greqlEvaluator
.getVertexEvaluatorGraphMarker()
.getMark(
exp.getFirstIsFirstValueOf(EdgeDirection.IN).getAlpha());
VertexEvaluator targetExpEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
exp.getFirstIsLastValueOf(EdgeDirection.IN).getAlpha());
long range = 0;
if (startExpEval instanceof IntLiteralEvaluator) {
if (targetExpEval instanceof IntLiteralEvaluator) {
try {
range = targetExpEval.getResult(null).toInteger()
- startExpEval.getResult(null).toInteger() + 1;
} catch (Exception ex) {
// if an exception occurs, the default value is used, so no
// exceptionhandling is needed
}
}
}
if (range > 0) {
return range;
} else {
return defaultListRangeSize;
}
}
@Override
public long calculateCardinalityRecordConstruction(
RecordConstructionEvaluator e, GraphSize graphSize) {
RecordConstruction recCons = (RecordConstruction) e.getVertex();
IsRecordElementOf inc = recCons
.getFirstIsRecordElementOf(EdgeDirection.IN);
long parts = 0;
while (inc != null) {
parts++;
inc = inc.getNextIsRecordElementOf(EdgeDirection.IN);
}
return parts;
}
@Override
public long calculateCardinalitySetComprehension(
SetComprehensionEvaluator e, GraphSize graphSize) {
SetComprehension setComp = (SetComprehension) e.getVertex();
Declaration decl = (Declaration) setComp.getFirstIsCompDeclOf()
.getAlpha();
DeclarationEvaluator declEval = (DeclarationEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(decl);
return declEval.getEstimatedCardinality(graphSize);
}
@Override
public long calculateCardinalitySetConstruction(SetConstructionEvaluator e,
GraphSize graphSize) {
SetConstruction setCons = (SetConstruction) e.getVertex();
IsPartOf inc = setCons.getFirstIsPartOf();
long parts = 0;
while (inc != null) {
parts++;
inc = inc.getNextIsPartOf();
}
return parts;
}
@Override
public long calculateCardinalitySimpleDeclaration(
SimpleDeclarationEvaluator e, GraphSize graphSize) {
SimpleDeclaration decl = (SimpleDeclaration) e.getVertex();
VertexEvaluator typeExprEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
decl.getFirstIsTypeExprOf(EdgeDirection.IN).getAlpha());
long singleCardinality = typeExprEval
.getEstimatedCardinality(graphSize);
long wholeCardinality = singleCardinality
* e.getDefinedVariables().size();
return wholeCardinality;
}
@Override
public long calculateCardinalityTableComprehension(
TableComprehensionEvaluator e, GraphSize graphSize) {
TableComprehension tableComp = (TableComprehension) e.getVertex();
Declaration decl = (Declaration) tableComp.getFirstIsCompDeclOf()
.getAlpha();
DeclarationEvaluator declEval = (DeclarationEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(decl);
return declEval.getEstimatedCardinality(graphSize);
}
@Override
public long calculateCardinalityTupleConstruction(
TupleConstructionEvaluator e, GraphSize graphSize) {
TupleConstruction tupleCons = (TupleConstruction) e.getVertex();
IsPartOf inc = tupleCons.getFirstIsPartOf(EdgeDirection.IN);
long parts = 0;
while (inc != null) {
parts++;
inc = inc.getNextIsPartOf(EdgeDirection.IN);
}
return parts;
}
@Override
public long calculateCardinalityVertexSetExpression(
VertexSetExpressionEvaluator e, GraphSize graphSize) {
VertexSetExpression exp = (VertexSetExpression) e.getVertex();
IsTypeRestrOf inc = exp.getFirstIsTypeRestrOf();
double selectivity = 1.0;
if (inc != null) {
TypeIdEvaluator typeIdEval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
selectivity = typeIdEval.getEstimatedSelectivity(graphSize);
}
return Math.round(graphSize.getVertexCount() * selectivity);
}
@Override
public long calculateCardinalityVertexSubgraphExpression(
VertexSubgraphExpressionEvaluator e, GraphSize graphSize) {
VertexSubgraphExpression exp = (VertexSubgraphExpression) e.getVertex();
IsTypeRestrOf inc = exp.getFirstIsTypeRestrOf();
double selectivity = 1.0;
if (inc != null) {
TypeIdEvaluator typeIdEval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
selectivity = typeIdEval.getEstimatedSelectivity(graphSize);
}
return Math.round((graphSize.getEdgeCount() + graphSize
.getVertexCount())
* selectivity);
}
@Override
public VertexCosts calculateCostsAlternativePathDescription(
AlternativePathDescriptionEvaluator e, GraphSize graphSize) {
AlternativePathDescription p = (AlternativePathDescription) e
.getVertex();
long aggregatedCosts = 0;
IsAlternativePathOf inc = p.getFirstIsAlternativePathOf();
long alternatives = 0;
while (inc != null) {
PathDescriptionEvaluator pathEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
aggregatedCosts += pathEval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsAlternativePathOf();
alternatives++;
}
aggregatedCosts += 10 * alternatives;
return new VertexCosts(10 * alternatives, 10 * alternatives,
aggregatedCosts);
}
@Override
public VertexCosts calculateCostsBackwardVertexSet(
BackwardVertexSetEvaluator e, GraphSize graphSize) {
BackwardVertexSet bwvertex = (BackwardVertexSet) e.getVertex();
Expression targetExpression = (Expression) bwvertex
.getFirstIsTargetExprOf().getAlpha();
VertexEvaluator vertexEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(targetExpression);
long targetCosts = vertexEval
.getCurrentSubtreeEvaluationCosts(graphSize);
PathDescription p = (PathDescription) bwvertex.getFirstIsPathOf()
.getAlpha();
PathDescriptionEvaluator pathDescEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(p);
long pathDescCosts = pathDescEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long searchCosts = Math.round(pathDescCosts * searchFactor
* Math.sqrt(graphSize.getEdgeCount()));
long ownCosts = searchCosts;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = targetCosts + pathDescCosts + iteratedCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsBagComprehension
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .BagComprehensionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsBagComprehension(
BagComprehensionEvaluator e, GraphSize graphSize) {
BagComprehension bagComp = (BagComprehension) e.getVertex();
Declaration decl = (Declaration) bagComp.getFirstIsCompDeclOf()
.getAlpha();
DeclarationEvaluator declEval = (DeclarationEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(decl);
long declCosts = declEval.getCurrentSubtreeEvaluationCosts(graphSize);
Vertex resultDef = bagComp.getFirstIsCompResultDefOf().getAlpha();
VertexEvaluator resultDefEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(resultDef);
long resultCosts = resultDefEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = declEval.getEstimatedCardinality(graphSize)
* addToBagCosts;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + resultCosts + declCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsBagConstruction
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .BagConstructionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsBagConstruction(
BagConstructionEvaluator e, GraphSize graphSize) {
BagConstruction bagCons = (BagConstruction) e.getVertex();
IsPartOf inc = bagCons.getFirstIsPartOf(EdgeDirection.IN);
long parts = 0;
long partCosts = 0;
while (inc != null) {
parts++;
VertexEvaluator partEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
partCosts += partEval.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsPartOf(EdgeDirection.IN);
}
long ownCosts = parts * addToBagCosts + 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + partCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsConditionalExpression(
ConditionalExpressionEvaluator e, GraphSize graphSize) {
ConditionalExpression vertex = (ConditionalExpression) e.getVertex();
Expression condition = (Expression) vertex.getFirstIsConditionOf()
.getAlpha();
VertexEvaluator conditionEvaluator = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(condition);
long conditionCosts = conditionEvaluator
.getCurrentSubtreeEvaluationCosts(graphSize);
Expression expressionToEvaluate;
expressionToEvaluate = (Expression) vertex.getFirstIsTrueExprOf()
.getAlpha();
VertexEvaluator vertexEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(expressionToEvaluate);
long trueCosts = vertexEval.getCurrentSubtreeEvaluationCosts(graphSize);
expressionToEvaluate = (Expression) vertex.getFirstIsFalseExprOf()
.getAlpha();
vertexEval = greqlEvaluator.getVertexEvaluatorGraphMarker().getMark(
expressionToEvaluate);
long falseCosts = vertexEval
.getCurrentSubtreeEvaluationCosts(graphSize);
expressionToEvaluate = (Expression) vertex.getFirstIsNullExprOf()
.getAlpha();
vertexEval = greqlEvaluator.getVertexEvaluatorGraphMarker().getMark(
expressionToEvaluate);
long nullCosts = vertexEval.getCurrentSubtreeEvaluationCosts(graphSize);
long maxCosts = trueCosts;
if (falseCosts > trueCosts) {
maxCosts = falseCosts;
}
if (nullCosts > maxCosts) {
maxCosts = nullCosts;
}
long ownCosts = 4;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + maxCosts + conditionCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsDeclaration
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.DeclarationEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsDeclaration(DeclarationEvaluator e,
GraphSize graphSize) {
Declaration decl = (Declaration) e.getVertex();
IsSimpleDeclOf inc = decl.getFirstIsSimpleDeclOf();
long simpleDeclCosts = 0;
while (inc != null) {
SimpleDeclaration simpleDecl = (SimpleDeclaration) inc.getAlpha();
SimpleDeclarationEvaluator simpleEval = (SimpleDeclarationEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(simpleDecl);
simpleDeclCosts += simpleEval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsSimpleDeclOf();
}
IsConstraintOf consInc = decl.getFirstIsConstraintOf();
int constraintsCosts = 0;
while (consInc != null) {
VertexEvaluator constraint = greqlEvaluator
.getVertexEvaluatorGraphMarker()
.getMark(consInc.getAlpha());
constraintsCosts += constraint
.getCurrentSubtreeEvaluationCosts(graphSize);
consInc = consInc.getNextIsConstraintOf();
}
long iterationCosts = e.getDefinedVariableCombinations(graphSize)
* declarationCostsFactor;
long ownCosts = iterationCosts + 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + constraintsCosts + simpleDeclCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsDefinition
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.DefinitionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsDefinition(DefinitionEvaluator e,
GraphSize graphSize) {
Definition def = (Definition) e.getVertex();
VertexEvaluator expEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
def.getFirstIsExprOf().getAlpha());
// + 1 for the Variable
long subtreeCosts = expEval.getCurrentSubtreeEvaluationCosts(graphSize) + 1;
long ownCosts = 2;
return new VertexCosts(ownCosts, ownCosts, ownCosts + subtreeCosts);
}
@Override
public VertexCosts calculateCostsEdgePathDescription(
EdgePathDescriptionEvaluator e, GraphSize graphSize) {
EdgePathDescription edgePathDesc = (EdgePathDescription) e.getVertex();
VertexEvaluator edgeEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
edgePathDesc.getFirstIsEdgeExprOf().getAlpha());
long edgeCosts = edgeEval.getCurrentSubtreeEvaluationCosts(graphSize);
return new VertexCosts(transitionCosts, transitionCosts,
transitionCosts + edgeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsEdgeRestriction
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .EdgeRestrictionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsEdgeRestriction(
EdgeRestrictionEvaluator e, GraphSize graphSize) {
EdgeRestriction er = (EdgeRestriction) e.getVertex();
long subtreeCosts = 0;
if (er.getFirstIsTypeIdOf(EdgeDirection.IN) != null) {
TypeIdEvaluator tEval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
er.getFirstIsTypeIdOf(EdgeDirection.IN).getAlpha());
subtreeCosts += tEval.getCurrentSubtreeEvaluationCosts(graphSize);
}
if (er.getFirstIsRoleIdOf(EdgeDirection.IN) != null) {
subtreeCosts += 1;
}
return new VertexCosts(transitionCosts, transitionCosts, subtreeCosts
+ transitionCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsEdgeSetExpression
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .EdgeSetExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsEdgeSetExpression(
EdgeSetExpressionEvaluator e, GraphSize graphSize) {
EdgeSetExpression ese = (EdgeSetExpression) e.getVertex();
long typeRestrCosts = 0;
IsTypeRestrOf inc = ese.getFirstIsTypeRestrOf();
while (inc != null) {
TypeIdEvaluator tideval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
typeRestrCosts += tideval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsTypeRestrOf();
}
long ownCosts = graphSize.getEdgeCount() * edgeSetExpressionCostsFactor;
return new VertexCosts(ownCosts, ownCosts, typeRestrCosts + ownCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsEdgeSubgraphExpression
* (de.uni_koblenz.jgralab.greql2.evaluator
* .vertexeval.EdgeSubgraphExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsEdgeSubgraphExpression(
EdgeSubgraphExpressionEvaluator e, GraphSize graphSize) {
EdgeSubgraphExpression ese = (EdgeSubgraphExpression) e.getVertex();
long typeRestrCosts = 0;
IsTypeRestrOf inc = ese.getFirstIsTypeRestrOf();
while (inc != null) {
TypeIdEvaluator tideval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
typeRestrCosts += tideval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsTypeRestrOf();
}
long ownCosts = graphSize.getEdgeCount()
* edgeSubgraphExpressionCostsFactor;
return new VertexCosts(ownCosts, ownCosts, typeRestrCosts + ownCosts);
}
@Override
public VertexCosts calculateCostsExponentiatedPathDescription(
ExponentiatedPathDescriptionEvaluator e, GraphSize graphSize) {
ExponentiatedPathDescription p = (ExponentiatedPathDescription) e
.getVertex();
long exponent = defaultExponent;
VertexEvaluator expEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
p.getFirstIsExponentOf().getAlpha());
if (expEval instanceof IntLiteralEvaluator) {
try {
exponent = expEval.getResult(null).toLong();
} catch (Exception ex) {
}
}
long exponentCosts = expEval
.getCurrentSubtreeEvaluationCosts(graphSize);
VertexEvaluator pathEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
p.getFirstIsExponentiatedPathOf().getAlpha());
long pathCosts = pathEval.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = (pathCosts * exponent) * 1 / 3;
long subtreeCosts = pathCosts + ownCosts + exponentCosts;
return new VertexCosts(ownCosts, ownCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsForwardVertexSet(
ForwardVertexSetEvaluator e, GraphSize graphSize) {
ForwardVertexSet bwvertex = (ForwardVertexSet) e.getVertex();
Expression targetExpression = (Expression) bwvertex
.getFirstIsStartExprOf().getAlpha();
VertexEvaluator vertexEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(targetExpression);
long targetCosts = vertexEval
.getCurrentSubtreeEvaluationCosts(graphSize);
PathDescription p = (PathDescription) bwvertex.getFirstIsPathOf()
.getAlpha();
PathDescriptionEvaluator pathDescEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(p);
long pathDescCosts = pathDescEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long searchCosts = Math.round(pathDescCosts * searchFactor
* Math.sqrt(graphSize.getEdgeCount()));
long ownCosts = searchCosts;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = targetCosts + pathDescCosts + iteratedCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsFunctionApplication
* (de.uni_koblenz.jgralab.greql2.evaluator.
* vertexeval.FunctionApplicationEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsFunctionApplication(
FunctionApplicationEvaluator e, GraphSize graphSize) {
FunctionApplication funApp = (FunctionApplication) e.getVertex();
IsArgumentOf inc = funApp.getFirstIsArgumentOf(EdgeDirection.IN);
long argCosts = 0;
ArrayList<Long> elements = new ArrayList<Long>();
while (inc != null) {
VertexEvaluator argEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
argCosts += argEval.getCurrentSubtreeEvaluationCosts(graphSize);
elements.add(argEval.getEstimatedCardinality(graphSize));
inc = inc.getNextIsArgumentOf(EdgeDirection.IN);
}
Greql2Function func = e.getGreql2Function();
long ownCosts = func.getEstimatedCosts(elements);
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + argCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsGreql2Expression
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .Greql2ExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsGreql2Expression(
Greql2ExpressionEvaluator e, GraphSize graphSize) {
Greql2Expression greqlExp = (Greql2Expression) e.getVertex();
VertexEvaluator queryExpEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
greqlExp.getFirstIsQueryExprOf().getAlpha());
long queryCosts = queryExpEval
.getCurrentSubtreeEvaluationCosts(graphSize);
logger.info("QueryCosts: " + queryCosts);
IsBoundVarOf boundVarInc = greqlExp.getFirstIsBoundVarOf();
int boundVars = 0;
while (boundVarInc != null) {
boundVars++;
boundVarInc = boundVarInc.getNextIsBoundVarOf();
}
long ownCosts = boundVars * greql2ExpressionCostsFactor;
long iteratedCosts = ownCosts;
long subtreeCosts = ownCosts + queryCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsIntermediateVertexPathDescription(
IntermediateVertexPathDescriptionEvaluator e, GraphSize graphSize) {
IntermediateVertexPathDescription pathDesc = (IntermediateVertexPathDescription) e
.getVertex();
IsSubPathOf inc = pathDesc.getFirstIsSubPathOf();
PathDescriptionEvaluator firstPathEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
inc = inc.getNextIsSubPathOf();
PathDescriptionEvaluator secondPathEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
long firstCosts = firstPathEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long secondCosts = secondPathEval
.getCurrentSubtreeEvaluationCosts(graphSize);
VertexEvaluator vertexEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
pathDesc.getFirstIsIntermediateVertexOf().getAlpha());
long intermVertexCosts = vertexEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = 10;
long iteratedCosts = 10;
long subtreeCosts = iteratedCosts + intermVertexCosts + firstCosts
+ secondCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsIteratedPathDescription(
IteratedPathDescriptionEvaluator e, GraphSize graphSize) {
IteratedPathDescription iterPath = (IteratedPathDescription) e
.getVertex();
VertexEvaluator pathEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
iterPath.getFirstIsIteratedPathOf().getAlpha());
long ownCosts = 5;
long iteratedCosts = 5;
long subtreeCosts = ownCosts
+ pathEval.getCurrentSubtreeEvaluationCosts(graphSize);
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsLetExpression
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .LetExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsLetExpression(LetExpressionEvaluator e,
GraphSize graphSize) {
LetExpression letExp = (LetExpression) e.getVertex();
IsDefinitionOf inc = letExp.getFirstIsDefinitionOf();
long definitionCosts = 0;
long definitions = 0;
while (inc != null) {
definitions++;
DefinitionEvaluator definEval = (DefinitionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
definitionCosts += definEval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsDefinitionOf();
}
VertexEvaluator boundExpressionEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
letExp.getFirstIsBoundExprOfDefinition().getAlpha());
long expressionCosts = boundExpressionEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = definitions * definitionExpressionCostsFactor + 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + definitionCosts + expressionCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsListConstruction
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .ListConstructionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsListConstruction(
ListConstructionEvaluator e, GraphSize graphSize) {
ListConstruction listCons = (ListConstruction) e.getVertex();
IsPartOf inc = listCons.getFirstIsPartOf();
long parts = 0;
long partCosts = 0;
while (inc != null) {
VertexEvaluator veval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
partCosts += veval.getCurrentSubtreeEvaluationCosts(graphSize);
parts++;
inc = inc.getNextIsPartOf();
}
long ownCosts = parts * addToListCosts + 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + partCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsListRangeConstruction(
ListRangeConstructionEvaluator e, GraphSize graphSize) {
ListRangeConstruction exp = (ListRangeConstruction) e.getVertex();
VertexEvaluator startExpEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
exp.getFirstIsFirstValueOf().getAlpha());
VertexEvaluator targetExpEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
exp.getFirstIsLastValueOf().getAlpha());
long startCosts = startExpEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long targetCosts = targetExpEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long range = 0;
if (startExpEval instanceof IntLiteralEvaluator) {
if (targetExpEval instanceof IntLiteralEvaluator) {
try {
range = targetExpEval.getResult(null).toInteger()
- startExpEval.getResult(null).toInteger() + 1;
} catch (Exception ex) {
// if an exception occurs, the default value is used, so no
// exceptionhandling is needed
}
}
}
if (range <= 0) {
range = defaultListRangeSize;
}
long ownCosts = addToListCosts * range;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + startCosts + targetCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsOptionalPathDescription(
OptionalPathDescriptionEvaluator e, GraphSize graphSize) {
OptionalPathDescription iterPath = (OptionalPathDescription) e
.getVertex();
VertexEvaluator pathEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
iterPath.getFirstIsOptionalPathOf().getAlpha());
long ownCosts = 5;
long iteratedCosts = 5;
long subtreeCosts = ownCosts
+ pathEval.getCurrentSubtreeEvaluationCosts(graphSize);
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsPathExistence(PathExistenceEvaluator e,
GraphSize graphSize) {
PathExistence existence = (PathExistence) e.getVertex();
Expression startExpression = (Expression) existence
.getFirstIsStartExprOf().getAlpha();
VertexEvaluator vertexEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(startExpression);
long startCosts = vertexEval
.getCurrentSubtreeEvaluationCosts(graphSize);
Expression targetExpression = (Expression) existence
.getFirstIsTargetExprOf().getAlpha();
vertexEval = greqlEvaluator.getVertexEvaluatorGraphMarker().getMark(
targetExpression);
long targetCosts = vertexEval
.getCurrentSubtreeEvaluationCosts(graphSize);
PathDescription p = (PathDescription) existence.getFirstIsPathOf()
.getAlpha();
PathDescriptionEvaluator pathDescEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(p);
long pathDescCosts = pathDescEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long searchCosts = Math.round(pathDescCosts * searchFactor / 2
* Math.sqrt(graphSize.getEdgeCount()));
long ownCosts = searchCosts;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = targetCosts + pathDescCosts + iteratedCosts
+ startCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsQuantifiedExpression
* (de.uni_koblenz.jgralab.greql2.evaluator
* .vertexeval.QuantifiedExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsQuantifiedExpression(
QuantifiedExpressionEvaluator e, GraphSize graphSize) {
QuantifiedExpression quantifiedExpr = (QuantifiedExpression) e
.getVertex();
VertexEvaluator declEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
quantifiedExpr.getFirstIsQuantifiedDeclOf().getAlpha());
long declCosts = declEval.getCurrentSubtreeEvaluationCosts(graphSize);
VertexEvaluator boundExprEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
quantifiedExpr.getFirstIsBoundExprOfQuantifier()
.getAlpha());
long boundExprCosts = boundExprEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = 20;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + declCosts + boundExprCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsRecordConstruction
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .RecordConstructionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsRecordConstruction(
RecordConstructionEvaluator e, GraphSize graphSize) {
RecordConstruction recCons = (RecordConstruction) e.getVertex();
IsPartOf inc = recCons.getFirstIsPartOf(EdgeDirection.IN);
long recElems = 0;
long recElemCosts = 0;
while (inc != null) {
RecordElement recElem = (RecordElement) inc.getAlpha();
VertexEvaluator veval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(recElem);
recElemCosts += veval.getCurrentSubtreeEvaluationCosts(graphSize);
recElems++;
inc = inc.getNextIsPartOf(EdgeDirection.IN);
}
long ownCosts = recElems * addToRecordCosts + 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + recElemCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsRecordElement
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .RecordElementEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsRecordElement(RecordElementEvaluator e,
GraphSize graphSize) {
RecordElement recElem = (RecordElement) e.getVertex();
IsRecordExprOf inc = recElem.getFirstIsRecordExprOf();
VertexEvaluator veval = greqlEvaluator.getVertexEvaluatorGraphMarker()
.getMark(inc.getAlpha());
long recordExprCosts = veval
.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = 3;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = recordExprCosts + iteratedCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsRestrictedExpression
* (de.uni_koblenz.jgralab.greql2.evaluator
* .vertexeval.RestrictedExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsRestrictedExpression(
RestrictedExpressionEvaluator e, GraphSize graphSize) {
RestrictedExpression resExp = (RestrictedExpression) e.getVertex();
VertexEvaluator restrictedExprEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
resExp.getFirstIsRestrictedExprOf().getAlpha());
long restrictedExprCosts = restrictedExprEval
.getCurrentSubtreeEvaluationCosts(graphSize);
VertexEvaluator restrictionEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
resExp.getFirstIsRestrictionOf().getAlpha());
long restrictionCosts = restrictionEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = 5;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + restrictedExprCosts
+ restrictionCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsSequentialPathDescription(
SequentialPathDescriptionEvaluator e, GraphSize graphSize) {
SequentialPathDescription p = (SequentialPathDescription) e.getVertex();
long aggregatedCosts = 0;
IsSequenceElementOf inc = p.getFirstIsSequenceElementOf();
long alternatives = 0;
while (inc != null) {
PathDescriptionEvaluator pathEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
aggregatedCosts += pathEval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsSequenceElementOf();
alternatives++;
}
aggregatedCosts += 10 * alternatives;
return new VertexCosts(10 * alternatives, 10 * alternatives,
aggregatedCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsSetComprehension
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .SetComprehensionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsSetComprehension(
SetComprehensionEvaluator e, GraphSize graphSize) {
SetComprehension setComp = (SetComprehension) e.getVertex();
Declaration decl = (Declaration) setComp.getFirstIsCompDeclOf()
.getAlpha();
DeclarationEvaluator declEval = (DeclarationEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(decl);
long declCosts = declEval.getCurrentSubtreeEvaluationCosts(graphSize);
Vertex resultDef = setComp.getFirstIsCompResultDefOf().getAlpha();
VertexEvaluator resultDefEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(resultDef);
long resultCosts = resultDefEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = resultDefEval.getEstimatedCardinality(graphSize)
* addToSetCosts;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + resultCosts + declCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsSetConstruction
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .SetConstructionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsSetConstruction(
SetConstructionEvaluator e, GraphSize graphSize) {
SetConstruction setCons = (SetConstruction) e.getVertex();
IsPartOf inc = setCons.getFirstIsPartOf();
long parts = 0;
long partCosts = 0;
while (inc != null) {
VertexEvaluator veval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
partCosts += veval.getCurrentSubtreeEvaluationCosts(graphSize);
parts++;
inc = inc.getNextIsPartOf();
}
long ownCosts = parts * addToSetCosts + 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + partCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsSimpleDeclaration
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .SimpleDeclarationEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsSimpleDeclaration(
SimpleDeclarationEvaluator e, GraphSize graphSize) {
SimpleDeclaration simpleDecl = (SimpleDeclaration) e.getVertex();
// Calculate the costs for the type definition
VertexEvaluator typeExprEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
simpleDecl.getFirstIsTypeExprOf().getAlpha());
long typeCosts = typeExprEval
.getCurrentSubtreeEvaluationCosts(graphSize);
// Calculate the costs for the declared variables
long declaredVarCosts = 0;
IsDeclaredVarOf inc = simpleDecl
.getFirstIsDeclaredVarOf(EdgeDirection.IN);
while (inc != null) {
VariableEvaluator varEval = (VariableEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
declaredVarCosts += varEval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsDeclaredVarOf(EdgeDirection.IN);
}
long ownCosts = 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + declaredVarCosts + typeCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsSimplePathDescription(
SimplePathDescriptionEvaluator e, GraphSize graphSize) {
return new VertexCosts(transitionCosts, transitionCosts,
transitionCosts);
}
@Override
public VertexCosts calculateCostsAggregationPathDescription(
AggregationPathDescriptionEvaluator e, GraphSize graphSize) {
return new VertexCosts(transitionCosts, transitionCosts,
transitionCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsTableComprehension
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .TableComprehensionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsTableComprehension(
TableComprehensionEvaluator e, GraphSize graphSize) {
// TODO (heimdall): What is a TableComprehension? Syntax? Where do the
// costs differ from a BagComprehension?
TableComprehension tableComp = (TableComprehension) e.getVertex();
Declaration decl = (Declaration) tableComp.getFirstIsCompDeclOf()
.getAlpha();
DeclarationEvaluator declEval = (DeclarationEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(decl);
long declCosts = declEval.getCurrentSubtreeEvaluationCosts(graphSize);
Vertex resultDef = tableComp.getFirstIsCompResultDefOf().getAlpha();
VertexEvaluator resultDefEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(resultDef);
long resultCosts = resultDefEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = resultDefEval.getEstimatedCardinality(graphSize)
* addToBagCosts;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + resultCosts + declCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public VertexCosts calculateCostsTransposedPathDescription(
TransposedPathDescriptionEvaluator e, GraphSize graphSize) {
TransposedPathDescription transPath = (TransposedPathDescription) e
.getVertex();
PathDescriptionEvaluator pathEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
transPath.getFirstIsTransposedPathOf().getAlpha());
long pathCosts = pathEval.getCurrentSubtreeEvaluationCosts(graphSize);
long transpositionCosts = pathCosts / 20;
long subtreeCosts = transpositionCosts + pathCosts;
return new VertexCosts(transpositionCosts, transpositionCosts,
subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsTupleConstruction
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .TupleConstructionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsTupleConstruction(
TupleConstructionEvaluator e, GraphSize graphSize) {
TupleConstruction tupCons = (TupleConstruction) e.getVertex();
IsPartOf inc = tupCons.getFirstIsPartOf(EdgeDirection.IN);
long parts = 0;
long partCosts = 0;
while (inc != null) {
VertexEvaluator veval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
partCosts += veval.getCurrentSubtreeEvaluationCosts(graphSize);
parts++;
inc = inc.getNextIsPartOf(EdgeDirection.IN);
}
long ownCosts = parts * addToTupleCosts + 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + partCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsTypeId
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.TypeIdEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsTypeId(TypeIdEvaluator e,
GraphSize graphSize) {
long costs = graphSize.getKnownEdgeTypes()
+ graphSize.getKnownVertexTypes();
return new VertexCosts(costs, costs, costs);
}
@Override
public VertexCosts calculateCostsVariable(VariableEvaluator e,
GraphSize graphSize) {
return new VertexCosts(1, 1, 1);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsVertexSetExpression
* (de.uni_koblenz.jgralab.greql2.evaluator.
* vertexeval.VertexSetExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsVertexSetExpression(
VertexSetExpressionEvaluator e, GraphSize graphSize) {
VertexSetExpression vse = (VertexSetExpression) e.getVertex();
long typeRestrCosts = 0;
IsTypeRestrOf inc = vse.getFirstIsTypeRestrOf();
while (inc != null) {
TypeIdEvaluator tideval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
typeRestrCosts += tideval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsTypeRestrOf();
}
long ownCosts = graphSize.getVertexCount()
* vertexSetExpressionCostsFactor;
return new VertexCosts(ownCosts, ownCosts, typeRestrCosts + ownCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsVertexSubgraphExpression
* (de.uni_koblenz.jgralab.greql2.evaluator
* .vertexeval.VertexSubgraphExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsVertexSubgraphExpression(
VertexSubgraphExpressionEvaluator e, GraphSize graphSize) {
VertexSubgraphExpression vse = (VertexSubgraphExpression) e.getVertex();
long typeRestrCosts = 0;
IsTypeRestrOf inc = vse.getFirstIsTypeRestrOf();
while (inc != null) {
TypeIdEvaluator tideval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
typeRestrCosts += tideval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsTypeRestrOf();
}
long ownCosts = graphSize.getVertexCount()
* vertexSubgraphExpressionCostsFactor;
return new VertexCosts(ownCosts, ownCosts, typeRestrCosts + ownCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateCostsWhereExpression
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .WhereExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public VertexCosts calculateCostsWhereExpression(
WhereExpressionEvaluator e, GraphSize graphSize) {
WhereExpression whereExp = (WhereExpression) e.getVertex();
IsDefinitionOf inc = whereExp.getFirstIsDefinitionOf();
long definitionCosts = 0;
long definitions = 0;
while (inc != null) {
definitions++;
DefinitionEvaluator definEval = (DefinitionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(inc.getAlpha());
definitionCosts += definEval
.getCurrentSubtreeEvaluationCosts(graphSize);
inc = inc.getNextIsDefinitionOf();
}
VertexEvaluator boundExpressionEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
whereExp.getFirstIsBoundExprOfDefinition().getAlpha());
long expressionCosts = boundExpressionEval
.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = definitions * definitionExpressionCostsFactor + 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + definitionCosts + expressionCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateEdgeSubgraphSize
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .EdgeSubgraphExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public GraphSize calculateEdgeSubgraphSize(
EdgeSubgraphExpressionEvaluator e, GraphSize graphSize) {
EdgeSubgraphExpression ese = (EdgeSubgraphExpression) e.getVertex();
IsTypeRestrOf inc = ese.getFirstIsTypeRestrOf(EdgeDirection.IN);
double selectivity = 1.0;
while (inc != null) {
TypeId tid = (TypeId) inc.getAlpha();
TypeIdEvaluator tidEval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(tid);
selectivity *= tidEval.getEstimatedSelectivity(graphSize);
+ inc = inc.getNextIsTypeRestrOf(EdgeDirection.IN);
}
return new GraphSize(Math.round(graphSize.getVertexCount()
* selectivity), Math.round(graphSize.getEdgeCount()
* selectivity), graphSize.getKnownVertexTypes(), graphSize
.getKnownVertexTypes());
}
@Override
public double calculateSelectivityFunctionApplication(
FunctionApplicationEvaluator e, GraphSize graphSize) {
Greql2Function func = e.getGreql2Function();
if (func != null) {
return func.getSelectivity();
} else {
return 1;
}
}
@Override
public double calculateSelectivityPathExistence(PathExistenceEvaluator e,
GraphSize graphSize) {
return 0.1;
}
@Override
public double calculateSelectivityTypeId(TypeIdEvaluator e,
GraphSize graphSize) {
int typesInSchema = (int) Math
.round((graphSize.getKnownEdgeTypes() + graphSize
.getKnownVertexTypes()) / 2.0);
double selectivity = 1.0;
TypeId id = (TypeId) e.getVertex();
if (id.isType()) {
selectivity = 1.0 / typesInSchema;
} else {
double avgSubclasses = (graphSize.getAverageEdgeSubclasses() + graphSize
.getAverageVertexSubclasses()) / 2.0;
selectivity = avgSubclasses / typesInSchema;
}
if (id.isExcluded()) {
selectivity = 1 - selectivity;
}
return selectivity;
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateVariableAssignments
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval.VariableEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public long calculateVariableAssignments(VariableEvaluator e,
GraphSize graphSize) {
Variable v = (Variable) e.getVertex();
IsDeclaredVarOf inc = v.getFirstIsDeclaredVarOf();
if (inc != null) {
SimpleDeclaration decl = (SimpleDeclaration) inc.getOmega();
VertexEvaluator typeExpEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(
decl.getFirstIsTypeExprOf().getAlpha());
return typeExpEval.getEstimatedCardinality(graphSize);
} else {
// if there exists no "isDeclaredVarOf"-Edge, the variable is not
// declared but defined, so there exists only 1 possible assignment
return 1;
}
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#
* calculateVertexSubgraphSize
* (de.uni_koblenz.jgralab.greql2.evaluator.vertexeval
* .VertexSubgraphExpressionEvaluator,
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize)
*/
@Override
public GraphSize calculateVertexSubgraphSize(
VertexSubgraphExpressionEvaluator e, GraphSize graphSize) {
VertexSubgraphExpression vse = (VertexSubgraphExpression) e.getVertex();
IsTypeRestrOf inc = vse.getFirstIsTypeRestrOf(EdgeDirection.IN);
double selectivity = 1.0;
while (inc != null) {
TypeId tid = (TypeId) inc.getAlpha();
TypeIdEvaluator tidEval = (TypeIdEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(tid);
selectivity *= tidEval.getEstimatedSelectivity(graphSize);
+ inc = inc.getNextIsTypeRestrOf(EdgeDirection.IN);
}
return new GraphSize((int) Math.round(graphSize.getVertexCount()
* selectivity), (int) Math.round(graphSize.getEdgeCount()
* selectivity), graphSize.getKnownVertexTypes(), graphSize
.getKnownVertexTypes());
}
/*
* (non-Javadoc)
*
* @see
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#isEquivalent
* (de.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel)
*/
@Override
public boolean isEquivalent(CostModel costModel) {
if (costModel instanceof DefaultCostModel) {
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see
* de.uni_koblenz.jgralab.greql2.evaluator.costmodel.CostModel#setGreqlEvaluator
* (de.uni_koblenz.jgralab.greql2.evaluator.GreqlEvaluator)
*/
@Override
public void setGreqlEvaluator(GreqlEvaluator eval) {
greqlEvaluator = eval;
}
@Override
public VertexCosts calculateCostsMapConstruction(
MapConstructionEvaluator e, GraphSize graphSize) {
MapConstruction mapCons = (MapConstruction) e.getVertex();
IsKeyExprOfConstruction keyInc = mapCons
.getFirstIsKeyExprOfConstruction(EdgeDirection.IN);
IsValueExprOfConstruction valInc = mapCons
.getFirstIsValueExprOfConstruction(EdgeDirection.IN);
long parts = 0;
long partCosts = 0;
while (keyInc != null) {
VertexEvaluator keyEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(keyInc.getAlpha());
partCosts += keyEval.getCurrentSubtreeEvaluationCosts(graphSize);
VertexEvaluator valueEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(valInc.getAlpha());
partCosts += keyEval.getCurrentSubtreeEvaluationCosts(graphSize)
+ valueEval.getCurrentSubtreeEvaluationCosts(graphSize);
parts++;
keyInc = keyInc.getNextIsKeyExprOfConstruction(EdgeDirection.IN);
valInc = valInc.getNextIsValueExprOfConstruction(EdgeDirection.IN);
}
long ownCosts = parts * addToSetCosts + 2;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + partCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public long calculateCardinalityMapConstruction(MapConstructionEvaluator e,
GraphSize graphSize) {
long mappings = 0;
MapConstruction mapCons = (MapConstruction) e.getVertex();
IsKeyExprOfConstruction inc = mapCons
.getFirstIsKeyExprOfConstruction(EdgeDirection.IN);
while (inc != null) {
mappings++;
inc = inc.getNextIsKeyExprOfConstruction(EdgeDirection.IN);
}
return mappings;
}
@Override
public VertexCosts calculateCostsMapComprehension(
MapComprehensionEvaluator e, GraphSize graphSize) {
MapComprehension mapComp = (MapComprehension) e.getVertex();
Declaration decl = (Declaration) mapComp.getFirstIsCompDeclOf()
.getAlpha();
DeclarationEvaluator declEval = (DeclarationEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(decl);
long declCosts = declEval.getCurrentSubtreeEvaluationCosts(graphSize);
Vertex key = mapComp.getFirstIsKeyExprOfComprehension(EdgeDirection.IN)
.getAlpha();
VertexEvaluator keyEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(key);
Vertex value = mapComp.getFirstIsValueExprOfComprehension(
EdgeDirection.IN).getAlpha();
VertexEvaluator valEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(value);
long resultCosts = keyEval.getCurrentSubtreeEvaluationCosts(graphSize)
+ valEval.getCurrentSubtreeEvaluationCosts(graphSize);
long ownCosts = keyEval.getEstimatedCardinality(graphSize)
+ valEval.getEstimatedCardinality(graphSize) * addToSetCosts;
long iteratedCosts = ownCosts * e.getVariableCombinations(graphSize);
long subtreeCosts = iteratedCosts + resultCosts + declCosts;
return new VertexCosts(ownCosts, iteratedCosts, subtreeCosts);
}
@Override
public long calculateCardinalityMapComprehension(
MapComprehensionEvaluator e, GraphSize graphSize) {
MapComprehension setComp = (MapComprehension) e.getVertex();
Declaration decl = (Declaration) setComp.getFirstIsCompDeclOf()
.getAlpha();
DeclarationEvaluator declEval = (DeclarationEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(decl);
return declEval.getEstimatedCardinality(graphSize);
}
}
diff --git a/src/de/uni_koblenz/jgralab/greql2/jvalue/JValueXMLOutputVisitor.java b/src/de/uni_koblenz/jgralab/greql2/jvalue/JValueXMLOutputVisitor.java
index 680de1b4d..1a84549af 100644
--- a/src/de/uni_koblenz/jgralab/greql2/jvalue/JValueXMLOutputVisitor.java
+++ b/src/de/uni_koblenz/jgralab/greql2/jvalue/JValueXMLOutputVisitor.java
@@ -1,327 +1,331 @@
/*
* JGraLab - The Java graph laboratory
* (c) 2006-2009 Institute for Software Technology
* University of Koblenz-Landau, Germany
*
* [email protected]
*
* Please report bugs to http://serres.uni-koblenz.de/bugzilla
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package de.uni_koblenz.jgralab.greql2.jvalue;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import de.uni_koblenz.jgralab.AttributedElement;
import de.uni_koblenz.jgralab.BooleanGraphMarker;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.greql2.exception.JValueVisitorException;
import de.uni_koblenz.jgralab.schema.AttributedElementClass;
public class JValueXMLOutputVisitor extends JValueDefaultVisitor {
/**
* The writer which stores the elements
*/
private BufferedWriter outputWriter;
/**
* The path to the file the value should be stored in
*/
private String filePath;
/**
* The graph all elements in the jvalue to visit belong to
*/
private Graph dataGraph = null;
private void storeln(String s) {
try {
outputWriter.write(s);
outputWriter.write("\n");
} catch (IOException e) {
throw new JValueVisitorException("Can't write to output file",
null, e);
}
}
private void store(String s) {
try {
outputWriter.write(s);
} catch (IOException e) {
throw new JValueVisitorException("Can't write to output file",
null, e);
}
}
private String xmlQuote(String string) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < string.length(); ++i) {
char c = string.charAt(i);
if (c == '<') {
result.append("<");
} else if (c == '>') {
result.append(">");
} else if (c == '"') {
result.append(""");
} else if (c == '\'') {
result.append("'");
} else if (c == '&') {
result.append("&");
} else {
result.append(c);
}
}
return result.toString();
}
private void storeBrowsingInfo(JValue n) {
AttributedElement browsingInfo = n.getBrowsingInfo();
if (browsingInfo instanceof Vertex) {
Vertex browsingVertex = (Vertex) browsingInfo;
store("<browsevertex>" + browsingVertex.getId() + "</browsevertex>");
} else if (browsingInfo instanceof Edge) {
Edge browsingEdge = (Edge) browsingInfo;
store("<browseedge>" + browsingEdge.getId() + "</browseedge>");
}
}
public JValueXMLOutputVisitor(JValue value, String filePath) {
this(value, filePath, null);
}
public JValueXMLOutputVisitor(JValue value, String filePath, Graph dataGraph) {
this.filePath = filePath;
this.dataGraph = dataGraph;
head();
value.accept(this);
foot();
}
@Override
public void visitSet(JValueSet set) {
storeln("<set>");
super.visitSet(set);
storeln("</set>");
}
@Override
public void visitBag(JValueBag bag) {
storeln("<bag>");
super.visitBag(bag);
storeln("</bag>");
}
@Override
public void visitList(JValueList list) {
storeln("<list>");
super.visitList(list);
storeln("</list>");
}
@Override
public void visitTuple(JValueTuple tuple) {
storeln("<tuple>");
super.visitTuple(tuple);
storeln("</tuple>");
}
@Override
public void visitRecord(JValueRecord record) {
storeln("<record>");
super.visitRecord(record);
storeln("</record>");
}
@Override
public void visitTable(JValueTable table) {
storeln("<table>");
storeln("<header>");
super.visitTuple(table.getHeader());
storeln("</header>");
storeln("<tabledata>");
table.getData().accept(this);
storeln("</tabledata>");
storeln("</table>");
}
@Override
public void visitVertex(JValue v) {
Vertex vertex = null;
vertex = v.toVertex();
storeln("<vertex>");
store("<value>" + vertex.getId() + "</value>");
storeBrowsingInfo(v);
storeln("</vertex>");
}
@Override
public void visitEdge(JValue e) {
Edge edge = null;
edge = e.toEdge();
store("<edge>");
store("<value>" + edge.getId() + "</value>");
storeBrowsingInfo(e);
storeln("</edge>");
}
@Override
public void visitInt(JValue n) {
Integer b = n.toInteger();
store("<integer>");
store("<value>" + b.intValue() + "</value>");
storeBrowsingInfo(n);
storeln("</integer>");
}
@Override
public void visitLong(JValue n) {
Long b = n.toLong();
store("<long>");
store("<value>" + b.longValue() + "</value>");
storeBrowsingInfo(n);
storeln("</long>");
}
@Override
public void visitDouble(JValue n) {
Double b = n.toDouble();
store("<double>");
store("<value>" + b.doubleValue() + "</value>");
storeBrowsingInfo(n);
storeln("</double>");
}
@Override
public void visitChar(JValue c) {
Character b = c.toCharacter();
String s = String.valueOf(b);
store("<char>");
store("<value>" + xmlQuote(s) + "</value>");
storeBrowsingInfo(c);
storeln("</char>");
}
@Override
public void visitString(JValue s) {
String st = s.toString();
store("<string>");
store("<value>" + xmlQuote(st) + "</value>");
storeBrowsingInfo(s);
storeln("</string>");
}
@Override
public void visitEnumValue(JValue e) {
String st = e.toString();
store("<enumvalue>");
store("<value>" + xmlQuote(st) + "</value>");
storeBrowsingInfo(e);
storeln("</enumvalue>");
}
@Override
public void visitGraph(JValue g) {
Graph gr = g.toGraph();
store("<graph>");
store("<value>" + gr.getId() + "</value>");
storeBrowsingInfo(g);
storeln("</graph>");
}
/**
* To store a subgraph is very tricky, one possibility is to store all
* vertices and edges
*/
+ @Override
public void visitSubgraph(JValue s) {
if (dataGraph == null) {
throw new JValueVisitorException(
"Cannot write a Subgraph to xml if no Graph is given", s);
}
storeln("<subgraph>");
storeBrowsingInfo(s);
BooleanGraphMarker subgraph = s.toSubgraphTempAttribute();
Vertex firstVertex = dataGraph.getFirstVertex();
Vertex currentVertex = firstVertex;
do {
- if ((subgraph == null) || (subgraph.isMarked(currentVertex)))
+ if ((subgraph == null) || (subgraph.isMarked(currentVertex))) {
storeln("<vertex>" + currentVertex.getId() + "</vertex>");
+ }
currentVertex = currentVertex.getNextVertex();
} while (firstVertex != currentVertex);
Edge firstEdge = dataGraph.getFirstEdgeInGraph();
Edge currentEdge = firstEdge;
do {
- if (subgraph.isMarked(currentEdge))
+ if (subgraph.isMarked(currentEdge)) {
storeln("<edge>" + currentEdge.getId() + "</edge>");
+ }
+ currentEdge = currentEdge.getNextEdgeInGraph();
} while (firstEdge != currentEdge);
storeln("</subgraph>");
}
@Override
public void visitBoolean(JValue b) {
Boolean bool = b.toBoolean();
store("<bool>");
store("<value>" + bool + "</value>");
storeBrowsingInfo(b);
storeln("</bool>");
}
@Override
public void visitObject(JValue o) {
Object t = o.toObject();
store("<object>");
store("<value>" + xmlQuote(t.toString()) + "</value>");
storeBrowsingInfo(o);
storeln("</object>");
}
@Override
public void visitAttributedElementClass(JValue a) {
AttributedElementClass c = a.toAttributedElementClass();
store("<attributedelementclass>");
store("<value>" + c.getQualifiedName() + "</value>");
storeBrowsingInfo(a);
storeln("</attributedelementclass>");
}
@Override
public void head() {
try {
outputWriter = new BufferedWriter(new FileWriter(filePath));
} catch (IOException e) {
throw new JValueVisitorException("Can't create output file", null,
e);
}
storeln("<xmlvalue>");
}
@Override
public void foot() {
storeln("</xmlvalue>");
try {
outputWriter.close();
} catch (IOException e) {
throw new JValueVisitorException("Can't close output file", null, e);
}
}
}
| false | false | null | null |
diff --git a/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/metadataprocessors/internal/MetaDataEnabledFeatureRegistry.java b/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/metadataprocessors/internal/MetaDataEnabledFeatureRegistry.java
index d67b5375b..2f342239b 100644
--- a/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/metadataprocessors/internal/MetaDataEnabledFeatureRegistry.java
+++ b/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/metadataprocessors/internal/MetaDataEnabledFeatureRegistry.java
@@ -1,177 +1,169 @@
/*******************************************************************************
* Copyright (c) 2006 Oracle Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Gerry Kessler/Oracle - initial API and implementation
*
********************************************************************************/
package org.eclipse.jst.jsf.metadataprocessors.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.InvalidRegistryObjectException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jst.jsf.core.internal.JSFCorePlugin;
import org.eclipse.jst.jsf.metadataprocessors.IType;
/**
* Registry of <code>AbstractMetaDataEnabledType</code>s loaded from
* the <code>MetaDataEnabledFeatures</code> extension point
*
* A map of features keyed by type id
*
*/
public class MetaDataEnabledFeatureRegistry{
private static final String EXTPTID = "MetaDataEnabledFeatures"; //$NON-NLS-1$
private Map<String, List<IMetaDataEnabledFeatureExtension>> featuresMap;
private Map<String, Class> typeCacheMap;
private static MetaDataEnabledFeatureRegistry INSTANCE;
/**
* @return the singleton instance of the MetaDataEnabledFeatureRegistry
*/
public static synchronized MetaDataEnabledFeatureRegistry getInstance(){
if (INSTANCE == null){
INSTANCE = new MetaDataEnabledFeatureRegistry();
}
return INSTANCE;
}
private MetaDataEnabledFeatureRegistry(){
featuresMap = new HashMap<String, List<IMetaDataEnabledFeatureExtension>>();
typeCacheMap = new HashMap<String, Class>();
readRegistry();
}
/**
* Reads the MetaDataEnabledFeatures extensions into a registry
*/
protected void readRegistry() {
try {
IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(JSFCorePlugin.PLUGIN_ID, EXTPTID);
IExtension[] extensions = point.getExtensions();
for (int i=0;i < extensions.length;i++){
IExtension ext = extensions[i];
for (int j=0;j < ext.getConfigurationElements().length;j++){
final String bundleId = ext.getConfigurationElements()[j].getContributor().getName();
final String id = ext.getConfigurationElements()[j].getAttribute("typeid"); //$NON-NLS-1$
final String klass = ext.getConfigurationElements()[j].getAttribute("class"); //$NON-NLS-1$
registerFeature(bundleId, id, klass);
}
}
} catch (InvalidRegistryObjectException e) {
JSFCorePlugin.log(e, "Unable to read " + JSFCorePlugin.PLUGIN_ID + EXTPTID + " registry"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Create {@link IMetaDataEnabledFeatureExtension}s and add to registry
* @param bundleID
* @param typeId
* @param klass
*/
protected void registerFeature(String bundleID, String typeId, String klass){
IMetaDataEnabledFeatureExtension aFeature = new MetaDataEnabledFeatureExtension(bundleID, typeId, klass);
if (canCreateTypeForFeatureExtension(aFeature)){
if (!featuresMap.containsKey(typeId)){
List list = new ArrayList();
list.add(aFeature);
featuresMap.put(typeId, list);
}
else {
List list = featuresMap.get(typeId);
list.add(aFeature);
}
}
}
private boolean canCreateTypeForFeatureExtension(IMetaDataEnabledFeatureExtension feature) {
if (! typeCacheMap.containsKey(feature.getTypeID())){
IType type = AttributeValueRuntimeTypeRegistry.getInstance().getType(feature.getTypeID());
if (type != null){
Class typeClass = AttributeValueRuntimeTypeFactory.getInstance().getClassForType(type);
typeCacheMap.put(feature.getTypeID(), typeClass);
}
else
return false;
}
return typeCacheMap.get(feature.getTypeID()) != null;
}
/**
* @param typeId
* @return List of <code>AbstractMetaDataEnabledRuntimeTypeExtensions</code>
* for a given by type id
*
* TODO: make more efficient... no need to keep calculating features for subtypes.
*/
public List<IMetaDataEnabledFeatureExtension> getFeatures(String typeId) {
if (!featuresMap.containsKey(typeId))
featuresMap.put(typeId,new ArrayList());
//copy current featuresMapped to typeId into return list
List<IMetaDataEnabledFeatureExtension> srcList = featuresMap.get(typeId);
List<IMetaDataEnabledFeatureExtension> ret = new ArrayList<IMetaDataEnabledFeatureExtension>(srcList.size());
copy(ret, srcList);
List subs = getFeatureExtensionsForMatchingSubclass(typeId);
for (Iterator<IMetaDataEnabledFeatureExtension> it=subs.iterator();it.hasNext();){
IMetaDataEnabledFeatureExtension featureExt = it.next();
if (!ret.contains(featureExt))
ret.add(featureExt);
}
return ret;
}
private void copy(List<IMetaDataEnabledFeatureExtension> destList,
List<IMetaDataEnabledFeatureExtension> srcList) {
for (Iterator<IMetaDataEnabledFeatureExtension> it=srcList.iterator();it.hasNext();){
destList.add(it.next());
}
}
/**
* If the feature adapter is mapped to a type which is a superclass of the type of interest, then the feature adapter is an extension of that type
* @param typeId
* @return list of IMetaDataEnabledFeatureExtension
*/
private List<IMetaDataEnabledFeatureExtension> getFeatureExtensionsForMatchingSubclass(String typeId) {
IType type = AttributeValueRuntimeTypeRegistry.getInstance().getType(typeId);
Class typeClass = AttributeValueRuntimeTypeFactory.getInstance().getClassForType(type);
List<IMetaDataEnabledFeatureExtension> ret = new ArrayList<IMetaDataEnabledFeatureExtension>();
// loop thru all of the type classes mapped to feature adapters that are subclasses of the type
for (Iterator it=typeCacheMap.keySet().iterator();it.hasNext();){
String featureTypeId = (String)it.next();
Class featureTypeClass = typeCacheMap.get(featureTypeId);
- try {
-// if (featureTypeClass.equals(typeClass)){
-// ret.add(featureTypeClass);
-// }
-// else
- if (typeClass.asSubclass(featureTypeClass) != null) {
- ret.addAll(featuresMap.get(featureTypeId));
- }
- } catch (ClassCastException e) {//
+ if (featureTypeClass.isAssignableFrom(typeClass)) {
+ ret.addAll(featuresMap.get(featureTypeId));
}
-
}
return ret;
}
}
| false | false | null | null |
diff --git a/src/DD/CombatSystem/Interpreter/System/I_PlaceCharacter.java b/src/DD/CombatSystem/Interpreter/System/I_PlaceCharacter.java
index 8080868..28d31c5 100644
--- a/src/DD/CombatSystem/Interpreter/System/I_PlaceCharacter.java
+++ b/src/DD/CombatSystem/Interpreter/System/I_PlaceCharacter.java
@@ -1,81 +1,81 @@
package DD.CombatSystem.Interpreter.System;
import org.newdawn.slick.SlickException;
import DD.Character.DDCharacter;
import DD.CombatSystem.Interpreter.CombatInterpreter;
import DD.MapTool.CharacterObjects;
import DD.Message.CombatMessage;
import DD.Message.CombatValidationMessage;
/*****************************************************************************************************
* I_PlaceCharacter is the interpreter for the PlaceCharacter ability. It will create a new character
* from the characterSheet provided, give it the provided characterID, and place it on the map using
* the provided coordinates.
*
* @author Carlos Vasquez
******************************************************************************************************/
public class I_PlaceCharacter extends CombatInterpreter
{
/************************************ Class Constants *************************************/
private static int I = 0;
public static final int CHARACTER_ID = I++; /* Characters ID */
public static final int POS_X = I++; /* X coordinate */
public static final int POS_Y = I++; /* Y Coordinate */
public static final int RESET = I++; /* reset or not to reset character */
public static final int BODY_SIZE = I;
/************************************ Class Methods *************************************/
@Override
public CombatValidationMessage validate(CombatMessage cm)
{
// TODO Auto-generated method stub
CombatValidationMessage returner = new CombatValidationMessage(true, null); // TODO: Check for validity
return returner;
} /* end validate method */
@Override
public void interpret(CombatMessage cm)
{
DDCharacter newCharacter = new DDCharacter(cm.getBody()[CHARACTER_ID]);
newCharacter.setCharacterID(cm.getBody()[CHARACTER_ID]);
newCharacter.setCharacterSheet(cm.getCharacterData());
/* Tell the CombatSystem abut the new character */
cs.addCharacter(newCharacter);
/* Add the character to the next turn */
cs.addToOrder(cm.getBody()[CHARACTER_ID], cs.getTurn() + 1);
/* Give to the player that owns the character */
if(cs.getNetID() == cm.getCharacterData().getNetID()) ab.addCharacter(cm.getBody()[CHARACTER_ID]);
- System.out.println("I_Plae its id " + cm.getCharacterData().getNetID());
+
/* Check for reset */
if(cm.getBody()[RESET] == 1) newCharacter.resetCharacter();
/* now place character on map */
try
{
cs.getMap().place
(
cm.getBody()[POS_X],
cm.getBody()[POS_Y],
new CharacterObjects
(
cm.getCharacterData().getName(),
cm.getCharacterData().getImage(),
cm.getBody()[POS_X],
cm.getBody()[POS_Y],
cs.getMap(),
newCharacter
)
);
} /* end try */
catch (SlickException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} /* end catch */
} /* end interpret method */
} /* end I_PlaceCharacter class */
diff --git a/src/DD/MapTool/CharacterObjects.java b/src/DD/MapTool/CharacterObjects.java
index 6ad4c08..21fecf7 100644
--- a/src/DD/MapTool/CharacterObjects.java
+++ b/src/DD/MapTool/CharacterObjects.java
@@ -1,67 +1,68 @@
package DD.MapTool;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import DD.Character.*;
import DD.CombatSystem.TargetingSystem.Coordinate;
import DD.SlickTools.*;
public class CharacterObjects extends Objects{
private static final long serialVersionUID = -942204818115561142L;
public DDCharacter ddchar;
public CharacterObjects(String name, DDImage image, int x, int y, Map owner, DDCharacter ddchar) throws SlickException {
super(name, image, owner, x, y);
this.ddchar = ddchar;
super.priority =10;
ddchar.addComponent(new CharacterStats());
}
public CharacterObjects(String name, DDImage image, Map owner, DDCharacter ddchar) throws SlickException {
this(name, image, 0, 0, owner, ddchar);
}
public CharacterObjects() {
// TODO Auto-generated constructor stub
}
public String toString(){
return "DDcharToString:(~*-*)~\n";
}
public void update(GameContainer gc, StateBasedGame sbg, int delta)
{
try
{
ddchar.update(gc, sbg, delta);
} /* end try */
catch (SlickException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} /* end catch */
}
public DDCharacter getDdchar(){
return ddchar;
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics gr)
{
float x = position.x;
float y = position.y;
float xCorrection = 30.85f;
float yCorrection = 30;
if(image != null) image.draw(x*xCorrection, (y+1)*yCorrection);
((CharacterEntity)ddchar).render(gc, sbg, gr, x*xCorrection, (y+1)*yCorrection);
} /* end render method */
public void setPosition(int x, int y) {
this.position = new Coordinate(x,y);
+ this.ddchar.setCoordiante(new Coordinate(x,y));
}
}
| false | false | null | null |
diff --git a/src/main/java/org/jboss/jandex/AnnotationValue.java b/src/main/java/org/jboss/jandex/AnnotationValue.java
index a970249..5433219 100644
--- a/src/main/java/org/jboss/jandex/AnnotationValue.java
+++ b/src/main/java/org/jboss/jandex/AnnotationValue.java
@@ -1,913 +1,914 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jandex;
/**
* An annotation value represents a specific name and value combination in the
- * parameter list of an annotation instance.
+ * parameter list of an annotation instance. It also can represent a nested
+ * array element in the case of an array value.
*
* <p>
* An annotation value can be any Java primitive:
* <ul>
* <li>byte</li>
* <li>short</li>
* <li>int</li>
* <li>char</li>
* <li>float</li>
* <li>double</li>
* <li>long</li>
* <li>boolean</li>
* </ul>
*
* <p>
* As well as any the following specialty types:
* <li>String</li>
* <li>Class</li>
* <li>Enum</li>
* <li>Nested annotation</li> </ul>
*
* <p>
* In addition a value can be a single-dimension array of any of the above types
*
* <p>
* To access a value, the proper typed method must be used that matches the
* expected type of the annotation parameter. In addition, some methods will
* allow conversion of different types. For example, a byte can be returned as
- * an integer using @link {@link #asInt()}. Also all value types support a
+ * an integer using {@link #asInt()}. Also all value types support a
* String representation.
*
* <p>
* <b>Thread-Safety</b>
* </p>
* This class is immutable and can be shared between threads without safe
* publication.
*
* @author Jason T. Greene
*
*/
public abstract class AnnotationValue implements Comparable<AnnotationValue> {
private final String name;
AnnotationValue(String name) {
this.name = name;
}
/**
* Returns the name of this value, which is typically the parameter name in the annotation
* declaration. The value may not represent a parameter (e.g an array element member), in
* which case name will simply return an empty string ("")
*
* @return the name of this value
*/
public final String name() {
return name;
}
/**
* Compares an annotation value with another annotation value. The result
* is ordered by parameter name.
*/
public int compareTo(AnnotationValue other) {
return name.compareTo(other.name);
}
/**
* Returns a detyped value that represents the underlying annotation value.
* It is recommended that the type specific methods be used instead.
*
* @return the underly value
*/
public abstract Object value();
/**
* Converts the underlying numerical type to an integer as if it was
* casted in Java.
*
* @return an integer representing the numerical parameter
* @throws IllegalArgumentException if the value is not numerical
*/
public int asInt() {
throw new IllegalArgumentException("Not a number");
}
/**
* Converts the underlying numerical type to an long as if it was
* casted in Java.
*
* @return a long representing the numerical parameter
* @throws IllegalArgumentException if the value is not numerical
*/
public long asLong() {
throw new IllegalArgumentException("Not a number");
}
/**
* Converts the underlying numerical type to a short as if it was
* casted in Java.
*
* @return a short representing the numerical parameter
* @throws IllegalArgumentException if the value is not numerical
*/
public short asShort() {
throw new IllegalArgumentException("not a number");
}
/**
* Converts the underlying numerical type to a byte as if it was
* casted in Java.
*
* @return a byte representing the numerical parameter
* @throws IllegalArgumentException if the value is not numerical
*/
public byte asByte() {
throw new IllegalArgumentException("not a number");
}
/**
* Converts the underlying numerical type to a float as if it was
* casted in Java.
*
* @return a float representing the numerical parameter
* @throws IllegalArgumentException if the value is not numerical
*/
public float asFloat() {
throw new IllegalArgumentException("not a number");
}
/**
* Converts the underlying numerical type to a double as if it was
* casted in Java.
*
* @return a double representing the numerical parameter
* @throws IllegalArgumentException if the value is not numerical
*/
public double asDouble() {
throw new IllegalArgumentException("not a number");
}
/**
* Returns the underlying character value as Java primitive char.
*
* @return a char representing the character parameter
* @throws IllegalArgumentException if the value is not a character
*/
public char asChar() {
throw new IllegalArgumentException("not a character");
}
/**
* Returns the underlying boolean value as Java primitive boolean.
*
* @return a boolean representing the character parameter
* @throws IllegalArgumentException if the value is not a boolean
*/
public boolean asBoolean() {
throw new IllegalArgumentException("not a boolean");
}
/**
* Returns the string representation of the underlying value type.
* The representation may or may not be convertible to the type
* it represents. This is best used on String types, but can also
* provide a useful way to quickly convert a value to a String.
*
* @return a string representing the value parameter
*/
public String asString() {
return value().toString();
}
/**
* Returns the constant name, in string form, that represents the
* Java enumeration of this value. The value is the same as the
* one returned by {@link Enum#name()}.
*
* @return the string name of a Java enumeration
* @throws IllegalArgumentException if the value is not an enum
*/
public String asEnum() {
throw new IllegalArgumentException("not an enum");
}
/**
* Returns the type name, in DotName form, that represents the
* Java enumeration of this value. The value is the same
* as the one returned by {@link Enum#getClass()}.
*
* @return the type name of a Java enumeration
* @throws IllegalArgumentException if the value is not an enum
*/
public DotName asEnumType() {
throw new IllegalArgumentException("not an enum");
}
/**
* Returns the class name, in {@link Type} form, that represents a Java
* Class used by this value. In addition to standard class name, it can also
* refer to specialty types, such as {@link Void} and primitive types (e.g.
* int.class). More specifically, any erased type that a method can return
* is a valid annotation Class type.
*
* @return the Java type of this value
* @throws IllegalArgumentException if the value is not a Class
*/
public Type asClass() {
throw new IllegalArgumentException("not a class");
}
/**
* Returns a nested annotation represented by this value. The nested annotation
* will have a null target, but may contain an arbitrary amount of nested values
*
* @return the underlying nested annotation instance
* @throws IllegalArgumentException if the value is not a nested annotation
*/
public AnnotationInstance asNested() {
throw new IllegalArgumentException("not a nested annotation");
}
AnnotationValue[] asArray() {
throw new IllegalArgumentException("Not an array");
}
/**
* Converts an underlying numerical array to a Java primitive
* integer array.
*
* @return an int array that represents this value
* @throws IllegalArgumentException if this value is not a numerical array.
*/
public int[] asIntArray() {
throw new IllegalArgumentException("Not a numerical array");
}
/**
* Converts an underlying numerical array to a Java primitive
* long array.
*
* @return a long array that represents this value
* @throws IllegalArgumentException if this value is not a numerical array.
*/
public long[] asLongArray() {
throw new IllegalArgumentException("Not a numerical array");
}
/**
* Converts an underlying numerical array to a Java primitive short array.
*
* @return a short array that represents this value
* @throws IllegalArgumentException if this value is not a numerical array.
*/
public short[] asShortArray() {
throw new IllegalArgumentException("not a numerical array");
}
/**
* Converts an underlying numerical array to a Java primitive byte array.
*
* @return a byte array that represents this value
* @throws IllegalArgumentException if this value is not a numerical array.
*/
public byte[] asByteArray() {
throw new IllegalArgumentException("not a numerical array");
}
/**
* Converts an underlying numerical array to a Java primitive float array.
*
* @return a float array that represents this value
* @throws IllegalArgumentException if this value is not a numerical array.
*/
public float[] asFloatArray() {
throw new IllegalArgumentException("not a numerical array");
}
/**
* Converts an underlying numerical array to a Java primitive double array.
*
* @return a double array that represents this value
* @throws IllegalArgumentException if this value is not a numerical array.
*/
public double[] asDoubleArray() {
throw new IllegalArgumentException("not a numerical array");
}
/**
* Returns the underlying character array.
*
* @return a character array that represents this value
* @throws IllegalArgumentException if this value is not a character array.
*/
public char[] asCharArray() {
throw new IllegalArgumentException("not a character array");
}
/**
* Returns the underlying boolean array.
*
* @return a boolean array that represents this value
* @throws IllegalArgumentException if this value is not a boolean array.
*/
public boolean[] asBooleanArray() {
throw new IllegalArgumentException("not a boolean array");
}
/**
* Returns a string array representation of the underlying array value.
* The behavior is identical to {@link #asString()} as if it were applied
* to every array element.
*
* @return a string array representing the underlying array value
* @throws IllegalArgumentException if this value is not an array
*/
public String[] asStringArray() {
throw new IllegalArgumentException("not a string array");
}
/**
* Returns an array of the constant name, in string form, that represents the
* Java enumeration of each array element The individual element values are
* the same as the one returned by {@link Enum#name()}.
*
* @return an array of string names of a Java enums
* @throws IllegalArgumentException if the value is not an enum array
*/
public String[] asEnumArray() {
throw new IllegalArgumentException("not an enum array");
}
/**
* Returns an array of the type name, in DotName form, that represents the
* Java enumeration of each array element. The individual element values are
* the same as the one returned by {@link Enum#getClass()}. Note that JLS
* restricts an enum array parameter to the same type. Also, when an empty
* array is specified in a value, it's types can not be determined.
*
* @return an array of string type names of Java enum array elements
* @throws IllegalArgumentException if the value is not an enum array
*/
public DotName[] asEnumTypeArray() {
throw new IllegalArgumentException("not an enum array");
}
/**
* Returns an array of class types representing the underlying class array value.
* Each element has the same behavior as @{link {@link #asClass()}
*
* @return a class array representing this class array value
* @throws IllegalArgumentException if the value is not a class array
*/
public Type[] asClassArray() {
throw new IllegalArgumentException("not a class array");
}
/**
* Returns an array of nested annotations representing the underlying annotation array value.
* Each element has the same behavior as @{link {@link #asNested()}
*
* @return an annotation array representing this annotation array value
* @throws IllegalArgumentException if the value is not an annotation array
*/
public AnnotationInstance[] asNestedArray() {
throw new IllegalArgumentException("not a nested annotation array");
}
public String toString() {
StringBuilder builder = new StringBuilder();
if (name.length() > 0)
builder.append(name).append(" = ");
return builder.append(value()).toString();
}
static final class StringValue extends AnnotationValue {
private final String value;
StringValue(String name, String value) {
super(name);
this.value = value;
}
public String value() {
return value;
}
public String toString() {
StringBuilder builder = new StringBuilder();
if (super.name.length() > 0)
builder.append(super.name).append(" = ");
return builder.append('"').append(value).append('"').toString();
}
}
static final class ByteValue extends AnnotationValue {
private final byte value;
ByteValue(String name, byte value) {
super(name);
this.value = value;
}
public Byte value() {
return value;
}
public int asInt() {
return value;
}
public long asLong() {
return value;
}
public short asShort() {
return value;
}
public byte asByte() {
return value;
}
public float asFloat() {
return value;
}
public double asDouble() {
return value;
}
}
static final class CharacterValue extends AnnotationValue {
private final char value;
CharacterValue(String name, char value) {
super(name);
this.value = value;
}
public Character value() {
return value;
}
public char asChar() {
return value;
}
}
static final class DoubleValue extends AnnotationValue {
private final double value;
public DoubleValue(String name, double value) {
super(name);
this.value = value;
}
public Double value() {
return value;
}
public int asInt() {
return (int) value;
}
public long asLong() {
return (long) value;
}
public short asShort() {
return (short) value;
}
public byte asByte() {
return (byte) value;
}
public float asFloat() {
return (float) value;
}
public double asDouble() {
return value;
}
}
static final class FloatValue extends AnnotationValue {
private final float value;
FloatValue(String name, float value) {
super(name);
this.value = value;
}
public Float value() {
return value;
}
public int asInt() {
return (int) value;
}
public long asLong() {
return (long) value;
}
public short asShort() {
return (short) value;
}
public byte asByte() {
return (byte) value;
}
public float asFloat() {
return value;
}
public double asDouble() {
return value;
}
}
static final class ShortValue extends AnnotationValue {
private final short value;
ShortValue(String name, short value) {
super(name);
this.value = value;
}
public Short value() {
return value;
}
public int asInt() {
return value;
}
public long asLong() {
return value;
}
public short asShort() {
return value;
}
public byte asByte() {
return (byte) value;
}
public float asFloat() {
return value;
}
public double asDouble() {
return value;
}
}
static final class IntegerValue extends AnnotationValue {
private final int value;
IntegerValue(String name, int value) {
super(name);
this.value = value;
}
public Integer value() {
return value;
}
public int asInt() {
return value;
}
public long asLong() {
return value;
}
public short asShort() {
return (short) value;
}
public byte asByte() {
return (byte) value;
}
public float asFloat() {
return value;
}
public double asDouble() {
return value;
}
}
static final class LongValue extends AnnotationValue {
private final long value;
LongValue(String name, long value) {
super(name);
this.value = value;
}
public Long value() {
return value;
}
public int asInt() {
return (int) value;
}
public long asLong() {
return value;
}
public short asShort() {
return (short) value;
}
public byte asByte() {
return (byte) value;
}
public float asFloat() {
return value;
}
public double asDouble() {
return value;
}
}
static final class BooleanValue extends AnnotationValue {
private final boolean value;
BooleanValue(String name, boolean value) {
super(name);
this.value = value;
}
public Boolean value() {
return value;
}
public boolean asBoolean() {
return value;
}
}
static final class EnumValue extends AnnotationValue {
private final String value;
private final DotName typeName;
EnumValue(String name, DotName typeName, String value) {
super(name);
this.typeName = typeName;
this.value = value;
}
public String value() {
return value;
}
public String asEnum() {
return value;
}
public DotName asEnumType() {
return typeName;
}
}
static final class ClassValue extends AnnotationValue {
private final Type type;
ClassValue(String name, Type type) {
super(name);
this.type = type;
}
public Type value() {
return type;
}
public Type asClass() {
return type;
}
}
static final class NestedAnnotation extends AnnotationValue {
private final AnnotationInstance value;
NestedAnnotation(String name, AnnotationInstance value) {
super(name);
this.value = value;
}
public AnnotationInstance value() {
return value;
}
public AnnotationInstance asNested() {
return value;
}
}
static final class ArrayValue extends AnnotationValue {
private final AnnotationValue[] value;
ArrayValue(String name, AnnotationValue value[]) {
super(name);
this.value = value;
}
public AnnotationValue[] value() {
return value;
}
AnnotationValue[] asArray() {
return value;
}
public String toString() {
StringBuilder builder = new StringBuilder();
if (super.name.length() > 0)
builder.append(super.name).append(" = ");
builder.append('[');
for (int i = 0; i < value.length; i++) {
builder.append(value[i]);
if (i < value.length - 1)
builder.append(',');
}
return builder.append(']').toString();
}
public int[] asIntArray() {
int length = value.length;
int[] array = new int[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asInt();
}
return array;
}
public long[] asLongArray() {
int length = value.length;
long[] array = new long[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asLong();
}
return array;
}
public short[] asShortArray() {
int length = value.length;
short[] array = new short[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asShort();
}
return array;
}
public byte[] asByteArray() {
int length = value.length;
byte[] array = new byte[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asByte();
}
return array;
}
public float[] asFloatArray() {
int length = value.length;
float[] array = new float[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asFloat();
}
return array;
}
public double[] asDoubleArray() {
int length = value.length;
double[] array = new double[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asDouble();
}
return array;
}
public char[] asCharArray() {
int length = value.length;
char[] array = new char[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asChar();
}
return array;
}
public boolean[] asBooleanArray() {
int length = value.length;
boolean[] array = new boolean[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asBoolean();
}
return array;
}
public String[] asStringArray() {
int length = value.length;
String[] array = new String[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asString();
}
return array;
}
public String[] asEnumArray() {
int length = value.length;
String[] array = new String[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asEnum();
}
return array;
}
public Type[] asClassArray() {
int length = value.length;
Type[] array = new Type[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asClass();
}
return array;
}
public AnnotationInstance[] asNestedArray() {
int length = value.length;
AnnotationInstance[] array = new AnnotationInstance[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asNested();
}
return array;
}
public DotName[] asEnumTypeArray() {
int length = value.length;
DotName[] array = new DotName[length];
for (int i = 0; i < length; i++) {
array[i] = value[i].asEnumType();
}
return array;
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.ui.terminals/src/org/eclipse/tcf/te/ui/terminals/streams/OutputStreamMonitor.java b/target_explorer/plugins/org.eclipse.tcf.te.ui.terminals/src/org/eclipse/tcf/te/ui/terminals/streams/OutputStreamMonitor.java
index 5e26d65db..2f383e339 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.ui.terminals/src/org/eclipse/tcf/te/ui/terminals/streams/OutputStreamMonitor.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.ui.terminals/src/org/eclipse/tcf/te/ui/terminals/streams/OutputStreamMonitor.java
@@ -1,262 +1,264 @@
/*******************************************************************************
* Copyright (c) 2011 Wind River Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.ui.terminals.streams;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.tcf.te.runtime.interfaces.IDisposable;
import org.eclipse.tcf.te.runtime.services.interfaces.constants.ILineSeparatorConstants;
import org.eclipse.tcf.te.ui.terminals.activator.UIPlugin;
import org.eclipse.tcf.te.ui.terminals.internal.tracing.ITraceIds;
import org.eclipse.tcf.te.ui.terminals.nls.Messages;
import org.eclipse.tm.internal.terminal.provisional.api.ITerminalControl;
/**
* Output stream monitor implementation.
* <p>
* <b>Note:</b> The output is going <i>to</i> the terminal. Therefore, the output
* stream monitor is attached to the stdout and/or stderr stream of the monitored
* (remote) process.
*/
@SuppressWarnings("restriction")
public class OutputStreamMonitor implements IDisposable {
// The default buffer size to use
private static final int BUFFER_SIZE = 8192;
// Reference to the parent terminal control
private final ITerminalControl terminalControl;
// Reference to the monitored (input) stream
private final InputStream stream;
// The line separator used by the monitored (input) stream
private final String lineSeparator;
// Reference to the thread reading the stream
private Thread thread;
// Flag to mark the monitor disposed. When disposed,
// no further data is read from the monitored stream.
private boolean disposed;
// A list of object to dispose if this monitor is disposed
private final List<IDisposable> disposables = new ArrayList<IDisposable>();
/**
* Constructor.
*
* @param terminalControl The parent terminal control. Must not be <code>null</code>.
* @param stream The stream. Must not be <code>null</code>.
* @param lineSeparator The line separator used by the stream.
*/
public OutputStreamMonitor(ITerminalControl terminalControl, InputStream stream, String lineSeparator) {
super();
Assert.isNotNull(terminalControl);
this.terminalControl = terminalControl;
Assert.isNotNull(stream);
this.stream = new BufferedInputStream(stream, BUFFER_SIZE);
this.lineSeparator = lineSeparator;
}
/**
* Adds the given disposable object to the list. The method will do nothing
* if either the disposable object is already part of the list or the monitor
* is disposed.
*
* @param disposable The disposable object. Must not be <code>null</code>.
*/
public final void addDisposable(IDisposable disposable) {
Assert.isNotNull(disposable);
if (!disposed && !disposables.contains(disposable)) disposables.add(disposable);
}
/**
* Removes the disposable object from the list.
*
* @param disposable The disposable object. Must not be <code>null</code>.
*/
public final void removeDisposable(IDisposable disposable) {
Assert.isNotNull(disposable);
disposables.remove(disposable);
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.runtime.interfaces.IDisposable#dispose()
*/
@Override
public void dispose() {
// If already disposed --> return immediately
if (disposed) return;
// Mark the monitor disposed
disposed = true;
// Close the stream (ignore exceptions on close)
try { stream.close(); } catch (IOException e) { /* ignored on purpose */ }
// Dispose all registered disposable objects
for (IDisposable disposable : disposables) disposable.dispose();
// Clear the list
disposables.clear();
}
/**
* Starts the terminal output stream monitor.
*/
protected void startMonitoring() {
// If already initialized -> return immediately
if (thread != null) return;
// Create a new runnable which is constantly reading from the stream
Runnable runnable = new Runnable() {
@Override
public void run() {
readStream();
}
};
// Create the reader thread
thread = new Thread(runnable, "Terminal Output Stream Monitor Thread"); //$NON-NLS-1$
// Configure the reader thread
thread.setDaemon(true);
thread.setPriority(Thread.MIN_PRIORITY);
// Start the processing
thread.start();
}
/**
* Returns the terminal control that this stream monitor is associated with.
*/
protected ITerminalControl getTerminalControl() {
return terminalControl;
}
/**
* Reads from the output stream and write the read content
* to the terminal control output stream.
*/
void readStream() {
// Creates the read buffer
byte[] readBuffer = new byte[BUFFER_SIZE];
// We need to maintain UI responsiveness but still stream the content
// to the terminal control fast. Put the thread to a short sleep each second.
long sleepMarker = System.currentTimeMillis();
// Read from the stream until EOS is reached or the
// monitor is marked disposed.
int read = 0;
while (read >= 0 && !disposed) {
try {
// Read from the stream
read = stream.read(readBuffer);
// If some data has been read, append to the terminal
// control output stream
if (read > 0) {
// Allow for post processing the read content before appending
byte[] processedReadBuffer = onContentReadFromStream(readBuffer, read);
if (processedReadBuffer != readBuffer) {
read = processedReadBuffer.length;
}
terminalControl.getRemoteToTerminalOutputStream().write(processedReadBuffer, 0, read);
}
} catch (IOException e) {
// IOException received. If this is happening when already disposed -> ignore
if (!disposed) {
IStatus status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(),
NLS.bind(Messages.OutputStreamMonitor_error_readingFromStream, e.getLocalizedMessage()), e);
UIPlugin.getDefault().getLog().log(status);
}
break;
} catch (NullPointerException e) {
// killing the stream monitor while reading can cause an NPE
// when reading from the stream
if (!disposed && thread != null) {
IStatus status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(),
NLS.bind(Messages.OutputStreamMonitor_error_readingFromStream, e.getLocalizedMessage()), e);
UIPlugin.getDefault().getLog().log(status);
}
break;
}
// See above -> Thread will go to sleep each second
if (System.currentTimeMillis() - sleepMarker > 1000) {
sleepMarker = System.currentTimeMillis();
try { Thread.sleep(1); } catch (InterruptedException e) { /* ignored on purpose */ }
}
}
// Dispose ourself
dispose();
}
/**
* Allow for processing of data from byte stream after it is read from
* client but before it is appended to the terminal. If the returned byte
* array is different than the one that was passed in with the byteBuffer
* argument, then the bytesRead value will be ignored and the full
* returned array will be written out.
*
* @param byteBuffer The byte stream. Must not be <code>null</code>.
* @param bytesRead The number of bytes that were read into the read buffer.
* @return The processed byte stream.
*
*/
protected byte[] onContentReadFromStream(byte[] byteBuffer, int bytesRead) {
Assert.isNotNull(byteBuffer);
// If tracing is enabled, print out the decimal byte values read
if (UIPlugin.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_OUTPUT_STREAM_MONITOR)) {
StringBuilder debug = new StringBuilder("byteBuffer [decimal, " + bytesRead + " bytes] : "); //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i < bytesRead; i++) {
debug.append(Byte.valueOf(byteBuffer[i]).intValue());
debug.append(' ');
}
System.out.println(debug.toString());
}
// Remember if the text got changed.
boolean changed = false;
// How can me make sure that we don't mess with the encoding here?
String text = new String(byteBuffer, 0, bytesRead);
// Shift-In (14) and Shift-Out(15) confuses the terminal widget
if (text.indexOf(14) != -1 || text.indexOf(15) != -1) {
text = text.replaceAll("\\x0e", "").replaceAll("\\x0f", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
changed = true;
}
// Check on the line separator setting
if (lineSeparator != null
- && !ILineSeparatorConstants.LINE_SEPARATOR_CRLF.equals(lineSeparator)
- && text.contains(lineSeparator)) {
- text = text.replaceAll(lineSeparator, "\r\n"); //$NON-NLS-1$
- changed = true;
+ && !ILineSeparatorConstants.LINE_SEPARATOR_CRLF.equals(lineSeparator)) {
+ String separator = ILineSeparatorConstants.LINE_SEPARATOR_LF.equals(lineSeparator) ? "\n" : "\r"; //$NON-NLS-1$ //$NON-NLS-2$
+ if (text.contains(separator)) {
+ text = text.replaceAll(separator, "\r\n"); //$NON-NLS-1$
+ changed = true;
+ }
}
// If changed, get the new bytes array
if (changed) byteBuffer = text.getBytes();
return byteBuffer;
}
}
| true | false | null | null |
diff --git a/src/main/java/Utils/Monopoly/MonopolyGame.java b/src/main/java/Utils/Monopoly/MonopolyGame.java
index 845a8f8..65e9959 100644
--- a/src/main/java/Utils/Monopoly/MonopolyGame.java
+++ b/src/main/java/Utils/Monopoly/MonopolyGame.java
@@ -1,156 +1,155 @@
package Utils.Monopoly;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by IntelliJ IDEA.
* User: bsankar
* Date: 9/11/12
*/
public class MonopolyGame {
private HashMap<String, Long> popularSquare = new HashMap<String, Long>();
private int communityChestPile = new Random().nextInt(16);
private int chancePile = new Random().nextInt(16);
private void init() {
for (MonopolySquares square : MonopolySquares.values()) {
popularSquare.put(square.modalValue, (long) 0);
}
}
public void startGame(MonopolyDice dice, long numberOfRolls) throws Exception {
init();
- n = numberOfRolls;
MonopolySquares currentSquare = MonopolySquares.GO;
popularSquare.put(currentSquare.getModalValue(), (long) 1);
for (long sample = 1; sample <= numberOfRolls; sample++) {
int diceRoll = dice.roll();
if (diceRoll == 0) {
currentSquare = MonopolySquares.JAIL;
} else {
currentSquare = nextSquare(currentSquare, diceRoll);
}
long counter = popularSquare.get(currentSquare.getModalValue());
popularSquare.put(currentSquare.getModalValue(), counter + 1);
}
}
public String getModalString() {
String sq1 = null, sq2 = null, sq3 = null;
long max1 = 0, max2 = 0, max3 = 0;
for (Map.Entry<String, Long> entry : popularSquare.entrySet()) {
long val = entry.getValue();
String key = entry.getKey();
if (val > max1) {
max3 = max2;
sq3 = sq2;
max2 = max1;
sq2 = sq1;
max1 = val;
sq1 = key;
} else if (val > max2) {
max3 = max2;
sq3 = sq2;
max2 = val;
sq2 = key;
} else if (val > max3) {
max3 = val;
sq3 = key;
}
}
/*System.out.println((((double) max1 / (double) n) * 100) + " "
+ (((double) max2 / (double) n) * 100) + " "
+ (((double) max3 / (double) n) * 100));*/
return (sq1 + sq2 + sq3);
}
private MonopolySquares nextSquare(MonopolySquares square, int steps) throws Exception {
int val = ((square.getValue() + steps) % MonopolySquares.size);
MonopolySquares sq = MonopolySquares.getByValue(val);
if (sq.equals(MonopolySquares.CH1)
|| sq.equals(MonopolySquares.CH2)
|| sq.equals(MonopolySquares.CH3)) {
return Chance(sq);
} else if (sq.equals(MonopolySquares.CC1)
|| sq.equals(MonopolySquares.CC2)
|| sq.equals(MonopolySquares.CC3)) {
return CommunityChest(sq);
} else if (sq.equals(MonopolySquares.G2J)) {
return MonopolySquares.JAIL;
}
return sq;
}
private MonopolySquares CommunityChest(MonopolySquares square) {
communityChestPile = (communityChestPile + 1) % 16;
//communityChestPile = (new Random().nextInt(16));
//Assumption the Go card is the 0th position of the pile
if (communityChestPile == 0) {
return MonopolySquares.GO;
}
//Assumption the Jail card is the 2th position of the pile
else if (communityChestPile == 1) {
return MonopolySquares.JAIL;
}
return square;
}
private MonopolySquares Chance(MonopolySquares square) {
chancePile = (chancePile + 1) % 16;
//chancePile = (new Random().nextInt(16));
switch (chancePile) {
case 0:
return MonopolySquares.GO;
case 1:
return MonopolySquares.JAIL;
case 2:
return MonopolySquares.C1;
case 3:
return MonopolySquares.E3;
case 4:
return MonopolySquares.H2;
case 5:
return MonopolySquares.R1;
case 7:
case 8:
return nextRailway(square);
case 9:
return nextUtility(square);
case 10:
return backThreeSquares(square);
default:
return square;
}
}
private MonopolySquares nextRailway(MonopolySquares square) {
if (square.equals(MonopolySquares.CH1)) {
return MonopolySquares.R2;
} else if (square.equals(MonopolySquares.CH2)) {
return MonopolySquares.R3;
}
return MonopolySquares.R1;
}
private MonopolySquares nextUtility(MonopolySquares square) {
if (square.equals(MonopolySquares.CH1) || square.equals(MonopolySquares.CH3)) {
return MonopolySquares.U1;
}
return MonopolySquares.U2;
}
private MonopolySquares backThreeSquares(MonopolySquares square) {
if (square.equals(MonopolySquares.CH1)) {
return MonopolySquares.T1;
} else if (square.equals(MonopolySquares.CH2)) {
return MonopolySquares.D3;
}
return CommunityChest(square);
//return MonopolySquares.CC3;
}
}
| true | false | null | null |
diff --git a/src/com/oneofthesevenbillion/ziah/ZCord/CommandPM.java b/src/com/oneofthesevenbillion/ziah/ZCord/CommandPM.java
index 9db1d43..0dbe17f 100644
--- a/src/com/oneofthesevenbillion/ziah/ZCord/CommandPM.java
+++ b/src/com/oneofthesevenbillion/ziah/ZCord/CommandPM.java
@@ -1,52 +1,52 @@
package com.oneofthesevenbillion.ziah.ZCord;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import com.oneofthesevenbillion.ziah.ZCord.utils.ArrayUtils;
import com.oneofthesevenbillion.ziah.ZCord.utils.ColorUtils;
import com.oneofthesevenbillion.ziah.ZCord.utils.Utils;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
public class CommandPM extends Command {
public CommandPM() {
super("privatemessage", "zcord.command.privatemessage", "pm");
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length >= 2) {
List<ProxiedPlayer> candidates = Utils.getPlayersFromInputName(args[0]);
- if (candidates.size() > 0) {
+ if (candidates.size() > 1) {
sender.sendMessage(ChatColor.RED + "Too many players" + ChatColor.GRAY + ":");
for (ProxiedPlayer player : candidates) {
sender.sendMessage(player.getName());
}
}else{
ProxiedPlayer client = candidates.get(0);
String message = ColorUtils.fakeMCtoRealMCColor(ArrayUtils.join(Arrays.copyOfRange(args, 1, args.length), " ").trim());
if (client != null) {
sender.sendMessage(ChatColor.GOLD + "You " + ChatColor.GRAY + ">" + ChatColor.GOLD + " " + client.getName() + ChatColor.GRAY + ": " + ChatColor.RESET + message);
client.sendMessage(ChatColor.GOLD + sender.getName() + " " + ChatColor.GRAY + ">" + ChatColor.GOLD + " You" + ChatColor.GRAY + ": " + ChatColor.RESET + message);
System.out.println(ColorUtils.removeAllColors(ChatColor.GOLD + sender.getName() + " " + ChatColor.GRAY + ">" + ChatColor.GOLD + " " + client.getName() + ChatColor.GRAY + ": " + ChatColor.RESET + message));
ProxyServer.getInstance().getLogger().log(Level.INFO, ColorUtils.removeAllColors(ChatColor.GOLD + sender.getName() + " " + ChatColor.GRAY + ">" + ChatColor.GOLD + " " + client.getName() + ChatColor.GRAY + ": " + ChatColor.RESET + message));
}else
if (args[0].equalsIgnoreCase("console")) {
sender.sendMessage(ChatColor.GOLD + "You " + ChatColor.GRAY + ">" + ChatColor.GOLD + " Console" + ChatColor.GRAY + ": " + ChatColor.RESET + message);
System.out.println(ColorUtils.removeAllColors(ChatColor.GOLD + sender.getName() + " " + ChatColor.GRAY + ">" + ChatColor.GOLD + " You" + ChatColor.GRAY + ": " + ChatColor.RESET + message));
ProxyServer.getInstance().getLogger().log(Level.INFO, ColorUtils.removeAllColors(ChatColor.GOLD + sender.getName() + " " + ChatColor.GRAY + ">" + ChatColor.GOLD + " Console" + ChatColor.GRAY + ": " + ChatColor.RESET + message));
}else{
sender.sendMessage(ChatColor.RED + "Player not found!");
}
}
}else{
sender.sendMessage(ChatColor.RED + "Invalid arguments!");
}
}
}
\ No newline at end of file
diff --git a/src/com/oneofthesevenbillion/ziah/ZCord/command/CommandRunCmd.java b/src/com/oneofthesevenbillion/ziah/ZCord/command/CommandRunCmd.java
index 9e4e288..d09f30a 100644
--- a/src/com/oneofthesevenbillion/ziah/ZCord/command/CommandRunCmd.java
+++ b/src/com/oneofthesevenbillion/ziah/ZCord/command/CommandRunCmd.java
@@ -1,42 +1,42 @@
package com.oneofthesevenbillion.ziah.ZCord.command;
import java.util.List;
import com.oneofthesevenbillion.ziah.ZCord.utils.ArrayUtils;
import com.oneofthesevenbillion.ziah.ZCord.utils.Utils;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.protocol.packet.Packet3Chat;
public class CommandRunCmd extends Command {
public CommandRunCmd() {
super("runcmd", "Forces another player to run the specifed command.", "zcord.command.runcmd");
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length >= 2) {
List<ProxiedPlayer> candidates = Utils.getPlayersFromInputName(args[0]);
- if (candidates.size() > 0) {
+ if (candidates.size() > 1) {
sender.sendMessage(ChatColor.RED + "Too many players" + ChatColor.GRAY + ":");
for (ProxiedPlayer player : candidates) {
sender.sendMessage(player.getName());
}
}else{
ProxiedPlayer player = candidates.get(0);
if (player != null) {
String command = ArrayUtils.join(args, " ");
command = command.substring(command.indexOf(" ") + 1, command.length());
sender.sendMessage(ChatColor.GOLD + "Forcing " + ChatColor.RED + player.getDisplayName() + ChatColor.GOLD + " to run the command " + ChatColor.RED + command + ChatColor.GOLD + "...");
player.getServer().unsafe().sendPacket(new Packet3Chat(command));
}else{
sender.sendMessage(ChatColor.RED + "Player not found.");
}
}
}else{
sender.sendMessage(ChatColor.RED + "Invalid arguments.");
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/plugins/org.eclipse.gmf.bridge.trace/src/org/eclipse/gmf/bridge/internal/trace/impl/GenLinkTraceImpl.java b/plugins/org.eclipse.gmf.bridge.trace/src/org/eclipse/gmf/bridge/internal/trace/impl/GenLinkTraceImpl.java
index 041e1569f..bf7fb06ee 100644
--- a/plugins/org.eclipse.gmf.bridge.trace/src/org/eclipse/gmf/bridge/internal/trace/impl/GenLinkTraceImpl.java
+++ b/plugins/org.eclipse.gmf.bridge.trace/src/org/eclipse/gmf/bridge/internal/trace/impl/GenLinkTraceImpl.java
@@ -1,185 +1,186 @@
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.eclipse.gmf.bridge.internal.trace.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.eclipse.emf.ocl.query.Query;
import org.eclipse.emf.ocl.query.QueryFactory;
import org.eclipse.gmf.bridge.internal.trace.GenLinkLabelTrace;
import org.eclipse.gmf.bridge.internal.trace.GenLinkTrace;
import org.eclipse.gmf.bridge.internal.trace.TracePackage;
import org.eclipse.gmf.codegen.gmfgen.FeatureModelFacet;
import org.eclipse.gmf.codegen.gmfgen.GMFGenPackage;
import org.eclipse.gmf.codegen.gmfgen.GenLink;
import org.eclipse.gmf.codegen.gmfgen.TypeLinkModelFacet;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Gen Link Trace</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.gmf.bridge.internal.trace.impl.GenLinkTraceImpl#getLinkLabelTraces <em>Link Label Traces</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class GenLinkTraceImpl extends MatchingTraceImpl implements GenLinkTrace {
/**
* The cached value of the '{@link #getLinkLabelTraces() <em>Link Label Traces</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLinkLabelTraces()
* @generated
* @ordered
*/
protected EList linkLabelTraces = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected GenLinkTraceImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return TracePackage.Literals.GEN_LINK_TRACE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList getLinkLabelTraces() {
if (linkLabelTraces == null) {
linkLabelTraces = new EObjectContainmentEList(GenLinkLabelTrace.class, this, TracePackage.GEN_LINK_TRACE__LINK_LABEL_TRACES);
}
return linkLabelTraces;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public void setContext(GenLink genLink) {
StringBuffer result = new StringBuffer();
result.append("modelFacet.oclIsKindOf(");
if (genLink.getModelFacet() instanceof FeatureModelFacet) {
EStructuralFeature feature = ((FeatureModelFacet) genLink.getModelFacet()).getMetaFeature().getEcoreFeature();
result.append("gmfgen::FeatureLinkModelFacet) and ");
result.append("(let _feature_:ecore::EStructuralFeature = modelFacet.oclAsType(gmfgen::FeatureLinkModelFacet).metaFeature.ecoreFeature in ");
result.append(getEStructuralFeatureComparison("_feature_", feature));
result.append(")");
} else if (genLink.getModelFacet() instanceof TypeLinkModelFacet) {
EClass eClass = ((TypeLinkModelFacet) genLink.getModelFacet()).getMetaClass().getEcoreClass();
result.append("gmfgen::TypeLinkModelFacet) and ");
result.append("(let _eClass_:ecore::EClass = modelFacet.oclAsType(gmfgen::TypeLinkModelFacet).metaClass.ecoreClass in ");
result.append(getEClassComparision("_eClass_", eClass));
result.append(")");
} else {
- throw new IllegalArgumentException("Incorrect gen link passed - Feature/TypeLinkModelFacet should be used");
+ return;
+ //throw new IllegalArgumentException("Incorrect gen link passed - Feature/TypeLinkModelFacet should be used");
}
setQueryText(result.toString());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case TracePackage.GEN_LINK_TRACE__LINK_LABEL_TRACES:
return ((InternalEList)getLinkLabelTraces()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case TracePackage.GEN_LINK_TRACE__LINK_LABEL_TRACES:
return getLinkLabelTraces();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case TracePackage.GEN_LINK_TRACE__LINK_LABEL_TRACES:
getLinkLabelTraces().clear();
getLinkLabelTraces().addAll((Collection)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eUnset(int featureID) {
switch (featureID) {
case TracePackage.GEN_LINK_TRACE__LINK_LABEL_TRACES:
getLinkLabelTraces().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean eIsSet(int featureID) {
switch (featureID) {
case TracePackage.GEN_LINK_TRACE__LINK_LABEL_TRACES:
return linkLabelTraces != null && !linkLabelTraces.isEmpty();
}
return super.eIsSet(featureID);
}
public Query createQuery() {
return QueryFactory.eINSTANCE.createQuery(getQueryText(), GMFGenPackage.eINSTANCE.getGenLink());
}
} //GenLinkTraceImpl
\ No newline at end of file
diff --git a/plugins/org.eclipse.gmf.bridge.trace/src/org/eclipse/gmf/bridge/internal/trace/impl/GenNodeTraceImpl.java b/plugins/org.eclipse.gmf.bridge.trace/src/org/eclipse/gmf/bridge/internal/trace/impl/GenNodeTraceImpl.java
index 2c0dad633..ec30e0d83 100644
--- a/plugins/org.eclipse.gmf.bridge.trace/src/org/eclipse/gmf/bridge/internal/trace/impl/GenNodeTraceImpl.java
+++ b/plugins/org.eclipse.gmf.bridge.trace/src/org/eclipse/gmf/bridge/internal/trace/impl/GenNodeTraceImpl.java
@@ -1,205 +1,208 @@
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.eclipse.gmf.bridge.internal.trace.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.eclipse.emf.ocl.query.Query;
import org.eclipse.emf.ocl.query.QueryFactory;
import org.eclipse.gmf.bridge.internal.trace.GenCompartmentTrace;
import org.eclipse.gmf.bridge.internal.trace.GenNodeLabelTrace;
import org.eclipse.gmf.bridge.internal.trace.GenNodeTrace;
import org.eclipse.gmf.bridge.internal.trace.TracePackage;
import org.eclipse.gmf.codegen.gmfgen.GMFGenPackage;
import org.eclipse.gmf.codegen.gmfgen.GenNode;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Gen Node Trace</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.gmf.bridge.internal.trace.impl.GenNodeTraceImpl#getNodeLabelTraces <em>Node Label Traces</em>}</li>
* <li>{@link org.eclipse.gmf.bridge.internal.trace.impl.GenNodeTraceImpl#getCompartmentTraces <em>Compartment Traces</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class GenNodeTraceImpl extends MatchingTraceImpl implements GenNodeTrace {
/**
* The cached value of the '{@link #getNodeLabelTraces() <em>Node Label Traces</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNodeLabelTraces()
* @generated
* @ordered
*/
protected EList nodeLabelTraces = null;
/**
* The cached value of the '{@link #getCompartmentTraces() <em>Compartment Traces</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCompartmentTraces()
* @generated
* @ordered
*/
protected EList compartmentTraces = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected GenNodeTraceImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return TracePackage.Literals.GEN_NODE_TRACE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList getNodeLabelTraces() {
if (nodeLabelTraces == null) {
nodeLabelTraces = new EObjectContainmentEList(GenNodeLabelTrace.class, this, TracePackage.GEN_NODE_TRACE__NODE_LABEL_TRACES);
}
return nodeLabelTraces;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList getCompartmentTraces() {
if (compartmentTraces == null) {
compartmentTraces = new EObjectContainmentEList(GenCompartmentTrace.class, this, TracePackage.GEN_NODE_TRACE__COMPARTMENT_TRACES);
}
return compartmentTraces;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public void setContext(GenNode genNode) {
+ if (genNode.getModelFacet() == null) {
+ return;
+ }
StringBuffer query = new StringBuffer();
query.append("let _eClass_:ecore::EClass = modelFacet.metaClass.ecoreClass in ");
query.append(getEClassComparision("_eClass_", genNode.getModelFacet().getMetaClass().getEcoreClass()));
setQueryText(query.toString());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case TracePackage.GEN_NODE_TRACE__NODE_LABEL_TRACES:
return ((InternalEList)getNodeLabelTraces()).basicRemove(otherEnd, msgs);
case TracePackage.GEN_NODE_TRACE__COMPARTMENT_TRACES:
return ((InternalEList)getCompartmentTraces()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case TracePackage.GEN_NODE_TRACE__NODE_LABEL_TRACES:
return getNodeLabelTraces();
case TracePackage.GEN_NODE_TRACE__COMPARTMENT_TRACES:
return getCompartmentTraces();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case TracePackage.GEN_NODE_TRACE__NODE_LABEL_TRACES:
getNodeLabelTraces().clear();
getNodeLabelTraces().addAll((Collection)newValue);
return;
case TracePackage.GEN_NODE_TRACE__COMPARTMENT_TRACES:
getCompartmentTraces().clear();
getCompartmentTraces().addAll((Collection)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eUnset(int featureID) {
switch (featureID) {
case TracePackage.GEN_NODE_TRACE__NODE_LABEL_TRACES:
getNodeLabelTraces().clear();
return;
case TracePackage.GEN_NODE_TRACE__COMPARTMENT_TRACES:
getCompartmentTraces().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean eIsSet(int featureID) {
switch (featureID) {
case TracePackage.GEN_NODE_TRACE__NODE_LABEL_TRACES:
return nodeLabelTraces != null && !nodeLabelTraces.isEmpty();
case TracePackage.GEN_NODE_TRACE__COMPARTMENT_TRACES:
return compartmentTraces != null && !compartmentTraces.isEmpty();
}
return super.eIsSet(featureID);
}
public Query createQuery() {
return QueryFactory.eINSTANCE.createQuery(getQueryText(), GMFGenPackage.eINSTANCE.getGenTopLevelNode());
}
} //GenNodeTraceImpl
\ No newline at end of file
| false | false | null | null |
diff --git a/src/com/litle/sdk/LitleBatchFileRequest.java b/src/com/litle/sdk/LitleBatchFileRequest.java
index e59dcfb..a21abe6 100644
--- a/src/com/litle/sdk/LitleBatchFileRequest.java
+++ b/src/com/litle/sdk/LitleBatchFileRequest.java
@@ -1,299 +1,299 @@
package com.litle.sdk;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import com.litle.sdk.generate.Authentication;
import com.litle.sdk.generate.LitleRequest;
public class LitleBatchFileRequest {
private JAXBContext jc;
private Properties properties;
private Communication communication;
private List<LitleBatchRequest> litleBatchRequestList;
private String requestFileName;
private File requestFile;
private File responseFile;
private File tempBatchRequestFile;
private File tempLitleRequestFile;
private String requestId;
private Marshaller marshaller;
protected int maxAllowedTransactionsPerFile;
/**
* Recommend NOT to change this value.
*/
protected final int litleLimit_maxAllowedTransactionsPerFile = 500000;
/**
* Construct a LitleBatchFileRequest using the configuration specified in
* $HOME/.litle_SDK_config.properties
*/
public LitleBatchFileRequest(String requestFileName) {
intializeMembers(requestFileName);
}
/**
* Construct a LitleBatchFileRequest specifying the file name for the request (ex: filename: TestFile.xml
* the extension should be provided if the file has to generated in certain format like xml or txt etc) and
* configuration in code. This should
* be used by integrations that have another way to specify their
* configuration settings (ofbiz, etc)
*
* Properties that *must* be set are:
*
* batchHost (eg https://payments.litle.com) batchPort (eg 8080)
* username merchantId password version (eg
* 8.10) batchTcpTimeout (in seconds) batchUseSSL
* BatchRequestPath folder - specify the absolute path
* BatchResponsePath folder - specify the absolute path
* Optional properties are: proxyHost proxyPort
* printxml (possible values "true" and "false" - defaults to false)
*
* @param RequestFileName, config
*/
public LitleBatchFileRequest(String requestFileName, Properties config) {
intializeMembers(requestFileName, config);
}
private void intializeMembers(String requestFileName){
intializeMembers(requestFileName, null);
}
public void intializeMembers(String requestFileName, Properties config){
try {
this.jc = JAXBContext.newInstance("com.litle.sdk.generate");
this.communication = new Communication();
this.litleBatchRequestList = new ArrayList<LitleBatchRequest>();
this.requestFileName = requestFileName;
marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
if( config == null || config.isEmpty() ){
this.properties = new Properties();
this.properties.load(new FileInputStream(Configuration.location()));
} else {
fillInMissingFieldsFromConfig(config);
this.properties = config;
}
this.maxAllowedTransactionsPerFile = Integer.parseInt(properties.getProperty("maxAllowedTransactionsPerFile"));
if( maxAllowedTransactionsPerFile > litleLimit_maxAllowedTransactionsPerFile ){
throw new LitleBatchException("maxAllowedTransactionsPerFile property value cannot exceed " + String.valueOf(litleLimit_maxAllowedTransactionsPerFile));
}
responseFile = getFileToWrite("batchResponseFolder");
} catch (FileNotFoundException e) {
throw new LitleBatchException("Configuration file not found. If you are not using the .litle_SDK_config.properties file, please use the LitleOnline(Properties) constructor. If you are using .litle_SDK_config.properties, you can generate one using java -jar litle-sdk-for-java-8.10.jar", e);
} catch (IOException e) {
throw new LitleBatchException(
"Configuration file could not be loaded. Check to see if the user running this has permission to access the file",
e);
} catch (JAXBException e) {
throw new LitleBatchException("Unable to load jaxb dependencies. Perhaps a classpath issue?", e);
}
}
protected void setCommunication(Communication communication) {
this.communication = communication;
}
Properties getConfig(){
return this.properties;
}
public LitleBatchRequest createBatch(String merchantId) throws FileNotFoundException, JAXBException {
LitleBatchRequest litleBatchRequest = new LitleBatchRequest(merchantId, this);
litleBatchRequestList.add(litleBatchRequest);
return litleBatchRequest;
}
/**
* This method generates the response file alone. To generate the response object call
* sendToLitle method.
*
* @throws LitleBatchException
* @throws JAXBException
*/
public void generateRequestFile() throws LitleBatchException, JAXBException {
try {
LitleRequest litleRequest = buildLitleRequest();
// Code to write to the file directly
File localFile = getFileToWrite("batchRequestFolder");
OutputStream os = new FileOutputStream(localFile.getAbsolutePath());
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(litleRequest, os);
requestFile = localFile;
}
catch (IOException e) {
// TODO Auto-generated catch block
throw new LitleBatchException(
"Error while sending batch", e);
}
}
public File getFile() {
return requestFile;
}
public int getMaxAllowedTransactionsPerFile(){
return this.maxAllowedTransactionsPerFile;
}
void fillInMissingFieldsFromConfig(Properties config) {
Properties localConfig = new Properties();
boolean propertiesReadFromFile = false;
try {
String[] allProperties = {"username","password","proxyHost","proxyPort","version","batchHost","batchPort","batchTcpTimeout","batchUseSSL","maxAllowedTransactionsPerFile","maxTransactionsPerBatch", "batchRequestFolder", "batchResponseFolder"};
for(String prop : allProperties){
if(config.getProperty(prop) == null) {
if(!propertiesReadFromFile){
localConfig.load(new FileInputStream(Configuration.location()));
propertiesReadFromFile = true;
}
config.setProperty(prop, localConfig.getProperty(prop));
}
}
} catch (FileNotFoundException e) {
throw new LitleBatchException("File was not found: " + Configuration.location(), e);
} catch (IOException e) {
throw new LitleBatchException("There was an IO exception.", e);
}
}
public int getNumberOfBatches() {
return this.litleBatchRequestList.size();
}
public int getNumberOfTransactionInFile() {
int i = 0;
int totalNumberOfTransactions = 0;
for (i = 0; i < getNumberOfBatches(); i++) {
LitleBatchRequest lbr = litleBatchRequestList.get(i);
totalNumberOfTransactions += lbr.getBatchRequest()
.getTransactions().size();
}
return totalNumberOfTransactions;
}
/**
* This method generates the response file and the objects to access the transaction responses.
*
* @throws LitleBatchException
*/
public LitleBatchFileResponse sendToLitle() throws LitleBatchException {
try {
java.util.Date date= new java.util.Date();
this.tempBatchRequestFile = new File("/tmp/tempBatchFile"+ date.getTime());
OutputStream batchReqWriter = new FileOutputStream(tempBatchRequestFile.getAbsoluteFile());
//close the all the batch files
byte[] readData = new byte[1024];
for(LitleBatchRequest batchReq: litleBatchRequestList) {
//TODO add the batch transaction before the closing tag
FileInputStream fis = new FileInputStream(batchReq.getFile());
int i = fis.read(readData);
while (i != -1) {
batchReqWriter.write(readData, 0, i);
i = fis.read(readData);
}
marshaller.marshal(batchReq, batchReqWriter);
batchReq.closeFile();
fis.close();
}
//close the file
batchReqWriter.close();
//create a file for writing the litlerequest
this.tempLitleRequestFile = new File("/tmp/tempLitleRequestFile"+ date.getTime());
//close it
generateRequestFile();
//communication.sendLitleBatchFileToIBC(tempBatchRequestFile, responseFile, properties);
LitleBatchFileResponse retObj = new LitleBatchFileResponse(responseFile);
return retObj;
} catch (JAXBException e) {
throw new LitleBatchException("There was a JAXB exception.", e);
}
catch (IOException e) {
throw new LitleBatchException("There was a IO exception.", e);
}
}
void setResponseFile(File inFile){
this.responseFile = inFile;
}
void setId(String id){
this.requestId = id;
}
/**
* This method initializes the high level properties for the XML(ex: initializes the user name and password for the presenter)
* @return
*/
private LitleRequest buildLitleRequest() {
Authentication authentication = new Authentication();
authentication.setPassword(this.properties.getProperty("password"));
authentication.setUser(this.properties.getProperty("username"));
LitleRequest litleRequest = new LitleRequest();
- if(requestId == null) {
+ if(requestId != null && requestId.length() != 0) {
litleRequest.setId(requestId);
}
litleRequest.setAuthentication(authentication);
litleRequest.setVersion(this.properties.getProperty("version"));
BigInteger numOfBatches = BigInteger.valueOf(this.litleBatchRequestList.size());
litleRequest.setNumBatchRequests(numOfBatches);
// for(LitleBatchRequest lbr : this.litleBatchRequestList) {
// litleRequest.getBatchRequests().add(lbr.getBatchRequest());
// }
return litleRequest;
}
/**
* This method gets the folder path of either the request or reposne.
* @param locationKey
* @return
*/
File getFileToWrite(String locationKey) {
String fileName = this.requestFileName;
String writeFolderPath = this.properties.getProperty(locationKey);
File fileToReturn = new File(writeFolderPath + File.separator + fileName);
if (!fileToReturn.getParentFile().exists()) {
fileToReturn.getParentFile().mkdir();
}
return fileToReturn;
}
public boolean isEmpty() {
return (getNumberOfTransactionInFile() == 0) ? true : false;
}
public boolean isFull() {
return (getNumberOfTransactionInFile() == this.maxAllowedTransactionsPerFile);
}
}
| true | false | null | null |
diff --git a/common/theboo/mods/customrecipes/RecipeLoader.java b/common/theboo/mods/customrecipes/RecipeLoader.java
index 6896d7e..8a093d2 100644
--- a/common/theboo/mods/customrecipes/RecipeLoader.java
+++ b/common/theboo/mods/customrecipes/RecipeLoader.java
@@ -1,886 +1,886 @@
package theboo.mods.customrecipes;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.logging.Level;
import java.lang.StringIndexOutOfBoundsException;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraft.item.crafting.ShapelessRecipes;
import theboo.mods.customrecipes.dictionary.Dictionary;
import theboo.mods.customrecipes.lib.Reference;
import theboo.mods.customrecipes.logger.Logger;
import cpw.mods.fml.common.IFuelHandler;
import cpw.mods.fml.common.registry.GameRegistry;
/**
* CustomRecipes RecipeLoader
*
* <br> The loader class loads all the recipes and holds all similar methods.
*
* @license
Copyright (C) 2013 TheBoo
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author TheBoo
* @author MightyPork
*
*/
public class RecipeLoader implements IFuelHandler {
private Hashtable<String,ItemStack> dict = new Hashtable<String,ItemStack>();
private Hashtable<String,Integer> fuels = new Hashtable<String,Integer>();
private int DICT_VERSION = 0;
public static RecipeLoader instance;
public RecipeLoader() {
instance = this;
}
public int getFuel(int i, int j) {
String identifier = Integer.toString(i) + "." + Integer.toString(j);
if(fuels.get(identifier)==null){return 0;}
return (Integer)fuels.get(identifier);
}
@Override
public int getBurnTime(ItemStack fuel) {
return getFuel(fuel.itemID, fuel.getItemDamage());
}
public void loadRecipes() {
boolean fail=!(new File(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/dictionary.txt")).exists();
if(fail){
(new File(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/")).mkdirs();
regenerateDictionary();
fail=false;
Logger.log(Level.INFO, "Creating dictionary file.\n");
}
loadRecipeFile(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/dictionary.txt", Reference.DEBUG);
Logger.log(Level.INFO, "Loading dictionary.txt");
if(DICT_VERSION != Dictionary.DICT_VERSION_CURRENT){
(new File(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/")).mkdirs();
regenerateDictionary();
DICT_VERSION = Dictionary.DICT_VERSION_CURRENT;
Logger.log(Level.INFO, "\nRecipe dictionary is outdated.\nBuilding new dictionary.\n");
loadRecipeFile(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/dictionary.txt", false);
Logger.log(Level.INFO, "Loading dictionary.txt");
}
File dir = new File(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/");
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".") && !name.substring(name.length()-1).equals("~");
}
};
fail=!(new File(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/dictionary_custom.txt")).exists();
if(fail){
(new File(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/")).mkdirs();
try{
BufferedWriter out = new BufferedWriter(new FileWriter(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/dictionary_custom.txt"));
out.write(
"# *** CUSTOM DICTIONARY ***\n"+
"# Here you can define aliases for mod items and blocks.\n"+
"#\n"+
"# To prevent confussion: You CAN'T create new blocks and items with this file.\n"+
"# They are added by other mods. This file only lets you define aliases for these items.\n"+
"#\n"+
"# This file will be read right after dictionary.txt to make sure\n"+
"# all your following recipes (in other files) can access these aliases.\n"+
"#\n"+
"# Example alias definition:\n"+
"# silmarilShoes = 7859\n"+
"# rubyGem = 9958,13 where 9958 is ID, 13 is DAMAGE\n#\n\n");
fail=false;
out.close();
Logger.log(Level.INFO, "Creating empty file for Custom Dictionary.\n");
}catch(IOException ioe){
Logger.log(Level.WARNING, "* I/O ERROR: Could not create Custom Dictionary file.\n");
}
}
Logger.log(Level.INFO, "Loading custom dictionary: dictionary_custom.txt");
loadRecipeFile(CustomRecipes.instance.getWorkingFolder() + "/mods/customrecipes/dictionary_custom.txt", true);
generateAliasByLocalizedName();
//do all other recipes
String[] children = dir.list(filter);
if (children == null) {
// Either dir does not exist or is not a directory
fail=true;
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
if(!filename.equals("dictionary.txt") && !filename.equals("dictionary_custom.txt")){
Logger.log(Level.INFO, "Loading recipes: "+filename);
loadRecipeFile(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/"+filename, true);
}
}
}
if(fail){
Logger.log(Level.INFO, "Dictionary not found, creating new one.");
(new File(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/")).mkdirs();
regenerateDictionary();
}
Logger.log(Level.INFO, "Recipes loaded.\n\n");
}
private void regenerateDictionary(){
try {
BufferedWriter out = new BufferedWriter(new FileWriter(CustomRecipes.instance.getWorkingFolder()+"/mods/customrecipes/dictionary.txt"));
for(int a=0;a<Dictionary.AliasDictionary.length;a++){
out.write(Dictionary.AliasDictionary[a]);
out.newLine();
}
out.close();
}
catch (IOException e)
{
Logger.log(Level.WARNING, "* I/O ERROR: Could not regenerate the dictionary in .minecraft/mods/customrecipes/dictionary.txt");
}
}
public void generateAliasByLocalizedName() {
Logger.log(Level.INFO, "Adding all the items localized names as dictionary entries...");
try {
for(Item item : Item.itemsList) {
if(item == null) continue;
dict.put(item.getStatName().replace(" ", ""), new ItemStack(item, 1, 0));
dict.put(item.getStatName().replace(" ", "").toLowerCase(), new ItemStack(item, 1, 0));
dict.put(item.getUnlocalizedName().substring(5).replace(" ", ""), new ItemStack(item, 1, 0));
dict.put(item.getUnlocalizedName().substring(5).replace(" ", "").toLowerCase(), new ItemStack(item, 1, 0));
}
for(Block block : Block.blocksList) {
if(block == null) continue;
dict.put(block.getLocalizedName().replace(" ", ""), new ItemStack(block, 1, 0));
dict.put(block.getLocalizedName().replace(" ", "").toLowerCase(), new ItemStack(block, 1, 0));
dict.put(block.getUnlocalizedName().substring(5).replace(" ", ""), new ItemStack(block, 1, 0));
dict.put(block.getUnlocalizedName().substring(5).replace(" ", "").toLowerCase(), new ItemStack(block, 1, 0));
}
} catch (StringIndexOutOfBoundsException e) {
e.printStackTrace();
Logger.log(Level.WARNING, "Failed to add items unlocalized names as dictionary entries, BUT prevented a crash. This is probably an issue from a mod developer.");
}
}
private int getNumberFromString(String str)
{
try{
int tmpi = Integer.valueOf(str).intValue();
if(tmpi < -1) {
return 32767;
}
return (tmpi < -1 ? 0 : tmpi) ;
} catch (NumberFormatException e)
{
return 0;
}
}
private int getAnyNumberFromString(String str){
try{
int tmpi=Integer.valueOf(str);
if(tmpi == -1) {
return 32767;
}
return tmpi;
}catch(NumberFormatException e){
return 0;
}
}
private boolean isValidItem(int i){
if(i>0 && i <32000){
if((i<4096 && Block.blocksList[i]!=null) || (i>=256 && Item.itemsList[i]!=null)){
return true;
}else{
return false;
}
}else{
return false;
}
}
private boolean isGoodNull = false;
/** get stack from alias, "null" or single number */
private ItemStack getStackFromAliasOrNumber(String str){
isGoodNull = false;
if(str.equalsIgnoreCase("null")||str.equalsIgnoreCase("none")||str.equalsIgnoreCase("nothing") ||str.equalsIgnoreCase("empty")||str.equalsIgnoreCase("air")){
isGoodNull = true;
return null;
}else{
try{
int tmpi=Integer.valueOf(str.trim());
if(isValidItem(tmpi)){
return (ItemStack) new ItemStack(tmpi,1,0);
}else{
errorUndefined(path, str, str);
return null;
}
}catch(NumberFormatException e){
if(dict.get(str.toLowerCase())!=null){
Object obj = dict.get(str.toLowerCase());
if(obj instanceof ItemStack){
return ((ItemStack)obj).copy();
}else if(obj instanceof Item){
return new ItemStack((Item)obj, 1, 0);
}else if(obj instanceof Block){
return new ItemStack((Block)obj, 1, 0);
}else{
System.out.println("CR: INVALID DICTIONARY ENTRY! @ "+path);
return null;
}
}else{
return null;
}
}
}
}
private String path;
/** get object (stack, item, block) for the recipe part */
private ItemStack getRecipeStack(String str){
return parseStack(str, false); //disable size, disable forcestack
}
/** get stack for recipe product */
private ItemStack getProductStack(String str){
return parseStack(str, true); //enabled size, make a stack
}
/** object parser */
private ItemStack parseStack(String str, boolean acceptSize){
String[] parts=str.split("[,]");
if(parts.length>=1){
// create or load from dictionary
ItemStack stack1 = getStackFromAliasOrNumber(parts[0]);
if(stack1 == null){
if(!isGoodNull) errorUndefined(path,str,str);
return null;
}
ItemStack stack = stack1.copy();
if(parts.length>=2){
if(!acceptSize){
int dmg = getAnyNumberFromString(parts[1]);
if(dmg >= 32000 && dmg != 32767){
//invalid damage
errorAlert(path,str,"Warning - invalid item damage.");
}else{
stack.setItemDamage(dmg);
}
}else{
int size = getNumberFromString(parts[1]);
if(size < 0 || size > 256){
//invalid size
errorAlert(path,str,"Warning - invalid stack size.");
}else{
stack.stackSize = size;
if(parts.length>=3){
int dmg = getNumberFromString(parts[2]);
if(dmg >= 32000){
//invalid damage
errorAlert(path,str,"Warning - invalid item damage.");
}else{
stack.setItemDamage(dmg);
}
}
}
}
}
if(acceptSize && stack.getItemDamage() == -1) stack.setItemDamage(0);
return stack;
}
errorUndefined(path,str,str);
return null;
}
private int getRecipeId(String str){
ItemStack stack = getStackFromAliasOrNumber(str);
if(stack == null) return -1;
return stack.itemID;
}
private void loadRecipeFile(String file_path, boolean log){
//int a,b,c;
//String tmp;
ArrayList<String> rawFile=readFile(file_path);
// save to global
path = file_path;
if(log) Logger.log(Level.INFO, "Started to load recipes at " + file_path);
for(int a=0; a < rawFile.size(); a++){
if(log) Logger.log(Level.INFO, "Loading Recipes syntaxes at " + file_path);
String entry=(String)rawFile.get(a);
String entryOrig=entry;
if(entry.length()>= 4 && entry.substring(0,1).equals("*")){
if(log) Logger.log(Level.INFO, "Found alias syntax in "+file_path);
parseRecipeAlias(file_path, entryOrig, entry);
}else if(entry.length() >= 16 && entry.substring(0,9).equals("shapeless")){
Logger.log(Level.INFO, "Found shapeless syntax in "+file_path);
parseRecipeShapeless(file_path, entryOrig, entry);
}else if(entry.length() >= 9 && entry.substring(0,4).equals("fuel")){
Logger.log(Level.INFO, "Found fuel syntax in "+file_path);
parseRecipeFuel(file_path, entryOrig, entry);
}else if(entry.length()>= 15 && entry.substring(0,8).equals("smelting")){
Logger.log(Level.INFO, "Found smelting syntax in "+file_path);
parseRecipeSmelting(file_path, entryOrig, entry);
}else if(entry.length()>= 13 && entry.substring(0,6).equals("shaped")){
- Logger.log(Level.INFO, "Found smelting syntax in "+file_path);
+ Logger.log(Level.INFO, "Found shaped syntax in "+file_path);
parseRecipeShaped(file_path, entryOrig, entry);
}
else if(entry.length()>= 13 && entry.substring(0,6).equals("remove")){
Logger.log(Level.INFO, "Found remove syntax in "+file_path);
parseRecipeRemove(file_path, entryOrig, entry);
}
}
}
private static final String ERR_MSG_UNDEFINED="Undefined alias or wrong ID (no such block or item exists).\nIf you are trying to get a mod item, try adding 256 to the id value.";
private static final String ERR_MSG_SYNTAX="Syntax error.";
private static final String ERR_MSG_SHAPE="Recipe is not rectangular or is larger than 3x3.";
private static final String ERR_MSG_NOBURNTIME="No burn time specified. Recipe does not make sense.";
private void errorAlert(String fpath, String line, String cause){
Logger.log(Level.SEVERE, "\n* ERROR in recipe file \""+fpath+"\": "+line+"\n"+(cause==null?"":" "+cause+"\n"));
}
private void errorUndefined(String fpath, String line, String fail){
errorAlert(fpath, line, " " + fail + " -> " + ERR_MSG_UNDEFINED);
}
private void errorSyntax(String fpath, String line){
errorAlert(fpath, line, ERR_MSG_SYNTAX);
}
private static Object[] OAappend(Object[] source, Object what){
Object[] tmp=new Object[source.length+1];
for(int a=0;a<source.length;a++){
tmp[a]=source[a];
}
tmp[source.length]=what;
return tmp;
}
private static Object[] OAappendAll(Object[] source, Object[] what){
Object[] tmp=new Object[source.length+what.length];
for(int a=0;a<source.length;a++){
tmp[a]=source[a];
}
for(int a=0;a<what.length;a++){
tmp[source.length+a]=what[a];
}
return tmp;
}
private ArrayList readFile(String url)
{
File file = new File(url);
FileInputStream fis = null;
//BufferedInputStream bis = null;
//DataInputStream dis = null;
BufferedReader reader = null;
ArrayList fileContents = new ArrayList();
try
{
fis = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(fis));
//bis = new BufferedInputStream(fis);
//dis = new DataInputStream(bis);
//bas = new BufferedReader(new InputStreamReader(bis));
String tmpString = reader.readLine(); // Read the first line
while (tmpString != null)
{
//String tmpString = bas.readLine();
tmpString = tmpString.replaceAll("#.*$", "");
tmpString = tmpString.replaceAll("//.*$", "");
if ((!tmpString.equals("")) && (!tmpString.equals("\n"))) {
tmpString = tmpString.replaceAll(" ", "");
tmpString = tmpString.replaceAll("\t", "");
tmpString = tmpString.replaceAll(":", ",");
tmpString = tmpString.replaceAll("[/|;]", "/");
if (((tmpString.length() >= 4) && (tmpString.substring(0, 1).equals("*"))) || ((tmpString.length() >= 9) && (tmpString.substring(0, 4).equals("fuel"))) || ((tmpString.length() >= 13) && (tmpString.substring(0, 6).equals("shaped"))) || ((tmpString.length() >= 16) && (tmpString.substring(0, 9).equals("shapeless"))) || ((tmpString.length() >= 15) && (tmpString.substring(0, 8).equals("smelting"))) || ((tmpString.length() >= 13) && (tmpString.substring(0, 6).equals("remove"))))
{
fileContents.add(tmpString);
}
else
{
Logger.log(Level.WARNING, "\nSyntax error in recipe file:\n" + url + "\n-> " + tmpString + "\n");
}
}
tmpString = reader.readLine(); // read the next line
}
reader.close();
fis.close();
//bis.close();
//dis.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileContents;
}
private void parseRecipeAlias(String fpath, String entryOrig, String entryo){
// ---------- dictionary entry --------------
//*Name=123
String entry=entryo.substring(1); //remove "*"
String[] tokens=entry.split("[=]");
if(tokens.length!=2){ // identifier, without a value
errorAlert(fpath,entryOrig,ERR_MSG_SYNTAX);
return;
}
String def = tokens[1];
if(def != null){
if(tokens[0].equals("DICTIONARY_VERSION")){
DICT_VERSION=getNumberFromString(def);
}else{
ItemStack stack = getRecipeStack(def);
if(stack != null){
dict.put((String)tokens[0].toLowerCase(),(ItemStack)stack);
}else{
errorUndefined(fpath,entryOrig,def);
return;
}
}
}else{
errorSyntax(fpath,entryOrig);
return;
}
}
private void parseRecipeShapeless(String par_path, String par_entryOrig, String par_entry){
String path = new String(par_path);
String entryOrig = new String(par_entryOrig);
String entry = new String(par_entry);
// -------------- shapeless recipe --------------
entry=entry.substring(9); //remove "shapeless"
//tokens = recipe, product
String[] tokens=entry.split("[>]");
//check syntax
if(tokens.length!=2 || tokens[0].length()<3 || tokens[1].length()<3){
errorAlert(path,entryOrig,ERR_MSG_SYNTAX);
return;
}
//2 parts, parse recipe
String tmp = tokens[0];
//remove trailing brackets
tmp=tmp.replaceAll("[()]","");
//split by "+" sign to individual items
String[] recipeParts=tmp.split("[+]");
//the output recipe
Object[] recipe = {};
//go through the recipe
for(int b=0;b<recipeParts.length;b++){
Object piece = getRecipeStack(recipeParts[b]);
if(piece==null){
errorUndefined(path,entryOrig,recipeParts[b]); return;
}
if(piece instanceof Block) piece = new ItemStack((Block)piece,1,-1);
recipe = OAappend(recipe, piece);
}
if(recipe.length <= 0 || recipe.length > 9){
errorAlert(path,entryOrig,"Bad recipe syntax: Crafting of air, or more than 9 elements.");
return;
}
//now do the product
tmp=tokens[1];
tmp=tmp.replaceAll("[()]","");
ItemStack product = getProductStack(tmp);
if(product==null){
errorUndefined(path,entryOrig,tmp);
return;
}
// finish, apply!
Logger.log(Level.INFO, "LOADED RECIPE");
GameRegistry.addShapelessRecipe(product,recipe);
}
private void parseRecipeShaped(String file_path, String entryOrig, String entryo) {
// --------------- shaped recipe ----------------
String entry=entryo.substring(6); //remove "shaped"
String[] tokens=entry.split("[>]");
if(tokens.length!=2 || tokens[0].length()<3 || tokens[1].length()<3){
errorSyntax(file_path,entryOrig);
return;
}
//2 parts
String tmp=tokens[0];
tmp=tmp.replaceAll("[()]","");
//get the rows
String[] rows=tmp.split("[/]");
//counts items in last row, if not matches, throw error
int lastRowLength=-1;
Object[] rowStrings = new Object[0];
Object[] explanation = new Object[0];
int explCnt=0;
Character[] table={'A','B','C','D','E','F','G','H','I'};
if(rows.length<1 || rows.length>3){
errorAlert(file_path,entryOrig,ERR_MSG_SHAPE);
return;
}
int validPieces = 0;
for(int c=0; c<rows.length; c++){
//split row by + sign
String[] recipeParts=rows[c].split("[+]");
//building the letter pattern
String rowbuilder="";
//not rectangular
if(lastRowLength != -1 && recipeParts.length != lastRowLength){
errorAlert(file_path,entryOrig,ERR_MSG_SHAPE);
return;
}
// too short or long row
if(recipeParts.length<1 || recipeParts.length>3){
errorAlert(file_path,entryOrig,ERR_MSG_SHAPE); return;
}
lastRowLength=recipeParts.length;
// go through this row
for(int b=0; b<recipeParts.length; b++){
char tmpec=table[explCnt++];
//add an unique letter
rowbuilder=rowbuilder+Character.toString(tmpec);
Object piece = getRecipeStack(recipeParts[b]);
// building itemstack if not blank field
if(piece != null){
validPieces++;
// add char
explanation = OAappend(explanation,Character.valueOf(tmpec));
// add the item
explanation = OAappend(explanation,piece);
}
}
//add a row to row strings list
rowStrings = OAappend(rowStrings,rowbuilder);
}
if(rowStrings.length <= 0){
errorAlert(file_path,entryOrig,"Crafting of air.");
return;
}
if(validPieces <= 0){
errorAlert(file_path,entryOrig,"No valid items in recipe.");
return;
}
Object[] recipe = OAappendAll(rowStrings,explanation);
//doing product
tmp=tokens[1];
tmp=tmp.replaceAll("[()]","");
ItemStack product = getProductStack(tmp);
if(product == null){
errorAlert(file_path,entryOrig,"Invalid product "+tmp);
return;
}
//product done
try{
GameRegistry.addRecipe(product,recipe);
}catch(ArrayIndexOutOfBoundsException e){
Logger.log(Level.WARNING, "Shaped recipe "+entryOrig+" @ path "+path+" threw ArrayIndexOutOfBoundsException");
}
}
private void parseRecipeSmelting(String file_path, String entryOrig, String entryo) {
// ------------ smelting recipe --------------
String entry=entryo.substring(8); //remove "smelting"
//split to recipe and pruduct
String[] tokens=entry.split("[>]");
// check syntax
if(tokens.length!=2 || tokens[0].length()<3 || tokens[1].length()<3){
errorAlert(file_path,entryOrig,ERR_MSG_SYNTAX);
return;
}
//2 parts
String recipe = tokens[0].replaceAll("[()]","");
//doing the recipe part
int intval=getRecipeId(recipe);
if(intval<1){
errorUndefined(file_path,entryOrig,recipe);
return;
}
int recipeId=intval;
//recipe done
String tmp=tokens[1];
tmp=tmp.replaceAll("[()]","");
ItemStack product = getProductStack(tmp);
//invalid
if(product==null){
errorUndefined(file_path,entryOrig,tmp);
return;
}
//product done
GameRegistry.addSmelting(recipeId,product, 4);
}
private void parseRecipeFuel(String file_path, String entryOrig, String oentry) {
// -------------- adding fuel --------------
// fuel(paper,100)
String entry=oentry.substring(4); //remove "fuel"
//remove brackets
entry=entry.replaceAll("[()]","");
//split by comma to ID and RATE
String[] tokens=entry.split("[,]");
if(tokens.length<2 || tokens.length>3){
errorAlert(file_path,entryOrig,ERR_MSG_SYNTAX);
return;
}
//2 or 3 parts
//work out itemstack
String tmp=tokens[0];
ItemStack fuelStack = getProductStack(tmp);
if(fuelStack==null){
errorUndefined(file_path,entryOrig,tmp);
return;
}
//set stack damage if present
if(tokens.length == 3){
fuelStack.setItemDamage(getNumberFromString(tokens[1]));
}
//get burntime
int burntime=getNumberFromString(tokens[tokens.length-1]);
// if valid, add to recipes
if(burntime>0){
fuels.put((String)Integer.toString(fuelStack.itemID)+ "."+(String)Integer.toString(fuelStack.getItemDamage()) , Integer.valueOf(burntime));
}else{
errorAlert(file_path,entryOrig,ERR_MSG_NOBURNTIME);
return;
}
}
private void parseRecipeRemove(String file_path, String entryOrig, String entryo)
{
//-----Remove recipe
//remove
String entry=entryo.substring(6); //remove "remove"
//remove brackets
String recipe = entry.replaceAll("[()]","");
int intval=getRecipeId(recipe);
if(intval<1){
errorUndefined(file_path,entryOrig,recipe);
return;
}
ItemStack stack = getProductStack(recipe);
Logger.log(Level.INFO, "About to remove recipe with input" + recipe);
removeRecipe(stack);
}
private void removeRecipe(ItemStack resultItem)
{
ItemStack recipeResult = null;
ArrayList recipes = (ArrayList) CraftingManager.getInstance().getRecipeList();
for (int scan = 0; scan < recipes.size(); scan++)
{
IRecipe tmpRecipe = (IRecipe) recipes.get(scan);
if (tmpRecipe instanceof ShapedRecipes)
{
ShapedRecipes recipe = (ShapedRecipes)tmpRecipe;
recipeResult = recipe.getRecipeOutput();
Logger.log(Level.INFO, "Found shaped recipe!");
}
if (tmpRecipe instanceof ShapelessRecipes)
{
ShapelessRecipes recipe = (ShapelessRecipes)tmpRecipe;
recipeResult = recipe.getRecipeOutput();
Logger.log(Level.INFO, "Found shapeless recipe!");
}
if (ItemStack.areItemStacksEqual(resultItem, recipeResult))
{
Logger.log(Level.INFO, "Removed Recipe: " + recipes.get(scan) + " -> " + recipeResult);
recipes.remove(scan);
}
else {
Logger.log(Level.WARNING, "Couldn't remove the recipe with result: " + resultItem.toString());
}
}
}
}
| true | false | null | null |
diff --git a/src/ServerThread.java b/src/ServerThread.java
index 60ab37d..b00f50a 100644
--- a/src/ServerThread.java
+++ b/src/ServerThread.java
@@ -1,298 +1,292 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Hashtable;
public abstract class ServerThread extends Thread{
private Socket socket;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
private Server parentServer;
//set by child classes
protected String fileName;
protected ArrayList <String> peerServers;
protected String twoPCCoordinator;
public ServerThread(Server psrv, Socket skt){
this.socket = skt;
parentServer = psrv;
this.peerServers = psrv.getPeerServers();
this.twoPCCoordinator = psrv.getTwoPCCoordinator();
try
{
// create output first
outputStream = new ObjectOutputStream(socket.getOutputStream()); //needs this or it wont work
inputStream = new ObjectInputStream(socket.getInputStream());
}
catch (IOException e) {
System.out.println("Error Creating Streams: " + e);
return;
}
}
public void run()
{
//check for message client read/append
// if read, return values
// if append start 2pc protocol then paxos protocol
ServerMessage msg;
try {
msg = (ServerMessage) inputStream.readObject();
System.out.println("RECIEVED:" + msg);
switch (msg.getType()) {
case ServerMessage.CLIENT_GET_LEADER:
if (parentServer.getPaxosLeaders().size() == 0) {
String public_host = "";
public_host = parentServer.getServerPublicIP();
parentServer.setPaxosLeader(true);
for (int i = 0; i < this.peerServers.size(); i++){
ServerMessage leaderMsg = new ServerMessage(ServerMessage.PAXOS_ADD_LEADER, public_host, public_host);
sendMessage(this.peerServers.get(i), 3000, leaderMsg);
}
reply(new ServerMessage(ServerMessage.LEADER_RESPONSE, public_host));
} else {
reply(new ServerMessage(ServerMessage.LEADER_RESPONSE, parentServer.getPaxosLeaders().get(0) ));
}
break;
case ServerMessage.CLIENT_READ:
//read the file (set in child class)
ServerMessage readResultsMsg = new ServerMessage(ServerMessage.CLIENT_READ, parentServer.readFile(fileName));
- String public_host = "";
- public_host = parentServer.getServerPublicIP();
-
- readResultsMsg.setSourceAddress(msg.getSourceAddress());
- sendMessage(public_host, 3003, readResultsMsg);
+ sendMessage(socket.getInetAddress().getHostAddress(), 3003, readResultsMsg);
break;
case ServerMessage.CLIENT_APPEND:
//create a new ballot by incrementing current ballot by 1
if (!parentServer.isPaxosLeader()){
parentServer.setPaxosLeader(true);
//send
}
- public_host = "";
-
- public_host = parentServer.getServerPublicIP();
+ String public_host = parentServer.getServerPublicIP();
parentServer.setCurrentBallotNumber(parentServer.getCurrentBallotNumber()+1);
ServerMessage ballotMsg = new ServerMessage(ServerMessage.PAXOS_PREPARE, msg.getMessage(), public_host );
ballotMsg.setBallotNumber(parentServer.getCurrentBallotNumber());
ballotMsg.setBallotProcID(parentServer.getProcessId());
ballotMsg.setSourceAddress(msg.getSourceAddress());
//send to all other stat or grade servers
for (int i = 0; i < this.peerServers.size(); i++){
sendMessage(this.peerServers.get(i), 3000, ballotMsg);
}
break;
case ServerMessage.PAXOS_PREPARE:
//contents of the incoming prepare message are ballotnum,processesid.
//if the incoming ballot is newer than my ballot, update my ballot and send an ack, otherwise the incoming
//ballot is old and we can ignore it
// if the ballots are the same, process id will be the tie breaker.
if (msg.getBallotNumber() > parentServer.getCurrentBallotNumber() || (msg.getBallotNumber() == parentServer.getCurrentBallotNumber() && msg.getBallotProcID() >= parentServer.getProcessId()) ){
parentServer.setCurrentBallotNumber(msg.getBallotNumber());
//send the ack message with the current ballot, the last accepted ballot, the current value.
public_host = "";
public_host = parentServer.getServerPublicIP();
ServerMessage ackMessage = new ServerMessage(ServerMessage.PAXOS_ACK, msg.getMessage(), public_host );
ackMessage.setBallotNumber(parentServer.getCurrentBallotNumber());
ackMessage.setLastAcceptNumber(parentServer.getCurrentAcceptNum());
ackMessage.setLastAcceptVal(parentServer.getAcceptValue());
ackMessage.setSourceAddress(msg.getSourceAddress());
sendMessage(socket.getInetAddress().getHostAddress(), 3000, ackMessage);
}
break;
case ServerMessage.PAXOS_ACK:
//contents of the incoming ack message are current ballot, the last accepted ballot, the current value
Hashtable<Integer,ArrayList<ServerMessage> > hash = parentServer.getMessageHash();
ArrayList<ServerMessage> ballot_msgs = hash.get( msg.getBallotNumber() );
//add the incoming message to a collection of responses for this ballot
if (ballot_msgs == null){
ballot_msgs = new ArrayList<ServerMessage>();
}
ballot_msgs.add(msg);
hash.put(msg.getBallotNumber(), ballot_msgs);
parentServer.setMessageHash(hash);
//check to see if we have gotten a majority of responses... if not, do nothing
if(ballot_msgs.size() > this.peerServers.size()/2)
{
//clear the ack count so this doesnt run twice.
//hash.put(msg.getBallotNumber(), new ArrayList<ServerMessage>());
//parentServer.setMessageHash(hash);
public_host = parentServer.getServerPublicIP();
ServerMessage acceptMsg = new ServerMessage(ServerMessage.PAXOS_ACCEPT, msg.getMessage() ,public_host);
acceptMsg.setBallotNumber(parentServer.getCurrentBallotNumber());
acceptMsg.setSourceAddress(msg.getSourceAddress());
sendMessage(this.twoPCCoordinator, 3000, acceptMsg);
}
break;
case ServerMessage.PAXOS_ACCEPT:
parentServer.setPaxosLeaderResponseCount(parentServer.getPaxosLeaderResponseCount() + 1);
if (parentServer.getPaxosLeaderResponseCount() == parentServer.getPaxosLeaders().size()){
//reset response count for the next query
parentServer.setPaxosLeaderResponseCount(0);
String acceptVal = msg.getMessage(); //for tie breakers
for (int i = 0; i < this.peerServers.size(); i++){
ServerMessage vote2pc = new ServerMessage(ServerMessage.TWOPHASE_VOTE_REQUEST, acceptVal);
vote2pc.setSourceAddress(msg.getSourceAddress());
sendMessage(this.peerServers.get(i), 3000, vote2pc);
}
}
break;
case ServerMessage.PAXOS_ADD_LEADER:
if (!parentServer.getPaxosLeaders().contains(msg.getMessage())){
parentServer.addPaxosLeaders(msg.getMessage());
}
break;
case ServerMessage.TWOPHASE_VOTE_REQUEST:
//attempt to write to redo log
try {
parentServer.appendFile("APPEND:"+msg.getMessage(), "REDO.log");
} catch (IOException e){
//reply no
ServerMessage replyNo = new ServerMessage(ServerMessage.TWOPHASE_VOTE_NO, msg.getMessage());
replyNo.setSourceAddress(msg.getSourceAddress());
sendMessage(this.twoPCCoordinator, 3000, replyNo);
break;
}
//reply yes
ServerMessage replyYes = new ServerMessage(ServerMessage.TWOPHASE_VOTE_YES, msg.getMessage());
replyYes.setSourceAddress(msg.getSourceAddress());
sendMessage(this.twoPCCoordinator, 3000, replyYes);
break;
case ServerMessage.TWOPHASE_VOTE_YES:
parentServer.setPaxosLeaderResponseCount(parentServer.getPaxosLeaderResponseCount() + 1);
if (parentServer.getPaxosLeaderResponseCount() == this.peerServers.size()){
//reset response count for the next query
parentServer.setPaxosLeaderResponseCount(0);
String acceptVal = msg.getMessage(); //for tie breakers
for (int i = 0; i < this.peerServers.size(); i++){
ServerMessage commitMsg = new ServerMessage(ServerMessage.TWOPHASE_COMMIT, acceptVal);
commitMsg.setSourceAddress(msg.getSourceAddress());
sendMessage(this.peerServers.get(i), 3000, commitMsg);
}
//tell the client we are writing
sendMessage(msg.getSourceAddress(), 3003, new ServerMessage(ServerMessage.TWOPHASE_COMMIT, "VALUE COMMITED: " + msg.getMessage() ));
}
break;
//tally yes vote
case ServerMessage.TWOPHASE_VOTE_NO:
//send abort
for (int i = 0; i < this.peerServers.size(); i++){
ServerMessage abortMsg = new ServerMessage(ServerMessage.TWOPHASE_ABORT, msg.getMessage());
abortMsg.setSourceAddress(msg.getSourceAddress());
sendMessage(this.peerServers.get(i), 3000, abortMsg);
}
break;
case ServerMessage.TWOPHASE_ABORT:
//cancel the write changes
parentServer.appendFile("ABORT:"+msg.getMessage(), "REDO.log");
//tell client we aborted the write
sendMessage(msg.getSourceAddress(), 3003,new ServerMessage(ServerMessage.TWOPHASE_ABORT, "ABORTED WRITING: " + msg.getMessage()) );
break;
case ServerMessage.TWOPHASE_COMMIT:
parentServer.appendFile(msg.getMessage(), fileName);
//write any changes
break;
}
}
catch (IOException e) {
System.out.println(" Exception reading Streams: " + e);
System.exit(1);
}
catch(ClassNotFoundException ex) {
//this shouldnt be a problem, only ServerMessages should be sent.
System.exit(1);
}
}
private void sendMessage(String host, int port, ServerMessage msg){
System.out.println("SENDING " + msg + " to Server:" + host + "...");
try {
InetAddress address = InetAddress.getByName(host);
System.out.print(" Connecting to Server:"+host+"...");
// open socket, then input and output streams to it
Socket socket = new Socket(address,port);
ObjectOutputStream to_server = new ObjectOutputStream(socket.getOutputStream());
System.out.print("Connected");
// send command to server, then read and print lines until
// the server closes the connection
to_server.writeObject(msg); to_server.flush();
System.out.println("....SENT");
} catch (IOException e){
System.out.println(" ERROR: Server failed sending message:" + e.getMessage());
}
}
private void reply(ServerMessage msg){
System.out.println("REPLYING " + msg + " to Server:" + socket.getInetAddress().getHostAddress() + "...");
try {
outputStream.writeObject(msg); outputStream.flush();
System.out.println("....SENT");
} catch (IOException e){
System.out.println(" ERROR: Server failed sending message:" + e.getMessage());
}
}
}
| false | false | null | null |
diff --git a/test/regression/src/org/jacorb/test/orb/rmi/RMITest.java b/test/regression/src/org/jacorb/test/orb/rmi/RMITest.java
index a13785b7..8b621b94 100644
--- a/test/regression/src/org/jacorb/test/orb/rmi/RMITest.java
+++ b/test/regression/src/org/jacorb/test/orb/rmi/RMITest.java
@@ -1,387 +1,387 @@
package org.jacorb.test.orb.rmi;
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2003 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
import java.rmi.Remote;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import javax.rmi.PortableRemoteObject;
import org.jacorb.test.common.ClientServerSetup;
import org.jacorb.test.common.ClientServerTestCase;
import org.jacorb.test.orb.rmi.Outer.StaticInner;
/**
* Abstract testclass for RMITests. subclasses are responsible for
* choosing which ORB should run on client and server.
*
* @see SunJacORBRMITest
* @see SunSunRMITest
* @see JacORBJacORBRMITest
*
- * @version $Id: RMITest.java,v 1.9 2006-05-30 12:41:52 alphonse.bendt Exp $
+ * @version $Id: RMITest.java,v 1.10 2006-05-30 18:35:15 alphonse.bendt Exp $
*/
public abstract class RMITest extends ClientServerTestCase
{
private RMITestInterface server;
public RMITest(String name, ClientServerSetup setup)
{
super(name, setup);
}
public final void setUp() throws Exception
{
server = (RMITestInterface)javax.rmi.PortableRemoteObject.narrow(
setup.getServerObject(),
RMITestInterface.class);
}
public void test_getString() throws Exception
{
String s = server.getString();
assertEquals(RMITestUtil.STRING, s);
}
public void test_primitiveTypes() throws Exception
{
String s;
s = server.testPrimitiveTypes(false,
'A',
Byte.MIN_VALUE,
Short.MIN_VALUE,
Integer.MIN_VALUE,
Long.MIN_VALUE,
Float.MIN_VALUE,
Double.MIN_VALUE);
assertEquals(RMITestUtil.primitiveTypesToString(false,
'A',
Byte.MIN_VALUE,
Short.MIN_VALUE,
Integer.MIN_VALUE,
Long.MIN_VALUE,
Float.MIN_VALUE,
Double.MIN_VALUE),
s);
s = server.testPrimitiveTypes(true,
'Z',
Byte.MAX_VALUE,
Short.MAX_VALUE,
Integer.MAX_VALUE,
Long.MAX_VALUE,
Float.MAX_VALUE,
Double.MAX_VALUE);
assertEquals(RMITestUtil.primitiveTypesToString(true,
'Z',
Byte.MAX_VALUE,
Short.MAX_VALUE,
Integer.MAX_VALUE,
Long.MAX_VALUE,
Float.MAX_VALUE,
Double.MAX_VALUE),
s);
}
public void test_String() throws Exception
{
String original = "0123456789";
String echoedBack = server.testString("0123456789");
assertEquals(RMITestUtil.echo(original), echoedBack);
}
public void test_RMITestInterface() throws Exception
{
RMITestInterface t = server.testRMITestInterface("the quick brown fox", server);
String s = t.getString();
assertEquals(RMITestUtil.STRING, s);
}
public void test_Remote() throws Exception
{
Remote r = server.testRemote("jumps over the lazy dog", server);
RMITestInterface t =
(RMITestInterface)PortableRemoteObject.narrow(r,
RMITestInterface.class);
String s = t.getString();
assertEquals(RMITestUtil.STRING, s);
}
public void test_Serializable() throws Exception
{
Foo original = new Foo(7, "foo test");
Foo echoedBack = server.testSerializable(original);
assertEquals(RMITestUtil.echoFoo(original), echoedBack);
}
public void test_intArray() throws Exception
{
int[] original= new int[10];
for (int i = 0; i < original.length; i++)
{
original[i] = 100 + i;
}
int[] echoedBack = server.testIntArray(original);
assertEquals(original.length, echoedBack.length);
for (int i = 0; i < echoedBack.length; i++)
{
assertEquals(original[i] + 1, echoedBack[i]);
}
}
public void test_valueArray() throws Exception
{
Foo[] original = new Foo[4];
for (int i = 0; i < original.length; i++)
{
original[i] = new Foo(100 + i, "foo array test");
}
Foo[] echoedBack = server.testValueArray(original);
assertEquals(original.length, echoedBack.length);
for (int i = 0; i < echoedBack.length; i++)
{
assertEquals(RMITestUtil.echoFoo(original[i]), echoedBack[i]);
}
}
public void test_exception() throws Exception
{
assertEquals("#0", server.testException(0));
assertEquals("#1", server.testException(1));
assertEquals("#2", server.testException(2));
try
{
server.testException(-2);
fail("NegativeArgumentException expected but not thrown.");
}
catch (NegativeArgumentException na)
{
assertEquals(-2, na.getNegativeArgument());
}
try
{
server.testException(-1);
fail("NegativeArgumentException expected but not thrown.");
}
catch (NegativeArgumentException na)
{
assertEquals(-1, na.getNegativeArgument());
}
assertEquals("#0", server.testException(0));
}
public void test_FooValueToObject() throws Exception
{
Foo original = new Foo(9999, "foo test");
java.lang.Object echoedBack = server.fooValueToObject(original);
assertEquals(RMITestUtil.echoFoo(original), echoedBack);
}
public void test_BooValueToObject() throws Exception
{
Boo original = new Boo("t1", "boo test");
java.lang.Object echoedBack = server.booValueToObject(original);
assertEquals(RMITestUtil.echoBoo(original), echoedBack);
}
public void test_valueArrayToVector() throws Exception
{
Foo[] original = new Foo[4];
for (int i = 0; i < original.length; i++)
{
original[i] = new Foo(100 + i, "foo vector test");
}
java.util.Vector v = server.valueArrayToVector(original);
java.lang.Object[] echoedBack = v.toArray();
assertEquals(original.length, echoedBack.length);
for (int i = 0; i < echoedBack.length; i++)
{
assertEquals(RMITestUtil.echoFoo(original[i]), echoedBack[i]);
}
}
public void test_vectorToValueArray() throws Exception
{
Foo[] original = new Foo[4];
for (int i = 0; i < original.length; i++)
{
original[i] = new Foo(100 + i, "foo vector test");
}
java.util.Vector v = server.valueArrayToVector(original);
Foo[] echoedBack = server.vectorToValueArray(v);
assertEquals(original.length, echoedBack.length);
for (int i = 0; i < echoedBack.length; i++)
{
assertEquals(
RMITestUtil.echoFoo(RMITestUtil.echoFoo(original[i])),
echoedBack[i]);
}
}
public void test_getException() throws Exception
{
java.lang.Object obj = server.getException();
NegativeArgumentException na = (NegativeArgumentException)obj;
assertEquals(-7777, na.getNegativeArgument());
}
public void test_getZooValue() throws Exception
{
java.lang.Object obj = server.getZooValue();
assertEquals(new Zoo("outer_zoo!",
"returned by getZooValue",
new Zoo("inner_zoo!", "inner")),
obj);
}
public void test_referenceSharingWithinArray() throws Exception
{
int n = 100;
Object[] original = new Object[n];
for (int i = 0; i < n; i++)
{
original[i] = new Boo("t" + i, "boo array test");
}
Object[] echoedBack =
server.testReferenceSharingWithinArray(original);
assertEquals(2 * n, echoedBack.length);
for (int i = 0; i < n; i++)
{
assertEquals(original[i], echoedBack[i]);
assertEquals(original[i], echoedBack[i + n]);
assertSame(echoedBack[i], echoedBack[i + n]);
}
}
public void test_referenceSharingWithinCollection() throws Exception
{
java.util.Collection original = new java.util.ArrayList();
int n = 10;
for (int i = 0; i < n; i++)
{
original.add(new Foo(100 + i, "foo collection test"));
}
java.util.Collection echoedBack =
server.testReferenceSharingWithinCollection(original);
assertEquals(2 * n, echoedBack.size());
java.util.ArrayList originalList = (java.util.ArrayList)original;
java.util.ArrayList echoedList = (java.util.ArrayList)echoedBack;
for (int i = 0; i < n; i++)
{
assertEquals(originalList.get(i), echoedList.get(i));
assertEquals(originalList.get(i), echoedList.get(i + n));
assertSame(echoedList.get(i), echoedList.get(i + n));
}
}
public void test_getVectorWithObjectArrayAsElement() throws Exception
{
java.util.Vector vector =
server.getVectorWithObjectArrayAsElement();
assertTrue(vector.size() == 1);
Object[] inner = (Object[]) vector.get(0);
assertEquals(new Integer(1), inner[0]);
assertEquals(new Integer(2), inner[1]);
assertEquals("Third Element", inner[2]);
}
public void test_getVectorWithVectorAsElement() throws Exception
{
java.util.Vector vector =
server.getVectorWithVectorAsElement();
assertTrue(vector.size() == 1);
java.util.Vector inner = (java.util.Vector) vector.get(0);
assertEquals(new Integer(1), inner.get(0));
assertEquals(new Integer(2), inner.get(1));
assertEquals("Third Element", inner.get(2));
}
public void test_getVectorWithHashtableAsElement() throws Exception
{
java.util.Vector vector =
server.getVectorWithHashtableAsElement();
assertTrue(vector.size() == 1);
java.util.Hashtable inner = (java.util.Hashtable) vector.get(0);
assertEquals(new Integer(1), inner.get(new Integer(0)));
assertEquals(new Integer(2), inner.get(new Integer(1)));
assertEquals("Third Element", inner.get(new Integer(2)));
}
public void testPassStaticInnerClass() throws Exception
{
StaticInner expect = new StaticInner("staticInner");
StaticInner result = server.staticInnerToStaticInner(expect);
assertEquals(expect, result);
}
public void testPassInnerClass() throws Exception
{
Outer expect = new Outer("outer");
Outer result = server.outerToOuter(expect);
assertEquals(expect, result);
}
public void testPassCollection() throws Exception
{
assertEquals(0, server.sizeOfCollection(Collections.EMPTY_LIST));
}
/**
* this test is currently failing between
* JacORB and Sun ORB.
- * @see testPassSerializable0
+ * @see #testPassSerializable0
*/
public void testPassSerializable1() throws Exception
{
Date date = new Date();
ArrayList list = new ArrayList();
StringParam param = new StringParam(date.toString());
list.add(param);
ArrayList result = (ArrayList) server.transmitSerializable(list);
assertEquals(param.payload, ((StringParam)result.get(0)).payload);
}
public void testPassSerializable0() throws Exception
{
Date date = new Date();
ArrayList list = new ArrayList();
ObjectParam param = new ObjectParam(date.toString());
list.add(param);
ArrayList result = (ArrayList) server.transmitSerializable(list);
assertEquals(param.payload, ((ObjectParam)result.get(0)).payload);
}
}
| false | false | null | null |
diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFile.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFile.java
index 4577a95e..86b4b505 100644
--- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFile.java
+++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFile.java
@@ -1,229 +1,231 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.osgi.baseadaptor.bundlefile;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Enumeration;
import org.eclipse.osgi.baseadaptor.BaseData;
import org.eclipse.osgi.framework.internal.core.*;
import org.eclipse.osgi.framework.internal.protocol.bundleresource.Handler;
import org.eclipse.osgi.framework.util.SecureAction;
import org.eclipse.osgi.util.ManifestElement;
/**
* The BundleFile API is used by Adaptors to read resources out of an
* installed Bundle in the Framework.
* <p>
* Clients may extend this class.
* </p>
* @since 3.2
*/
abstract public class BundleFile {
protected static final String PROP_SETPERMS_CMD = "osgi.filepermissions.command"; //$NON-NLS-1$
static final SecureAction secureAction = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction());
/**
* The File object for this BundleFile.
*/
protected File basefile;
private int mruIndex = -1;
/**
* Default constructor
*
*/
public BundleFile() {
// do nothing
}
/**
* BundleFile constructor
* @param basefile The File object where this BundleFile is
* persistently stored.
*/
public BundleFile(File basefile) {
this.basefile = basefile;
}
/**
* Returns a File for the bundle entry specified by the path.
* If required the content of the bundle entry is extracted into a file
* on the file system.
* @param path The path to the entry to locate a File for.
* @param nativeCode true if the path is native code.
* @return A File object to access the contents of the bundle entry.
*/
abstract public File getFile(String path, boolean nativeCode);
/**
* Locates a file name in this bundle and returns a BundleEntry object
*
* @param path path of the entry to locate in the bundle
* @return BundleEntry object or null if the file name
* does not exist in the bundle
*/
abstract public BundleEntry getEntry(String path);
/**
* Allows to access the entries of the bundle.
* Since the bundle content is usually a jar, this
* allows to access the jar contents.
*
* GetEntryPaths allows to enumerate the content of "path".
* If path is a directory, it is equivalent to listing the directory
* contents. The returned names are either files or directories
* themselves. If a returned name is a directory, it finishes with a
* slash. If a returned name is a file, it does not finish with a slash.
* @param path path of the entry to locate in the bundle
* @return an Enumeration of Strings that indicate the paths found or
* null if the path does not exist.
*/
abstract public Enumeration getEntryPaths(String path);
/**
* Closes the BundleFile.
* @throws IOException if any error occurs.
*/
abstract public void close() throws IOException;
/**
* Opens the BundleFiles.
* @throws IOException if any error occurs.
*/
abstract public void open() throws IOException;
/**
* Determines if any BundleEntries exist in the given directory path.
* @param dir The directory path to check existence of.
* @return true if the BundleFile contains entries under the given directory path;
* false otherwise.
*/
abstract public boolean containsDir(String dir);
/**
* Returns a URL to access the contents of the entry specified by the path
* @param path the path to the resource
* @param hostBundleID the host bundle ID
* @return a URL to access the contents of the entry specified by the path
* @deprecated use {@link #getResourceURL(String, BaseData, int)}
*/
public URL getResourceURL(String path, long hostBundleID) {
return getResourceURL(path, hostBundleID, 0);
}
/**
* Returns a URL to access the contents of the entry specified by the path
* @param path the path to the resource
* @param hostBundleID the host bundle ID
* @param index the resource index
* @return a URL to access the contents of the entry specified by the path
* @deprecated use {@link #getResourceURL(String, BaseData, int)}
*/
public URL getResourceURL(String path, long hostBundleID, int index) {
return internalGetResourceURL(path, null, hostBundleID, index);
}
/**
* Returns a URL to access the contents of the entry specified by the path
* @param path the path to the resource
* @param hostData the host BaseData
* @param index the resource index
* @return a URL to access the contents of the entry specified by the path
*/
public URL getResourceURL(String path, BaseData hostData, int index) {
return internalGetResourceURL(path, hostData, 0, index);
}
private URL internalGetResourceURL(String path, BaseData hostData, long hostBundleID, int index) {
BundleEntry bundleEntry = getEntry(path);
if (bundleEntry == null)
return null;
if (hostData != null)
hostBundleID = hostData.getBundleID();
path = fixTrailingSlash(path, bundleEntry);
try {
//use the constant string for the protocol to prevent duplication
return secureAction.getURL(Constants.OSGI_RESOURCE_URL_PROTOCOL, Long.toString(hostBundleID) + BundleResourceHandler.BID_FWKID_SEPARATOR + Integer.toString(hostData.getAdaptor().hashCode()), index, path, new Handler(bundleEntry, hostData == null ? null : hostData.getAdaptor()));
} catch (MalformedURLException e) {
return null;
}
}
/**
* Returns the base file for this BundleFile
* @return the base file for this BundleFile
*/
public File getBaseFile() {
return basefile;
}
void setMruIndex(int index) {
mruIndex = index;
}
int getMruIndex() {
return mruIndex;
}
/**
* Attempts to set the permissions of the file in a system dependent way.
* @param file the file to set the permissions on
*/
public static void setPermissions(File file) {
String commandProp = FrameworkProperties.getProperty(PROP_SETPERMS_CMD);
if (commandProp == null)
commandProp = FrameworkProperties.getProperty(Constants.FRAMEWORK_EXECPERMISSION);
if (commandProp == null)
return;
String[] temp = ManifestElement.getArrayFromList(commandProp, " "); //$NON-NLS-1$
ArrayList command = new ArrayList(temp.length + 1);
boolean foundFullPath = false;
for (int i = 0; i < temp.length; i++) {
if ("[fullpath]".equals(temp[i]) || "${abspath}".equals(temp[i])) { //$NON-NLS-1$ //$NON-NLS-2$
command.add(file.getAbsolutePath());
foundFullPath = true;
} else
command.add(temp[i]);
}
if (!foundFullPath)
command.add(file.getAbsolutePath());
try {
Runtime.getRuntime().exec((String[]) command.toArray(new String[command.size()])).waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
public String toString() {
return String.valueOf(basefile);
}
public static String fixTrailingSlash(String path, BundleEntry entry) {
- if (path.length() == 0 || path.charAt(0) != '/')
+ if (path.length() == 0)
+ return "/"; //$NON-NLS-1$
+ if (path.charAt(0) != '/')
path = '/' + path;
String name = entry.getName();
boolean pathSlash = path.charAt(path.length() - 1) == '/';
boolean entrySlash = name.length() > 0 && name.charAt(name.length() - 1) == '/';
if (entrySlash != pathSlash) {
if (entrySlash)
path = path + '/';
else
path = path.substring(0, path.length() - 1);
}
return path;
}
}
diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirZipBundleEntry.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirZipBundleEntry.java
index 352a67ee..6e33778b 100644
--- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirZipBundleEntry.java
+++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirZipBundleEntry.java
@@ -1,74 +1,74 @@
/*******************************************************************************
* Copyright (c) 2005, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.osgi.baseadaptor.bundlefile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Represents a directory entry in a ZipBundleFile. This object is used to
* reference a directory entry in a ZipBundleFile when the directory entries are
* not included in the zip file.
* @since 3.2
*/
public class DirZipBundleEntry extends BundleEntry {
/**
* ZipBundleFile for this entry.
*/
private ZipBundleFile bundleFile;
/**
* The name for this entry
*/
String name;
public DirZipBundleEntry(ZipBundleFile bundleFile, String name) {
- this.name = (name.length() > 0 && name.charAt(0) == '/') ? name.substring(1) : name;
+ this.name = (name.length() > 1 && name.charAt(0) == '/') ? name.substring(1) : name;
this.bundleFile = bundleFile;
}
public InputStream getInputStream() throws IOException {
return null;
}
public long getSize() {
return 0;
}
public String getName() {
return name;
}
public long getTime() {
return 0;
}
public URL getLocalURL() {
try {
return new URL("jar:" + bundleFile.basefile.toURL() + "!/" + name); //$NON-NLS-1$ //$NON-NLS-2$
} catch (MalformedURLException e) {
//This can not happen, unless the jar protocol is not supported.
return null;
}
}
public URL getFileURL() {
try {
return bundleFile.extractDirectory(name).toURL();
} catch (MalformedURLException e) {
// this cannot happen.
return null;
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/thoughtworks/twu/service/OfferService.java b/src/main/java/com/thoughtworks/twu/service/OfferService.java
index 3809a31..1a2ee00 100644
--- a/src/main/java/com/thoughtworks/twu/service/OfferService.java
+++ b/src/main/java/com/thoughtworks/twu/service/OfferService.java
@@ -1,39 +1,39 @@
package com.thoughtworks.twu.service;
import com.thoughtworks.twu.domain.Offer;
import com.thoughtworks.twu.persistence.OfferDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class OfferService implements OfferServiceInterface {
@Autowired
private OfferDao offerDao;
@Override
public Offer getOfferById(String offerId) {
return offerDao.getOfferById(offerId);
}
@Override
public String saveOffer(Offer offer) {
return offerDao.saveOffer(offer);
}
@Override
public List<Offer> getAll() {
List<Offer> tempOrderedList = offerDao.getAll();
- List<Offer> reverseList = new ArrayList<>();
+ List<Offer> reverseList = new ArrayList<Offer>();
for (int index = tempOrderedList.size()-1; index >= 0; index--) {
reverseList.add(tempOrderedList.get(index));
}
return reverseList;
}
}
| true | true | public List<Offer> getAll() {
List<Offer> tempOrderedList = offerDao.getAll();
List<Offer> reverseList = new ArrayList<>();
for (int index = tempOrderedList.size()-1; index >= 0; index--) {
reverseList.add(tempOrderedList.get(index));
}
return reverseList;
}
| public List<Offer> getAll() {
List<Offer> tempOrderedList = offerDao.getAll();
List<Offer> reverseList = new ArrayList<Offer>();
for (int index = tempOrderedList.size()-1; index >= 0; index--) {
reverseList.add(tempOrderedList.get(index));
}
return reverseList;
}
|
diff --git a/ComparatorScript.java b/ComparatorScript.java
index c72caaf..f1443a4 100644
--- a/ComparatorScript.java
+++ b/ComparatorScript.java
@@ -1,14 +1,14 @@
public class ComparatorScript {
-public static void main(String[] args) {
- ComparatorScript script = new ComparatorScript();
- script.launch();
- }
+ public static void main(String[] args) {
+ ComparatorScript script = new ComparatorScript();
+ script.launch();
+ }
public void launch() {
- Comparator myComp = new Comparator();
- System.out.println(myComp.getMax(1,2));
- System.out.println(myComp.getMax(1.0,2.0));
- System.out.println(myComp.getMax("1","2"));
+ Comparator myComp = new Comparator();
+ System.out.println(myComp.getMax(1,2));
+ System.out.println(myComp.getMax(1.0,2.0));
+ System.out.println(myComp.getMax("1","2"));
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseMarkSetProvider.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseMarkSetProvider.java
index f7143e889..faf6c666f 100644
--- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseMarkSetProvider.java
+++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseMarkSetProvider.java
@@ -1,126 +1,128 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.p2.touchpoint.eclipse;
import java.io.File;
import java.util.*;
import org.eclipse.equinox.frameworkadmin.BundleInfo;
import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils;
import org.eclipse.equinox.internal.p2.garbagecollector.MarkSet;
import org.eclipse.equinox.internal.p2.garbagecollector.MarkSetProvider;
import org.eclipse.equinox.internal.p2.update.*;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.core.ProvisionException;
import org.eclipse.equinox.p2.engine.IProfile;
import org.eclipse.equinox.p2.engine.IProfileRegistry;
import org.eclipse.equinox.p2.metadata.*;
import org.eclipse.equinox.p2.query.IQueryResult;
import org.eclipse.equinox.p2.query.QueryUtil;
import org.eclipse.equinox.p2.repository.artifact.ArtifactKeyQuery;
import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
/**
* MarkSetProvider implementation for the Eclipse touchpoint.
*/
public class EclipseMarkSetProvider extends MarkSetProvider {
private static final String ARTIFACT_CLASSIFIER_OSGI_BUNDLE = "osgi.bundle"; //$NON-NLS-1$
private static final String ARTIFACT_CLASSIFIER_FEATURE = "org.eclipse.update.feature"; //$NON-NLS-1$
private Collection<IArtifactKey> artifactKeyList = null;
public MarkSet[] getMarkSets(IProvisioningAgent agent, IProfile inProfile) {
artifactKeyList = new HashSet<IArtifactKey>();
IArtifactRepository repositoryToGC = Util.getBundlePoolRepository(agent, inProfile);
if (repositoryToGC == null)
return new MarkSet[0];
addArtifactKeys(inProfile);
IProfile currentProfile = getCurrentProfile(agent);
if (currentProfile != null && inProfile.getProfileId().equals(currentProfile.getProfileId())) {
addRunningBundles(repositoryToGC);
addRunningFeatures(inProfile, repositoryToGC);
}
return new MarkSet[] {new MarkSet(artifactKeyList.toArray(new IArtifactKey[artifactKeyList.size()]), repositoryToGC)};
}
private void addRunningFeatures(IProfile profile, IArtifactRepository repositoryToGC) {
try {
List<Feature> allFeatures = getAllFeatures(Configuration.load(new File(Util.getConfigurationFolder(profile), "org.eclipse.update/platform.xml"), null)); //$NON-NLS-1$
for (Feature f : allFeatures) {
IArtifactKey match = searchArtifact(f.getId(), Version.create(f.getVersion()), ARTIFACT_CLASSIFIER_FEATURE, repositoryToGC);
if (match != null)
artifactKeyList.add(match);
}
} catch (ProvisionException e) {
//Ignore the exception
}
}
private List<Feature> getAllFeatures(Configuration cfg) {
if (cfg == null)
return CollectionUtils.emptyList();
List<Site> sites = cfg.getSites();
ArrayList<Feature> result = new ArrayList<Feature>();
for (Site object : sites) {
Feature[] features = object.getFeatures();
for (int i = 0; i < features.length; i++) {
result.add(features[i]);
}
}
return result;
}
private IProfile getCurrentProfile(IProvisioningAgent agent) {
IProfileRegistry pr = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME);
if (pr == null)
return null;
return pr.getProfile(IProfileRegistry.SELF);
}
private void addArtifactKeys(IProfile aProfile) {
Iterator<IInstallableUnit> installableUnits = aProfile.query(QueryUtil.createIUAnyQuery(), null).iterator();
while (installableUnits.hasNext()) {
Collection<IArtifactKey> keys = installableUnits.next().getArtifacts();
if (keys == null)
continue;
artifactKeyList.addAll(keys);
}
}
public IArtifactRepository getRepository(IProvisioningAgent agent, IProfile aProfile) {
return Util.getBundlePoolRepository(agent, aProfile);
}
private void addRunningBundles(IArtifactRepository repo) {
artifactKeyList.addAll(findCorrespondinArtifacts(new WhatIsRunning().getBundlesBeingRun(), repo));
}
private IArtifactKey searchArtifact(String searchedId, Version searchedVersion, String classifier, IArtifactRepository repo) {
//This is somewhat cheating since normally we should get the artifact key from the IUs that were representing the running system (e.g. we could get that info from the rollback repo)
VersionRange range = searchedVersion != null ? new VersionRange(searchedVersion, true, searchedVersion, true) : null;
ArtifactKeyQuery query = new ArtifactKeyQuery(classifier, searchedId, range);
//TODO short-circuit the query when we find one?
IQueryResult<IArtifactKey> keys = repo.query(query, null);
if (!keys.isEmpty())
return keys.iterator().next();
return null;
}
//Find for each bundle info a corresponding artifact in repo
private List<IArtifactKey> findCorrespondinArtifacts(BundleInfo[] bis, IArtifactRepository repo) {
ArrayList<IArtifactKey> toRetain = new ArrayList<IArtifactKey>();
for (int i = 0; i < bis.length; i++) {
- IArtifactKey match = searchArtifact(bis[i].getSymbolicName(), Version.create(bis[i].getVersion()), ARTIFACT_CLASSIFIER_OSGI_BUNDLE, repo);
+ // if version is "0.0.0", we will use null to find all versions, see bug 305710
+ Version version = BundleInfo.EMPTY_VERSION.equals(bis[i].getVersion()) ? null : Version.create(bis[i].getVersion());
+ IArtifactKey match = searchArtifact(bis[i].getSymbolicName(), version, ARTIFACT_CLASSIFIER_OSGI_BUNDLE, repo);
if (match != null)
toRetain.add(match);
}
return toRetain;
}
}
| true | false | null | null |
diff --git a/contactlist/src/com/dmdirc/addons/contactlist/ContactListCommand.java b/contactlist/src/com/dmdirc/addons/contactlist/ContactListCommand.java
index 4e251064..66ba5a23 100644
--- a/contactlist/src/com/dmdirc/addons/contactlist/ContactListCommand.java
+++ b/contactlist/src/com/dmdirc/addons/contactlist/ContactListCommand.java
@@ -1,76 +1,78 @@
/*
* Copyright (c) 2006-2014 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.contactlist;
import com.dmdirc.FrameContainer;
import com.dmdirc.commandparser.BaseCommandInfo;
import com.dmdirc.commandparser.CommandArguments;
import com.dmdirc.commandparser.CommandInfo;
import com.dmdirc.commandparser.CommandType;
import com.dmdirc.commandparser.commands.Command;
import com.dmdirc.commandparser.commands.IntelligentCommand;
import com.dmdirc.commandparser.commands.context.ChannelCommandContext;
import com.dmdirc.commandparser.commands.context.CommandContext;
+import com.dmdirc.events.NickListClientsChangedEvent;
import com.dmdirc.interfaces.CommandController;
import com.dmdirc.ui.input.AdditionalTabTargets;
import javax.annotation.Nonnull;
import javax.inject.Inject;
/**
* Generates a contact list for the channel the command is used in.
*/
public class ContactListCommand extends Command implements IntelligentCommand {
/** A command info object for this command. */
public static final CommandInfo INFO = new BaseCommandInfo("contactlist",
"contactlist - show a contact list for the current channel",
CommandType.TYPE_CHANNEL);
/**
* Creates a new instance of this command.
*
* @param controller The controller to use for command information.
*/
@Inject
public ContactListCommand(final CommandController controller) {
super(controller);
}
@Override
public void execute(@Nonnull final FrameContainer origin,
final CommandArguments args, final CommandContext context) {
final ChannelCommandContext chanContext = (ChannelCommandContext) context;
final ContactListListener listener = new ContactListListener(chanContext.getChannel());
listener.addListeners();
- //listener.clientListUpdated(chanContext.getChannel().getChannelInfo().getChannelClients());
+ listener.handleClientsUpdated(new NickListClientsChangedEvent(chanContext.getChannel(),
+ chanContext.getChannel().getUsers()));
}
@Override
public AdditionalTabTargets getSuggestions(final int arg,
final IntelligentCommandContext context) {
return new AdditionalTabTargets().excludeAll();
}
}
diff --git a/contactlist/src/com/dmdirc/addons/contactlist/ContactListListener.java b/contactlist/src/com/dmdirc/addons/contactlist/ContactListListener.java
index 956bfad2..94c1ba47 100644
--- a/contactlist/src/com/dmdirc/addons/contactlist/ContactListListener.java
+++ b/contactlist/src/com/dmdirc/addons/contactlist/ContactListListener.java
@@ -1,103 +1,103 @@
/*
* Copyright (c) 2006-2014 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.contactlist;
import com.dmdirc.DMDircMBassador;
import com.dmdirc.Query;
import com.dmdirc.events.ChannelUserAwayEvent;
import com.dmdirc.events.ChannelUserBackEvent;
import com.dmdirc.events.FrameClosingEvent;
import com.dmdirc.events.NickListClientAddedEvent;
import com.dmdirc.events.NickListClientsChangedEvent;
import com.dmdirc.interfaces.GroupChat;
-import com.dmdirc.parser.interfaces.ChannelClientInfo;
+import com.dmdirc.interfaces.GroupChatUser;
import net.engio.mbassy.listener.Handler;
/**
* Listens for contact list related events.
*/
public class ContactListListener {
/** The group chat this listener is for. */
private final GroupChat groupChat;
/** Event bus to register listeners with. */
private final DMDircMBassador eventBus;
/**
* Creates a new ContactListListener for the specified group chat.
*
* @param groupChat The group chat to show a contact list for
*/
public ContactListListener(final GroupChat groupChat) {
this.groupChat = groupChat;
this.eventBus = groupChat.getEventBus();
}
/**
* Adds all necessary listeners for this contact list listener to function.
*/
public void addListeners() {
eventBus.subscribe(this);
}
/**
* Removes the listeners added by {@link #addListeners()}.
*/
public void removeListeners() {
eventBus.unsubscribe(this);
}
@Handler
public void handleClientsUpdated(final NickListClientsChangedEvent event) {
- //event.getUsers().forEach(this::clientAdded);
+ event.getUsers().forEach(this::clientAdded);
}
@Handler
public void handleClientAdded(final NickListClientAddedEvent event) {
- //clientAdded(event.getUser());
+ clientAdded(event.getUser());
}
@Handler
public void handleUserAway(final ChannelUserAwayEvent event) {
- //clientAdded(event.getUser());
+ clientAdded(event.getUser());
}
@Handler
public void handleUserBack(final ChannelUserBackEvent event) {
- //clientAdded(event.getUser());
+ clientAdded(event.getUser());
}
@Handler
public void windowClosing(final FrameClosingEvent event) {
removeListeners();
}
- private void clientAdded(final ChannelClientInfo client) {
+ private void clientAdded(final GroupChatUser client) {
final Query query = groupChat.getConnection().get()
- .getQuery(client.getClient().getNickname(), false);
+ .getQuery(client.getNickname(), false);
- query.setIcon("query-" + client.getClient().getAwayState().name().toLowerCase());
+ query.setIcon("query-" + client.getUser().getAwayState().name().toLowerCase());
}
}
| false | false | null | null |
diff --git a/src/main/java/net/nexisonline/spade/SpadePlugin.java b/src/main/java/net/nexisonline/spade/SpadePlugin.java
index 2686385..a8c9280 100644
--- a/src/main/java/net/nexisonline/spade/SpadePlugin.java
+++ b/src/main/java/net/nexisonline/spade/SpadePlugin.java
@@ -1,61 +1,62 @@
package net.nexisonline.spade;
import java.util.HashMap;
+import java.util.Random;
import net.nexisonline.spade.chunkproviders.ChunkProviderFlatGrass;
import net.nexisonline.spade.chunkproviders.ChunkProviderMountains;
import net.nexisonline.spade.chunkproviders.ChunkProviderStock;
import net.nexisonline.spade.commands.SetWorldGenCommand;
import net.nexisonline.spade.commands.TP2WorldCommand;
import org.bukkit.ChunkProvider;
import org.bukkit.World.Environment;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Sample plugin for Bukkit
*
* @author Dinnerbone
*/
public class SpadePlugin extends JavaPlugin {
private final SpadeWorldListener worldListener = new SpadeWorldListener(this);
private HashMap<String,ChunkProvider> chunkProviders = new HashMap<String,ChunkProvider>();
public void onEnable() {
// Register our events
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.WORLD_LOAD, worldListener, Event.Priority.Monitor, this);
pm.registerEvent(Event.Type.WORLD_SAVE, worldListener, Event.Priority.Monitor, this);
// Register our commands
getCommand("setworldgen").setExecutor(new SetWorldGenCommand(this));
getCommand("tpw").setExecutor(new TP2WorldCommand(this));
registerChunkProviders();
// Load World Settings
worldListener.loadWorlds();
// EXAMPLE: Custom code, here we just output some info so we can check all is well
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
}
private void registerChunkProviders() {
chunkProviders.put("stock", new ChunkProviderStock());
chunkProviders.put("flatgrass", new ChunkProviderFlatGrass());
chunkProviders.put("mountains", new ChunkProviderMountains());
}
public void onDisable() {
}
public void loadWorld(String worldName, String cmName, String cpName) {
ChunkProvider cp = chunkProviders.get(cpName);
- getServer().createWorld(worldName, Environment.NORMAL, null, cp);
+ getServer().createWorld(worldName, Environment.NORMAL, (new Random()).nextLong(), null, cp);
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/model/Turtle.java b/src/model/Turtle.java
index ece994f..fdd058f 100644
--- a/src/model/Turtle.java
+++ b/src/model/Turtle.java
@@ -1,320 +1,329 @@
package model;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Iterator;
import util.Location;
import util.Paintable;
import util.Pixmap;
import util.Sprite;
import util.Vector;
/**
* Represents the turtle on the canvas. Can be painted. Can be called with its custom methods by
* commands. Also implements dataSource and can be accessed to give information about itself.
*
* @author David Winegar
* @author Zhen Gou
*/
public class Turtle extends Sprite implements Paintable {
private static final Pixmap DEFAULT_IMAGE = new Pixmap("turtle.gif");
private static final Dimension DEFAULT_DIMENSION = new Dimension(30, 30);
private static final int HALF_TURN_DEGREES = 180;
private static final int FULL_TURN_DEGREES = 360;
private static final int THREE_QUARTER_TURN_DEGREES = 270;
private static final int ONE_QUARTER_TURN_DEGREES = 90;
private static final int NO_TURN_DEGREES = 0;
+ private static final double PRECISION_LEVEL=0.0000001;
private boolean myPenDown = true;
private boolean myTurtleShowing = true;
private Line myLine = new Line();
private Dimension myCanvasBounds;
private int myCenterXValue;
private int myCenterYValue;
/**
* Creates a turtle sprite.
*
* @param image image to use
* @param center center of turtle
* @param size size of turtle
* @param canvasBounds bounds of canvas that turtle uses
*/
public Turtle (Pixmap image, Location center, Dimension size, Dimension canvasBounds) {
super(image, center, size);
myCanvasBounds = canvasBounds;
myCenterXValue = (int) myCanvasBounds.getWidth() / 2;
myCenterYValue = (int) myCanvasBounds.getHeight() / 2;
}
/**
* Uses default values for constructor, except for canvasBounds.
*
* @param canvasBounds bounds to use.
*/
public Turtle (Dimension canvasBounds) {
this(DEFAULT_IMAGE,
new Location(canvasBounds.getWidth() / 2, canvasBounds.getHeight() / 2),
DEFAULT_DIMENSION, canvasBounds);
}
/**
* Move forward or backward by number of pixels.
*
* @param pixels to move by
* @return command return value
*/
public int move (int pixels) {
int pixelsToMove = pixels;
// ensure that moveRecursiveHelper doesn't take a negative argument
if (Math.abs(pixels) != pixels){
pixelsToMove = -pixelsToMove;
turn(HALF_TURN_DEGREES);
}
moveRecursiveHelper(pixelsToMove);
if (Math.abs(pixels) != pixels){
turn(HALF_TURN_DEGREES);
}
return Math.abs(pixels);
}
- private void moveRecursiveHelper (int pixels) {
- if (pixels <= 0) return;
+ private void moveRecursiveHelper (double pixels) {
+
+
+ if (pixels <= 0+PRECISION_LEVEL) return;
Location currentLocation = getLocation();
Location nextLocation = getLocation();
Location nextCenter = nextLocation;
nextLocation.translate(new Vector(getHeading(), pixels));
// top
if (nextLocation.getY() < 0) {
double angle = FULL_TURN_DEGREES - getHeading();
if(getHeading() < THREE_QUARTER_TURN_DEGREES){
angle = getHeading() - HALF_TURN_DEGREES;
}
+ angle=Math.toRadians(angle);
nextLocation = new Location(getX() + getY() / Math.tan(angle), 0);
nextCenter = new Location(getX() + getY() / Math.tan(angle),
myCanvasBounds.getHeight());
if(getHeading() == THREE_QUARTER_TURN_DEGREES){
nextLocation = new Location(getX(), 0);
nextCenter = new Location(getX(), myCanvasBounds.getHeight());
}
// bottom
}
else if (nextLocation.getY() > myCanvasBounds.getHeight()) {
double angle = getHeading();
if(getHeading() > ONE_QUARTER_TURN_DEGREES){
angle = HALF_TURN_DEGREES - getHeading();
}
+ angle=Math.toRadians(angle);
nextLocation = new Location(getX() + getY() / Math.tan(angle), myCanvasBounds.getHeight());
nextCenter = new Location(getX() + getY() / Math.tan(angle),
0);
if(getHeading() == ONE_QUARTER_TURN_DEGREES){
nextLocation = new Location(getX(), myCanvasBounds.getHeight());
nextCenter = new Location(getX(), 0);
}
// right
}
else if (nextLocation.getX() > myCanvasBounds.getWidth()) {
nextLocation =
new Location(myCanvasBounds.getWidth(), getY() + getX() /
Math.tan(getHeading()));
nextCenter = new Location(0, getY() + getX() / Math.tan(getHeading()));
double angle = getHeading();
if(getHeading() > HALF_TURN_DEGREES){
angle = HALF_TURN_DEGREES - getHeading();
}
+ angle=Math.toRadians(angle);
nextLocation =
new Location(myCanvasBounds.getWidth(), getY() + getX() /
Math.tan(angle));
nextCenter = new Location(0, getY() + getX() / Math.tan(angle));
if(getHeading() == ONE_QUARTER_TURN_DEGREES){
nextLocation = new Location(myCanvasBounds.getWidth(), getY());
nextCenter = new Location(0, getY());
}
// left
}
else if (nextLocation.getX() < 0) {
- nextLocation = new Location(0, getY() + getX() / Math.tan(getHeading()));
+ double angle=Math.toRadians(getHeading());
+ nextLocation = new Location(0, getY() + getX() / Math.tan(angle));
nextCenter = new Location(myCanvasBounds.getWidth(), getY() + getX() /
- Math.tan(getHeading()));
+ Math.tan(angle));
if(getHeading() == THREE_QUARTER_TURN_DEGREES){
nextLocation = new Location(0, getY());
nextCenter = new Location(myCanvasBounds.getWidth(), getY());
}
}
setCenter(nextCenter);
- int newPixels = pixels - (int) (Vector.distanceBetween(currentLocation, nextLocation));
+ double newPixels = pixels - (Vector.distanceBetween(currentLocation, nextLocation));
if (myPenDown) {
myLine.addLineSegment(currentLocation, nextLocation);
}
moveRecursiveHelper(newPixels);
+
+
}
/**
* Turns turtle by given degrees.
*
* @param degrees to turn by
* @return command return value
*/
public double turn (double degrees) {
setHeading(getHeading() + degrees);
return Math.abs(degrees);
}
/**
* sets current heading.
*
* @param heading to set
* @return current heading
*/
public double setHeading (double heading) {
double oldHeading = getHeading();
setMyHeading(heading);
return Math.abs(heading - oldHeading);
}
/**
* Sets heading to go towards location
*
* @param location location to set heading towards
* @return distance of turn
*/
public double towards (Location location) {
Location convertedLocation = convertFromViewCoordinates(location);
double turnDistance = Vector.angleBetween(new Location(getX(), getY()), convertedLocation);
turn(turnDistance);
return turnDistance;
}
/**
* Moves turtle to location
*
* @param location to move to
* @return distance of move
*/
public int setLocation (Location location) {
Location locationToMove = convertFromViewCoordinates(location);
double heading = getHeading();
towards(locationToMove);
int distance = (int) Vector.distanceBetween(location, getLocation());
setHeading(heading);
return distance;
}
/**
* Sets turtle to showing.
*
* @return command value
*/
public int showTurtle () {
myTurtleShowing = true;
return 1;
}
/**
* Sets turtle to hiding.
*
* @return command value
*/
public int hideTurtle () {
myTurtleShowing = false;
return 0;
}
/**
* Sets lines to show up on new moves.
*
* @return command value
*/
public int showPen () {
myPenDown = true;
return 1;
}
/**
* Sets lines to not show up on new moves.
*
* @return command value
*/
public int hidePen () {
myPenDown = false;
return 0;
}
/**
* Moves turtle to center and original heading.
*
* @return
*/
public int home () {
Location center = new Location(myCenterXValue, myCenterYValue);
int distance = (int) Vector.distanceBetween(getLocation(), center);
setLocation(center);
resetHeading();
return distance;
}
/**
* Clears all lines and moves turtle home.
*
* @return
*/
public int clearScreen () {
int distance = home();
myLine.clear();
return distance;
}
/**
* Gets if turtle is showing or not.
*
* @return 1 if turtle is showing, 0 if not
*/
public int isTurtleShowing () {
if (myTurtleShowing) return 1;
return 0;
}
/**
* Gets if pen is down or not.
*
* @return 1 if pen is down, 0 if not
*/
public int isPenDown () {
if (myPenDown) return 1;
return 0;
}
private Location convertFromViewCoordinates (Location location) {
return new Location(location.getX() - myCenterXValue, myCenterYValue - location.getY());
}
/**
* Gets all paintable objects currently showing and returns them in an iterator.
* @return iterator of paintables
*/
public Iterator<Paintable> getPaintableIterator () {
ArrayList<Paintable> paintList = new ArrayList<Paintable>();
if (myTurtleShowing) {
paintList.add(this);
}
paintList.add(myLine);
return paintList.iterator();
}
/**
*
* @return current turtle position.
*/
public Location getTurtlePosition () {
return convertFromViewCoordinates(getLocation());
}
}
diff --git a/src/util/Sprite.java b/src/util/Sprite.java
index e6ea608..585f0dc 100644
--- a/src/util/Sprite.java
+++ b/src/util/Sprite.java
@@ -1,309 +1,309 @@
package util;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
/**
* This class represents a shape that moves on its own.
*
* Note, Sprite is a technical term:
* http://en.wikipedia.org/wiki/Sprite_(computer_graphics)
*
* @author Robert C. Duvall
* @author David Winegar
* @author Zhen Gou
*/
public abstract class Sprite implements Paintable {
// canonical directions for a collision
public static final int RIGHT_DIRECTION = 0;
public static final int DOWN_DIRECTION = 90;
public static final int LEFT_DIRECTION = 180;
public static final int UP_DIRECTION = 270;
private static final double DEFAULT_HEADING = UP_DIRECTION;
// state
private Location myCenter;
private Vector myVelocity;
private double myHeading;
private Dimension mySize;
private Pixmap myView;
// keep copies of the original state so shape can be reset as needed
private Location myOriginalCenter;
// private Vector myOriginalVelocity;
private Dimension myOriginalSize;
private Pixmap myOriginalView;
// cached for efficiency
private Rectangle myBounds;
/**
* Create a shape at the given position, with the given size.
*/
public Sprite (Pixmap image, Location center, Dimension size) {
this(image, center, size, DEFAULT_HEADING);
}
/**
* Create a shape at the given position, with the given size, velocity, and color.
*/
public Sprite (Pixmap image, Location center, Dimension size, double heading) {
// make copies just to be sure no one else has access
myOriginalCenter = new Location(center);
myOriginalSize = new Dimension(size);
myOriginalView = new Pixmap(image);
myHeading = heading;
reset();
resetBounds();
}
/**
* Describes how to "animate" the shape by changing its state.
*
* Currently, moves by the current velocity.
*/
public void update (double elapsedTime, Dimension bounds) {
// do not change original velocity
Vector v = new Vector(myVelocity);
v.scale(elapsedTime);
translate(v);
}
/**
* Moves shape's center by given vector.
*/
public void translate (Vector v) {
myCenter.translate(v);
resetBounds();
}
/**
* Resets shape's center.
*/
public void setCenter (double x, double y) {
myCenter.setLocation(x, y);
- resetBounds();
+ // resetBounds();
}
/**
* Resets shape's center.
*/
public void setCenter (Location center) {
setCenter(center.getX(), center.getY());
}
/**
* Returns shape's x coordinate in pixels.
*/
public double getX () {
return myCenter.getX();
}
/**
* Returns shape's y-coordinate in pixels.
*/
public double getY () {
return myCenter.getY();
}
/**
* Returns shape's left-most coordinate in pixels.
*/
public double getLeft () {
return myCenter.getX() - mySize.width / 2;
}
/**
* Returns shape's top-most coordinate in pixels.
*/
public double getTop () {
return myCenter.getY() - mySize.height / 2;
}
/**
* Returns shape's right-most coordinate in pixels.
*/
public double getRight () {
return myCenter.getX() + mySize.width / 2;
}
/**
* Returns shape's bottom-most coordinate in pixels.
*/
public double getBottom () {
return myCenter.getY() + mySize.height / 2;
}
/**
* Returns shape's width in pixels.
*/
public double getWidth () {
return mySize.getWidth();
}
/**
* Returns shape's height in pixels.
*/
public double getHeight () {
return mySize.getHeight();
}
/**
* Scales shape's size by the given factors.
*/
public void scale (double widthFactor, double heightFactor) {
mySize.setSize(mySize.width * widthFactor, mySize.height * heightFactor);
resetBounds();
}
/**
* Resets shape's size.
*/
public void setSize (int width, int height) {
mySize.setSize(width, height);
resetBounds();
}
/**
* Resets shape's size.
*/
public void setSize (Dimension size) {
setSize(size.width, size.height);
}
/**
* Returns shape's velocity.
*/
public Vector getVelocity () {
return myVelocity;
}
/**
* Resets shape's velocity.
*/
public void setVelocity (double angle, double magnitude) {
myVelocity = new Vector(angle, magnitude);
}
/**
* Resets shape's velocity.
*/
public void setVelocity (Vector velocity) {
setVelocity(velocity.getDirection(), velocity.getMagnitude());
}
/**
* Resets shape's image.
*/
public void setView (Pixmap image) {
if (image != null) {
myView = image;
}
}
/**
* Returns rectangle that encloses this shape.
*/
public Rectangle getBounds () {
return myBounds;
}
/**
* Returns true if the given point is within a rectangle representing this shape.
*/
public boolean intersects (Sprite other) {
return getBounds().intersects(other.getBounds());
}
/**
* Returns true if the given point is within a rectangle representing this shape.
*/
public boolean intersects (Point2D pt) {
return getBounds().contains(pt);
}
/**
* Reset shape back to its original values.
*/
public void reset () {
myCenter = new Location(myOriginalCenter);
mySize = new Dimension(myOriginalSize);
myHeading = DEFAULT_HEADING;
myView = new Pixmap(myOriginalView);
}
/**
* Display this shape on the screen.
*/
@Override
public void paint (Graphics2D pen)
{
myView.paint(pen, myCenter, mySize, myHeading);
}
/**
* Returns rectangle that encloses this shape.
*/
protected void resetBounds () {
myBounds = new Rectangle((int) getLeft(), (int) getTop(), mySize.width, mySize.height);
}
/**
* Returns approximate direction from center of rectangle to side which was hit or
* NaN if no hit took place.
*/
protected double getHitDirection (Rectangle bounds) {
// double angle = Vector.angleBetween(myCenter, new Location(bounds.getCenterX(),
// bounds.getCenterY()));
if (bounds.contains(new Location(getLeft(), getY())))
return RIGHT_DIRECTION;
else if (bounds.contains(new Location(getX(), getBottom())))
return UP_DIRECTION;
else if (bounds.contains(new Location(getRight(), getY())))
return LEFT_DIRECTION;
else if (bounds.contains(new Location(getX(), getTop()))) return DOWN_DIRECTION;
return 0;
// return Double.NaN;
}
/**
* Gets the current location. Returns a copy so Location can't be changed using this method.
*
* @return copy of current location.
*/
protected Location getLocation () {
return new Location(myCenter.getX(), myCenter.getY());
}
/**
* Returns the current heading.
*
* @return current heading
*/
public double getHeading () {
return myHeading;
}
/**
* Sets the current heading to the passed in value.
* @param heading to set
*/
public void setMyHeading (double heading) {
myHeading = heading;
myVelocity = new Vector(heading, 0);
}
/**
* resets the heading to the default value.
*/
public void resetHeading () {
myHeading = DEFAULT_HEADING;
myVelocity = new Vector(DEFAULT_HEADING, 0);
}
}
| false | false | null | null |
diff --git a/whois-commons/src/main/java/net/ripe/db/whois/common/rpsl/DummifierCurrent.java b/whois-commons/src/main/java/net/ripe/db/whois/common/rpsl/DummifierCurrent.java
index 862406101..d10f13ce8 100644
--- a/whois-commons/src/main/java/net/ripe/db/whois/common/rpsl/DummifierCurrent.java
+++ b/whois-commons/src/main/java/net/ripe/db/whois/common/rpsl/DummifierCurrent.java
@@ -1,120 +1,131 @@
package net.ripe.db.whois.common.rpsl;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
-import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
-import static net.ripe.db.whois.common.rpsl.AttributeType.*;
+import static net.ripe.db.whois.common.rpsl.AttributeType.ABUSE_MAILBOX;
+import static net.ripe.db.whois.common.rpsl.AttributeType.ADDRESS;
+import static net.ripe.db.whois.common.rpsl.AttributeType.AUTH;
+import static net.ripe.db.whois.common.rpsl.AttributeType.CHANGED;
+import static net.ripe.db.whois.common.rpsl.AttributeType.E_MAIL;
+import static net.ripe.db.whois.common.rpsl.AttributeType.FAX_NO;
+import static net.ripe.db.whois.common.rpsl.AttributeType.IRT_NFY;
+import static net.ripe.db.whois.common.rpsl.AttributeType.MNT_NFY;
+import static net.ripe.db.whois.common.rpsl.AttributeType.NOTIFY;
+import static net.ripe.db.whois.common.rpsl.AttributeType.PERSON;
+import static net.ripe.db.whois.common.rpsl.AttributeType.PHONE;
+import static net.ripe.db.whois.common.rpsl.AttributeType.REF_NFY;
+import static net.ripe.db.whois.common.rpsl.AttributeType.UPD_TO;
@Component
public class DummifierCurrent implements Dummifier {
private static final Logger LOGGER = LoggerFactory.getLogger(DummifierCurrent.class);
private static final String PERSON_REPLACEMENT = "Name Removed";
private static final String FILTERED_APPENDIX = " # Filtered";
private static final Splitter EMAIL_SPLITTER = Splitter.on('@');
private static final Splitter SPACE_SPLITTER = Splitter.on(' ');
private static final Set<AttributeType> EMAIL_ATTRIBUTES = Sets.immutableEnumSet(E_MAIL, NOTIFY, CHANGED, REF_NFY, IRT_NFY, MNT_NFY, UPD_TO);
private static final Set<AttributeType> PHONE_FAX_ATTRIBUTES = Sets.immutableEnumSet(PHONE, FAX_NO);
public RpslObject dummify(final int version, final RpslObject rpslObject) {
final ObjectType objectType = rpslObject.getType();
Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version);
final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes());
RpslAttribute lastAddressLine = null;
int lastAddressLineIndex = 0;
for (int i = 0; i < attributes.size(); i++) {
RpslAttribute replacement = attributes.get(i);
final AttributeType attributeType = replacement.getType();
try {
if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) {
replacement = replacePerson(attributeType, replacement);
replacement = replaceAuth(attributeType, replacement);
replacement = replacePhoneFax(attributeType, replacement);
if (attributeType == ADDRESS) {
lastAddressLine = replacement;
lastAddressLineIndex = i;
replacement = new RpslAttribute(ADDRESS, "***");
}
}
replacement = replaceEmail(attributeType, replacement);
attributes.set(i, replacement);
} catch (RuntimeException e) {
// leaving attribute as it is if dummification failed
LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e);
}
}
if (lastAddressLine != null) {
attributes.set(lastAddressLineIndex, lastAddressLine);
}
- return new RpslObject(rpslObject.getObjectId(), attributes);
+ return new RpslObject(rpslObject, attributes);
}
private RpslAttribute replacePhoneFax(final AttributeType attributeType, final RpslAttribute attribute) {
if (PHONE_FAX_ATTRIBUTES.contains(attributeType)) {
char[] phone = attribute.getCleanValue().toString().toCharArray();
for (int i = phone.length / 2; i < phone.length; i++) {
if (!Character.isWhitespace(phone[i])) {
phone[i] = '.';
}
}
return new RpslAttribute(attributeType, new String(phone));
}
return attribute;
}
private RpslAttribute replaceEmail(final AttributeType attributeType, final RpslAttribute attribute) {
if (EMAIL_ATTRIBUTES.contains(attributeType)) {
Iterator it = EMAIL_SPLITTER.split(attribute.getCleanValue().toString()).iterator();
it.next();
return new RpslAttribute(attributeType, "***@" + it.next());
}
return attribute;
}
// TODO: [AH] we should relay on a single implementation of Authentication Filter; this method duplicates FilterAuthFunction
private RpslAttribute replaceAuth(final AttributeType attributeType, final RpslAttribute attribute) {
if (attributeType != AUTH) {
return attribute;
}
String passwordType = SPACE_SPLITTER.split(attribute.getCleanValue().toUpperCase()).iterator().next();
if (passwordType.endsWith("-PW") || passwordType.startsWith("SSO")) { // history table has CRYPT-PW, has to be able to dummify that too!
return new RpslAttribute(AttributeType.AUTH, passwordType + FILTERED_APPENDIX);
}
return attribute;
}
private RpslAttribute replacePerson(final AttributeType attributeType, final RpslAttribute attribute) {
if (attributeType == PERSON) {
return new RpslAttribute(attributeType, PERSON_REPLACEMENT);
}
return attribute;
}
public boolean isAllowed(final int version, final RpslObject object) {
return version >= 3;
}
}
diff --git a/whois-commons/src/main/java/net/ripe/db/whois/common/rpsl/DummifierLegacy.java b/whois-commons/src/main/java/net/ripe/db/whois/common/rpsl/DummifierLegacy.java
index ff36339b4..78682b976 100644
--- a/whois-commons/src/main/java/net/ripe/db/whois/common/rpsl/DummifierLegacy.java
+++ b/whois-commons/src/main/java/net/ripe/db/whois/common/rpsl/DummifierLegacy.java
@@ -1,263 +1,263 @@
package net.ripe.db.whois.common.rpsl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.ripe.db.whois.common.domain.CIString;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Component
public class DummifierLegacy implements Dummifier {
private static final Logger LOGGER = LoggerFactory.getLogger(DummifierLegacy.class);
public static final RpslObject PLACEHOLDER_PERSON_OBJECT = RpslObject.parse("" +
"person: Placeholder Person Object\n" +
"address: RIPE Network Coordination Centre\n" +
"address: P.O. Box 10096\n" +
"address: 1001 EB Amsterdam\n" +
"address: The Netherlands\n" +
"phone: +31 20 535 4444\n" +
"nic-hdl: DUMY-RIPE\n" +
"mnt-by: RIPE-DBM-MNT\n" +
"remarks: **********************************************************\n" +
"remarks: * This is a placeholder object to protect personal data.\n" +
"remarks: * To view the original object, please query the RIPE\n" +
"remarks: * Database at:\n" +
"remarks: * http://www.ripe.net/whois\n" +
"remarks: **********************************************************\n" +
"changed: [email protected] 20090724\n" +
"source: RIPE"
);
public static final RpslObject PLACEHOLDER_ROLE_OBJECT = RpslObject.parse("" +
"role: Placeholder Role Object\n" +
"address: RIPE Network Coordination Centre\n" +
"address: P.O. Box 10096\n" +
"address: 1001 EB Amsterdam\n" +
"address: The Netherlands\n" +
"phone: +31 20 535 4444\n" +
"e-mail: [email protected]\n" +
"admin-c: DUMY-RIPE\n" +
"tech-c: DUMY-RIPE\n" +
"nic-hdl: ROLE-RIPE\n" +
"mnt-by: RIPE-DBM-MNT\n" +
"remarks: **********************************************************\n" +
"remarks: * This is a placeholder object to protect personal data.\n" +
"remarks: * To view the original object, please query the RIPE\n" +
"remarks: * Database at:\n" +
"remarks: * http://www.ripe.net/whois\n" +
"remarks: **********************************************************\n" +
"changed: [email protected] 20090724\n" +
"source: RIPE"
);
static final Set<ObjectType> SKIPPED_OBJECT_TYPES = Sets.immutableEnumSet(ObjectType.PERSON, ObjectType.ROLE);
static final Set<ObjectType> STRIPPED_OBJECT_TYPES = Sets.immutableEnumSet(ObjectType.MNTNER, ObjectType.ORGANISATION);
private static final String PERSON_ROLE_PLACEHOLDER = "DUMY-RIPE";
static final Set<AttributeType> PERSON_ROLE_REFERENCES = Sets.immutableEnumSet(
AttributeType.ADMIN_C,
AttributeType.AUTHOR,
AttributeType.PING_HDL,
AttributeType.TECH_C,
AttributeType.ZONE_C
);
static final Map<AttributeType, String> DUMMIFICATION_REPLACEMENTS = Maps.newEnumMap(AttributeType.class);
static {
DUMMIFICATION_REPLACEMENTS.put(AttributeType.ADDRESS, "Dummy address for %s");
DUMMIFICATION_REPLACEMENTS.put(AttributeType.AUTH, "MD5-PW $1$SaltSalt$DummifiedMD5HashValue. # Real value hidden for security");
DUMMIFICATION_REPLACEMENTS.put(AttributeType.CHANGED, "[email protected] 20000101");
DUMMIFICATION_REPLACEMENTS.put(AttributeType.E_MAIL, "[email protected]");
DUMMIFICATION_REPLACEMENTS.put(AttributeType.FAX_NO, "+31205354444");
DUMMIFICATION_REPLACEMENTS.put(AttributeType.PHONE, "+31205354444");
DUMMIFICATION_REPLACEMENTS.put(AttributeType.UPD_TO, "[email protected]");
}
public RpslObject dummify(final int version, final RpslObject rpslObject) {
final ObjectType objectType = rpslObject.getType();
Validate.isTrue(isAllowed(version, rpslObject), "The given object type should be skipped", objectType);
// [EB]: Shortcircuit for objects we'd normally skip for old protocols.
if (version <= 2 && usePlaceHolder(rpslObject)) {
return objectType.equals(ObjectType.ROLE) ? PLACEHOLDER_ROLE_OBJECT : PLACEHOLDER_PERSON_OBJECT;
}
final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes());
stripOptionalAttributes(attributes, objectType);
dummifyMandatoryAttributes(attributes, rpslObject.getKey());
insertPlaceholder(attributes);
attributes.addAll(getDummificationRemarks(rpslObject));
- return new RpslObject(rpslObject.getObjectId(), attributes);
+ return new RpslObject(rpslObject, attributes);
}
private void stripOptionalAttributes(List<RpslAttribute> attributes, ObjectType objectType) {
if (!STRIPPED_OBJECT_TYPES.contains(objectType)) {
return;
}
final ObjectTemplate objectTemplate = ObjectTemplate.getTemplate(objectType);
final Set<AttributeType> mandatoryAttributes = objectTemplate.getMandatoryAttributes();
for (Iterator<RpslAttribute> iterator = attributes.iterator(); iterator.hasNext(); ) {
final RpslAttribute attribute = iterator.next();
if (!mandatoryAttributes.contains(attribute.getType()) && !AttributeType.ABUSE_C.equals(attribute.getType())) {
iterator.remove();
}
}
}
private void dummifyMandatoryAttributes(final List<RpslAttribute> attributes, final CIString key) {
final Set<AttributeType> seenAttributes = Sets.newHashSet();
for (int i = 0; i < attributes.size(); i++) {
final RpslAttribute attribute = attributes.get(i);
final AttributeType attributeType = attribute.getType();
final String replacementValue = DUMMIFICATION_REPLACEMENTS.get(attributeType);
if (replacementValue == null) {
continue;
}
final RpslAttribute replacement;
if (seenAttributes.add(attributeType)) {
replacement = new RpslAttribute(attribute.getKey(), String.format(replacementValue, key));
} else {
replacement = null;
}
attributes.set(i, replacement);
}
for (Iterator<RpslAttribute> iterator = attributes.iterator(); iterator.hasNext(); ) {
if (iterator.next() == null) {
iterator.remove();
}
}
}
private void insertPlaceholder(List<RpslAttribute> attributes) {
final Set<AttributeType> seenAttributes = Sets.newHashSet();
for (int i = 0; i < attributes.size(); i++) {
final RpslAttribute attribute = attributes.get(i);
if (!PERSON_ROLE_REFERENCES.contains(attribute.getType())) {
continue;
}
if (seenAttributes.add(attribute.getType())) {
attributes.set(i, new RpslAttribute(attribute.getKey(), PERSON_ROLE_PLACEHOLDER));
} else {
attributes.remove(i);
i--;
}
}
}
public boolean isAllowed(final int version, final RpslObject rpslObject) {
return version <= 2 || !usePlaceHolder(rpslObject);
}
private boolean usePlaceHolder(final RpslObject rpslObject) {
final ObjectType objectType = rpslObject.getType();
return SKIPPED_OBJECT_TYPES.contains(objectType)
&& (!ObjectType.ROLE.equals(objectType) || rpslObject.findAttributes(AttributeType.ABUSE_MAILBOX).isEmpty());
}
private static List<RpslAttribute> getDummificationRemarks(final RpslObject rpslObject) {
final String source = rpslObject.getValueForAttribute(AttributeType.SOURCE).toLowerCase();
switch(source) {
case "ripe":
case "ripe-grs":
case "test":
case "test-grs":
return Lists.newArrayList(
new RpslAttribute("remarks", " ****************************"),
new RpslAttribute("remarks", " * THIS OBJECT IS MODIFIED"),
new RpslAttribute("remarks", " * Please note that all data that is generally regarded as personal"),
new RpslAttribute("remarks", " * data has been removed from this object."),
new RpslAttribute("remarks", " * To view the original object, please query the RIPE Database at:"),
new RpslAttribute("remarks", " * http://www.ripe.net/whois"),
new RpslAttribute("remarks", " ****************************"));
case "afrinic-grs":
return Lists.newArrayList(
new RpslAttribute("remarks", " ****************************"),
new RpslAttribute("remarks", " * THIS OBJECT IS MODIFIED"),
new RpslAttribute("remarks", " * Please note that all data that is generally regarded as personal"),
new RpslAttribute("remarks", " * data has been removed from this object."),
new RpslAttribute("remarks", " * To view the original object, please query the AFRINIC Database at:"),
new RpslAttribute("remarks", " * http://www.afrinic.net/"),
new RpslAttribute("remarks", " ****************************"));
case "apnic-grs":
return Lists.newArrayList(
new RpslAttribute("remarks", " ****************************"),
new RpslAttribute("remarks", " * THIS OBJECT IS MODIFIED"),
new RpslAttribute("remarks", " * Please note that all data that is generally regarded as personal"),
new RpslAttribute("remarks", " * data has been removed from this object."),
new RpslAttribute("remarks", " * To view the original object, please query the APNIC Database at:"),
new RpslAttribute("remarks", " * http://www.apnic.net/"),
new RpslAttribute("remarks", " ****************************"));
case "arin-grs":
return Lists.newArrayList(
new RpslAttribute("remarks", " ****************************"),
new RpslAttribute("remarks", " * THIS OBJECT IS MODIFIED"),
new RpslAttribute("remarks", " * Please note that all data that is generally regarded as personal"),
new RpslAttribute("remarks", " * data has been removed from this object."),
new RpslAttribute("remarks", " * To view the original object, please query the ARIN Database at:"),
new RpslAttribute("remarks", " * http://www.arin.net/"),
new RpslAttribute("remarks", " ****************************"));
case "jpirr-grs":
return Lists.newArrayList(
new RpslAttribute("remarks", " ****************************"),
new RpslAttribute("remarks", " * THIS OBJECT IS MODIFIED"),
new RpslAttribute("remarks", " * Please note that all data that is generally regarded as personal"),
new RpslAttribute("remarks", " * data has been removed from this object."),
new RpslAttribute("remarks", " * To view the original object, please query the JPIRR Database at:"),
new RpslAttribute("remarks", " * http://www.nic.ad.jp/"),
new RpslAttribute("remarks", " ****************************"));
case "lacnic-grs":
return Lists.newArrayList(
new RpslAttribute("remarks", " ****************************"),
new RpslAttribute("remarks", " * THIS OBJECT IS MODIFIED"),
new RpslAttribute("remarks", " * Please note that all data that is generally regarded as personal"),
new RpslAttribute("remarks", " * data has been removed from this object."),
new RpslAttribute("remarks", " * To view the original object, please query the LACNIC Database at:"),
new RpslAttribute("remarks", " * http://www.lacnic.net/"),
new RpslAttribute("remarks", " ****************************"));
case "radb-grs":
return Lists.newArrayList(
new RpslAttribute("remarks", " ****************************"),
new RpslAttribute("remarks", " * THIS OBJECT IS MODIFIED"),
new RpslAttribute("remarks", " * Please note that all data that is generally regarded as personal"),
new RpslAttribute("remarks", " * data has been removed from this object."),
new RpslAttribute("remarks", " * To view the original object, please query the RADB Database at:"),
new RpslAttribute("remarks", " * http://www.ra.net/"),
new RpslAttribute("remarks", " ****************************"));
default:
LOGGER.warn("Unknown source {} in object {}", source, rpslObject.getKey());
return Lists.newArrayList();
}
}
}
| false | false | null | null |
diff --git a/src/simpleserver/util/UnicodeReader.java b/src/simpleserver/util/UnicodeReader.java
index 4635709..79505ac 100644
--- a/src/simpleserver/util/UnicodeReader.java
+++ b/src/simpleserver/util/UnicodeReader.java
@@ -1,129 +1,131 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package simpleserver.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.io.Reader;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
public class UnicodeReader extends Reader {
private static final int BOM_SIZE = 4;
private static LinkedHashMap<String, byte[]> BOMS;
private PushbackInputStream pushbackReader;
private InputStreamReader reader;
private String encoding;
public UnicodeReader(InputStream in) {
this(in, "UTF-8");
}
public UnicodeReader(InputStream in, String encoding) {
pushbackReader = new PushbackInputStream(in, BOM_SIZE);
this.encoding = encoding;
BOMS = new LinkedHashMap<String, byte[]>(5);
BOMS.put("UTF-8", new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
BOMS.put("UTF-32BE", new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF });
BOMS.put("UTF-32LE", new byte[] { (byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00 });
BOMS.put("UTF-16BE", new byte[] { (byte) 0xFE, (byte) 0xFF });
BOMS.put("UTF-16LE", new byte[] { (byte) 0xFF, (byte) 0xFE });
}
public String getEncoding() {
try {
return reader.getEncoding();
} catch (NullPointerException e) {
return null;
}
}
protected void init() throws IOException {
if (reader != null) {
return;
}
processBOM();
}
protected void processBOM() throws IOException {
byte[] bom = new byte[BOM_SIZE];
int read = pushbackReader.read(bom, 0, BOM_SIZE);
int unread = 0;
- Set<String> encodings = BOMS.keySet();
- Iterator<String> itr = encodings.iterator();
- while (itr.hasNext()) {
- String currentEncoding = itr.next();
- byte[] currentBOM = BOMS.get(currentEncoding);
- if (arrayStartsWith(bom, currentBOM)) {
- encoding = currentEncoding;
- unread = currentBOM.length;
- break;
+ if (read > 0) {
+ Set<String> encodings = BOMS.keySet();
+ Iterator<String> itr = encodings.iterator();
+ while (itr.hasNext()) {
+ String currentEncoding = itr.next();
+ byte[] currentBOM = BOMS.get(currentEncoding);
+ if (arrayStartsWith(bom, currentBOM)) {
+ encoding = currentEncoding;
+ unread = currentBOM.length;
+ break;
+ }
}
- }
- if (unread <= 4) {
- pushbackReader.unread(bom, unread, read - unread);
+ if (unread <= BOM_SIZE && unread > 0) {
+ pushbackReader.unread(bom, unread, read - unread);
+ }
}
if (encoding == null) {
reader = new InputStreamReader(pushbackReader);
} else {
reader = new InputStreamReader(pushbackReader, encoding);
}
}
protected boolean arrayStartsWith(byte[] in, byte[] needleBytes) {
int pos = 0;
boolean found = true;
if (in.length < needleBytes.length) {
return false;
}
for (byte c : needleBytes) {
if (c != in[pos++]) {
found = false;
break;
}
}
return found;
}
@Override
public void close() throws IOException {
if (reader != null) {
reader.close();
}
}
@Override
public int read(char[] buffer, int offset, int length) throws IOException {
init();
return reader.read(buffer, offset, length);
}
}
| false | true | protected void processBOM() throws IOException {
byte[] bom = new byte[BOM_SIZE];
int read = pushbackReader.read(bom, 0, BOM_SIZE);
int unread = 0;
Set<String> encodings = BOMS.keySet();
Iterator<String> itr = encodings.iterator();
while (itr.hasNext()) {
String currentEncoding = itr.next();
byte[] currentBOM = BOMS.get(currentEncoding);
if (arrayStartsWith(bom, currentBOM)) {
encoding = currentEncoding;
unread = currentBOM.length;
break;
}
}
if (unread <= 4) {
pushbackReader.unread(bom, unread, read - unread);
}
if (encoding == null) {
reader = new InputStreamReader(pushbackReader);
} else {
reader = new InputStreamReader(pushbackReader, encoding);
}
}
| protected void processBOM() throws IOException {
byte[] bom = new byte[BOM_SIZE];
int read = pushbackReader.read(bom, 0, BOM_SIZE);
int unread = 0;
if (read > 0) {
Set<String> encodings = BOMS.keySet();
Iterator<String> itr = encodings.iterator();
while (itr.hasNext()) {
String currentEncoding = itr.next();
byte[] currentBOM = BOMS.get(currentEncoding);
if (arrayStartsWith(bom, currentBOM)) {
encoding = currentEncoding;
unread = currentBOM.length;
break;
}
}
if (unread <= BOM_SIZE && unread > 0) {
pushbackReader.unread(bom, unread, read - unread);
}
}
if (encoding == null) {
reader = new InputStreamReader(pushbackReader);
} else {
reader = new InputStreamReader(pushbackReader, encoding);
}
}
|
diff --git a/belajar-restful-domain/src/main/java/com/artivisi/belajar/restful/service/BelajarRestfulService.java b/belajar-restful-domain/src/main/java/com/artivisi/belajar/restful/service/BelajarRestfulService.java
index ca803c9..f358cd5 100644
--- a/belajar-restful-domain/src/main/java/com/artivisi/belajar/restful/service/BelajarRestfulService.java
+++ b/belajar-restful-domain/src/main/java/com/artivisi/belajar/restful/service/BelajarRestfulService.java
@@ -1,64 +1,64 @@
/**
* Copyright (C) 2011 ArtiVisi Intermedia <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.artivisi.belajar.restful.service;
import com.artivisi.belajar.restful.domain.ApplicationConfig;
import com.artivisi.belajar.restful.domain.Menu;
import com.artivisi.belajar.restful.domain.Permission;
import com.artivisi.belajar.restful.domain.Role;
import com.artivisi.belajar.restful.domain.User;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface BelajarRestfulService extends MonitoredService {
// konfigurasi aplikasi
void save(ApplicationConfig ac);
void delete(ApplicationConfig ac);
ApplicationConfig findApplicationConfigById(String id);
Page<ApplicationConfig> findAllApplicationConfigs(Pageable pageable);
Long countAllApplicationConfigs();
Long countApplicationConfigs(String search);
Page<ApplicationConfig> findApplicationConfigs(String search, Pageable pageable);
// menu
void save(Menu m);
void delete(Menu m);
Menu findMenuById(String id);
List<Menu> findTopLevelMenu();
List<Menu> findMenuByParent(Menu m);
// permission
void save(Permission m);
void delete(Permission m);
Permission findPermissionById(String id);
Page<Permission> findAllPermissions(Pageable pageable);
Long countAllPermissions();
// role
void save(Role role);
void delete(Role role);
Role findRoleById(String id);
Page<Role> findAllRoles(Pageable pageable);
Long countAllRoles();
- // permission
+ // user
void save(User m);
void delete(User m);
User findUserById(String id);
Page<User> findAllUsers(Pageable pageable);
Long countAllUsers();
}
diff --git a/belajar-restful-web/src/test/java/com/artivisi/belajar/restful/ui/controller/MenuControllerTestIT.java b/belajar-restful-web/src/test/java/com/artivisi/belajar/restful/ui/controller/MenuControllerTestIT.java
index 76f0c95..260c105 100644
--- a/belajar-restful-web/src/test/java/com/artivisi/belajar/restful/ui/controller/MenuControllerTestIT.java
+++ b/belajar-restful-web/src/test/java/com/artivisi/belajar/restful/ui/controller/MenuControllerTestIT.java
@@ -1,125 +1,125 @@
/**
* Copyright (C) 2011 ArtiVisi Intermedia <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.artivisi.belajar.restful.ui.controller;
import com.artivisi.belajar.restful.domain.Menu;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.RestAssured.with;
import com.jayway.restassured.authentication.FormAuthConfig;
import groovyx.net.http.ContentType;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class MenuControllerTestIT {
private String target = "http://localhost:10000/menu";
private String login = "http://localhost:10000/j_spring_security_check";
private String username = "endy";
private String password = "123";
@Test
public void testSaveUpdateDelete() {
Menu x = new Menu();
x.setLabel("Menu Percobaan");
x.setAction("test");
x.setLevel(0);
x.setOrder(99);
String id = testSave(target, x);
System.out.println("Id : " + id);
testGetExistingById(id, x);
x.setLabel("Ganti Label");
x.setAction("ganti action");
testUpdateExisting(id, x);
testGetExistingById(id, x);
testDeleteExistingById(id);
}
private String testSave(String target, Menu x) {
String location = given()
.auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.body(x).contentType(ContentType.JSON)
.expect().statusCode(201).when().post(target)
.getHeader("Location");
assertNotNull(location);
assertTrue(location.startsWith(target));
String[] locationSplit = location.split("/");
String id = locationSplit[locationSplit.length - 1];
return id;
}
private void testGetExistingById(String id, Menu x) {
with().header("Accept", "application/json")
.auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.expect()
.statusCode(200)
.body("label", equalTo(x.getLabel()), "action", equalTo(x.getAction()))
.when().get(target + "/" + id);
}
private void testUpdateExisting(String id, Menu x) {
given()
.auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.body(x).contentType(ContentType.JSON).expect()
.statusCode(200).when().put(target + "/" + id);
}
private void testDeleteExistingById(String id) {
given().auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.expect().statusCode(200).when().delete(target + "/" + id);
given().auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.expect().statusCode(404).when().get(target + "/" + id);
}
@Test
- public void testGetExistingConfigById() {
+ public void testGetExistingById() {
with().header("Accept", "application/json")
.auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.expect()
.statusCode(200)
.body("id", equalTo("system"),
"label", equalTo("System"),
"action", equalTo("#")).when()
.get(target + "/" + "system");
}
@Test
- public void testGetNonExistentConfigById() {
+ public void testGetNonExistentById() {
with()
.auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.expect().statusCode(404).when().get(target + "/" + "/nonexistentconfig");
}
@Test
public void testFindAll() {
with()
.auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.header("Accept", "application/json").expect().statusCode(200)
.body("id", hasItems("system", "master")).when().get(target);
}
}
| false | false | null | null |
diff --git a/jsyslogd/src/com/github/picologger/syslog/Parser.java b/jsyslogd/src/com/github/picologger/syslog/Parser.java
index 8ffb1cf..0ee18a8 100644
--- a/jsyslogd/src/com/github/picologger/syslog/Parser.java
+++ b/jsyslogd/src/com/github/picologger/syslog/Parser.java
@@ -1,116 +1,116 @@
/*
* Copyright (C) 2011 cybertk
*
* -- https://github.com/kyan-he/picologger/raw/master/jsyslogd/src/com/github/picologger/syslog/Parser.java--
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.picologger.syslog;
public abstract class Parser
{
public static Syslog parse(String record) throws IllegalArgumentException
{
- if (null == record)
+ if (null == record || "".equals(record))
{
throw new IllegalArgumentException("no record.");
}
Syslog log = new Syslog();
int pos0 = 0;
int pos = 0;
// Validate format.
pos = record.indexOf('>');
if (record.charAt(0) != '<' || pos > 4)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Header.
// Parse facility and severity.
try
{
int pri = Integer.parseInt((record.substring(1, pos)));
log.setFacility(pri >> 3);
log.setSeverity(pri & 0x7);
}
catch (NumberFormatException e)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Version.
++pos;
final int version = record.charAt(pos) - 0x30;
// Validate Version.
if (version != 1)
{
throw new IllegalArgumentException(
"Malformed syslog record. RFC3164?");
}
log.setVersion(version);
String[] token = record.split(" ", 7);
log.setTimestamp(token[1]);
log.setHostname(token[2]);
log.setAppname(token[3]);
log.setProcid(token[4]);
log.setMsgid(token[5]);
// Parse SD
if (token[6].charAt(0) == '[')
{
while (true)
{
pos0 = token[6].indexOf(']', pos0);
if (pos0 == -1)
{
break;
}
++pos0;
// Record the index.
if (token[6].charAt(pos0 - 2) != '\\')
{
// Make sure it's not a escaped "]".
pos = pos0;
}
}
}
else
{
// NILVAULE, "-".
pos = 1;
}
log.setSd(token[6].substring(0, pos));
// Parse message.
if (pos < token[6].length())
{
log.setMsg(token[6].substring(pos + 1));
}
else
{
log.setMsg("");
}
return log;
}
}
| true | true | public static Syslog parse(String record) throws IllegalArgumentException
{
if (null == record)
{
throw new IllegalArgumentException("no record.");
}
Syslog log = new Syslog();
int pos0 = 0;
int pos = 0;
// Validate format.
pos = record.indexOf('>');
if (record.charAt(0) != '<' || pos > 4)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Header.
// Parse facility and severity.
try
{
int pri = Integer.parseInt((record.substring(1, pos)));
log.setFacility(pri >> 3);
log.setSeverity(pri & 0x7);
}
catch (NumberFormatException e)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Version.
++pos;
final int version = record.charAt(pos) - 0x30;
// Validate Version.
if (version != 1)
{
throw new IllegalArgumentException(
"Malformed syslog record. RFC3164?");
}
log.setVersion(version);
String[] token = record.split(" ", 7);
log.setTimestamp(token[1]);
log.setHostname(token[2]);
log.setAppname(token[3]);
log.setProcid(token[4]);
log.setMsgid(token[5]);
// Parse SD
if (token[6].charAt(0) == '[')
{
while (true)
{
pos0 = token[6].indexOf(']', pos0);
if (pos0 == -1)
{
break;
}
++pos0;
// Record the index.
if (token[6].charAt(pos0 - 2) != '\\')
{
// Make sure it's not a escaped "]".
pos = pos0;
}
}
}
else
{
// NILVAULE, "-".
pos = 1;
}
log.setSd(token[6].substring(0, pos));
// Parse message.
if (pos < token[6].length())
{
log.setMsg(token[6].substring(pos + 1));
}
else
{
log.setMsg("");
}
return log;
}
| public static Syslog parse(String record) throws IllegalArgumentException
{
if (null == record || "".equals(record))
{
throw new IllegalArgumentException("no record.");
}
Syslog log = new Syslog();
int pos0 = 0;
int pos = 0;
// Validate format.
pos = record.indexOf('>');
if (record.charAt(0) != '<' || pos > 4)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Header.
// Parse facility and severity.
try
{
int pri = Integer.parseInt((record.substring(1, pos)));
log.setFacility(pri >> 3);
log.setSeverity(pri & 0x7);
}
catch (NumberFormatException e)
{
throw new IllegalArgumentException("Malformed syslog record.");
}
// Parse Version.
++pos;
final int version = record.charAt(pos) - 0x30;
// Validate Version.
if (version != 1)
{
throw new IllegalArgumentException(
"Malformed syslog record. RFC3164?");
}
log.setVersion(version);
String[] token = record.split(" ", 7);
log.setTimestamp(token[1]);
log.setHostname(token[2]);
log.setAppname(token[3]);
log.setProcid(token[4]);
log.setMsgid(token[5]);
// Parse SD
if (token[6].charAt(0) == '[')
{
while (true)
{
pos0 = token[6].indexOf(']', pos0);
if (pos0 == -1)
{
break;
}
++pos0;
// Record the index.
if (token[6].charAt(pos0 - 2) != '\\')
{
// Make sure it's not a escaped "]".
pos = pos0;
}
}
}
else
{
// NILVAULE, "-".
pos = 1;
}
log.setSd(token[6].substring(0, pos));
// Parse message.
if (pos < token[6].length())
{
log.setMsg(token[6].substring(pos + 1));
}
else
{
log.setMsg("");
}
return log;
}
|
diff --git a/modules/plus/src/main/java/org/mortbay/jetty/plus/jaas/JAASUserRealm.java b/modules/plus/src/main/java/org/mortbay/jetty/plus/jaas/JAASUserRealm.java
index 0fefd4a75..8c057034b 100644
--- a/modules/plus/src/main/java/org/mortbay/jetty/plus/jaas/JAASUserRealm.java
+++ b/modules/plus/src/main/java/org/mortbay/jetty/plus/jaas/JAASUserRealm.java
@@ -1,378 +1,378 @@
// ========================================================================
// $Id$
// Copyright 2003-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.mortbay.jetty.plus.jaas;
import java.security.Principal;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.plus.jaas.callback.AbstractCallbackHandler;
import org.mortbay.jetty.plus.jaas.callback.DefaultCallbackHandler;
import org.mortbay.jetty.security.UserRealm;
import org.mortbay.log.Log;
import org.mortbay.util.Loader;
/* ---------------------------------------------------- */
/** JAASUserRealm
* <p>
*
* <p><h4>Notes</h4>
* <p>
*
* <p><h4>Usage</h4>
*
*
*
*
* @org.apache.xbean.XBean element="jaasUserRealm" description="Creates a UserRealm suitable for use with JAAS"
*/
public class JAASUserRealm implements UserRealm
{
public static String DEFAULT_ROLE_CLASS_NAME = "org.mortbay.jetty.plus.jaas.JAASRole";
public static String[] DEFAULT_ROLE_CLASS_NAMES = {DEFAULT_ROLE_CLASS_NAME};
protected String[] roleClassNames = DEFAULT_ROLE_CLASS_NAMES;
protected String callbackHandlerClass;
protected String realmName;
protected String loginModuleName;
protected RoleCheckPolicy roleCheckPolicy;
protected JAASUserPrincipal defaultUser = new JAASUserPrincipal(null, null);
/* ---------------------------------------------------- */
/**
* Constructor.
*
*/
public JAASUserRealm ()
{
}
/* ---------------------------------------------------- */
/**
* Constructor.
*
* @param name the name of the realm
*/
public JAASUserRealm(String name)
{
this();
realmName = name;
}
/* ---------------------------------------------------- */
/**
* Get the name of the realm.
*
* @return name or null if not set.
*/
public String getName()
{
return realmName;
}
/* ---------------------------------------------------- */
/**
* Set the name of the realm
*
* @param name a <code>String</code> value
*/
public void setName (String name)
{
realmName = name;
}
/**
* Set the name to use to index into the config
* file of LoginModules.
*
* @param name a <code>String</code> value
*/
public void setLoginModuleName (String name)
{
loginModuleName = name;
}
public void setCallbackHandlerClass (String classname)
{
callbackHandlerClass = classname;
}
public void setRoleClassNames (String[] classnames)
{
ArrayList tmp = new ArrayList();
if (classnames != null)
tmp.addAll(Arrays.asList(classnames));
if (!tmp.contains(DEFAULT_ROLE_CLASS_NAME))
tmp.add(DEFAULT_ROLE_CLASS_NAME);
- roleClassNames = (String[])tmp.toArray();
+ roleClassNames = (String[])tmp.toArray(new String[tmp.size()]);
}
public String[] getRoleClassNames()
{
return roleClassNames;
}
public void setRoleCheckPolicy (RoleCheckPolicy policy)
{
roleCheckPolicy = policy;
}
//TODO: delete?!
public Principal getPrincipal(String username)
{
return null;
}
/* ------------------------------------------------------------ */
public boolean isUserInRole(Principal user, String role)
{
JAASUserPrincipal thePrincipal = null;
if (user == null)
thePrincipal = defaultUser;
else
{
if (! (user instanceof JAASUserPrincipal))
return false;
thePrincipal = (JAASUserPrincipal)user;
}
return ((JAASUserPrincipal)user).isUserInRole(role);
}
/* ------------------------------------------------------------ */
public boolean reauthenticate(Principal user)
{
if (user instanceof JAASUserPrincipal)
return true;
else
return false;
}
/* ---------------------------------------------------- */
/**
* Authenticate a user.
*
*
* @param username provided by the user at login
* @param credentials provided by the user at login
* @param request a <code>Request</code> value
* @return authenticated JAASUserPrincipal or null if authenticated failed
*/
public Principal authenticate(String username,
Object credentials,
Request request)
{
try
{
AbstractCallbackHandler callbackHandler = null;
//user has not been authenticated
if (callbackHandlerClass == null)
{
Log.warn("No CallbackHandler configured: using DefaultCallbackHandler");
callbackHandler = new DefaultCallbackHandler();
}
else
{
callbackHandler = (AbstractCallbackHandler)Loader.loadClass(JAASUserRealm.class, callbackHandlerClass).getConstructors()[0].newInstance(new Object[0]);
}
if (callbackHandler instanceof DefaultCallbackHandler)
{
((DefaultCallbackHandler)callbackHandler).setRequest (request);
}
callbackHandler.setUserName(username);
callbackHandler.setCredential(credentials);
//set up the login context
LoginContext loginContext = new LoginContext(loginModuleName,
callbackHandler);
loginContext.login();
//login success
JAASUserPrincipal userPrincipal = new JAASUserPrincipal(this, username);
userPrincipal.setSubject(loginContext.getSubject());
userPrincipal.setRoleCheckPolicy (roleCheckPolicy);
userPrincipal.setLoginContext(loginContext);
return userPrincipal;
}
catch (Exception e)
{
Log.warn(e.toString());
Log.debug(e);
return null;
}
}
/* ---------------------------------------------------- */
/**
* Removes any auth info associated with eg. the thread.
*
* @param user a UserPrincipal to disassociate
*/
public void disassociate(Principal user)
{
//TODO: should this apply to the default user?
if (user == null)
defaultUser.disassociate();
else
((JAASUserPrincipal)user).disassociate();
}
/* ---------------------------------------------------- */
/**
* Temporarily adds a role to a user.
*
* Temporarily granting a role pushes the role onto a stack
* of temporary roles. Temporary roles must therefore be
* removed in order.
*
* @param user the Principal to which to add the role
* @param role the role name
* @return the Principal with the role added
*/
public Principal pushRole(Principal user, String role)
{
JAASUserPrincipal thePrincipal = (JAASUserPrincipal)user;
//use the default user
if (thePrincipal == null)
thePrincipal = defaultUser;
thePrincipal.pushRole(role);
return thePrincipal;
}
/* ------------------------------------------------------------ */
public Principal popRole(Principal user)
{
JAASUserPrincipal thePrincipal = (JAASUserPrincipal)user;
//use the default user
if (thePrincipal == null)
thePrincipal = defaultUser;
thePrincipal.popRole();
return thePrincipal;
}
public Group getRoles (JAASUserPrincipal principal)
{
//get all the roles of the various types
String[] roleClassNames = getRoleClassNames();
Group roleGroup = new JAASGroup(JAASGroup.ROLES);
try
{
JAASUserPrincipal thePrincipal = principal;
if (thePrincipal == null)
thePrincipal = defaultUser;
for (int i=0; i<roleClassNames.length;i++)
{
Class load_class=Thread.currentThread().getContextClassLoader().loadClass(roleClassNames[i]);
Set rolesForType = thePrincipal.getSubject().getPrincipals (load_class);
Iterator itor = rolesForType.iterator();
while (itor.hasNext())
roleGroup.addMember((Principal) itor.next());
}
return roleGroup;
}
catch (ClassNotFoundException e)
{
throw new RuntimeException(e);
}
}
/* ---------------------------------------------------- */
/**
* Logout a previously logged in user.
* This can only work for FORM authentication
* as BasicAuthentication is stateless.
*
* The user's LoginContext logout() method is called.
* @param user an <code>Principal</code> value
*/
public void logout(Principal user)
{
try
{
JAASUserPrincipal authenticUser = null;
if (user == null)
authenticUser = defaultUser; //TODO: should the default user ever be logged in?
if (!(user instanceof JAASUserPrincipal))
throw new IllegalArgumentException (user + " is not a JAASUserPrincipal");
authenticUser = (JAASUserPrincipal)user;
authenticUser.getLoginContext().logout();
Log.debug (user+" has been LOGGED OUT");
}
catch (LoginException e)
{
Log.warn (e);
}
}
}
| true | false | null | null |
diff --git a/src/de/remk0/shopshopviewer/ShopShopViewerActivity.java b/src/de/remk0/shopshopviewer/ShopShopViewerActivity.java
index a36ab04..9d10393 100755
--- a/src/de/remk0/shopshopviewer/ShopShopViewerActivity.java
+++ b/src/de/remk0/shopshopviewer/ShopShopViewerActivity.java
@@ -1,248 +1,249 @@
/**
* ShopShopViewer
* Copyright (C) 2011 Remko Plantenga
*
* This file is part of ShopShopViewer.
*
* ShopShopViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ShopShopViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ShopShopViewer. If not, see <http://www.gnu.org/licenses/>.
*/
package de.remk0.shopshopviewer;
import java.io.File;
import java.io.FilenameFilter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import de.remk0.shopshopviewer.ShopShopViewerApplication.AppState;
import de.remk0.shopshopviewer.io.DropboxFileAccess;
import de.remk0.shopshopviewer.io.ExternalFilesDirFileAccess;
import de.remk0.shopshopviewer.task.SynchronizeTask;
/**
* The main activity that shows a list of files and allows the user to
* synchronize with Dropbox.
*
* @author Remko Plantenga
*
*/
public class ShopShopViewerActivity extends ListActivity {
private static final int DIALOG_DROPBOX_FAILED = 1;
private static final int DIALOG_STORAGE_ERROR = 2;
private static final int DIALOG_PROGRESS_SYNC = 3;
private static final int REQUEST_CODE = 1;
private static final String REVISIONS_STORE = "REV_STORE";
private ShopShopViewerApplication application;
private DropboxAPI<AndroidAuthSession> mDBApi;
private ArrayAdapter<String> listAdapter;
private ProgressDialog progressDialog;
private String hash = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
application = (ShopShopViewerApplication) getApplicationContext();
application.setAppState(AppState.STARTED);
if (!application.isExternalStorageAvailable()) {
showDialog(DIALOG_STORAGE_ERROR);
} else {
getFiles();
}
}
private void getFiles() {
File appFolder = getExternalFilesDir(null);
String[] files = appFolder.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename
.endsWith(ShopShopViewerApplication.SHOPSHOP_EXTENSION)) {
return true;
}
return false;
}
});
listAdapter = new ArrayAdapter<String>(this, R.layout.filelist, files) {
@Override
public String getItem(int position) {
return super.getItem(position).split("\\.")[0];
}
};
setListAdapter(listAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listview_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.synchronize:
startDropboxSynchronize();
default:
return super.onOptionsItemSelected(item);
}
}
private void startDropboxSynchronize() {
application.setAppState(AppState.SYNCHRONIZE);
startActivityForResult(new Intent(this, DropboxAuthActivity.class),
REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
mDBApi = application.getDropboxAPI();
} else {
showDialog(DIALOG_DROPBOX_FAILED);
}
}
}
@Override
protected void onResume() {
super.onResume();
if (mDBApi != null
&& application.getAppState() == AppState.AUTH_SUCCESS) {
showDialog(DIALOG_PROGRESS_SYNC);
new MyDropboxSynchronizeTask().execute();
}
application.setAppState(AppState.WAITING);
}
private class MyDropboxSynchronizeTask extends SynchronizeTask {
@Override
protected void onPreExecute() {
setRemoteFileAccess(new DropboxFileAccess(mDBApi));
SharedPreferences prefs = getSharedPreferences(REVISIONS_STORE,
MODE_PRIVATE);
setRevisionsStore(prefs.getAll());
setRevisionsEditor(prefs.edit());
setFileAccess(new ExternalFilesDirFileAccess(
ShopShopViewerActivity.this));
setHash(hash);
}
@Override
protected void onProgressUpdate(Integer... values) {
float count = values[0];
float total = values[1];
Log.d(ShopShopViewerApplication.APP_NAME, "Progress updated to "
+ count + " " + total + " " + +(count / total * 100f));
progressDialog.setProgress((int) (count / total * 100));
}
@Override
protected void onPostExecute(Boolean result) {
dismissDialog(DIALOG_PROGRESS_SYNC);
if (result) {
hash = getHash();
getFiles();
}
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String e = (String) this.getListAdapter().getItem(position);
Intent intent = new Intent(this, DisplayFileActivity.class);
- intent.putExtra(this.getPackageName() + ".fileName", e);
+ intent.putExtra(this.getPackageName() + ".fileName",
+ e.concat(ShopShopViewerApplication.SHOPSHOP_EXTENSION));
startActivity(intent);
}
@Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch (id) {
case DIALOG_DROPBOX_FAILED:
builder.setMessage(
"Connection to Dropbox failed, please check your internet connection.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
});
return builder.create();
case DIALOG_STORAGE_ERROR:
builder.setMessage("External storage is not available.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
});
return builder.create();
case DIALOG_PROGRESS_SYNC:
progressDialog = new ProgressDialog(ShopShopViewerActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Synchronizing...");
return progressDialog;
default:
return null;
}
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_PROGRESS_SYNC:
progressDialog.setProgress(0);
}
}
}
\ No newline at end of file
diff --git a/src/de/remk0/shopshopviewer/task/ReadShopShopFileTask.java b/src/de/remk0/shopshopviewer/task/ReadShopShopFileTask.java
index 12eeb20..87ece61 100755
--- a/src/de/remk0/shopshopviewer/task/ReadShopShopFileTask.java
+++ b/src/de/remk0/shopshopviewer/task/ReadShopShopFileTask.java
@@ -1,83 +1,82 @@
/**
* ShopShopViewer
* Copyright (C) 2012 Remko Plantenga
*
* This file is part of ShopShopViewer.
*
* ShopShopViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ShopShopViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ShopShopViewer. If not, see <http://www.gnu.org/licenses/>.
*/
package de.remk0.shopshopviewer.task;
import java.io.InputStream;
import android.os.AsyncTask;
import android.util.Log;
import com.dd.plist.NSDictionary;
import com.dd.plist.NSObject;
import de.remk0.shopshopviewer.ShopShopViewerApplication;
import de.remk0.shopshopviewer.io.FileAccess;
import de.remk0.shopshopviewer.io.FileAccessException;
import de.remk0.shopshopviewer.parse.ShopShopFileParser;
import de.remk0.shopshopviewer.parse.ShopShopFileParserException;
/**
* Task to read a ShopShop file.
*
* @author Remko Plantenga
*
*/
public class ReadShopShopFileTask extends AsyncTask<String, Integer, Boolean> {
private FileAccess fileAccess;
private ShopShopFileParser parser;
public void setFileAccess(FileAccess fileAccess) {
this.fileAccess = fileAccess;
}
public void setParser(ShopShopFileParser parser) {
this.parser = parser;
}
public NSDictionary getRoot() {
return parser.getRoot();
}
public NSObject[] getShoppingList() {
return parser.getShoppingList();
}
@Override
protected final Boolean doInBackground(String... params) {
- String fileName = params[0]
- .concat(ShopShopViewerApplication.SHOPSHOP_EXTENSION);
+ String fileName = params[0];
try {
InputStream is = fileAccess.getFile(fileName);
return parser.read(is);
} catch (FileAccessException e) {
Log.e(ShopShopViewerApplication.APP_NAME, "Error while accessing "
+ fileName, e);
} catch (ShopShopFileParserException e) {
Log.e(ShopShopViewerApplication.APP_NAME, "Error while parsing "
+ fileName, e);
}
return false;
}
}
\ No newline at end of file
diff --git a/tests/src/de/remk0/shopshopviewer/DisplayFileActivityTest.java b/tests/src/de/remk0/shopshopviewer/DisplayFileActivityTest.java
index 7fc32f6..4e0b2f3 100755
--- a/tests/src/de/remk0/shopshopviewer/DisplayFileActivityTest.java
+++ b/tests/src/de/remk0/shopshopviewer/DisplayFileActivityTest.java
@@ -1,94 +1,94 @@
/**
* ShopShopViewer
* Copyright (C) 2012 Remko Plantenga
*
* This file is part of ShopShopViewer.
*
* ShopShopViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ShopShopViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ShopShopViewer. If not, see <http://www.gnu.org/licenses/>.
*/
package de.remk0.shopshopviewer;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.easymock.EasyMock;
import android.app.ListActivity;
import android.content.Intent;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.jayway.android.robotium.solo.Solo;
import de.remk0.shopshopviewer.io.FileAccess;
import de.remk0.test.ActivityInstrumentationTestCase2WithResources;
/**
* @author Remko Plantenga
*
*/
public class DisplayFileActivityTest extends
ActivityInstrumentationTestCase2WithResources<DisplayFileActivity> {
private Solo solo;
private ByteArrayOutputStream out = new ByteArrayOutputStream();
public DisplayFileActivityTest() {
super("de.remk0.shopshopviewer", DisplayFileActivity.class);
}
@Override
protected void setUp() throws Exception {
ShopShopViewerApplication context = (ShopShopViewerApplication) this
.getInstrumentation().getTargetContext()
.getApplicationContext();
FileAccess fileAccess = EasyMock.createMock(FileAccess.class);
final InputStream is = getResources("de.remk0.shopshopviewer.test")
.openRawResource(de.remk0.shopshopviewer.test.R.raw.nederland2);
- EasyMock.expect(fileAccess.getFile("file1.shopshop")).andReturn(is);
+ EasyMock.expect(fileAccess.getFile("file1")).andReturn(is);
BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
// TODO why 2 times?
EasyMock.expect(fileAccess.openFile("file1")).andReturn(bufferedOut)
.times(2);
EasyMock.replay(fileAccess);
context.setFileAccess(fileAccess);
Intent intent = new Intent();
intent.putExtra("de.remk0.shopshopviewer.fileName", "file1");
setActivityIntent(intent);
solo = new Solo(getInstrumentation(), getActivity());
}
@Override
protected void tearDown() {
solo.finishOpenedActivities();
}
public void testResume() {
solo.waitForView(ListView.class);
ListAdapter currentListAdapter = ((ListActivity) solo
.getCurrentActivity()).getListAdapter();
assertNotNull(currentListAdapter);
getInstrumentation().callActivityOnPause(getActivity());
getInstrumentation().callActivityOnResume(getActivity());
solo.waitForView(ListView.class);
}
}
diff --git a/tests/src/de/remk0/shopshopviewer/task/ReadShopShopFileTaskTest.java b/tests/src/de/remk0/shopshopviewer/task/ReadShopShopFileTaskTest.java
index 8da4a2f..178bf6c 100755
--- a/tests/src/de/remk0/shopshopviewer/task/ReadShopShopFileTaskTest.java
+++ b/tests/src/de/remk0/shopshopviewer/task/ReadShopShopFileTaskTest.java
@@ -1,66 +1,66 @@
/**
* ShopShopViewer
* Copyright (C) 2012 Remko Plantenga
*
* This file is part of ShopShopViewer.
*
* ShopShopViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ShopShopViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ShopShopViewer. If not, see <http://www.gnu.org/licenses/>.
*/
package de.remk0.shopshopviewer.task;
import java.io.InputStream;
import org.easymock.EasyMock;
import com.dd.plist.NSDictionary;
import com.dd.plist.NSObject;
import de.remk0.shopshopviewer.io.FileAccess;
import de.remk0.shopshopviewer.parse.ShopShopFileParser;
import de.remk0.test.AndroidTestCaseWithResources;
/**
* @author Remko Plantenga
*
*/
public class ReadShopShopFileTaskTest extends AndroidTestCaseWithResources {
public void testExecute() throws Exception {
ReadShopShopFileTask task = new ReadShopShopFileTask();
FileAccess fileAccess = EasyMock.createMock(FileAccess.class);
final InputStream is = getResources("de.remk0.shopshopviewer.test")
.openRawResource(de.remk0.shopshopviewer.test.R.raw.nederland2);
- EasyMock.expect(fileAccess.getFile("file1.shopshop")).andReturn(is);
+ EasyMock.expect(fileAccess.getFile("file1")).andReturn(is);
EasyMock.replay(fileAccess);
task.setFileAccess(fileAccess);
ShopShopFileParser parser = EasyMock
.createMock(ShopShopFileParser.class);
EasyMock.expect(parser.read(is)).andReturn(true);
NSDictionary root = new NSDictionary();
EasyMock.expect(parser.getRoot()).andReturn(root);
NSObject[] shoppingList = new NSObject[3];
EasyMock.expect(parser.getShoppingList()).andReturn(shoppingList);
EasyMock.replay(parser);
task.setParser(parser);
task.execute(new String[] { "file1" });
assertTrue(task.get());
assertEquals(root, task.getRoot());
assertEquals(shoppingList, task.getShoppingList());
}
}
| false | false | null | null |
diff --git a/impl/src/java/org/sakaiproject/profile2/logic/ProfileLogicImpl.java b/impl/src/java/org/sakaiproject/profile2/logic/ProfileLogicImpl.java
index e1c8ecd3..9afdfb2b 100644
--- a/impl/src/java/org/sakaiproject/profile2/logic/ProfileLogicImpl.java
+++ b/impl/src/java/org/sakaiproject/profile2/logic/ProfileLogicImpl.java
@@ -1,1972 +1,1977 @@
package org.sakaiproject.profile2.logic;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
-import javax.management.Query;
-
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
-import org.apache.wicket.Session;
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.Session;
import org.sakaiproject.api.common.edu.person.SakaiPerson;
import org.sakaiproject.profile2.model.ProfileFriend;
import org.sakaiproject.profile2.model.ProfileImage;
import org.sakaiproject.profile2.model.ProfileImageExternal;
import org.sakaiproject.profile2.model.ProfilePreferences;
import org.sakaiproject.profile2.model.ProfilePrivacy;
import org.sakaiproject.profile2.model.ProfileStatus;
import org.sakaiproject.profile2.model.ResourceWrapper;
import org.sakaiproject.profile2.model.SearchResult;
import org.sakaiproject.profile2.util.ProfileConstants;
import org.sakaiproject.profile2.util.ProfileUtils;
+import org.sakaiproject.tinyurl.api.TinyUrlService;
+import org.springframework.orm.hibernate3.HibernateCallback;
+import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
+
+import twitter4j.Twitter;
/**
* This is the Profile2 API Implementation to be used by the Profile2 tool only.
*
* DO NOT USE THIS YOURSELF, use the ProfileService instead (todo)
*
* @author Steve Swinsburg ([email protected])
*
*/
public class ProfileLogicImpl extends HibernateDaoSupport implements ProfileLogic {
private static final Logger log = Logger.getLogger(ProfileLogicImpl.class);
// Hibernate query constants
private static final String QUERY_GET_FRIEND_REQUESTS_FOR_USER = "getFriendRequestsForUser"; //$NON-NLS-1$
private static final String QUERY_GET_CONFIRMED_FRIEND_USERIDS_FOR_USER = "getConfirmedFriendUserIdsForUser"; //$NON-NLS-1$
private static final String QUERY_GET_FRIEND_REQUEST = "getFriendRequest"; //$NON-NLS-1$
private static final String QUERY_GET_FRIEND_RECORD = "getFriendRecord"; //$NON-NLS-1$
private static final String QUERY_GET_USER_STATUS = "getUserStatus"; //$NON-NLS-1$
private static final String QUERY_GET_PRIVACY_RECORD = "getPrivacyRecord"; //$NON-NLS-1$
private static final String QUERY_GET_CURRENT_PROFILE_IMAGE_RECORD = "getCurrentProfileImageRecord"; //$NON-NLS-1$
private static final String QUERY_OTHER_PROFILE_IMAGE_RECORDS = "getOtherProfileImageRecords"; //$NON-NLS-1$
private static final String QUERY_FIND_SAKAI_PERSONS_BY_NAME_OR_EMAIL = "findSakaiPersonsByNameOrEmail"; //$NON-NLS-1$
private static final String QUERY_FIND_SAKAI_PERSONS_BY_INTEREST = "findSakaiPersonsByInterest"; //$NON-NLS-1$
private static final String QUERY_LIST_ALL_SAKAI_PERSONS = "listAllSakaiPersons"; //$NON-NLS-1$
private static final String QUERY_GET_PREFERENCES_RECORD = "getPreferencesRecord"; //$NON-NLS-1$
private static final String QUERY_GET_EXTERNAL_IMAGE_RECORD = "getProfileImageExternalRecord"; //$NON-NLS-1$
// Hibernate object fields
private static final String USER_UUID = "userUuid"; //$NON-NLS-1$
private static final String FRIEND_UUID = "friendUuid"; //$NON-NLS-1$
private static final String CONFIRMED = "confirmed"; //$NON-NLS-1$
private static final String OLDEST_STATUS_DATE = "oldestStatusDate"; //$NON-NLS-1$
private static final String SEARCH = "search"; //$NON-NLS-1$
/**
* {@inheritDoc}
*/
public List<String> getFriendRequestsForUser(final String userId) {
if(userId == null){
throw new IllegalArgumentException("Null Argument in Profile.getFriendRequestsForUser()"); //$NON-NLS-1$
}
List<String> requests = new ArrayList<String>();
//get friends of this user [and map it automatically to the Friend object]
//updated: now just returns a List of Strings
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_FRIEND_REQUESTS_FOR_USER);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
q.setBoolean("false", Boolean.FALSE); //$NON-NLS-1$
//q.setResultTransformer(Transformers.aliasToBean(Friend.class));
return q.list();
}
};
requests = (List<String>) getHibernateTemplate().executeFind(hcb);
return requests;
}
/**
* {@inheritDoc}
*/
public List<String> getConfirmedFriendUserIdsForUser(final String userId) {
List<String> userUuids = new ArrayList<String>();
//get
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_CONFIRMED_FRIEND_USERIDS_FOR_USER);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
q.setBoolean("true", Boolean.TRUE); //$NON-NLS-1$
return q.list();
}
};
userUuids = (List<String>) getHibernateTemplate().executeFind(hcb);
return userUuids;
}
/**
* {@inheritDoc}
*/
public int countConfirmedFriendUserIdsForUser(final String userId) {
//this should operhaps be a count(*) query but since we need to use unions, hmm.
List<String> userUuids = new ArrayList<String>(getConfirmedFriendUserIdsForUser(userId));
int count = userUuids.size();
return count;
}
/**
* {@inheritDoc}
*/
public boolean requestFriend(String userId, String friendId) {
if(userId == null || friendId == null){
throw new IllegalArgumentException("Null Argument in Profile.getFriendsForUser"); //$NON-NLS-1$
}
//check values are valid, ie userId, friendId etc
try {
//make a ProfileFriend object with 'Friend Request' constructor
ProfileFriend profileFriend = new ProfileFriend(userId, friendId, ProfileConstants.RELATIONSHIP_FRIEND);
getHibernateTemplate().save(profileFriend);
log.info("User: " + userId + " requested friend: " + friendId); //$NON-NLS-1$ //$NON-NLS-2$
return true;
} catch (Exception e) {
log.error("Profile.requestFriend() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isFriendRequestPending(String fromUser, String toUser) {
ProfileFriend profileFriend = getPendingFriendRequest(fromUser, toUser);
if(profileFriend == null) {
log.debug("Profile.isFriendRequestPending: No pending friend request from userId: " + fromUser + " to friendId: " + toUser + " found."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean confirmFriendRequest(final String fromUser, final String toUser) {
if(fromUser == null || toUser == null){
throw new IllegalArgumentException("Null Argument in Profile.confirmFriendRequest"); //$NON-NLS-1$
}
//get pending ProfileFriend object request for the given details
ProfileFriend profileFriend = getPendingFriendRequest(fromUser, toUser);
if(profileFriend == null) {
log.error("Profile.confirmFriendRequest() failed. No pending friend request from userId: " + fromUser + " to friendId: " + toUser + " found."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
//make necessary changes to the ProfileFriend object.
profileFriend.setConfirmed(true);
profileFriend.setConfirmedDate(new Date());
//save
try {
getHibernateTemplate().update(profileFriend);
log.info("User: " + fromUser + " confirmed friend request from: " + toUser); //$NON-NLS-1$ //$NON-NLS-2$
return true;
} catch (Exception e) {
log.error("Profile.confirmFriendRequest() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean ignoreFriendRequest(final String fromUser, final String toUser) {
if(fromUser == null || toUser == null){
throw new IllegalArgumentException("Null Argument in Profile.ignoreFriendRequest"); //$NON-NLS-1$
}
//get pending ProfileFriend object request for the given details
ProfileFriend profileFriend = getPendingFriendRequest(fromUser, toUser);
if(profileFriend == null) {
log.error("Profile.ignoreFriendRequest() failed. No pending friend request from userId: " + fromUser + " to friendId: " + toUser + " found."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
//delete
try {
getHibernateTemplate().delete(profileFriend);
log.info("User: " + toUser + " ignored friend request from: " + fromUser); //$NON-NLS-1$ //$NON-NLS-2$
return true;
} catch (Exception e) {
log.error("Profile.ignoreFriendRequest() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean removeFriend(String userId, String friendId) {
if(userId == null || friendId == null){
throw new IllegalArgumentException("Null Argument in Profile.removeFriend"); //$NON-NLS-1$
}
//get the friend object for this connection pair (could be any way around)
ProfileFriend profileFriend = getFriendRecord(userId, friendId);
if(profileFriend == null){
log.error("ProfileFriend record does not exist for userId: " + userId + ", friendId: " + friendId); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
//if ok, delete it
try {
getHibernateTemplate().delete(profileFriend);
log.info("User: " + userId + " removed friend: " + friendId); //$NON-NLS-1$ //$NON-NLS-2$
return true;
} catch (Exception e) {
log.error("Profile.removeFriend() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
//only gets a pending request
private ProfileFriend getPendingFriendRequest(final String userId, final String friendId) {
if(userId == null || friendId == null){
throw new IllegalArgumentException("Null Argument in Profile.getPendingFriendRequest"); //$NON-NLS-1$
}
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_FRIEND_REQUEST);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
q.setParameter(FRIEND_UUID, friendId, Hibernate.STRING);
q.setParameter(CONFIRMED, false, Hibernate.BOOLEAN);
q.setMaxResults(1);
return q.uniqueResult();
}
};
return (ProfileFriend) getHibernateTemplate().execute(hcb);
}
/**
* {@inheritDoc}
*/
public int getUnreadMessagesCount(String userId) {
int unreadMessages = 0;
return unreadMessages;
}
/**
* {@inheritDoc}
*/
public ProfileStatus getUserStatus(final String userId) {
if(userId == null){
throw new IllegalArgumentException("Null Argument in Profile.getUserStatus"); //$NON-NLS-1$
}
// compute oldest date for status
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -7);
final Date oldestStatusDate = cal.getTime();
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_USER_STATUS);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
q.setParameter(OLDEST_STATUS_DATE, oldestStatusDate, Hibernate.DATE);
q.setMaxResults(1);
return q.uniqueResult();
}
};
return (ProfileStatus) getHibernateTemplate().execute(hcb);
}
/**
* {@inheritDoc}
*/
public boolean setUserStatus(String userId, String status) {
//create object
ProfileStatus profileStatus = new ProfileStatus(userId,status,new Date());
return setUserStatus(profileStatus);
}
/**
* Set user status
*
* @param profileStatus ProfileStatus object for the user
*/
public boolean setUserStatus(ProfileStatus profileStatus) {
try {
//only allowing oen status object per user, hence saveOrUpdate
getHibernateTemplate().saveOrUpdate(profileStatus);
log.info("Updated status for user: " + profileStatus.getUserUuid());
return true;
} catch (Exception e) {
log.error("Profile.setUserStatus() failed. " + e.getClass() + ": " + e.getMessage());
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean clearUserStatus(String userId) {
//validate userId here - TODO
ProfileStatus profileStatus = getUserStatus(userId);
if(profileStatus == null){
log.error("ProfileStatus null for userId: " + userId); //$NON-NLS-1$
return false;
}
//if ok, delete it
try {
getHibernateTemplate().delete(profileStatus);
log.info("User: " + userId + " cleared status"); //$NON-NLS-1$ //$NON-NLS-2$
return true;
} catch (Exception e) {
log.error("Profile.clearUserStatus() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
/**
* {@inheritDoc}
*/
public ProfilePrivacy createDefaultPrivacyRecord(String userId) {
//see ProfilePrivacy for this constructor and what it all means
ProfilePrivacy profilePrivacy = getDefaultPrivacyRecord(userId);
//save
try {
getHibernateTemplate().save(profilePrivacy);
log.info("Created default privacy record for user: " + userId); //$NON-NLS-1$
return profilePrivacy;
} catch (Exception e) {
log.error("Profile.createDefaultPrivacyRecord() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
}
/**
* {@inheritDoc}
*/
public ProfilePrivacy getDefaultPrivacyRecord(String userId) {
- //get the overriden privacy settings, if supplied
- HashMap<String, Integer> props = sakaiProxy.getOverriddenPrivacySettings();
+ //get the overriden privacy settings. they'll be defaults if not specified
+ HashMap<String, Object> props = sakaiProxy.getOverriddenPrivacySettings();
+
+ //using the overriden/defaults, set them into the ProfilePrivacy object
ProfilePrivacy profilePrivacy = new ProfilePrivacy(
userId,
- //ProfileConstants.DEFAULT_PRIVACY_OPTION_PROFILEIMAGE,
-
- ProfileUtils.getValueFromMapOrDefault(props, "profileImage", ProfileConstants.DEFAULT_PRIVACY_OPTION_PROFILEIMAGE),
-
+ ProfileConstants.DEFAULT_PRIVACY_OPTION_PROFILEIMAGE,
ProfileConstants.DEFAULT_PRIVACY_OPTION_BASICINFO,
ProfileConstants.DEFAULT_PRIVACY_OPTION_CONTACTINFO,
ProfileConstants.DEFAULT_PRIVACY_OPTION_ACADEMICINFO,
ProfileConstants.DEFAULT_PRIVACY_OPTION_PERSONALINFO,
ProfileConstants.DEFAULT_BIRTHYEAR_VISIBILITY,
ProfileConstants.DEFAULT_PRIVACY_OPTION_SEARCH,
ProfileConstants.DEFAULT_PRIVACY_OPTION_MYFRIENDS,
ProfileConstants.DEFAULT_PRIVACY_OPTION_MYSTATUS);
return profilePrivacy;
}
/**
* {@inheritDoc}
*/
public ProfilePrivacy getPrivacyRecordForUser(final String userId) {
if(userId == null){
throw new IllegalArgumentException("Null Argument in Profile.getPrivacyRecordForUser"); //$NON-NLS-1$
}
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_PRIVACY_RECORD);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
q.setMaxResults(1);
return q.uniqueResult();
}
};
return (ProfilePrivacy) getHibernateTemplate().execute(hcb);
}
/**
* {@inheritDoc}
*/
public boolean savePrivacyRecord(ProfilePrivacy profilePrivacy) {
try {
getHibernateTemplate().saveOrUpdate(profilePrivacy);
log.info("Saved privacy record for user: " + profilePrivacy.getUserUuid()); //$NON-NLS-1$
return true;
} catch (Exception e) {
log.error("Profile.savePrivacyRecordForUser() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean addNewProfileImage(String userId, String mainResource, String thumbnailResource) {
- //first get the current ProfileImage records
+ //first get the current ProfileImage records for this user
List<ProfileImage> currentImages = new ArrayList<ProfileImage>(getCurrentProfileImageRecords(userId));
for(Iterator<ProfileImage> i = currentImages.iterator(); i.hasNext();){
ProfileImage currentImage = (ProfileImage)i.next();
//invalidate each
currentImage.setCurrent(false);
//save
try {
getHibernateTemplate().update(currentImage);
log.info("Profile.saveProfileImageRecord(): Invalidated profileImage: " + currentImage.getId() + " for user: " + currentImage.getUserUuid()); //$NON-NLS-1$ //$NON-NLS-2$
} catch (Exception e) {
log.error("Profile.saveProfileImageRecord(): Couldn't invalidate profileImage: " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
//now create a new ProfileImage object with the new data - this is our new current ProfileImage
ProfileImage newProfileImage = new ProfileImage(userId, mainResource, thumbnailResource, true);
//save the new ProfileImage to the db
try {
getHibernateTemplate().save(newProfileImage);
log.info("Profile.saveProfileImageRecord(): Saved new profileImage for user: " + newProfileImage.getUserUuid()); //$NON-NLS-1$
return true;
} catch (Exception e) {
log.error("Profile.saveProfileImageRecord() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
/**
* {@inheritDoc}
*/
public List<SearchResult> findUsersByNameOrEmail(String search, String userId) {
//perform search (uses private method to wrap the two searches into one)
List<String> userUuids = new ArrayList<String>(findUsersByNameOrEmail(search));
//restrict to only return the max number. UI will print message
int maxResults = ProfileConstants.MAX_SEARCH_RESULTS;
if(userUuids.size() >= maxResults) {
userUuids = userUuids.subList(0, maxResults);
}
//format into SearchResult records (based on friend status, privacy status etc)
List<SearchResult> results = new ArrayList<SearchResult>(createSearchResultRecordsFromSearch(userUuids, userId));
return results;
}
/**
* {@inheritDoc}
*/
public List<SearchResult> findUsersByInterest(String search, String userId) {
//perform search (uses private method to wrap the search)
List<String> userUuids = new ArrayList<String>(findSakaiPersonsByInterest(search));
//restrict to only return the max number. UI will print message
int maxResults = ProfileConstants.MAX_SEARCH_RESULTS;
if(userUuids.size() >= maxResults) {
userUuids = userUuids.subList(0, maxResults);
}
//format into SearchResult records (based on friend status, privacy status etc)
List<SearchResult> results = new ArrayList<SearchResult>(createSearchResultRecordsFromSearch(userUuids, userId));
return results;
}
/**
* {@inheritDoc}
*/
public List<String> listAllSakaiPersons() {
List<String> userUuids = new ArrayList<String>();
//get
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_LIST_ALL_SAKAI_PERSONS);
return q.list();
}
};
userUuids = (List<String>) getHibernateTemplate().executeFind(hcb);
return userUuids;
}
/**
* {@inheritDoc}
*/
public boolean isUserXFriendOfUserY(String userX, String userY) {
//if same then friends.
//added this check so we don't need to do it everywhere else and can call isFriend for all user pairs.
if(userY.equals(userX)) {
return true;
}
//get friends of current user
//TODO change this to be a single lookup rather than iterating over a list
List<String> friendUuids = new ArrayList<String>(getConfirmedFriendUserIdsForUser(userY));
//if list of confirmed friends contains this user, they are a friend
if(friendUuids.contains(userX)) {
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public boolean isUserXVisibleInSearchesByUserY(String userX, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//get privacy record for userX
ProfilePrivacy profilePrivacy = getPrivacyRecordForUser(userX);
//pass to main
return isUserXVisibleInSearchesByUserY(userX, profilePrivacy, userY, friend);
}
/**
* {@inheritDoc}
*/
public boolean isUserXVisibleInSearchesByUserY(String userX, ProfilePrivacy profilePrivacy, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//if no privacy record, return whatever the flag is set as by default
if(profilePrivacy == null) {
log.debug("SEARCH VISIBILITY for " + userX + ": user is current user"); //$NON-NLS-1$ //$NON-NLS-2$
return ProfileConstants.SELF_SEARCH_VISIBILITY;
}
//if restricted to only self, not allowed
/* DEPRECATED via PRFL-24 when the privacy settings were relaxed
if(profilePrivacy.getProfile() == ProfilePrivacyManager.PRIVACY_OPTION_ONLYME) {
return false;
}
*/
//if friend and set to friends only
if(friend && profilePrivacy.getSearch() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
log.debug("SEARCH VISIBILITY for " + userX + ": only friends and " + userY + " is friend"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return true;
}
//if not friend and set to friends only
if(!friend && profilePrivacy.getSearch() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
log.debug("SEARCH VISIBILITY for " + userX + ": only friends and " + userY + " not friend"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
//if everyone is allowed
if(profilePrivacy.getSearch() == ProfileConstants.PRIVACY_OPTION_EVERYONE) {
log.debug("SEARCH VISIBILITY: everyone"); //$NON-NLS-1$
return true;
}
//uncaught rule, return false
log.error("Profile.isUserXVisibleInSearchesByUserY. Uncaught rule. userX: " + userX + ", userY: " + userY + ", friend: " + friend); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
/**
* {@inheritDoc}
*/
public boolean isUserXProfileImageVisibleByUserY(String userX, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//get privacy record for userX
ProfilePrivacy profilePrivacy = getPrivacyRecordForUser(userX);
//pass to main
return isUserXProfileImageVisibleByUserY(userX, profilePrivacy, userY, friend);
}
/**
* {@inheritDoc}
*/
public boolean isUserXProfileImageVisibleByUserY(String userX, ProfilePrivacy profilePrivacy, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//if no privacy record, return whatever the flag is set as by default
if(profilePrivacy == null) {
return ProfileConstants.DEFAULT_PROFILEIMAGE_VISIBILITY;
}
//if restricted to only self, not allowed
/* DEPRECATED via PRFL-24 when the privacy settings were relaxed
if(profilePrivacy.getProfile() == ProfilePrivacyManager.PRIVACY_OPTION_ONLYME) {
return false;
}
*/
//if user is friend and friends are allowed
if(friend && profilePrivacy.getProfileImage() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return true;
}
//if not friend and set to friends only
if(!friend && profilePrivacy.getProfileImage() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return false;
}
//if everyone is allowed
if(profilePrivacy.getProfileImage() == ProfileConstants.PRIVACY_OPTION_EVERYONE) {
return true;
}
//uncaught rule, return false
log.error("Profile.isUserProfileImageVisibleByCurrentUser. Uncaught rule. userX: " + userX + ", userY: " + userY + ", friend: " + friend); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
/**
* {@inheritDoc}
*/
public boolean isUserXBasicInfoVisibleByUserY(String userX, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//get privacy record for userX
ProfilePrivacy profilePrivacy = getPrivacyRecordForUser(userX);
//pass to main
return isUserXBasicInfoVisibleByUserY(userX, profilePrivacy, userY, friend);
}
/**
* {@inheritDoc}
*/
public boolean isUserXBasicInfoVisibleByUserY(String userX, ProfilePrivacy profilePrivacy, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//if no privacy record, return whatever the flag is set as by default
if(profilePrivacy == null) {
return ProfileConstants.DEFAULT_BASICINFO_VISIBILITY;
}
//if restricted to only self, not allowed
if(profilePrivacy.getBasicInfo() == ProfileConstants.PRIVACY_OPTION_ONLYME) {
return false;
}
//if user is friend and friends are allowed
if(friend && profilePrivacy.getBasicInfo() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return true;
}
//if not friend and set to friends only
if(!friend && profilePrivacy.getBasicInfo() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return false;
}
//if everyone is allowed
if(profilePrivacy.getBasicInfo() == ProfileConstants.PRIVACY_OPTION_EVERYONE) {
return true;
}
//uncaught rule, return false
log.error("Profile.isUserXBasicInfoVisibleByUserY. Uncaught rule. userX: " + userX + ", userY: " + userY + ", friend: " + friend); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
/**
* {@inheritDoc}
*/
public boolean isUserXContactInfoVisibleByUserY(String userX, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//get privacy record for this user
ProfilePrivacy profilePrivacy = getPrivacyRecordForUser(userX);
//pass to main
return isUserXContactInfoVisibleByUserY(userX, profilePrivacy, userY, friend);
}
/**
* {@inheritDoc}
*/
public boolean isUserXContactInfoVisibleByUserY(String userX, ProfilePrivacy profilePrivacy, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//if no privacy record, return whatever the flag is set as by default
if(profilePrivacy == null) {
return ProfileConstants.DEFAULT_CONTACTINFO_VISIBILITY;
}
//if restricted to only self, not allowed
if(profilePrivacy.getContactInfo() == ProfileConstants.PRIVACY_OPTION_ONLYME) {
return false;
}
//if user is friend and friends are allowed
if(friend && profilePrivacy.getContactInfo() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return true;
}
//if not friend and set to friends only
if(!friend && profilePrivacy.getContactInfo() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return false;
}
//if everyone is allowed
if(profilePrivacy.getContactInfo() == ProfileConstants.PRIVACY_OPTION_EVERYONE) {
return true;
}
//uncaught rule, return false
log.error("Profile.isUserXContactInfoVisibleByUserY. Uncaught rule. userX: " + userX + ", userY: " + userY + ", friend: " + friend); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
/**
* {@inheritDoc}
*/
public boolean isUserXAcademicInfoVisibleByUserY(String userX, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//get privacy record for this user
ProfilePrivacy profilePrivacy = getPrivacyRecordForUser(userX);
//pass to main
return isUserXAcademicInfoVisibleByUserY(userX, profilePrivacy, userY, friend);
}
/**
* {@inheritDoc}
*/
public boolean isUserXAcademicInfoVisibleByUserY(String userX, ProfilePrivacy profilePrivacy, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//if no privacy record, return whatever the flag is set as by default
if(profilePrivacy == null) {
return ProfileConstants.DEFAULT_ACADEMICINFO_VISIBILITY;
}
//if restricted to only self, not allowed
if(profilePrivacy.getAcademicInfo() == ProfileConstants.PRIVACY_OPTION_ONLYME) {
return false;
}
//if user is friend and friends are allowed
if(friend && profilePrivacy.getAcademicInfo() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return true;
}
//if not friend and set to friends only
if(!friend && profilePrivacy.getAcademicInfo() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return false;
}
//if everyone is allowed
if(profilePrivacy.getAcademicInfo() == ProfileConstants.PRIVACY_OPTION_EVERYONE) {
return true;
}
//uncaught rule, return false
log.error("Profile.isUserXAcademicInfoVisibleByUserY. Uncaught rule. userX: " + userX + ", userY: " + userY + ", friend: " + friend); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
/**
* {@inheritDoc}
*/
public boolean isUserXPersonalInfoVisibleByUserY(String userX, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//get privacy record for this user
ProfilePrivacy profilePrivacy = getPrivacyRecordForUser(userX);
//pass to main
return isUserXPersonalInfoVisibleByUserY(userX, profilePrivacy, userY, friend);
}
/**
* {@inheritDoc}
*/
public boolean isUserXPersonalInfoVisibleByUserY(String userX, ProfilePrivacy profilePrivacy, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//if no privacy record, return whatever the flag is set as by default
if(profilePrivacy == null) {
return ProfileConstants.DEFAULT_PERSONALINFO_VISIBILITY;
}
//if restricted to only self, not allowed
if(profilePrivacy.getPersonalInfo() == ProfileConstants.PRIVACY_OPTION_ONLYME) {
return false;
}
//if user is friend and friends are allowed
if(friend && profilePrivacy.getPersonalInfo() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return true;
}
//if not friend and set to friends only
if(!friend && profilePrivacy.getPersonalInfo() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return false;
}
//if everyone is allowed
if(profilePrivacy.getPersonalInfo() == ProfileConstants.PRIVACY_OPTION_EVERYONE) {
return true;
}
//uncaught rule, return false
log.error("Profile.isUserXPersonalInfoVisibleByUserY. Uncaught rule. userX: " + userX + ", userY: " + userY + ", friend: " + friend); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
/**
* {@inheritDoc}
*/
public boolean isUserXFriendsListVisibleByUserY(String userX, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//get privacy record for this user
ProfilePrivacy profilePrivacy = getPrivacyRecordForUser(userX);
//pass to main
return isUserXFriendsListVisibleByUserY(userX, profilePrivacy, userY, friend);
}
/**
* {@inheritDoc}
*/
public boolean isUserXFriendsListVisibleByUserY(String userX, ProfilePrivacy profilePrivacy, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//if no privacy record, return whatever the flag is set as by default
if(profilePrivacy == null) {
return ProfileConstants.DEFAULT_MYFRIENDS_VISIBILITY;
}
//if restricted to only self, not allowed
if(profilePrivacy.getMyFriends() == ProfileConstants.PRIVACY_OPTION_ONLYME) {
return false;
}
//if user is friend and friends are allowed
if(friend && profilePrivacy.getMyFriends() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return true;
}
//if not friend and set to friends only
if(!friend && profilePrivacy.getMyFriends() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return false;
}
//if everyone is allowed
if(profilePrivacy.getMyFriends() == ProfileConstants.PRIVACY_OPTION_EVERYONE) {
return true;
}
//uncaught rule, return false
log.error("Profile.isUserXFriendsListVisibleByUserY. Uncaught rule. userX: " + userX + ", userY: " + userY + ", friend: " + friend); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
/**
* {@inheritDoc}
*/
public boolean isUserXStatusVisibleByUserY(String userX, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//get privacy record for this user
ProfilePrivacy profilePrivacy = getPrivacyRecordForUser(userX);
//pass to main
return isUserXStatusVisibleByUserY(userX, profilePrivacy, userY, friend);
}
/**
* {@inheritDoc}
*/
public boolean isUserXStatusVisibleByUserY(String userX, ProfilePrivacy profilePrivacy, String userY, boolean friend) {
//if user is requesting own info, they ARE allowed
if(userY.equals(userX)) {
return true;
}
//if no privacy record, return whatever the flag is set as by default
if(profilePrivacy == null) {
return ProfileConstants.DEFAULT_MYSTATUS_VISIBILITY;
}
//if restricted to only self, not allowed
/* DEPRECATED via PRFL-24 when the privacy settings were relaxed
if(profilePrivacy.getMyStatus() == ProfilePrivacyManager.PRIVACY_OPTION_ONLYME) {
return false;
}
*/
//if user is friend and friends are allowed
if(friend && profilePrivacy.getMyStatus() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return true;
}
//if not friend and set to friends only
if(!friend && profilePrivacy.getMyStatus() == ProfileConstants.PRIVACY_OPTION_ONLYFRIENDS) {
return false;
}
//if everyone is allowed
if(profilePrivacy.getMyStatus() == ProfileConstants.PRIVACY_OPTION_EVERYONE) {
return true;
}
//uncaught rule, return false
log.error("Profile.isUserXStatusVisibleByUserY. Uncaught rule. userX: " + userX + ", userY: " + userY + ", friend: " + friend); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false;
}
/**
* {@inheritDoc}
*/
public boolean isBirthYearVisible(String userId) {
//get privacy record for this user
ProfilePrivacy profilePrivacy = getPrivacyRecordForUser(userId);
return isBirthYearVisible(profilePrivacy);
}
/**
* {@inheritDoc}
*/
public boolean isBirthYearVisible(ProfilePrivacy profilePrivacy) {
//return value or whatever the flag is set as by default
if(profilePrivacy == null) {
return ProfileConstants.DEFAULT_BIRTHYEAR_VISIBILITY;
} else {
return profilePrivacy.isShowBirthYear();
}
}
/**
* {@inheritDoc}
*/
public byte[] getCurrentProfileImageForUser(String userId, int imageType) {
byte[] image = null;
//get record from db
ProfileImage profileImage = getCurrentProfileImageRecord(userId);
if(profileImage == null) {
log.debug("Profile.getCurrentProfileImageForUser() null for userId: " + userId);
return null;
}
//get main image
if(imageType == ProfileConstants.PROFILE_IMAGE_MAIN) {
image = sakaiProxy.getResource(profileImage.getMainResource());
}
//or get thumbnail
if(imageType == ProfileConstants.PROFILE_IMAGE_THUMBNAIL) {
image = sakaiProxy.getResource(profileImage.getThumbnailResource());
if(image == null) {
image = sakaiProxy.getResource(profileImage.getMainResource());
}
}
return image;
}
/**
* {@inheritDoc}
*/
public ResourceWrapper getCurrentProfileImageForUserWrapped(String userId, int imageType) {
ResourceWrapper resource = new ResourceWrapper();
//get record from db
ProfileImage profileImage = getCurrentProfileImageRecord(userId);
if(profileImage == null) {
log.debug("Profile.getCurrentProfileImageForUserWrapped() null for userId: " + userId);
return null;
}
//get main image
if(imageType == ProfileConstants.PROFILE_IMAGE_MAIN) {
resource = sakaiProxy.getResourceWrapped(profileImage.getMainResource());
}
//or get thumbnail
if(imageType == ProfileConstants.PROFILE_IMAGE_THUMBNAIL) {
resource = sakaiProxy.getResourceWrapped(profileImage.getThumbnailResource());
if(resource == null) {
resource = sakaiProxy.getResourceWrapped(profileImage.getMainResource());
}
}
return resource;
}
/**
* {@inheritDoc}
*/
public boolean hasUploadedProfileImage(String userId) {
//get record from db
ProfileImage record = getCurrentProfileImageRecord(userId);
if(record == null) {
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean hasExternalProfileImage(String userId) {
//get record from db
ProfileImageExternal record = getExternalImageRecordForUser(userId);
if(record == null) {
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
public ProfilePreferences createDefaultPreferencesRecord(final String userId) {
ProfilePreferences prefs = getDefaultPreferencesRecord(userId);
//save
try {
getHibernateTemplate().save(prefs);
log.info("Created default preferences record for user: " + userId); //$NON-NLS-1$
return prefs;
} catch (Exception e) {
log.error("Profile.createDefaultPreferencesRecord() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
}
/**
* {@inheritDoc}
*/
public ProfilePreferences getDefaultPreferencesRecord(final String userId) {
ProfilePreferences prefs = new ProfilePreferences(
userId,
ProfileConstants.DEFAULT_EMAIL_REQUEST_SETTING,
ProfileConstants.DEFAULT_EMAIL_CONFIRM_SETTING,
ProfileConstants.DEFAULT_TWITTER_SETTING);
return prefs;
}
/**
* {@inheritDoc}
*/
public ProfilePreferences getPreferencesRecordForUser(final String userId) {
if(userId == null){
throw new IllegalArgumentException("Null Argument in Profile.getPreferencesRecordForUser"); //$NON-NLS-1$
}
ProfilePreferences prefs = null;
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_PREFERENCES_RECORD);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
q.setMaxResults(1);
return q.uniqueResult();
}
};
prefs = (ProfilePreferences) getHibernateTemplate().execute(hcb);
if(prefs == null) {
return null;
}
//decrypt password and set into field
prefs.setTwitterPasswordDecrypted(ProfileUtils.decrypt(prefs.getTwitterPasswordEncrypted()));
return prefs;
}
/**
* {@inheritDoc}
*/
public boolean savePreferencesRecord(ProfilePreferences prefs) {
//validate fields are set and encrypt password if necessary, else clear them all
if(checkTwitterFields(prefs)) {
prefs.setTwitterPasswordEncrypted(ProfileUtils.encrypt(prefs.getTwitterPasswordDecrypted()));
} else {
prefs.setTwitterEnabled(false);
prefs.setTwitterUsername(null);
prefs.setTwitterPasswordDecrypted(null);
prefs.setTwitterPasswordEncrypted(null);
}
try {
getHibernateTemplate().saveOrUpdate(prefs);
log.info("Updated preferences record for user: " + prefs.getUserUuid()); //$NON-NLS-1$
return true;
} catch (Exception e) {
log.error("Profile.savePreferencesRecord() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isTwitterIntegrationEnabledForUser(final String userId) {
//check global settings
if(!sakaiProxy.isTwitterIntegrationEnabledGlobally()) {
return false;
}
//check own preferences
ProfilePreferences profilePreferences = getPreferencesRecordForUser(userId);
if(profilePreferences == null) {
return false;
}
if(profilePreferences.isTwitterEnabled()) {
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public boolean isTwitterIntegrationEnabledForUser(ProfilePreferences prefs) {
//check global settings
if(!sakaiProxy.isTwitterIntegrationEnabledGlobally()) {
return false;
}
//check own prefs
if(prefs == null) {
return false;
}
return prefs.isTwitterEnabled();
}
/**
* {@inheritDoc}
*/
public void sendMessageToTwitter(final String userId, final String message){
//setup class thread to call later
class TwitterUpdater implements Runnable{
private Thread runner;
private String username;
private String password;
private String message;
public TwitterUpdater(String username, String password, String message) {
this.username=username;
this.password=password;
this.message=message;
runner = new Thread(this,"Profile2 TwitterUpdater thread"); //$NON-NLS-1$
runner.start();
}
//do it!
public synchronized void run() {
Twitter twitter = new Twitter(username, password);
try {
twitter.setSource(sakaiProxy.getTwitterSource());
twitter.update(message);
log.info("Twitter status updated for: " + userId); //$NON-NLS-1$
}
catch (Exception e) {
log.error("Profile.sendMessageToTwitter() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
//get preferences for this user
ProfilePreferences profilePreferences = getPreferencesRecordForUser(userId);
if(profilePreferences == null) {
return;
}
//get details
String username = profilePreferences.getTwitterUsername();
String password = profilePreferences.getTwitterPasswordDecrypted();
//instantiate class to send the data
new TwitterUpdater(username, password, message);
}
/**
* {@inheritDoc}
*/
public boolean validateTwitterCredentials(final String twitterUsername, final String twitterPassword) {
if(StringUtils.isNotBlank(twitterUsername) && StringUtils.isNotBlank(twitterPassword)) {
Twitter twitter = new Twitter(twitterUsername, twitterPassword);
if(twitter.verifyCredentials()) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
public boolean validateTwitterCredentials(ProfilePreferences prefs) {
String twitterUsername = prefs.getTwitterUsername();
String twitterPassword = prefs.getTwitterPasswordDecrypted();
return validateTwitterCredentials(twitterUsername, twitterPassword);
}
/**
* {@inheritDoc}
*/
public String generateTinyUrl(final String url) {
return tinyUrlService.generateTinyUrl(url);
}
/**
* {@inheritDoc}
*/
public boolean isEmailEnabledForThisMessageType(final String userId, final int messageType) {
//get preferences record for this user
ProfilePreferences profilePreferences = getPreferencesRecordForUser(userId);
//if none, return whatever the flag is set as by default
if(profilePreferences == null) {
return ProfileConstants.DEFAULT_EMAIL_NOTIFICATION_SETTING;
}
//if its a request and requests enabled, true
if(messageType == ProfileConstants.EMAIL_NOTIFICATION_REQUEST && profilePreferences.isRequestEmailEnabled()) {
return true;
}
//if its a confirm and confirms enabled, true
if(messageType == ProfileConstants.EMAIL_NOTIFICATION_CONFIRM && profilePreferences.isConfirmEmailEnabled()) {
return true;
}
//add more cases here as need progresses
//no notification for this message type, return false
log.debug("Profile.isEmailEnabledForThisMessageType. False for userId: " + userId + ", messageType: " + messageType); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
/**
* {@inheritDoc}
*/
public ProfileImageExternal getExternalImageRecordForUser(final String userId) {
if(userId == null){
throw new IllegalArgumentException("Null Argument in Profile.getExternalImageRecordForUser"); //$NON-NLS-1$
}
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_EXTERNAL_IMAGE_RECORD);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
q.setMaxResults(1);
return q.uniqueResult();
}
};
return (ProfileImageExternal) getHibernateTemplate().execute(hcb);
}
/**
* {@inheritDoc}
*/
public String getExternalImageUrl(final String userId, final int imageType) {
//get external image record for this user
ProfileImageExternal externalImage = getExternalImageRecordForUser(userId);
//if none, return null
if(externalImage == null) {
return null;
}
//else return the url for the type they requested
if(imageType == ProfileConstants.PROFILE_IMAGE_MAIN) {
String url = externalImage.getMainUrl();
if(StringUtils.isBlank(url)) {
return null;
}
return url;
}
if(imageType == ProfileConstants.PROFILE_IMAGE_THUMBNAIL) {
String url = externalImage.getThumbnailUrl();
if(StringUtils.isBlank(url)) {
url = externalImage.getMainUrl();
if(StringUtils.isBlank(url)) {
return null;
}
return url;
}
return url;
}
//no notification for this message type, return false
log.error("Profile.getExternalImageUrl. No URL for userId: " + userId + ", imageType: " + imageType); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
/**
* {@inheritDoc}
*/
public boolean saveExternalImage(final String userId, final String mainUrl, final String thumbnailUrl) {
//make an object out of the params
ProfileImageExternal ext = new ProfileImageExternal(userId, mainUrl, thumbnailUrl);
try {
getHibernateTemplate().saveOrUpdate(ext);
log.info("Updated external image record for user: " + ext.getUserUuid()); //$NON-NLS-1$
return true;
} catch (Exception e) {
log.error("Profile.setExternalImage() failed. " + e.getClass() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
/**
* {@inheritDoc}
*/
public ResourceWrapper getURLResourceAsBytes(String url) {
ResourceWrapper wrapper = new ResourceWrapper();
try {
URL u = new URL(url);
URLConnection uc = u.openConnection();
int contentLength = uc.getContentLength();
String contentType = uc.getContentType();
uc.setReadTimeout(5000); //timeout of 5 sec just to be on the safe side.
InputStream in = new BufferedInputStream(uc.getInputStream());
byte[] data = new byte[contentLength];
int bytes = 0;
int offset = 0;
while (offset < contentLength) {
bytes = in.read(data, offset, data.length - offset);
if (bytes == -1) {
break;
}
offset += bytes;
}
in.close();
if (offset != contentLength) {
throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes.");
}
wrapper.setBytes(data);
wrapper.setMimeType(contentType);
wrapper.setLength(contentLength);
wrapper.setExternal(true);
wrapper.setResourceID(url);
} catch (Exception e) {
log.error("Failed to retrieve resource: " + e.getClass() + ": " + e.getMessage());
}
return wrapper;
}
/**
* {@inheritDoc}
*/
public String getUnavailableImageURL() {
StringBuilder path = new StringBuilder();
path.append(sakaiProxy.getServerUrl());
path.append(ProfileConstants.UNAVAILABLE_IMAGE_FULL);
return path.toString();
}
// helper method to check if all required twitter fields are set properly
private boolean checkTwitterFields(ProfilePreferences prefs) {
return (prefs.isTwitterEnabled() &&
StringUtils.isNotBlank(prefs.getTwitterUsername()) &&
StringUtils.isNotBlank(prefs.getTwitterPasswordDecrypted()));
}
//private method to query SakaiPerson for matches
//this should go in the profile ProfilePersistence API
private List<String> findSakaiPersonsByNameOrEmail(final String search) {
List<String> userUuids = new ArrayList<String>();
//get
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_FIND_SAKAI_PERSONS_BY_NAME_OR_EMAIL);
q.setParameter(SEARCH, '%' + search + '%', Hibernate.STRING);
return q.list();
}
};
userUuids = (List<String>) getHibernateTemplate().executeFind(hcb);
return userUuids;
}
//private method to query SakaiPerson for matches
//this should go in the profile ProfilePersistence API
private List<String> findSakaiPersonsByInterest(final String search) {
List<String> userUuids = new ArrayList<String>();
//get
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_FIND_SAKAI_PERSONS_BY_INTEREST);
q.setParameter(SEARCH, '%' + search + '%', Hibernate.STRING);
return q.list();
}
};
userUuids = (List<String>) getHibernateTemplate().executeFind(hcb);
return userUuids;
}
/**
* Get the current ProfileImage records from the database.
* There should only ever be one, but in case things get out of sync this returns all.
* This method is only used when we are adding a new image as we need to invalidate all of the others
* If you are just wanting to retrieve the latest image, see getCurrentProfileImageRecord()
*
* @param userId userId of the user
*/
private List<ProfileImage> getCurrentProfileImageRecords(final String userId) {
List<ProfileImage> images = new ArrayList<ProfileImage>();
//get
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_CURRENT_PROFILE_IMAGE_RECORD);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
return q.list();
}
};
images = (List<ProfileImage>) getHibernateTemplate().executeFind(hcb);
return images;
}
/**
* Get the current ProfileImage record from the database.
* There should only ever be one, but if there are more this will return the latest.
* This is called when retrieving a profile image for a user. When adding a new image, there is a call
* to a private method called getCurrentProfileImageRecords() which should invalidate any multiple current images
*
* @param userId userId of the user
*/
private ProfileImage getCurrentProfileImageRecord(final String userId) {
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_CURRENT_PROFILE_IMAGE_RECORD);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
q.setMaxResults(1);
return q.uniqueResult();
}
};
return (ProfileImage) getHibernateTemplate().execute(hcb);
}
/**
* Get old ProfileImage records from the database.
* TODO: Used for displaying old the profile pictures album
*
* @param userId userId of the user
*/
private List<ProfileImage> getOtherProfileImageRecords(final String userId) {
List<ProfileImage> images = new ArrayList<ProfileImage>();
//get
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_OTHER_PROFILE_IMAGE_RECORDS);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
return q.list();
}
};
images = (List<ProfileImage>) getHibernateTemplate().executeFind(hcb);
return images;
}
//gets a friend record and tries both column arrangements
private ProfileFriend getFriendRecord(final String userId, final String friendId) {
if(userId == null || friendId == null){
throw new IllegalArgumentException("Null Argument in Profile.getFriendRecord"); //$NON-NLS-1$
}
ProfileFriend profileFriend = null;
//this particular query checks for records when userId/friendId is in either column
HibernateCallback hcb = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.getNamedQuery(QUERY_GET_FRIEND_RECORD);
q.setParameter(USER_UUID, userId, Hibernate.STRING);
q.setParameter(FRIEND_UUID, friendId, Hibernate.STRING);
q.setMaxResults(1);
return q.uniqueResult();
}
};
profileFriend = (ProfileFriend) getHibernateTemplate().execute(hcb);
return profileFriend;
}
//private method to back the search methods. returns only uuids which then need to be checked for privacy settings etc.
private List<String> findUsersByNameOrEmail(String search) {
//get users from SakaiPerson
List<String> userUuids = new ArrayList<String>(findSakaiPersonsByNameOrEmail(search));
//get users from UserDirectoryService
List<String> usersUuidsFromUserDirectoryService = new ArrayList<String>(sakaiProxy.searchUsers(search));
//combine with no duplicates
userUuids.removeAll(usersUuidsFromUserDirectoryService);
userUuids.addAll(usersUuidsFromUserDirectoryService);
return userUuids;
}
//private utility method used by findUsersByNameOrEmail() and findUsersByInterest() to format results from
//the supplied userUuids to SearchResult records based on friend or friendRequest status and the privacy settings for each user
//that was in the initial search results
private List<SearchResult> createSearchResultRecordsFromSearch(List<String> userUuids, String userId) {
List<SearchResult> results = new ArrayList<SearchResult>();
//for each userUuid, is userId a friend?
//also, get privacy record for the userUuid. if searches not allowed for this user pair, skip to next
//otherwise create SearchResult record and add to list
for(Iterator<String> i = userUuids.iterator(); i.hasNext();){
String userUuid = (String)i.next();
//friend?
boolean friend = isUserXFriendOfUserY(userUuid, userId);
//init request flags
boolean friendRequestToThisPerson = false;
boolean friendRequestFromThisPerson = false;
//if not friend, has a friend request already been made to this person?
if(!friend) {
friendRequestToThisPerson = isFriendRequestPending(userId, userUuid);
}
//if not friend and no friend request to this person, has a friend request been made from this person to the current user?
if(!friend && !friendRequestToThisPerson) {
friendRequestFromThisPerson = isFriendRequestPending(userUuid, userId);
}
//get privacy record
ProfilePrivacy privacy = getPrivacyRecordForUser(userUuid);
//is this user visible in searches by this user? if not, skip
if(!isUserXVisibleInSearchesByUserY(userUuid, privacy, userId, friend)) {
continue;
}
//is profile photo visible to this user
boolean profileImageAllowed = isUserXProfileImageVisibleByUserY(userUuid, privacy, userId, friend);
//is status visible to this user
boolean statusVisible = isUserXStatusVisibleByUserY(userUuid, privacy, userId, friend);
//is friends list visible to this user
boolean friendsListVisible = isUserXFriendsListVisibleByUserY(userUuid, privacy, userId, friend);
//make object
SearchResult searchResult = new SearchResult(
userUuid,
friend,
profileImageAllowed,
statusVisible,
friendsListVisible,
friendRequestToThisPerson,
friendRequestFromThisPerson
);
results.add(searchResult);
}
return results;
}
//init method called when Tomcat starts up
public void init() {
log.info("Profile2: init()"); //$NON-NLS-1$
//do we need to run the conversion utility?
if(sakaiProxy.isProfileConversionEnabled()) {
convertProfile();
}
}
//method to convert profileImages
private void convertProfile() {
log.info("Profile2: ==============================="); //$NON-NLS-1$
log.info("Profile2: Conversion utility starting up."); //$NON-NLS-1$
log.info("Profile2: ==============================="); //$NON-NLS-1$
//get list of users
List<String> allUsers = new ArrayList<String>(listAllSakaiPersons());
if(allUsers.isEmpty()){
log.info("Profile2 conversion util: No SakaiPersons to process."); //$NON-NLS-1$
return;
}
//for each, do they have a profile image record. if so, skip (perhaps null the SakaiPerson JPEG_PHOTO bytes?)
for(Iterator<String> i = allUsers.iterator(); i.hasNext();) {
String userUuid = (String)i.next();
//if already have a current ProfileImage record, skip to next user
if(hasUploadedProfileImage(userUuid)) {
log.info("Profile2 conversion util: valid ProfileImage record already exists for " + userUuid + ". Skipping..."); //$NON-NLS-1$ //$NON-NLS-2$
continue;
}
//get SakaiPerson
SakaiPerson sakaiPerson = sakaiProxy.getSakaiPerson(userUuid);
if(sakaiPerson == null) {
log.error("Profile2 conversion util: No valid SakaiPerson record for " + userUuid + ". Skipping..."); //$NON-NLS-1$ //$NON-NLS-2$
continue;
}
//get photo from SakaiPerson
byte[] image = null;
image = sakaiPerson.getJpegPhoto();
//if none, nothing to do
if(image == null) {
log.info("Profile2 conversion util: Nothing to convert for " + userUuid + ". Skipping..."); //$NON-NLS-1$ //$NON-NLS-2$
continue;
}
//set some defaults for the image we are adding to ContentHosting
String fileName = "Profile Image"; //$NON-NLS-1$
String mimeType = "image/jpeg"; //$NON-NLS-1$
//scale the main image
byte[] imageMain = ProfileUtils.scaleImage(image, ProfileConstants.MAX_IMAGE_XY);
//create resource ID
String mainResourceId = sakaiProxy.getProfileImageResourcePath(userUuid, ProfileConstants.PROFILE_IMAGE_MAIN);
log.info("Profile2 conversion util: mainResourceId: " + mainResourceId); //$NON-NLS-1$
//save, if error, log and return.
if(!sakaiProxy.saveFile(mainResourceId, userUuid, fileName, mimeType, imageMain)) {
log.error("Profile2 conversion util: Saving main profile image failed."); //$NON-NLS-1$
continue;
}
/*
* THUMBNAIL PROFILE IMAGE
*/
//scale image
byte[] imageThumbnail = ProfileUtils.scaleImage(image, ProfileConstants.MAX_THUMBNAIL_IMAGE_XY);
//create resource ID
String thumbnailResourceId = sakaiProxy.getProfileImageResourcePath(userUuid, ProfileConstants.PROFILE_IMAGE_THUMBNAIL);
log.info("Profile2 conversion util: thumbnailResourceId:" + thumbnailResourceId); //$NON-NLS-1$
//save, if error, log and return.
if(!sakaiProxy.saveFile(thumbnailResourceId, userUuid, fileName, mimeType, imageThumbnail)) {
log.error("Profile2 conversion util: Saving thumbnail profile image failed."); //$NON-NLS-1$
continue;
}
/*
* SAVE IMAGE RESOURCE IDS
*/
if(addNewProfileImage(userUuid, mainResourceId, thumbnailResourceId)) {
log.info("Profile2 conversion util: images converted and saved for " + userUuid); //$NON-NLS-1$
} else {
log.error("Profile2 conversion util: image conversion failed for " + userUuid); //$NON-NLS-1$
continue;
}
//go to next user
}
return;
}
//setup SakaiProxy API
private SakaiProxy sakaiProxy;
public void setSakaiProxy(SakaiProxy sakaiProxy) {
this.sakaiProxy = sakaiProxy;
}
//setup TinyUrlService API
private TinyUrlService tinyUrlService;
public void setTinyUrlService(TinyUrlService tinyUrlService) {
this.tinyUrlService = tinyUrlService;
}
}
diff --git a/util/src/java/org/sakaiproject/profile2/util/ProfileUtils.java b/util/src/java/org/sakaiproject/profile2/util/ProfileUtils.java
index 6301986c..221162e3 100644
--- a/util/src/java/org/sakaiproject/profile2/util/ProfileUtils.java
+++ b/util/src/java/org/sakaiproject/profile2/util/ProfileUtils.java
@@ -1,363 +1,364 @@
package org.sakaiproject.profile2.util;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import javax.swing.ImageIcon;
import org.apache.log4j.Logger;
+import org.jasypt.util.text.BasicTextEncryptor;
import org.sakaiproject.util.ResourceLoader;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ProfileUtils {
private static final Logger log = Logger.getLogger(ProfileUtils.class);
/**
* Check content type against allowed types. only JPEG,GIF and PNG are support at the moment
*
* @param contentType string of the content type determined by some image parser
*/
public static boolean checkContentTypeForProfileImage(String contentType) {
ArrayList<String> allowedTypes = new ArrayList<String>();
allowedTypes.add("image/jpeg");
allowedTypes.add("image/gif");
allowedTypes.add("image/png");
if(allowedTypes.contains(contentType)) {
return true;
}
return false;
}
/**
* Scale an image so one side is a maximum of maxSize in pixels.
*
* @param imageData bytes of the original image
* @param maxSize maximum dimension in px that the image should have on any one side
*/
public static byte[] scaleImage(byte[] imageData, int maxSize) {
log.debug("Scaling image...");
// Get the image
Image inImage = new ImageIcon(imageData).getImage();
// Determine the scale (we could change this to only determine scale from one dimension, ie the width only?)
double scale = (double) maxSize / (double) inImage.getHeight(null);
if (inImage.getWidth(null) > inImage.getHeight(null)) {
scale = (double) maxSize / (double) inImage.getWidth(null);
}
/*
log.debug("===========Image scaling============");
log.debug("WIDTH: " + inImage.getWidth(null));
log.debug("HEIGHT: " + inImage.getHeight(null));
log.debug("SCALE: " + scale);
log.debug("========End of image scaling========");
*/
//if image is smaller than desired image size (ie scale is larger) just return the original image bytes
if (scale >= 1.0d) {
return imageData;
}
// Determine size of new image.
// One of the dimensions should equal maxSize.
int scaledW = (int) (scale * inImage.getWidth(null));
int scaledH = (int) (scale * inImage.getHeight(null));
// Create an image buffer in which to paint on.
BufferedImage outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);
// Set the scale.
AffineTransform tx = new AffineTransform();
//scale
tx.scale(scale, scale);
// Paint image.
Graphics2D g2d = outImage.createGraphics();
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON
);
g2d.drawImage(inImage, tx, null);
g2d.dispose();
// JPEG-encode the image
// and write to file.
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(outImage);
os.close();
log.debug("Scaling done.");
} catch (IOException e) {
log.error("Scaling image failed.");
}
return os.toByteArray();
}
/**
* Convert a Date into a String according to format
*
* @param date date to convert
* @param format format in SimpleDateFormat syntax
*/
public static String convertDateToString(Date date, String format) {
if(date == null || "".equals(format)) {
throw new IllegalArgumentException("Null Argument in Profile.convertDateToString()");
}
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
String dateStr = dateFormat.format(date);
log.debug("Profile.convertDateToString(): Input date: " + date.toString());
log.debug("Profile.convertDateToString(): Converted date string: " + dateStr);
return dateStr;
}
/**
* Convert a string into a Date object (reverse of above
*
* @param dateStr date string to convert
* @param format format of the input date in SimpleDateFormat syntax
*/
public static Date convertStringToDate(String dateStr, String format) {
if("".equals(dateStr) || "".equals(format)) {
throw new IllegalArgumentException("Null Argument in Profile.convertStringToDate()");
}
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
try {
Date date = dateFormat.parse(dateStr);
log.debug("Profile.convertStringToDate(): Input date string: " + dateStr);
log.debug("Profile.convertStringToDate(): Converted date: " + date.toString());
return date;
} catch (Exception e) {
log.error("Profile.convertStringToDate() failed. " + e.getClass() + ": " + e.getMessage());
return null;
}
}
/**
* Get the localised name of the day (ie Monday for en, Maandag for nl)
* @param day int according to Calendar.DAY_OF_WEEK
* @param locale locale to render dayname in
* @return
*/
public static String getDayName(int day, Locale locale) {
//localised daynames
String dayNames[] = new DateFormatSymbols(locale).getWeekdays();
String dayName = null;
try {
dayName = dayNames[day];
} catch (Exception e) {
log.error("Profile.getDayName() failed. " + e.getClass() + ": " + e.getMessage());
}
return dayName;
}
/**
* Convert a string to propercase. ie This Is Proper Text
* @param input string to be formatted
* @return
*/
public static String toProperCase(String input) {
if (input == null || input.trim().length() == 0) {
return input;
}
String output = input.toLowerCase();
return output.substring(0, 1).toUpperCase() + output.substring(1);
}
/**
* Convert a date into a field like "just then, 2 minutes ago, 4 hours ago, yesterday, on sunday, etc"
*
* @param date date to convert
*/
public static String convertDateForStatus(Date date) {
//current time
Calendar currentCal = Calendar.getInstance();
long currentTimeMillis = currentCal.getTimeInMillis();
//posting time
long postingTimeMillis = date.getTime();
//difference
int diff = (int)(currentTimeMillis - postingTimeMillis);
Locale locale = getUserPreferredLocale();
//System.out.println("currentDate:" + currentTimeMillis);
//System.out.println("postingDate:" + postingTimeMillis);
//System.out.println("diff:" + diff);
int MILLIS_IN_SECOND = 1000;
int MILLIS_IN_MINUTE = 1000 * 60;
int MILLIS_IN_HOUR = 1000 * 60 * 60;
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
int MILLIS_IN_WEEK = 1000 * 60 * 60 * 24 * 7;
String message="";
if(diff < MILLIS_IN_SECOND) {
//less than a second
message = Messages.getString("Label.just_then");
} else if (diff < MILLIS_IN_MINUTE) {
//less than a minute, calc seconds
int numSeconds = diff/MILLIS_IN_SECOND;
if(numSeconds == 1) {
//one sec
message = numSeconds + Messages.getString("Label.second_ago");
} else {
//more than one sec
message = numSeconds + Messages.getString("Label.seconds_ago");
}
} else if (diff < MILLIS_IN_HOUR) {
//less than an hour, calc minutes
int numMinutes = diff/MILLIS_IN_MINUTE;
if(numMinutes == 1) {
//one minute
message = numMinutes + Messages.getString("Label.minute_ago");
} else {
//more than one minute
message = numMinutes + Messages.getString("Label.minutes_ago");
}
} else if (diff < MILLIS_IN_DAY) {
//less than a day, calc hours
int numHours = diff/MILLIS_IN_HOUR;
if(numHours == 1) {
//one hour
message = numHours + Messages.getString("Label.hour_ago");
} else {
//more than one hour
message = numHours + Messages.getString("Label.hours_ago");
}
} else if (diff < MILLIS_IN_WEEK) {
//less than a week, calculate days
int numDays = diff/MILLIS_IN_DAY;
//now calculate which day it was
if(numDays == 1) {
message = Messages.getString("Label.yesterday");
} else {
//set calendar and get day of week
Calendar postingCal = Calendar.getInstance();
postingCal.setTimeInMillis(postingTimeMillis);
int postingDay = postingCal.get(Calendar.DAY_OF_WEEK);
//set to localised value: 'on Wednesday' for example
String dayName = getDayName(postingDay,locale);
if(dayName != null) {
message = Messages.getString("Label.on") + toProperCase(dayName);
}
}
} else {
//over a week ago, we want it blank though.
}
return message;
}
/**
* Gets the users preferred locale, either from the user's session or Sakai preferences and returns it
* This depends on Sakai's ResourceLoader.
*
* @return
*/
public static Locale getUserPreferredLocale() {
ResourceLoader rl = new ResourceLoader();
return rl.getLocale();
}
/**
* Creates a full profile event reference for a give reference
* @param eventId
* @return
*/
public static String createEventRef(String ref) {
return "/profile/"+ref;
}
/**
* Method for getting a value from a map based on the given key, but if it does not exist, use the given default
* @param map
* @param key
* @param defaultValue
* @return
*/
public static Object getValueFromMapOrDefault(Map<?,?> map, Object key, Object defaultValue) {
return (map.containsKey(key) ? map.get(key) : defaultValue);
}
/**
* Encrypt the string
* @param encryptedText
* @return
*/
public static String decrypt(final String encryptedText) {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(BASIC_ENCRYPTION_KEY);
return(textEncryptor.decrypt(encryptedText));
}
/**
* Decrypt the string
* @param plainText
* @return
*/
public static String encrypt(final String plainText) {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(BASIC_ENCRYPTION_KEY);
return(textEncryptor.encrypt(plainText));
}
/**
* the user's password needs to be decrypted and sent to Twitter for updates
* so we can't just one-way encrypt it.
*
* Note to casual observers:
* Having just this key won't allow you to decrypt a password.
* No two encryptions are the same using the encryption method that Profile2 uses
* but they decrypt to the same value which is why we can use it.
*/
private static final String BASIC_ENCRYPTION_KEY = "AbrA_ca-DabRa.123";
}
| false | false | null | null |
diff --git a/tests/src/com/android/providers/contacts/ContactAggregatorPerformanceTest.java b/tests/src/com/android/providers/contacts/ContactAggregatorPerformanceTest.java
index 28f0d6e..81d73a2 100644
--- a/tests/src/com/android/providers/contacts/ContactAggregatorPerformanceTest.java
+++ b/tests/src/com/android/providers/contacts/ContactAggregatorPerformanceTest.java
@@ -1,98 +1,103 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.providers.contacts;
import android.content.Context;
import android.content.res.Resources;
import android.os.Debug;
import android.provider.ContactsContract;
import android.test.AndroidTestCase;
import android.test.IsolatedContext;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import android.test.mock.MockContext;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;
/**
* Performance test for {@link ContactAggregator}.
*
* Run the test like this:
* <code>
* adb push <large contacts2.db> \
* data/data/com.android.providers.contacts/databases/perf.contacts2.db
* adb shell am instrument \
* -e class com.android.providers.contacts.ContactAggregatorPerformanceTest \
* -w com.android.providers.contacts.tests/android.test.InstrumentationTestRunner
* </code>
*/
@LargeTest
public class ContactAggregatorPerformanceTest extends AndroidTestCase {
private static final String TAG = "ContactAggregatorPerformanceTest";
private static final boolean TRACE = false;
public void testPerformance() {
final Context targetContext = getContext();
MockContentResolver resolver = new MockContentResolver();
MockContext context = new MockContext() {
@Override
public Resources getResources() {
return targetContext.getResources();
}
+
+ @Override
+ public String getPackageName() {
+ return "no.package";
+ }
};
RenamingDelegatingContext targetContextWrapper =
new RenamingDelegatingContext(context, targetContext, "perf.");
targetContextWrapper.makeExistingFilesAndDbsAccessible();
IsolatedContext providerContext = new IsolatedContext(resolver, targetContextWrapper);
SynchronousContactsProvider2 provider = new SynchronousContactsProvider2();
provider.setDataWipeEnabled(false);
provider.attachInfo(providerContext, null);
resolver.addProvider(ContactsContract.AUTHORITY, provider);
long rawContactCount = provider.getRawContactCount();
if (rawContactCount == 0) {
Log.w(TAG, "The test has not been set up. Use this command to copy a contact db"
+ " to the device:\nadb push <large contacts2.db> "
+ "data/data/com.android.providers.contacts/databases/perf.contacts2.db");
return;
}
provider.prepareForFullAggregation(500);
rawContactCount = provider.getRawContactCount();
long start = System.currentTimeMillis();
if (TRACE) {
Debug.startMethodTracing("aggregation");
}
provider.aggregate();
if (TRACE) {
Debug.stopMethodTracing();
}
long end = System.currentTimeMillis();
long contactCount = provider.getContactCount();
Log.i(TAG, String.format("Aggregated contacts in %d ms.\n" +
"Raw contacts: %d\n" +
"Aggregated contacts: %d\n" +
"Per raw contact: %.3f",
end-start,
rawContactCount,
contactCount,
((double)(end-start)/rawContactCount)));
}
}
| true | false | null | null |
diff --git a/src/me/kukkii/janken/Janken.java b/src/me/kukkii/janken/Janken.java
index 5a241b2..32866a6 100644
--- a/src/me/kukkii/janken/Janken.java
+++ b/src/me/kukkii/janken/Janken.java
@@ -1,82 +1,83 @@
package me.kukkii.janken;
import me.kukkii.janken.bot.BotManager;
import me.kukkii.janken.bot.AbstractBot;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import android.graphics.drawable.Drawable;
import android.content.res.Resources;
public class Janken extends Activity{
private AbstractBot bot;
// private ImageView view = (ImageView) findViewById(R.id.view_BOT);
private Hand userHand;
private Hand botHand;
private Result result;
private Judge judge = new Judge();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onResume(){
super.onResume();
newGame();
- TimerThread tt = new TimerThread(this);
- tt.run();
}
public void afterPon(){
botHand = bot.hand2();
result = judge.judge(userHand, botHand);
String text = bot.getName() + "\n" + userHand.toString() + "\n" + botHand.toString() + "\n" + result.toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
newGame();
}
public void newGame(){
bot =(AbstractBot) BotManager.getManager().next();
Resources res = getResources();
int drawableId = bot.getImage();
// Drawable drawable = res.getDrawable(drawableId);
ImageView view = (ImageView) findViewById(R.id.view_BOT);
view.setImageResource(drawableId);
+ TimerThread tt = new TimerThread(this);
+ Thread t = new Thread(tt);
+ t.start();
}
public void jan(){
Toast.makeText(getApplicationContext(), "Jan", Toast.LENGTH_SHORT).show();
}
public void ken(){
Toast.makeText(getApplicationContext(), "Ken", Toast.LENGTH_SHORT).show();
}
public void pon(){
Toast.makeText(getApplicationContext(), "pon!", Toast.LENGTH_SHORT).show();
}
public void hand(View view){
userHand = null;
int id = view.getId();
if(id==R.id.button_ROCK){
userHand = Hand.ROCK;
}
if(id==R.id.button_SCISSOR){
userHand = Hand.SCISSOR;
}
if(id==R.id.button_PAPER){
userHand = Hand.PAPER;
}
}
}
| false | false | null | null |
diff --git a/user/src/com/google/gwt/user/cellview/client/CellList.java b/user/src/com/google/gwt/user/cellview/client/CellList.java
index 2c557d584..c7100d1c2 100644
--- a/user/src/com/google/gwt/user/cellview/client/CellList.java
+++ b/user/src/com/google/gwt/user/cellview/client/CellList.java
@@ -1,538 +1,538 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.cellview.client;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.CssResource.ImportedWithPrefix;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.client.ImageResource.ImageOptions;
import com.google.gwt.resources.client.ImageResource.RepeatStyle;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.HasDataPresenter.LoadingState;
import com.google.gwt.user.client.Event;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionModel;
import java.util.List;
import java.util.Set;
/**
* A single column list of cells.
*
* <p>
* <h3>Examples</h3>
* <dl>
* <dt>Trivial example</dt>
* <dd>{@example com.google.gwt.examples.cellview.CellListExample}</dd>
* <dt>ValueUpdater example</dt>
* <dd>{@example com.google.gwt.examples.cellview.CellListValueUpdaterExample}</dd>
* <dt>Key provider example</dt>
* <dd>{@example com.google.gwt.examples.view.KeyProviderExample}</dd>
* </dl>
* </p>
*
* @param <T> the data type of list items
*/
public class CellList<T> extends AbstractHasData<T> {
/**
* A ClientBundle that provides images for this widget.
*/
public interface Resources extends ClientBundle {
/**
* The background used for selected items.
*/
@ImageOptions(repeatStyle = RepeatStyle.Horizontal, flipRtl = true)
ImageResource cellListSelectedBackground();
/**
* The styles used in this widget.
*/
@Source(Style.DEFAULT_CSS)
Style cellListStyle();
}
/**
* Styles used by this widget.
*/
@ImportedWithPrefix("gwt-CellList")
public interface Style extends CssResource {
/**
* The path to the default CSS styles used by this resource.
*/
String DEFAULT_CSS = "com/google/gwt/user/cellview/client/CellList.css";
/**
* Applied to even items.
*/
String cellListEvenItem();
/**
* Applied to the keyboard selected item.
*/
String cellListKeyboardSelectedItem();
/**
* Applied to odd items.
*/
String cellListOddItem();
/**
* Applied to selected items.
*/
String cellListSelectedItem();
/**
* Applied to the widget.
*/
String cellListWidget();
}
interface Template extends SafeHtmlTemplates {
@Template("<div onclick=\"\" __idx=\"{0}\" class=\"{1}\" style=\"outline:none;\" >{2}</div>")
SafeHtml div(int idx, String classes, SafeHtml cellContents);
@Template("<div onclick=\"\" __idx=\"{0}\" class=\"{1}\" style=\"outline:none;\" tabindex=\"{2}\">{3}</div>")
SafeHtml divFocusable(int idx, String classes, int tabIndex,
SafeHtml cellContents);
@Template("<div onclick=\"\" __idx=\"{0}\" class=\"{1}\" style=\"outline:none;\" tabindex=\"{2}\" accesskey=\"{3}\">{4}</div>")
SafeHtml divFocusableWithKey(int idx, String classes, int tabIndex,
char accessKey, SafeHtml cellContents);
}
/**
* The default page size.
*/
private static final int DEFAULT_PAGE_SIZE = 25;
private static Resources DEFAULT_RESOURCES;
private static final Template TEMPLATE = GWT.create(Template.class);
private static Resources getDefaultResources() {
if (DEFAULT_RESOURCES == null) {
DEFAULT_RESOURCES = GWT.create(Resources.class);
}
return DEFAULT_RESOURCES;
}
private final Cell<T> cell;
private boolean cellIsEditing;
private final Element childContainer;
private SafeHtml emptyListMessage = SafeHtmlUtils.fromSafeConstant("");
private final Element emptyMessageElem;
private final Style style;
private ValueUpdater<T> valueUpdater;
/**
* Construct a new {@link CellList}.
*
* @param cell the cell used to render each item
*/
public CellList(final Cell<T> cell) {
this(cell, getDefaultResources(), null);
}
/**
* Construct a new {@link CellList} with the specified {@link Resources}.
*
* @param cell the cell used to render each item
* @param resources the resources used for this widget
*/
public CellList(final Cell<T> cell, Resources resources) {
this(cell, resources, null);
}
/**
* Construct a new {@link CellList} with the specified {@link ProvidesKey key provider}.
*
* @param cell the cell used to render each item
* @param keyProvider an instance of ProvidesKey<T>, or null if the record
* object should act as its own key
*/
public CellList(final Cell<T> cell, ProvidesKey<T> keyProvider) {
this(cell, getDefaultResources(), keyProvider);
}
/**
* Construct a new {@link CellList} with the specified {@link Resources}
* and {@link ProvidesKey key provider}.
*
* @param cell the cell used to render each item
* @param resources the resources used for this widget
* @param keyProvider an instance of ProvidesKey<T>, or null if the record
* object should act as its own key
*/
public CellList(final Cell<T> cell, Resources resources, ProvidesKey<T> keyProvider) {
super(Document.get().createDivElement(), DEFAULT_PAGE_SIZE, keyProvider);
this.cell = cell;
this.style = resources.cellListStyle();
this.style.ensureInjected();
String widgetStyle = this.style.cellListWidget();
if (widgetStyle != null) {
// The widget style is null when used in CellBrowser.
addStyleName(widgetStyle);
}
// Create the DOM hierarchy.
childContainer = Document.get().createDivElement();
emptyMessageElem = Document.get().createDivElement();
showOrHide(emptyMessageElem, false);
DivElement outerDiv = getElement().cast();
outerDiv.appendChild(childContainer);
outerDiv.appendChild(emptyMessageElem);
// Sink events that the cell consumes.
CellBasedWidgetImpl.get().sinkEvents(this, cell.getConsumedEvents());
}
/**
* Get the message that is displayed when there is no data.
*
* @return the empty message
* @see #setEmptyListMessage(SafeHtml)
*/
public SafeHtml getEmptyListMessage() {
return emptyListMessage;
}
/**
* Get the {@link Element} for the specified index. If the element has not
* been created, null is returned.
*
* @param indexOnPage the index on the page
* @return the element, or null if it doesn't exists
* @throws IndexOutOfBoundsException if the index is outside of the current
* page
*/
public Element getRowElement(int indexOnPage) {
getPresenter().flush();
checkRowBounds(indexOnPage);
if (childContainer.getChildCount() > indexOnPage) {
return childContainer.getChild(indexOnPage).cast();
}
return null;
}
/**
* Set the message to display when there is no data.
*
* @param html the message to display when there are no results
* @see #getEmptyListMessage()
*/
public void setEmptyListMessage(SafeHtml html) {
this.emptyListMessage = html;
emptyMessageElem.setInnerHTML(html.asString());
}
/**
* Set the value updater to use when cells modify items.
*
* @param valueUpdater the {@link ValueUpdater}
*/
public void setValueUpdater(ValueUpdater<T> valueUpdater) {
this.valueUpdater = valueUpdater;
}
@Override
protected boolean dependsOnSelection() {
return cell.dependsOnSelection();
}
/**
* Called when a user action triggers selection.
*
* @param event the event that triggered selection
* @param value the value that was selected
* @param indexOnPage the index of the value on the page
* @deprecated use
* {@link #addCellPreviewHandler(com.google.gwt.view.client.CellPreviewEvent.Handler)}
* instead
*/
@Deprecated
protected void doSelection(Event event, T value, int indexOnPage) {
}
/**
* Fire an event to the cell.
*
* @param context the {@link Context} of the cell
* @param event the event that was fired
* @param parent the parent of the cell
* @param value the value of the cell
*/
protected void fireEventToCell(Context context, Event event, Element parent,
T value) {
Set<String> consumedEvents = cell.getConsumedEvents();
if (consumedEvents != null && consumedEvents.contains(event.getType())) {
boolean cellWasEditing = cell.isEditing(context, parent, value);
cell.onBrowserEvent(context, parent, value, event, valueUpdater);
cellIsEditing = cell.isEditing(context, parent, value);
if (cellWasEditing && !cellIsEditing) {
CellBasedWidgetImpl.get().resetFocus(new Scheduler.ScheduledCommand() {
public void execute() {
setFocus(true);
}
});
}
}
}
/**
* Return the cell used to render each item.
*/
protected Cell<T> getCell() {
return cell;
}
/**
* Get the parent element that wraps the cell from the list item. Override
* this method if you add structure to the element.
*
* @param item the row element that wraps the list item
* @return the parent element of the cell
*/
protected Element getCellParent(Element item) {
return item;
}
@Override
protected Element getChildContainer() {
return childContainer;
}
@Override
protected Element getKeyboardSelectedElement() {
// Do not use getRowElement() because that will flush the presenter.
int rowIndex = getKeyboardSelectedRow();
- if (childContainer.getChildCount() > rowIndex) {
+ if (rowIndex >= 0 && childContainer.getChildCount() > rowIndex) {
return childContainer.getChild(rowIndex).cast();
}
return null;
}
@Override
protected boolean isKeyboardNavigationSuppressed() {
return cellIsEditing;
}
@Override
protected void onBlur() {
// Remove the keyboard selection style.
Element elem = getKeyboardSelectedElement();
if (elem != null) {
elem.removeClassName(style.cellListKeyboardSelectedItem());
}
}
@SuppressWarnings("deprecation")
@Override
protected void onBrowserEvent2(Event event) {
// Get the event target.
EventTarget eventTarget = event.getEventTarget();
if (!Element.is(eventTarget)) {
return;
}
final Element target = event.getEventTarget().cast();
// Forward the event to the cell.
String idxString = "";
Element cellTarget = target;
while ((cellTarget != null)
&& ((idxString = cellTarget.getAttribute("__idx")).length() == 0)) {
cellTarget = cellTarget.getParentElement();
}
if (idxString.length() > 0) {
// Select the item if the cell does not consume events. Selection occurs
// before firing the event to the cell in case the cell operates on the
// currently selected item.
String eventType = event.getType();
boolean isClick = "click".equals(eventType);
int idx = Integer.parseInt(idxString);
int indexOnPage = idx - getPageStart();
if (!isRowWithinBounds(indexOnPage)) {
// If the event causes us to page, then the index will be out of bounds.
return;
}
// Get the cell parent before doing selection in case the list is redrawn.
boolean isSelectionHandled = cell.handlesSelection()
|| KeyboardSelectionPolicy.BOUND_TO_SELECTION == getKeyboardSelectionPolicy();
Element cellParent = getCellParent(cellTarget);
T value = getVisibleItem(indexOnPage);
Context context = new Context(idx, 0, getValueKey(value));
CellPreviewEvent<T> previewEvent = CellPreviewEvent.fire(this, event,
this, context, value, cellIsEditing, isSelectionHandled);
if (isClick && !cellIsEditing && !isSelectionHandled) {
doSelection(event, value, indexOnPage);
}
// Focus on the cell.
if (isClick) {
/*
* If the selected element is natively focusable, then we do not want to
* steal focus away from it.
*/
boolean isFocusable = CellBasedWidgetImpl.get().isFocusable(target);
isFocused = isFocused || isFocusable;
getPresenter().setKeyboardSelectedRow(indexOnPage, !isFocusable, false);
}
// Fire the event to the cell if the list has not been refreshed.
if (!previewEvent.isCanceled()) {
fireEventToCell(context, event, cellParent, value);
}
}
}
@Override
protected void onFocus() {
// Add the keyboard selection style.
Element elem = getKeyboardSelectedElement();
if (elem != null) {
elem.addClassName(style.cellListKeyboardSelectedItem());
}
}
@Override
protected void renderRowValues(SafeHtmlBuilder sb, List<T> values, int start,
SelectionModel<? super T> selectionModel) {
String keyboardSelectedItem = " " + style.cellListKeyboardSelectedItem();
String selectedItem = " " + style.cellListSelectedItem();
String evenItem = style.cellListEvenItem();
String oddItem = style.cellListOddItem();
int keyboardSelectedRow = getKeyboardSelectedRow() + getPageStart();
int length = values.size();
int end = start + length;
for (int i = start; i < end; i++) {
T value = values.get(i - start);
boolean isSelected = selectionModel == null ? false
: selectionModel.isSelected(value);
StringBuilder classesBuilder = new StringBuilder();
classesBuilder.append(i % 2 == 0 ? evenItem : oddItem);
if (isSelected) {
classesBuilder.append(selectedItem);
}
SafeHtmlBuilder cellBuilder = new SafeHtmlBuilder();
Context context = new Context(i, 0, getValueKey(value));
cell.render(context, value, cellBuilder);
if (i == keyboardSelectedRow) {
// This is the focused item.
if (isFocused) {
classesBuilder.append(keyboardSelectedItem);
}
char accessKey = getAccessKey();
if (accessKey != 0) {
sb.append(TEMPLATE.divFocusableWithKey(i, classesBuilder.toString(),
getTabIndex(), accessKey, cellBuilder.toSafeHtml()));
} else {
sb.append(TEMPLATE.divFocusable(i, classesBuilder.toString(),
getTabIndex(), cellBuilder.toSafeHtml()));
}
} else {
sb.append(TEMPLATE.div(i, classesBuilder.toString(),
cellBuilder.toSafeHtml()));
}
}
}
@Override
protected boolean resetFocusOnCell() {
int row = getKeyboardSelectedRow();
if (isRowWithinBounds(row)) {
Element rowElem = getKeyboardSelectedElement();
Element cellParent = getCellParent(rowElem);
T value = getVisibleItem(row);
Context context = new Context(row + getPageStart(), 0, getValueKey(value));
return cell.resetFocus(context, cellParent, value);
}
return false;
}
@Override
protected void setKeyboardSelected(int index, boolean selected,
boolean stealFocus) {
if (!isRowWithinBounds(index)) {
return;
}
Element elem = getRowElement(index);
if (!selected || isFocused || stealFocus) {
setStyleName(elem, style.cellListKeyboardSelectedItem(), selected);
}
setFocusable(elem, selected);
if (selected && stealFocus && !cellIsEditing) {
elem.focus();
onFocus();
}
}
/**
* @deprecated this method is never called by AbstractHasData, render the
* selected styles in
* {@link #renderRowValues(SafeHtmlBuilder, List, int, SelectionModel)}
*/
@Override
@Deprecated
protected void setSelected(Element elem, boolean selected) {
setStyleName(elem, style.cellListSelectedItem(), selected);
}
@Override
void setLoadingState(LoadingState state) {
showOrHide(emptyMessageElem, state == LoadingState.EMPTY);
// TODO(jlabanca): Add a loading icon.
}
/**
* Show or hide an element.
*
* @param element the element
* @param show true to show, false to hide
*/
private void showOrHide(Element element, boolean show) {
if (show) {
element.getStyle().clearDisplay();
} else {
element.getStyle().setDisplay(Display.NONE);
}
}
}
diff --git a/user/src/com/google/gwt/user/cellview/client/CellTable.java b/user/src/com/google/gwt/user/cellview/client/CellTable.java
index 5096fee49..65ec3c239 100644
--- a/user/src/com/google/gwt/user/cellview/client/CellTable.java
+++ b/user/src/com/google/gwt/user/cellview/client/CellTable.java
@@ -1,1646 +1,1646 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.cellview.client;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableColElement;
import com.google.gwt.dom.client.TableElement;
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.dom.client.TableSectionElement;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.CssResource.ImportedWithPrefix;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.client.ImageResource.ImageOptions;
import com.google.gwt.resources.client.ImageResource.RepeatStyle;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.HasDataPresenter.LoadingState;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.user.client.ui.HasVerticalAlignment.VerticalAlignmentConstant;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionModel;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A tabular view that supports paging and columns.
*
* <p>
* <h3>Columns</h3>
* The {@link Column} class defines the {@link Cell} used to render a column.
* Implement {@link Column#getValue(Object)} to retrieve the field value from
* the row object that will be rendered in the {@link Cell}.
* </p>
*
* <p>
* <h3>Headers and Footers</h3>
* A {@link Header} can be placed at the top (header) or bottom (footer) of the
* {@link CellTable}. You can specify a header as text using
* {@link #addColumn(Column, String)}, or you can create a custom {@link Header}
* that can change with the value of the cells, such as a column total. The
* {@link Header} will be rendered every time the row data changes or the table
* is redrawn. If you pass the same header instance (==) into adjacent columns,
* the header will span the columns.
* </p>
*
* <p>
* <h3>Examples</h3>
* <dl>
* <dt>Trivial example</dt>
* <dd>{@example com.google.gwt.examples.cellview.CellTableExample}</dd>
* <dt>FieldUpdater example</dt>
* <dd>{@example com.google.gwt.examples.cellview.CellTableFieldUpdaterExample}</dd>
* <dt>Key provider example</dt>
* <dd>{@example com.google.gwt.examples.view.KeyProviderExample}</dd>
* </dl>
* </p>
*
* @param <T> the data type of each row
*/
public class CellTable<T> extends AbstractHasData<T> {
/**
* Resources that match the GWT standard style theme.
*/
public interface BasicResources extends Resources {
/**
* The styles used in this widget.
*/
@Source(BasicStyle.DEFAULT_CSS)
BasicStyle cellTableStyle();
}
/**
* A ClientBundle that provides images for this widget.
*/
public interface Resources extends ClientBundle {
/**
* The background used for footer cells.
*/
@Source("cellTableHeaderBackground.png")
@ImageOptions(repeatStyle = RepeatStyle.Horizontal, flipRtl = true)
ImageResource cellTableFooterBackground();
/**
* The background used for header cells.
*/
@ImageOptions(repeatStyle = RepeatStyle.Horizontal, flipRtl = true)
ImageResource cellTableHeaderBackground();
/**
* The loading indicator used while the table is waiting for data.
*/
@ImageOptions(flipRtl = true)
ImageResource cellTableLoading();
/**
* The background used for selected cells.
*/
@Source("cellListSelectedBackground.png")
@ImageOptions(repeatStyle = RepeatStyle.Horizontal, flipRtl = true)
ImageResource cellTableSelectedBackground();
/**
* The styles used in this widget.
*/
@Source(Style.DEFAULT_CSS)
Style cellTableStyle();
}
/**
* Styles used by this widget.
*/
@ImportedWithPrefix("gwt-CellTable")
public interface Style extends CssResource {
/**
* The path to the default CSS styles used by this resource.
*/
String DEFAULT_CSS = "com/google/gwt/user/cellview/client/CellTable.css";
/**
* Applied to every cell.
*/
String cellTableCell();
/**
* Applied to even rows.
*/
String cellTableEvenRow();
/**
* Applied to cells in even rows.
*/
String cellTableEvenRowCell();
/**
* Applied to the first column.
*/
String cellTableFirstColumn();
/**
* Applied to the first column footers.
*/
String cellTableFirstColumnFooter();
/**
* Applied to the first column headers.
*/
String cellTableFirstColumnHeader();
/**
* Applied to footers cells.
*/
String cellTableFooter();
/**
* Applied to headers cells.
*/
String cellTableHeader();
/**
* Applied to the hovered row.
*/
String cellTableHoveredRow();
/**
* Applied to the cells in the hovered row.
*/
String cellTableHoveredRowCell();
/**
* Applied to the keyboard selected cell.
*/
String cellTableKeyboardSelectedCell();
/**
* Applied to the keyboard selected row.
*/
String cellTableKeyboardSelectedRow();
/**
* Applied to the cells in the keyboard selected row.
*/
String cellTableKeyboardSelectedRowCell();
/**
* Applied to the last column.
*/
String cellTableLastColumn();
/**
* Applied to the last column footers.
*/
String cellTableLastColumnFooter();
/**
* Applied to the last column headers.
*/
String cellTableLastColumnHeader();
/**
* Applied to the loading indicator.
*/
String cellTableLoading();
/**
* Applied to odd rows.
*/
String cellTableOddRow();
/**
* Applied to cells in odd rows.
*/
String cellTableOddRowCell();
/**
* Applied to selected rows.
*/
String cellTableSelectedRow();
/**
* Applied to cells in selected rows.
*/
String cellTableSelectedRowCell();
/**
* Applied to the table.
*/
String cellTableWidget();
}
/**
* Styles used by {@link BasicResources}.
*/
@ImportedWithPrefix("gwt-CellTable")
interface BasicStyle extends Style {
/**
* The path to the default CSS styles used by this resource.
*/
String DEFAULT_CSS = "com/google/gwt/user/cellview/client/CellTableBasic.css";
}
interface Template extends SafeHtmlTemplates {
@Template("<div style=\"outline:none;\">{0}</div>")
SafeHtml div(SafeHtml contents);
@Template("<div style=\"outline:none;\" tabindex=\"{0}\">{1}</div>")
SafeHtml divFocusable(int tabIndex, SafeHtml contents);
@Template("<div style=\"outline:none;\" tabindex=\"{0}\" accessKey=\"{1}\">{2}</div>")
SafeHtml divFocusableWithKey(int tabIndex, char accessKey, SafeHtml contents);
@Template("<div class=\"{0}\"></div>")
SafeHtml loading(String loading);
@Template("<table><tbody>{0}</tbody></table>")
SafeHtml tbody(SafeHtml rowHtml);
@Template("<td class=\"{0}\">{1}</td>")
SafeHtml td(String classes, SafeHtml contents);
@Template("<td class=\"{0}\" align=\"{1}\" valign=\"{2}\">{3}</td>")
SafeHtml tdBothAlign(String classes, String hAlign, String vAlign,
SafeHtml contents);
@Template("<td class=\"{0}\" align=\"{1}\">{2}</td>")
SafeHtml tdHorizontalAlign(String classes, String hAlign, SafeHtml contents);
@Template("<td class=\"{0}\" valign=\"{1}\">{2}</td>")
SafeHtml tdVerticalAlign(String classes, String vAlign, SafeHtml contents);
@Template("<table><tfoot>{0}</tfoot></table>")
SafeHtml tfoot(SafeHtml rowHtml);
@Template("<th colspan=\"{0}\" class=\"{1}\">{2}</th>")
SafeHtml th(int colspan, String classes, SafeHtml contents);
@Template("<table><thead>{0}</thead></table>")
SafeHtml thead(SafeHtml rowHtml);
@Template("<tr onclick=\"\" class=\"{0}\">{1}</tr>")
SafeHtml tr(String classes, SafeHtml contents);
}
/**
* Implementation of {@link CellTable}.
*/
private static class Impl {
private final com.google.gwt.user.client.Element tmpElem = Document.get().createDivElement().cast();
/**
* Convert the rowHtml into Elements wrapped by the specified table section.
*
* @param table the {@link CellTable}
* @param sectionTag the table section tag
* @param rowHtml the Html for the rows
* @return the section element
*/
protected TableSectionElement convertToSectionElement(CellTable<?> table,
String sectionTag, SafeHtml rowHtml) {
// Attach an event listener so we can catch synchronous load events from
// cached images.
DOM.setEventListener(tmpElem, table);
// Render the rows into a table.
// IE doesn't support innerHtml on a TableSection or Table element, so we
// generate the entire table.
sectionTag = sectionTag.toLowerCase();
if ("tbody".equals(sectionTag)) {
tmpElem.setInnerHTML(template.tbody(rowHtml).asString());
} else if ("thead".equals(sectionTag)) {
tmpElem.setInnerHTML(template.thead(rowHtml).asString());
} else if ("tfoot".equals(sectionTag)) {
tmpElem.setInnerHTML(template.tfoot(rowHtml).asString());
} else {
throw new IllegalArgumentException("Invalid table section tag: "
+ sectionTag);
}
TableElement tableElem = tmpElem.getFirstChildElement().cast();
// Detach the event listener.
DOM.setEventListener(tmpElem, null);
// Get the section out of the table.
if ("tbody".equals(sectionTag)) {
return tableElem.getTBodies().getItem(0);
} else if ("thead".equals(sectionTag)) {
return tableElem.getTHead();
} else if ("tfoot".equals(sectionTag)) {
return tableElem.getTFoot();
} else {
throw new IllegalArgumentException("Invalid table section tag: "
+ sectionTag);
}
}
/**
* Render a table section in the table.
*
* @param table the {@link CellTable}
* @param section the {@link TableSectionElement} to replace
* @param html the html to render
*/
protected void replaceAllRows(CellTable<?> table,
TableSectionElement section, SafeHtml html) {
// If the widget is not attached, attach an event listener so we can catch
// synchronous load events from cached images.
if (!table.isAttached()) {
DOM.setEventListener(table.getElement(), table);
}
// Render the html.
section.setInnerHTML(html.asString());
// Detach the event listener.
if (!table.isAttached()) {
DOM.setEventListener(table.getElement(), null);
}
}
}
/**
* Implementation of {@link CellTable} used by IE.
*/
@SuppressWarnings("unused")
private static class ImplTrident extends Impl {
/**
* IE doesn't support innerHTML on tbody, nor does it support removing or
* replacing a tbody. The only solution is to remove and replace the rows
* themselves.
*/
@Override
protected void replaceAllRows(CellTable<?> table,
TableSectionElement section, SafeHtml html) {
// Remove all children.
Element child = section.getFirstChildElement();
while (child != null) {
Element next = child.getNextSiblingElement();
section.removeChild(child);
child = next;
}
// Add new child elements.
TableSectionElement newSection = convertToSectionElement(table,
section.getTagName(), html);
child = newSection.getFirstChildElement();
while (child != null) {
Element next = child.getNextSiblingElement();
section.appendChild(child);
child = next;
}
}
}
/**
* The default page size.
*/
private static final int DEFAULT_PAGESIZE = 15;
private static Resources DEFAULT_RESOURCES;
/**
* The table specific {@link Impl}.
*/
private static Impl TABLE_IMPL;
private static Template template;
private static Resources getDefaultResources() {
if (DEFAULT_RESOURCES == null) {
DEFAULT_RESOURCES = GWT.create(Resources.class);
}
return DEFAULT_RESOURCES;
}
private boolean cellIsEditing;
private final TableColElement colgroup;
private final List<Column<T, ?>> columns = new ArrayList<Column<T, ?>>();
/**
* Indicates that at least one column depends on selection.
*/
private boolean dependsOnSelection;
private final List<Header<?>> footers = new ArrayList<Header<?>>();
/**
* Indicates that at least one column handles selection.
*/
private boolean handlesSelection;
private final List<Header<?>> headers = new ArrayList<Header<?>>();
private TableRowElement hoveringRow;
/**
* Indicates that at least one column is interactive.
*/
private boolean isInteractive;
private int keyboardSelectedColumn = 0;
private RowStyles<T> rowStyles;
private final Style style;
private final TableElement table;
private final TableSectionElement tbody;
private final TableSectionElement tbodyLoading;
private final TableSectionElement tfoot;
private final TableSectionElement thead;
/**
* Constructs a table with a default page size of 15.
*/
public CellTable() {
this(DEFAULT_PAGESIZE);
}
/**
* Constructs a table with the given page size.
*
* @param pageSize the page size
*/
public CellTable(final int pageSize) {
this(pageSize, getDefaultResources(), null);
}
/**
* Constructs a table with a default page size of 15, and the given
* {@link ProvidesKey key provider}.
*
* @param keyProvider an instance of ProvidesKey<T>, or null if the record
* object should act as its own key
*/
public CellTable(ProvidesKey<T> keyProvider) {
this(DEFAULT_PAGESIZE, getDefaultResources(), keyProvider);
}
/**
* Constructs a table with the given page size with the specified
* {@link Resources}.
*
* @param pageSize the page size
* @param resources the resources to use for this widget
*/
public CellTable(final int pageSize, Resources resources) {
this(pageSize, resources, null);
}
/**
* Constructs a table with the given page size and the given
* {@link ProvidesKey key provider}.
*
* @param pageSize the page size
* @param keyProvider an instance of ProvidesKey<T>, or null if the record
* object should act as its own key
*/
public CellTable(final int pageSize, ProvidesKey<T> keyProvider) {
this(pageSize, getDefaultResources(), keyProvider);
}
/**
* Constructs a table with the given page size, the specified
* {@link Resources}, and the given key provider.
*
* @param pageSize the page size
* @param resources the resources to use for this widget
* @param keyProvider an instance of ProvidesKey<T>, or null if the record
* object should act as its own key
*/
public CellTable(final int pageSize, Resources resources,
ProvidesKey<T> keyProvider) {
super(Document.get().createTableElement(), pageSize, keyProvider);
if (TABLE_IMPL == null) {
TABLE_IMPL = GWT.create(Impl.class);
}
if (template == null) {
template = GWT.create(Template.class);
}
this.style = resources.cellTableStyle();
this.style.ensureInjected();
table = getElement().cast();
table.setCellSpacing(0);
colgroup = Document.get().createColGroupElement();
table.appendChild(colgroup);
thead = table.createTHead();
// Some browsers create a tbody automatically, others do not.
if (table.getTBodies().getLength() > 0) {
tbody = table.getTBodies().getItem(0);
} else {
tbody = Document.get().createTBodyElement();
table.appendChild(tbody);
}
table.appendChild(tbodyLoading = Document.get().createTBodyElement());
tfoot = table.createTFoot();
setStyleName(this.style.cellTableWidget());
// Create the loading indicator.
{
TableCellElement td = Document.get().createTDElement();
TableRowElement tr = Document.get().createTRElement();
tbodyLoading.appendChild(tr);
tr.appendChild(td);
td.setAlign("center");
td.setInnerHTML(template.loading(style.cellTableLoading()).asString());
setLoadingIconVisible(false);
}
// Sink events.
Set<String> eventTypes = new HashSet<String>();
eventTypes.add("mouseover");
eventTypes.add("mouseout");
CellBasedWidgetImpl.get().sinkEvents(this, eventTypes);
}
/**
* Adds a column to the end of the table.
*
* @param col the column to be added
*/
public void addColumn(Column<T, ?> col) {
insertColumn(getColumnCount(), col);
}
/**
* Adds a column to the end of the table with an associated header.
*
* @param col the column to be added
* @param header the associated {@link Header}
*/
public void addColumn(Column<T, ?> col, Header<?> header) {
insertColumn(getColumnCount(), col, header);
}
/**
* Adds a column to the end of the table with an associated header and footer.
*
* @param col the column to be added
* @param header the associated {@link Header}
* @param footer the associated footer (as a {@link Header} object)
*/
public void addColumn(Column<T, ?> col, Header<?> header, Header<?> footer) {
insertColumn(getColumnCount(), col, header, footer);
}
/**
* Adds a column to the end of the table with an associated String header.
*
* @param col the column to be added
* @param headerString the associated header text, as a String
*/
public void addColumn(Column<T, ?> col, String headerString) {
insertColumn(getColumnCount(), col, headerString);
}
/**
* Adds a column to the end of the table with an associated {@link SafeHtml}
* header.
*
* @param col the column to be added
* @param headerHtml the associated header text, as safe HTML
*/
public void addColumn(Column<T, ?> col, SafeHtml headerHtml) {
insertColumn(getColumnCount(), col, headerHtml);
}
/**
* Adds a column to the end of the table with an associated String header and
* footer.
*
* @param col the column to be added
* @param headerString the associated header text, as a String
* @param footerString the associated footer text, as a String
*/
public void addColumn(Column<T, ?> col, String headerString,
String footerString) {
insertColumn(getColumnCount(), col, headerString, footerString);
}
/**
* Adds a column to the end of the table with an associated {@link SafeHtml}
* header and footer.
*
* @param col the column to be added
* @param headerHtml the associated header text, as safe HTML
* @param footerHtml the associated footer text, as safe HTML
*/
public void addColumn(Column<T, ?> col, SafeHtml headerHtml,
SafeHtml footerHtml) {
insertColumn(getColumnCount(), col, headerHtml, footerHtml);
}
/**
* Add a style name to the {@link TableColElement} at the specified index,
* creating it if necessary.
*
* @param index the column index
* @param styleName the style name to add
*/
public void addColumnStyleName(int index, String styleName) {
ensureTableColElement(index).addClassName(styleName);
}
/**
* Return the height of the table body.
*
* @return an int representing the body height
*/
public int getBodyHeight() {
int height = getClientHeight(tbody);
return height;
}
/**
* Get the column at the specified index.
*
* @param col the index of the column to retrieve
* @return the {@link Column} at the index
*/
public Column<T, ?> getColumn(int col) {
checkColumnBounds(col);
return columns.get(col);
}
/**
* Get the number of columns in the table.
*
* @return the column count
*/
public int getColumnCount() {
return columns.size();
}
/**
* Return the height of the table header.
*
* @return an int representing the header height
*/
public int getHeaderHeight() {
int height = getClientHeight(thead);
return height;
}
/**
* Get the {@link TableRowElement} for the specified row. If the row element
* has not been created, null is returned.
*
* @param row the row index
* @return the row element, or null if it doesn't exists
* @throws IndexOutOfBoundsException if the row index is outside of the
* current page
*/
public TableRowElement getRowElement(int row) {
getPresenter().flush();
checkRowBounds(row);
NodeList<TableRowElement> rows = tbody.getRows();
return rows.getLength() > row ? rows.getItem(row) : null;
}
/**
* Inserts a column into the table at the specified index.
*
* @param beforeIndex the index to insert the column
* @param col the column to be added
*/
public void insertColumn(int beforeIndex, Column<T, ?> col) {
insertColumn(beforeIndex, col, (Header<?>) null, (Header<?>) null);
}
/**
* Inserts a column into the table at the specified index with an associated
* header.
*
* @param beforeIndex the index to insert the column
* @param col the column to be added
* @param header the associated {@link Header}
*/
public void insertColumn(int beforeIndex, Column<T, ?> col, Header<?> header) {
insertColumn(beforeIndex, col, header, null);
}
/**
* Inserts a column into the table at the specified index with an associated
* header and footer.
*
* @param beforeIndex the index to insert the column
* @param col the column to be added
* @param header the associated {@link Header}
* @param footer the associated footer (as a {@link Header} object)
* @throws IndexOutOfBoundsException if the index is out of range
*/
public void insertColumn(int beforeIndex, Column<T, ?> col, Header<?> header,
Header<?> footer) {
// Allow insert at the end.
if (beforeIndex != getColumnCount()) {
checkColumnBounds(beforeIndex);
}
headers.add(beforeIndex, header);
footers.add(beforeIndex, footer);
columns.add(beforeIndex, col);
boolean wasinteractive = isInteractive;
updateDependsOnSelection();
// Move the keyboard selected column if the current column is not
// interactive.
if (!wasinteractive && isInteractive) {
keyboardSelectedColumn = beforeIndex;
}
// Sink events used by the new column.
Set<String> consumedEvents = new HashSet<String>();
{
Set<String> cellEvents = col.getCell().getConsumedEvents();
if (cellEvents != null) {
consumedEvents.addAll(cellEvents);
}
}
if (header != null) {
Set<String> headerEvents = header.getCell().getConsumedEvents();
if (headerEvents != null) {
consumedEvents.addAll(headerEvents);
}
}
if (footer != null) {
Set<String> footerEvents = footer.getCell().getConsumedEvents();
if (footerEvents != null) {
consumedEvents.addAll(footerEvents);
}
}
CellBasedWidgetImpl.get().sinkEvents(this, consumedEvents);
redraw();
}
/**
* Inserts a column into the table at the specified index with an associated
* String header.
*
* @param beforeIndex the index to insert the column
* @param col the column to be added
* @param headerString the associated header text, as a String
*/
public void insertColumn(int beforeIndex, Column<T, ?> col,
String headerString) {
insertColumn(beforeIndex, col, new TextHeader(headerString), null);
}
/**
* Inserts a column into the table at the specified index with an associated
* {@link SafeHtml} header.
*
* @param beforeIndex the index to insert the column
* @param col the column to be added
* @param headerHtml the associated header text, as safe HTML
*/
public void insertColumn(int beforeIndex, Column<T, ?> col,
SafeHtml headerHtml) {
insertColumn(beforeIndex, col, new SafeHtmlHeader(headerHtml), null);
}
/**
* Inserts a column into the table at the specified index with an associated
* String header and footer.
*
* @param beforeIndex the index to insert the column
* @param col the column to be added
* @param headerString the associated header text, as a String
* @param footerString the associated footer text, as a String
*/
public void insertColumn(int beforeIndex, Column<T, ?> col,
String headerString, String footerString) {
insertColumn(beforeIndex, col, new TextHeader(headerString),
new TextHeader(footerString));
}
/**
* Inserts a column into the table at the specified index with an associated
* {@link SafeHtml} header and footer.
*
* @param beforeIndex the index to insert the column
* @param col the column to be added
* @param headerHtml the associated header text, as safe HTML
* @param footerHtml the associated footer text, as safe HTML
*/
public void insertColumn(int beforeIndex, Column<T, ?> col,
SafeHtml headerHtml, SafeHtml footerHtml) {
insertColumn(beforeIndex, col, new SafeHtmlHeader(headerHtml),
new SafeHtmlHeader(footerHtml));
}
/**
* Redraw the table's footers.
*/
public void redrawFooters() {
createHeaders(true);
}
/**
* Redraw the table's headers.
*/
public void redrawHeaders() {
createHeaders(false);
}
/**
* Remove a column.
*
* @param col the column to remove
*/
public void removeColumn(Column<T, ?> col) {
int index = columns.indexOf(col);
if (index < 0) {
throw new IllegalArgumentException(
"The specified column is not part of this table.");
}
removeColumn(index);
}
/**
* Remove a column.
*
* @param index the column index
*/
public void removeColumn(int index) {
if (index < 0 || index >= columns.size()) {
throw new IndexOutOfBoundsException(
"The specified column index is out of bounds.");
}
columns.remove(index);
headers.remove(index);
footers.remove(index);
updateDependsOnSelection();
// Find an interactive column. Stick with 0 if no column is interactive.
if (index <= keyboardSelectedColumn) {
keyboardSelectedColumn = 0;
if (isInteractive) {
for (int i = 0; i < columns.size(); i++) {
if (isColumnInteractive(columns.get(i))) {
keyboardSelectedColumn = i;
break;
}
}
}
}
// Redraw the table asynchronously.
redraw();
// We don't unsink events because other handlers or user code may have sunk
// them intentionally.
}
/**
* Remove a style from the {@link TableColElement} at the specified index.
*
* @param index the column index
* @param styleName the style name to remove
*/
public void removeColumnStyleName(int index, String styleName) {
if (index >= colgroup.getChildCount()) {
return;
}
ensureTableColElement(index).removeClassName(styleName);
}
/**
* Sets the object used to determine how a row is styled; the change will take
* effect the next time that the table is rendered.
*
* @param rowStyles a {@link RowStyles} object
*/
public void setRowStyles(RowStyles<T> rowStyles) {
this.rowStyles = rowStyles;
}
@Override
protected Element convertToElements(SafeHtml html) {
return TABLE_IMPL.convertToSectionElement(CellTable.this, "tbody", html);
}
@Override
protected boolean dependsOnSelection() {
return dependsOnSelection;
}
/**
* Called when a user action triggers selection.
*
* @param event the event that triggered selection
* @param value the value that was selected
* @param row the row index of the value on the page
* @param column the column index where the event occurred
* @deprecated use
* {@link #addCellPreviewHandler(com.google.gwt.view.client.CellPreviewEvent.Handler)}
* instead
*/
@Deprecated
protected void doSelection(Event event, T value, int row, int column) {
}
@Override
protected Element getChildContainer() {
return tbody;
}
@Override
protected Element getKeyboardSelectedElement() {
// Do not use getRowElement() because that will flush the presenter.
int rowIndex = getKeyboardSelectedRow();
NodeList<TableRowElement> rows = tbody.getRows();
- if (rowIndex < rows.getLength() && columns.size() > 0) {
+ if (rowIndex >= 0 && rowIndex < rows.getLength() && columns.size() > 0) {
TableRowElement tr = rows.getItem(rowIndex);
TableCellElement td = tr.getCells().getItem(keyboardSelectedColumn);
return getCellParent(td);
}
return null;
}
@Override
protected boolean isKeyboardNavigationSuppressed() {
return cellIsEditing;
}
@Override
protected void onBlur() {
Element elem = getKeyboardSelectedElement();
if (elem != null) {
TableCellElement td = elem.getParentElement().cast();
TableRowElement tr = td.getParentElement().cast();
td.removeClassName(style.cellTableKeyboardSelectedCell());
setRowStyleName(tr, style.cellTableKeyboardSelectedRow(),
style.cellTableKeyboardSelectedRowCell(), false);
}
}
@SuppressWarnings("deprecation")
@Override
protected void onBrowserEvent2(Event event) {
// Get the event target.
EventTarget eventTarget = event.getEventTarget();
if (!Element.is(eventTarget)) {
return;
}
final Element target = event.getEventTarget().cast();
// Ignore keydown events unless the cell is in edit mode
String eventType = event.getType();
if ("keydown".equals(eventType) && !isKeyboardNavigationSuppressed()
&& KeyboardSelectionPolicy.DISABLED != getKeyboardSelectionPolicy()) {
if (handleKey(event)) {
return;
}
}
// Find the cell where the event occurred.
TableCellElement tableCell = findNearestParentCell(target);
if (tableCell == null) {
return;
}
// Determine if we are in the header, footer, or body. Its possible that
// the table has been refreshed before the current event fired (ex. change
// event refreshes before mouseup fires), so we need to check each parent
// element.
Element trElem = tableCell.getParentElement();
if (trElem == null) {
return;
}
TableRowElement tr = TableRowElement.as(trElem);
Element sectionElem = tr.getParentElement();
if (sectionElem == null) {
return;
}
TableSectionElement section = TableSectionElement.as(sectionElem);
// Forward the event to the associated header, footer, or column.
int col = tableCell.getCellIndex();
if (section == thead) {
Header<?> header = headers.get(col);
if (header != null && cellConsumesEventType(header.getCell(), eventType)) {
Context context = new Context(0, col, header.getKey());
header.onBrowserEvent(context, tableCell, event);
}
} else if (section == tfoot) {
Header<?> footer = footers.get(col);
if (footer != null && cellConsumesEventType(footer.getCell(), eventType)) {
Context context = new Context(0, col, footer.getKey());
footer.onBrowserEvent(context, tableCell, event);
}
} else if (section == tbody) {
// Update the hover state.
boolean isClick = "click".equals(eventType);
int row = tr.getSectionRowIndex();
if ("mouseover".equals(eventType)) {
// Unstyle the old row if it is still part of the table.
if (hoveringRow != null && tbody.isOrHasChild(hoveringRow)) {
setRowStyleName(hoveringRow, style.cellTableHoveredRow(),
style.cellTableHoveredRowCell(), false);
}
hoveringRow = tr;
setRowStyleName(hoveringRow, style.cellTableHoveredRow(),
style.cellTableHoveredRowCell(), true);
} else if ("mouseout".equals(eventType) && hoveringRow != null) {
setRowStyleName(hoveringRow, style.cellTableHoveredRow(),
style.cellTableHoveredRowCell(), false);
hoveringRow = null;
} else if (isClick
&& ((getPresenter().getKeyboardSelectedRowInView() != row) || (keyboardSelectedColumn != col))) {
// Move keyboard focus. Since the user clicked, allow focus to go to a
// non-interactive column.
boolean isFocusable = CellBasedWidgetImpl.get().isFocusable(target);
isFocused = isFocused || isFocusable;
keyboardSelectedColumn = col;
getPresenter().setKeyboardSelectedRow(row, !isFocusable, true);
}
// Update selection. Selection occurs before firing the event to the cell
// in case the cell operates on the currently selected item.
if (!isRowWithinBounds(row)) {
// If the event causes us to page, then the physical index will be out
// of bounds of the underlying data.
return;
}
boolean isSelectionHandled = handlesSelection
|| KeyboardSelectionPolicy.BOUND_TO_SELECTION == getKeyboardSelectionPolicy();
T value = getVisibleItem(row);
Context context = new Context(row + getPageStart(), col,
getValueKey(value));
CellPreviewEvent<T> previewEvent = CellPreviewEvent.fire(this, event,
this, context, value, cellIsEditing, isSelectionHandled);
if (isClick && !cellIsEditing && !isSelectionHandled) {
doSelection(event, value, row, col);
}
// Pass the event to the cell.
if (!previewEvent.isCanceled()) {
fireEventToCell(event, eventType, tableCell, value, context,
columns.get(col));
}
}
}
@Override
protected void onFocus() {
Element elem = getKeyboardSelectedElement();
if (elem != null) {
TableCellElement td = elem.getParentElement().cast();
TableRowElement tr = td.getParentElement().cast();
td.addClassName(style.cellTableKeyboardSelectedCell());
setRowStyleName(tr, style.cellTableKeyboardSelectedRow(),
style.cellTableKeyboardSelectedRowCell(), true);
}
}
@Override
protected void renderRowValues(SafeHtmlBuilder sb, List<T> values, int start,
SelectionModel<? super T> selectionModel) {
createHeadersAndFooters();
int keyboardSelectedRow = getKeyboardSelectedRow() + getPageStart();
String evenRowStyle = style.cellTableEvenRow();
String oddRowStyle = style.cellTableOddRow();
String cellStyle = style.cellTableCell();
String evenCellStyle = " " + style.cellTableEvenRowCell();
String oddCellStyle = " " + style.cellTableOddRowCell();
String firstColumnStyle = " " + style.cellTableFirstColumn();
String lastColumnStyle = " " + style.cellTableLastColumn();
String selectedRowStyle = " " + style.cellTableSelectedRow();
String selectedCellStyle = " " + style.cellTableSelectedRowCell();
String keyboardRowStyle = " " + style.cellTableKeyboardSelectedRow();
String keyboardRowCellStyle = " "
+ style.cellTableKeyboardSelectedRowCell();
String keyboardCellStyle = " " + style.cellTableKeyboardSelectedCell();
int columnCount = columns.size();
int length = values.size();
int end = start + length;
for (int i = start; i < end; i++) {
T value = values.get(i - start);
boolean isSelected = (selectionModel == null || value == null) ? false
: selectionModel.isSelected(value);
boolean isEven = i % 2 == 0;
boolean isKeyboardSelected = i == keyboardSelectedRow && isFocused;
String trClasses = isEven ? evenRowStyle : oddRowStyle;
if (isSelected) {
trClasses += selectedRowStyle;
}
if (isKeyboardSelected) {
trClasses += keyboardRowStyle;
}
if (rowStyles != null) {
String extraRowStyles = rowStyles.getStyleNames(value, i);
if (extraRowStyles != null) {
trClasses += " ";
trClasses += extraRowStyles;
}
}
SafeHtmlBuilder trBuilder = new SafeHtmlBuilder();
int curColumn = 0;
for (Column<T, ?> column : columns) {
String tdClasses = cellStyle;
tdClasses += isEven ? evenCellStyle : oddCellStyle;
if (curColumn == 0) {
tdClasses += firstColumnStyle;
}
if (isSelected) {
tdClasses += selectedCellStyle;
}
if (isKeyboardSelected) {
tdClasses += keyboardRowCellStyle;
}
// The first and last column could be the same column.
if (curColumn == columnCount - 1) {
tdClasses += lastColumnStyle;
}
SafeHtmlBuilder cellBuilder = new SafeHtmlBuilder();
if (value != null) {
Context context = new Context(i, curColumn, getValueKey(value));
column.render(context, value, cellBuilder);
}
// Build the contents.
SafeHtml contents = SafeHtmlUtils.EMPTY_SAFE_HTML;
if (i == keyboardSelectedRow && curColumn == keyboardSelectedColumn) {
// This is the focused cell.
if (isFocused) {
tdClasses += keyboardCellStyle;
}
char accessKey = getAccessKey();
if (accessKey != 0) {
contents = template.divFocusableWithKey(getTabIndex(), accessKey,
cellBuilder.toSafeHtml());
} else {
contents = template.divFocusable(getTabIndex(),
cellBuilder.toSafeHtml());
}
} else {
contents = template.div(cellBuilder.toSafeHtml());
}
// Build the cell.
HorizontalAlignmentConstant hAlign = column.getHorizontalAlignment();
VerticalAlignmentConstant vAlign = column.getVerticalAlignment();
if (hAlign != null && vAlign != null) {
trBuilder.append(template.tdBothAlign(tdClasses,
hAlign.getTextAlignString(), vAlign.getVerticalAlignString(),
contents));
} else if (hAlign != null) {
trBuilder.append(template.tdHorizontalAlign(tdClasses,
hAlign.getTextAlignString(), contents));
} else if (vAlign != null) {
trBuilder.append(template.tdVerticalAlign(tdClasses,
vAlign.getVerticalAlignString(), contents));
} else {
trBuilder.append(template.td(tdClasses, contents));
}
curColumn++;
}
sb.append(template.tr(trClasses, trBuilder.toSafeHtml()));
}
}
@Override
protected void replaceAllChildren(List<T> values, SafeHtml html) {
TABLE_IMPL.replaceAllRows(CellTable.this, tbody,
CellBasedWidgetImpl.get().processHtml(html));
}
@Override
protected boolean resetFocusOnCell() {
int row = getKeyboardSelectedRow();
if (isRowWithinBounds(row) && columns.size() > 0) {
Column<T, ?> column = columns.get(keyboardSelectedColumn);
return resetFocusOnCellImpl(row, keyboardSelectedColumn, column);
}
return false;
}
@Override
protected void setKeyboardSelected(int index, boolean selected,
boolean stealFocus) {
if (KeyboardSelectionPolicy.DISABLED == getKeyboardSelectionPolicy()
|| !isRowWithinBounds(index) || columns.size() == 0) {
return;
}
TableRowElement tr = getRowElement(index);
String cellStyle = style.cellTableKeyboardSelectedCell();
boolean updatedSelection = !selected || isFocused || stealFocus;
setRowStyleName(tr, style.cellTableKeyboardSelectedRow(),
style.cellTableKeyboardSelectedRowCell(), selected);
NodeList<TableCellElement> cells = tr.getCells();
for (int i = 0; i < cells.getLength(); i++) {
TableCellElement td = cells.getItem(i);
// Update the selected style.
setStyleName(td, cellStyle, updatedSelection && selected
&& i == keyboardSelectedColumn);
// Mark as focusable.
final com.google.gwt.user.client.Element cellParent = getCellParent(td).cast();
setFocusable(cellParent, selected && i == keyboardSelectedColumn);
}
// Move focus to the cell.
if (selected && stealFocus && !cellIsEditing) {
TableCellElement td = tr.getCells().getItem(keyboardSelectedColumn);
final com.google.gwt.user.client.Element cellParent = getCellParent(td).cast();
CellBasedWidgetImpl.get().resetFocus(new Scheduler.ScheduledCommand() {
public void execute() {
cellParent.focus();
}
});
}
}
/**
* @deprecated this method is never called by AbstractHasData, render the
* selected styles in
* {@link #renderRowValues(SafeHtmlBuilder, List, int, SelectionModel)}
*/
@Override
@Deprecated
protected void setSelected(Element elem, boolean selected) {
TableRowElement tr = elem.cast();
setRowStyleName(tr, style.cellTableSelectedRow(),
style.cellTableSelectedRowCell(), selected);
}
@Override
void setLoadingState(LoadingState state) {
setLoadingIconVisible(state == LoadingState.LOADING);
}
/**
* Check that the specified column is within bounds.
*
* @param col the column index
* @throws IndexOutOfBoundsException if the column is out of bounds
*/
private void checkColumnBounds(int col) {
if (col < 0 || col >= getColumnCount()) {
throw new IndexOutOfBoundsException("Column index is out of bounds: "
+ col);
}
}
/**
* Render the header or footer.
*
* @param isFooter true if this is the footer table, false if the header table
*/
private void createHeaders(boolean isFooter) {
List<Header<?>> theHeaders = isFooter ? footers : headers;
TableSectionElement section = isFooter ? tfoot : thead;
String className = isFooter ? style.cellTableFooter()
: style.cellTableHeader();
boolean hasHeader = false;
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<tr>");
int columnCount = columns.size();
if (columnCount > 0) {
// Setup the first column.
Header<?> prevHeader = theHeaders.get(0);
int prevColspan = 1;
StringBuilder classesBuilder = new StringBuilder(className);
classesBuilder.append(" ");
classesBuilder.append(isFooter ? style.cellTableFirstColumnFooter()
: style.cellTableFirstColumnHeader());
// Loop through all column headers.
int curColumn;
for (curColumn = 1; curColumn < columnCount; curColumn++) {
Header<?> header = theHeaders.get(curColumn);
if (header != prevHeader) {
// The header has changed, so append the previous one.
SafeHtmlBuilder headerBuilder = new SafeHtmlBuilder();
if (prevHeader != null) {
hasHeader = true;
Context context = new Context(0, curColumn - prevColspan,
prevHeader.getKey());
prevHeader.render(context, headerBuilder);
}
sb.append(template.th(prevColspan, classesBuilder.toString(),
headerBuilder.toSafeHtml()));
// Reset the previous header.
prevHeader = header;
prevColspan = 1;
classesBuilder = new StringBuilder(className);
} else {
// Increment the colspan if the headers == each other.
prevColspan++;
}
}
// Append the last header.
SafeHtmlBuilder headerBuilder = new SafeHtmlBuilder();
if (prevHeader != null) {
hasHeader = true;
Context context = new Context(0, curColumn - prevColspan,
prevHeader.getKey());
prevHeader.render(context, headerBuilder);
}
// The first and last columns could be the same column.
classesBuilder.append(" ");
classesBuilder.append(isFooter ? style.cellTableLastColumnFooter()
: style.cellTableLastColumnHeader());
sb.append(template.th(prevColspan, classesBuilder.toString(),
headerBuilder.toSafeHtml()));
}
sb.appendHtmlConstant("</tr>");
// Render the section contents.
TABLE_IMPL.replaceAllRows(this, section, sb.toSafeHtml());
// If the section isn't used, hide it.
setVisible(section, hasHeader);
}
private void createHeadersAndFooters() {
createHeaders(false);
createHeaders(true);
}
/**
* Get the {@link TableColElement} at the specified index, creating it if
* necessary.
*
* @param index the column index
* @return the {@link TableColElement}
*/
private TableColElement ensureTableColElement(int index) {
// Ensure that we have enough columns.
for (int i = colgroup.getChildCount(); i <= index; i++) {
colgroup.appendChild(Document.get().createColElement());
}
return colgroup.getChild(index).cast();
}
/**
* Find and return the index of the next interactive column. If no column is
* interactive, 0 is returned. If the start index is the only interactive
* column, it is returned.
*
* @param start the start index, exclusive unless it is the only option
* @param reverse true to do a reverse search
* @return the interactive column index, or 0 if not interactive
*/
private int findInteractiveColumn(int start, boolean reverse) {
if (!isInteractive) {
return 0;
} else if (reverse) {
for (int i = start - 1; i >= 0; i--) {
if (isColumnInteractive(columns.get(i))) {
return i;
}
}
// Wrap to the end.
for (int i = columns.size() - 1; i >= start; i--) {
if (isColumnInteractive(columns.get(i))) {
return i;
}
}
} else {
for (int i = start + 1; i < columns.size(); i++) {
if (isColumnInteractive(columns.get(i))) {
return i;
}
}
// Wrap to the start.
for (int i = 0; i <= start; i++) {
if (isColumnInteractive(columns.get(i))) {
return i;
}
}
}
return 0;
}
/**
* Find the cell that contains the element. Note that the TD element is not
* the parent. The parent is the div inside the TD cell.
*
* @param elem the element
* @return the parent cell
*/
private TableCellElement findNearestParentCell(Element elem) {
while ((elem != null) && (elem != table)) {
// TODO: We need is() implementations in all Element subclasses.
// This would allow us to use TableCellElement.is() -- much cleaner.
String tagName = elem.getTagName();
if ("td".equalsIgnoreCase(tagName) || "th".equalsIgnoreCase(tagName)) {
return elem.cast();
}
elem = elem.getParentElement();
}
return null;
}
/**
* Fire an event to the Cell within the specified {@link TableCellElement}.
*/
private <C> void fireEventToCell(Event event, String eventType,
TableCellElement tableCell, T value, Context context, Column<T, C> column) {
Cell<C> cell = column.getCell();
if (cellConsumesEventType(cell, eventType)) {
C cellValue = column.getValue(value);
Element parentElem = getCellParent(tableCell);
boolean cellWasEditing = cell.isEditing(context, parentElem, cellValue);
column.onBrowserEvent(context, parentElem, value, event);
cellIsEditing = cell.isEditing(context, parentElem, cellValue);
if (cellWasEditing && !cellIsEditing) {
CellBasedWidgetImpl.get().resetFocus(new Scheduler.ScheduledCommand() {
public void execute() {
setFocus(true);
}
});
}
}
}
/**
* Get the parent element that is passed to the {@link Cell} from the table
* cell element.
*
* @param td the table cell
* @return the parent of the {@link Cell}
*/
private Element getCellParent(TableCellElement td) {
return td.getFirstChildElement();
}
private native int getClientHeight(Element element) /*-{
return element.clientHeight;
}-*/;
private boolean handleKey(Event event) {
HasDataPresenter<T> presenter = getPresenter();
int oldRow = getKeyboardSelectedRow();
boolean isRtl = LocaleInfo.getCurrentLocale().isRTL();
int keyCodeLineEnd = isRtl ? KeyCodes.KEY_LEFT : KeyCodes.KEY_RIGHT;
int keyCodeLineStart = isRtl ? KeyCodes.KEY_RIGHT : KeyCodes.KEY_LEFT;
int keyCode = event.getKeyCode();
if (keyCode == keyCodeLineEnd) {
int nextColumn = findInteractiveColumn(keyboardSelectedColumn, false);
if (nextColumn <= keyboardSelectedColumn) {
// Wrap to the next row.
if (presenter.hasKeyboardNext()) {
keyboardSelectedColumn = nextColumn;
presenter.keyboardNext();
event.preventDefault();
return true;
}
} else {
// Reselect the row to move the selected column.
keyboardSelectedColumn = nextColumn;
getPresenter().setKeyboardSelectedRow(oldRow, true, true);
event.preventDefault();
return true;
}
} else if (keyCode == keyCodeLineStart) {
int prevColumn = findInteractiveColumn(keyboardSelectedColumn, true);
if (prevColumn >= keyboardSelectedColumn) {
// Wrap to the previous row.
if (presenter.hasKeyboardPrev()) {
keyboardSelectedColumn = prevColumn;
presenter.keyboardPrev();
event.preventDefault();
return true;
}
} else {
// Reselect the row to move the selected column.
keyboardSelectedColumn = prevColumn;
getPresenter().setKeyboardSelectedRow(oldRow, true, true);
event.preventDefault();
return true;
}
}
return false;
}
/**
* Check if a column consumes events.
*/
private boolean isColumnInteractive(Column<T, ?> column) {
Set<String> consumedEvents = column.getCell().getConsumedEvents();
return consumedEvents != null && consumedEvents.size() > 0;
}
private <C> boolean resetFocusOnCellImpl(int row, int col, Column<T, C> column) {
Element parent = getKeyboardSelectedElement();
T value = getVisibleItem(row);
Object key = getValueKey(value);
C cellValue = column.getValue(value);
Cell<C> cell = column.getCell();
Context context = new Context(row + getPageStart(), col, key);
return cell.resetFocus(context, parent, cellValue);
}
/**
* Show or hide the loading icon.
*
* @param visible true to show, false to hide.
*/
private void setLoadingIconVisible(boolean visible) {
// Clear the current data.
if (visible) {
tbody.getStyle().setDisplay(Display.NONE);
} else {
tbody.getStyle().clearDisplay();
}
// Update the colspan.
TableCellElement td = tbodyLoading.getRows().getItem(0).getCells().getItem(
0);
td.setColSpan(Math.max(1, columns.size()));
setVisible(tbodyLoading, visible);
}
/**
* Apply a style to a row and all cells in the row.
*
* @param tr the row element
* @param rowStyle the style to apply to the row
* @param cellStyle the style to apply to the cells
* @param add true to add the style, false to remove
*/
private void setRowStyleName(TableRowElement tr, String rowStyle,
String cellStyle, boolean add) {
setStyleName(tr, rowStyle, add);
NodeList<TableCellElement> cells = tr.getCells();
for (int i = 0; i < cells.getLength(); i++) {
setStyleName(cells.getItem(i), cellStyle, add);
}
}
/**
* Update the dependsOnSelection and handlesSelection booleans.
*/
private void updateDependsOnSelection() {
dependsOnSelection = false;
handlesSelection = false;
isInteractive = false;
for (Column<T, ?> column : columns) {
Cell<?> cell = column.getCell();
if (cell.dependsOnSelection()) {
dependsOnSelection = true;
}
if (cell.handlesSelection()) {
handlesSelection = true;
}
if (isColumnInteractive(column)) {
isInteractive = true;
}
}
}
}
diff --git a/user/test/com/google/gwt/user/cellview/client/AbstractHasDataTestBase.java b/user/test/com/google/gwt/user/cellview/client/AbstractHasDataTestBase.java
index d56a3f5fa..5f4bc4fd8 100644
--- a/user/test/com/google/gwt/user/cellview/client/AbstractHasDataTestBase.java
+++ b/user/test/com/google/gwt/user/cellview/client/AbstractHasDataTestBase.java
@@ -1,254 +1,270 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.cellview.client;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
+import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.client.Window;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.Range;
import java.util.ArrayList;
import java.util.List;
/**
* Base tests for {@link AbstractHasData}.
*/
public abstract class AbstractHasDataTestBase extends GWTTestCase {
/**
* A mock cell that tests the index specified in each method.
*
* @param <C> the cell type
*/
protected static class IndexCell<C> extends AbstractCell<C> {
private int lastBrowserEventIndex = -1;
private int lastEditingIndex = -1;
private int lastRenderIndex = -1;
private int lastResetFocusIndex = -1;
public IndexCell(String... consumedEvents) {
super(consumedEvents);
}
public void assertLastBrowserEventIndex(int expected) {
assertEquals(expected, lastBrowserEventIndex);
}
public void assertLastEditingIndex(int expected) {
assertEquals(expected, lastEditingIndex);
}
public void assertLastRenderIndex(int expected) {
assertEquals(expected, lastRenderIndex);
}
public void assertLastResetFocusIndex(int expected) {
assertEquals(expected, lastResetFocusIndex);
}
@Override
public boolean isEditing(Context context, Element parent, C value) {
this.lastEditingIndex = context.getIndex();
return false;
}
@Override
public void onBrowserEvent(Context context, Element parent, C value,
NativeEvent event, ValueUpdater<C> valueUpdater) {
this.lastBrowserEventIndex = context.getIndex();
}
@Override
public void render(Context context, C value, SafeHtmlBuilder sb) {
this.lastRenderIndex = context.getIndex();
sb.appendEscaped("index " + this.lastRenderIndex);
}
@Override
public boolean resetFocus(Context context, Element parent, C value) {
this.lastResetFocusIndex = context.getIndex();
return false;
}
}
@Override
public String getModuleName() {
return "com.google.gwt.user.cellview.CellView";
}
public void testGetVisibleItem() {
AbstractHasData<String> display = createAbstractHasData(new TextCell());
ListDataProvider<String> provider = new ListDataProvider<String>(
createData(0, 13));
provider.addDataDisplay(display);
display.setVisibleRange(10, 10);
// No items when no data is present.
assertEquals("test 10", display.getVisibleItem(0));
assertEquals("test 11", display.getVisibleItem(1));
assertEquals("test 12", display.getVisibleItem(2));
// Out of range.
try {
assertEquals("test 10", display.getVisibleItem(-1));
fail("Expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected.
}
// Within page range, but out of data range.
try {
assertEquals("test 10", display.getVisibleItem(4));
fail("Expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected.
}
}
public void testGetVisibleItems() {
AbstractHasData<String> display = createAbstractHasData(new TextCell());
ListDataProvider<String> provider = new ListDataProvider<String>();
provider.addDataDisplay(display);
display.setVisibleRange(10, 3);
// No items when no data is present.
assertEquals(0, display.getVisibleItems().size());
// Set some data.
provider.setList(createData(0, 13));
List<String> items = display.getVisibleItems();
assertEquals(3, items.size());
assertEquals("test 10", items.get(0));
assertEquals("test 11", items.get(1));
assertEquals("test 12", items.get(2));
}
+ /**
+ * Test that we don't get any errors when keyboard selection is disabled.
+ */
+ public void testKeyboardSelectionPolicyDisabled() {
+ AbstractHasData<String> display = createAbstractHasData(new TextCell());
+ display.setRowData(createData(0, 10));
+ display.getPresenter().flush();
+ display.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.DISABLED);
+
+ assertNull(display.getKeyboardSelectedElement());
+ display.resetFocusOnCell();
+ display.setAccessKey('a');
+ display.setTabIndex(1);
+ }
+
public void testResetFocus() {
IndexCell<String> cell = new IndexCell<String>();
AbstractHasData<String> display = createAbstractHasData(cell);
display.setRowData(createData(0, 10));
display.getPresenter().flush();
cell.assertLastResetFocusIndex(-1);
display.getPresenter().setKeyboardSelectedRow(5, false, false);
display.resetFocusOnCell();
cell.assertLastResetFocusIndex(5);
}
public void testSetRowData() {
IndexCell<String> cell = new IndexCell<String>();
AbstractHasData<String> display = createAbstractHasData(cell);
// Set exact data.
List<String> values = createData(0, 62);
display.setRowData(values);
assertEquals(62, display.getRowCount());
assertTrue(display.isRowCountExact());
assertEquals(values, display.getVisibleItems());
assertEquals(new Range(0, 62), display.getVisibleRange());
// Add some data.
List<String> moreValues = createData(62, 10);
display.setVisibleRange(0, 100);
display.setRowData(62, moreValues);
assertEquals(72, display.getRowCount());
assertTrue(display.isRowCountExact());
assertEquals("test 62", display.getVisibleItem(62));
assertEquals("test 71", display.getVisibleItem(71));
assertEquals(72, display.getVisibleItems().size());
assertEquals(new Range(0, 100), display.getVisibleRange());
// Push the exact data again.
display.setRowData(values);
assertEquals(62, display.getRowCount());
assertTrue(display.isRowCountExact());
assertEquals(values, display.getVisibleItems());
assertEquals(new Range(0, 62), display.getVisibleRange());
display.getPresenter().flush();
// Render one row and verify the index.
display.setRowData(5, createData(100, 1));
display.getPresenter().flush();
assertEquals("test 100", display.getVisibleItem(5));
cell.assertLastRenderIndex(5);
}
public void testSetTabIndex() {
// Skip this test on Safari 3 because it does not support focusable divs.
String userAgent = Window.Navigator.getUserAgent();
if (userAgent.contains("Safari")) {
RegExp versionRegExp = RegExp.compile("Version/[0-3]", "ig");
MatchResult result = versionRegExp.exec(userAgent);
if (result != null && result.getGroupCount() > 0) {
return;
}
}
AbstractHasData<String> display = createAbstractHasData(new TextCell());
ListDataProvider<String> provider = new ListDataProvider<String>(
createData(0, 10));
provider.addDataDisplay(display);
display.getPresenter().flush();
// Default tab index is 0.
assertEquals(0, display.getTabIndex());
assertEquals(0, display.getKeyboardSelectedElement().getTabIndex());
// Set tab index to 2.
display.setTabIndex(2);
assertEquals(2, display.getTabIndex());
assertEquals(2, display.getKeyboardSelectedElement().getTabIndex());
// Push new data.
provider.refresh();
display.getPresenter().flush();
assertEquals(2, display.getTabIndex());
assertEquals(2, display.getKeyboardSelectedElement().getTabIndex());
}
/**
* Create an {@link AbstractHasData} to test.
*
* @param cell the cell to use
* @return the widget to test
*/
protected abstract AbstractHasData<String> createAbstractHasData(
Cell<String> cell);
/**
* Create a list of data for testing.
*
* @param start the start index
* @param length the length
* @return a list of data
*/
protected List<String> createData(int start, int length) {
List<String> toRet = new ArrayList<String>();
for (int i = 0; i < length; i++) {
toRet.add("test " + (i + start));
}
return toRet;
}
}
| false | false | null | null |
diff --git a/src/test/java/org.bloodtorrent/repository/UsersRepositoryTest.java b/src/test/java/org.bloodtorrent/repository/UsersRepositoryTest.java
index 0397b5e..fd37b62 100644
--- a/src/test/java/org.bloodtorrent/repository/UsersRepositoryTest.java
+++ b/src/test/java/org.bloodtorrent/repository/UsersRepositoryTest.java
@@ -1,33 +1,28 @@
package org.bloodtorrent.repository;
import com.yammer.dropwizard.db.DatabaseConfiguration;
import com.yammer.dropwizard.hibernate.HibernateBundle;
import org.bloodtorrent.bootstrap.SimpleConfiguration;
import org.bloodtorrent.dto.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import static junit.framework.Assert.fail;
/**
* Created with IntelliJ IDEA.
* User: sds
* Date: 13. 3. 14
* Time: 오후 1:37
* To change this template use File | Settings | File Templates.
*/
public class UsersRepositoryTest {
@Test
public void crateNewDonar(){
}
- @Test
- public void shouldFail() {
- fail();
- }
-
}
| true | false | null | null |
diff --git a/src/main/java/AllTests.java b/src/main/java/AllTests.java
index 6f2e0d0..1356ba3 100644
--- a/src/main/java/AllTests.java
+++ b/src/main/java/AllTests.java
@@ -1,18 +1,19 @@
public class AllTests {
public static void main(String[] args) {
AdvancedPointerAnalysis.main(args);
ArithmeticTests.main(args);
ConditionalTests.main(args);
ConstantTests.main(args);
// IntervalTests is a proper unit test class, it does not require soot
LoopTests.main(args);
OtherTeamTests.main(args);
PointerAnalysisTests.main(args);
SoftDeadlineTests.main(args);
StaticFieldTests.main(args);
TemplateTests.main(args);
WideningTests.main(args);
+ ImprecisionTests.main(args);
}
}
diff --git a/src/main/java/Analysis.java b/src/main/java/Analysis.java
index bbf7f50..7b461ed 100644
--- a/src/main/java/Analysis.java
+++ b/src/main/java/Analysis.java
@@ -1,471 +1,482 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import soot.BooleanType;
import soot.IntType;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.BinopExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.ConditionExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.DivExpr;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.MulExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.OrExpr;
import soot.jimple.ParameterRef;
import soot.jimple.RemExpr;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.SubExpr;
import soot.jimple.ThisRef;
import soot.jimple.UshrExpr;
import soot.jimple.XorExpr;
import soot.jimple.internal.JArrayRef;
import soot.jimple.internal.JInstanceFieldRef;
import soot.jimple.internal.JNewArrayExpr;
import soot.jimple.internal.JimpleLocal;
import soot.jimple.toolkits.annotation.logic.Loop;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.LoopNestTree;
import soot.toolkits.scalar.ForwardBranchedFlowAnalysis;
/**
* Computes a fix point of the abstract variable states in an individual method
* using the interval domain.
*
* Besides mapping integer and boolean variables to an interval, it also maps an
* array allocated in the method to an interval, indicating its possible size.
*/
public class Analysis extends ForwardBranchedFlowAnalysis<IntervalPerVar> {
/**
* The maximum number of times that a back-jump statement of any loop in the
* method is allowed be handled by the method
* {@link #flowThrough(IntervalPerVar, Unit, List, List)} before widening
* kicks in.
*/
private static final int LOOP_BACK_JUMP_COUNT_THRESHOLD = 100;
private static final Logger LOG = Logger.getLogger(Analysis.class);
private final Map<NewArrayExpr, Interval> allocationNodeMap;
/**
* Keeps track of how many times the back-jump statement of any loop in the
* method was handled in the
* {@link #flowThrough(IntervalPerVar, Unit, List, List)} method.
*/
private final Map<Stmt, Integer> loopBackJumpCountMap;
private final LoopNestTree loopNestTree;
public Analysis(SootMethod method) {
super(new BriefUnitGraph(method.retrieveActiveBody()));
allocationNodeMap = new HashMap<NewArrayExpr, Interval>();
loopNestTree = new LoopNestTree(method.retrieveActiveBody());
loopBackJumpCountMap = new HashMap<Stmt, Integer>();
// Set the counter for every back-jump statement to zero
for (Loop loop : loopNestTree) {
loopBackJumpCountMap.put(loop.getBackJumpStmt(), 0);
}
LOG.debug(getGraph().toString());
}
protected DirectedGraph<Unit> getGraph() {
return graph;
}
protected LoopNestTree getLoopNestTree() {
return loopNestTree;
}
void run() {
doAnalysis();
}
/**
* Returns the first potentially unsafe statement in the method associated
* with this {@link Analysis}, or <code>null</code> if there is no unsafe
* statement.
*
* @param context
* may contain additional array size intervals that the analysis
* itself cannot determine, i.e., because it requires a points-to
* analysis
* @return the first unsafe statement or <code>null</code> if there is none
*/
Stmt getFirstUnsafeStatement(IntervalPerVar context) {
for (Unit unit : getGraph()) {
Stmt stmt = (Stmt) unit;
if (stmt instanceof DefinitionStmt) {
DefinitionStmt defStmt = (DefinitionStmt) stmt;
Value left = defStmt.getLeftOp();
Value right = defStmt.getRightOp();
IntervalPerVar intervalPerVar = getFlowBefore(unit);
if (intervalPerVar.isInDeadCode()) {
continue;
}
IntervalPerVar merged = new IntervalPerVar();
merged.mergeFrom(intervalPerVar, context);
if (!merged.isSafe(left) || !merged.isSafe(right)) {
return stmt;
}
}
}
return null;
}
/**
* Stops the analysis because it cannot or does not need to handle a certain
* feature.
*
* @param what
* a description of the feature not handled
*/
static void unhandled(String what) {
LOG.error("Can't handle " + what);
System.exit(1); // TODO: is System.exit(1) a good idea for code that we
// want to unit-test?
}
@Override
protected void flowThrough(IntervalPerVar current, Unit op,
List<IntervalPerVar> fallOut, List<IntervalPerVar> branchOuts) {
LOG.debug(op.getClass().getName() + ": " + op);
Stmt stmt = (Stmt) op;
IntervalPerVar fallState = new IntervalPerVar();
fallState.copyFrom(current);
IntervalPerVar branchState = new IntervalPerVar();
branchState.copyFrom(current);
if (stmt instanceof DefinitionStmt) {
DefinitionStmt defStmt = (DefinitionStmt) stmt;
Value left = defStmt.getLeftOp();
Value right = defStmt.getRightOp();
LOG.debug("\tLeft: " + left.getClass().getName());
LOG.debug("\tRight: " + right.getClass().getName());
// Only handle cases where the left value is either a
// StaticFieldRef, JimpleLoca, JArrayRef or JInstanceFieldRef
if ((!(left instanceof StaticFieldRef))
&& (!(left instanceof JimpleLocal))
&& (!(left instanceof JArrayRef))
&& (!(left instanceof JInstanceFieldRef))) {
unhandled("assignment to non-variables is not handled.");
} else if ((left instanceof JArrayRef)
&& (!((((JArrayRef) left).getBase()) instanceof JimpleLocal))) {
unhandled("assignment to a non-local array variable is not handled.");
}
if (left instanceof JimpleLocal) {
String varName = ((JimpleLocal) left).getName();
Interval newInterval = null;
if (right instanceof IntConstant
|| right instanceof JimpleLocal
|| right instanceof LengthExpr) {
Interval interval = current.tryGetIntervalForValue(right);
fallState.putIntervalForVar(varName, interval);
} else if (right instanceof BinopExpr) {
Value firstValue = ((BinopExpr) right).getOp1();
Value secondValue = ((BinopExpr) right).getOp2();
Interval first = current.tryGetIntervalForValue(firstValue);
Interval second = current
.tryGetIntervalForValue(secondValue);
if (first != null && second != null) {
if (right instanceof AddExpr) {
newInterval = Interval.plus(first, second);
} else if (right instanceof SubExpr) {
newInterval = Interval.sub(first, second);
} else if (right instanceof MulExpr) {
newInterval = Interval.mul(first, second);
} else if (right instanceof DivExpr) {
newInterval = Interval.div(first, second);
} else if (right instanceof RemExpr) {
newInterval = Interval.rem(first, second);
} else if (right instanceof ShlExpr) {
newInterval = Interval.shl(first, second);
} else if (right instanceof ShrExpr) {
newInterval = Interval.shr(first, second);
} else if (right instanceof UshrExpr) {
newInterval = Interval.ushr(first, second);
} else if (right instanceof AndExpr) {
newInterval = Interval.and(first, second);
} else if (right instanceof OrExpr) {
newInterval = Interval.or(first, second);
} else if (right instanceof XorExpr) {
newInterval = Interval.xor(first, second);
} else {
LOG.warn("loss of precision due to unsupported binary expression of type "
+ right.getClass().getName());
if (first.isBottom() || second.isBottom()) {
newInterval = Interval.BOTTOM;
} else {
newInterval = Interval.TOP;
}
}
}
} else if (right instanceof NegExpr) {
NegExpr negExpr = (NegExpr) right;
Value value = negExpr.getOp();
newInterval = Interval.neg(current
.tryGetIntervalForValue(value));
} else if (right instanceof NewArrayExpr) {
// This statement allocates a new array
// Store the array size interval in the state
NewArrayExpr newArrayExpr = (JNewArrayExpr) right;
Value size = newArrayExpr.getSize();
newInterval = current.tryGetIntervalForValue(size);
// Also associate allocation site with size interval
// for use from other methods (via pointer-analysis)
getAllocationNodeMap().put(newArrayExpr, newInterval);
} else if (right instanceof InstanceFieldRef) {
InstanceFieldRef instFieldRef = (InstanceFieldRef) right;
if (isBooleanOrIntType(instFieldRef.getType())) {
newInterval = Interval.TOP;
}
} else if (right instanceof StaticFieldRef) {
StaticFieldRef staticFieldRef = (StaticFieldRef) right;
if (isBooleanOrIntType(staticFieldRef.getType())) {
newInterval = Interval.TOP;
}
} else if (right instanceof JArrayRef) {
JArrayRef arrayRef = (JArrayRef) right;
if (isBooleanOrIntType(arrayRef.getType())) {
newInterval = Interval.TOP;
}
} else if (right instanceof NewExpr) {
// Do nothing
} else if (right instanceof InvokeExpr) {
// When calling a method that returns an integer, assume
// that the return value could be anything
InvokeExpr invokeExpr = (InvokeExpr) right;
SootMethod method = invokeExpr.getMethod();
if (isBooleanOrIntType(method.getReturnType())) {
newInterval = Interval.TOP;
}
} else if (right instanceof ParameterRef) {
ParameterRef parameterRef = (ParameterRef) right;
Type parameterType = parameterRef.getType();
if (isBooleanOrIntType(parameterType)) {
newInterval = Interval.TOP;
} else {
// Do nothing
}
} else if (right instanceof ThisRef) {
// nothing to do
} else if (right instanceof CaughtExceptionRef) {
// nothing to do
} else if (right instanceof ClassConstant) {
// a reference to a class object, not relevant for us
} else {
if (isBooleanOrIntType(left.getType())) {
LOG.warn("cannot handle right-hand side of assignment of type "
+ right.getClass().getName()
+ ", assuming TOP to be on the safe side");
newInterval = Interval.TOP;
}
}
if (newInterval != null) {
Interval oldInterval = fallState.getIntervalForVar(varName);
fallState.putIntervalForVar(varName, newInterval);
LOG.debug("\t" + varName + ": " + oldInterval + " -> "
+ newInterval);
}
} else if (left instanceof JArrayRef) {
// Do nothing
// The array access is relevant at the end of the analysis
} else if (left instanceof StaticFieldRef
|| left instanceof InstanceFieldRef) {
// Do nothing
} else {
// This branch will never be taken due to the earlier check
// regarding the type of 'left'
unhandled("left-hand side of assignment");
}
} else if (op instanceof IfStmt) {
IfStmt ifStmt = (IfStmt) op;
Value condition = ifStmt.getCondition();
LOG.debug("\tCondition: " + condition.getClass().getName());
if (condition instanceof ConditionExpr) {
ConditionExpr conditionExpr = (ConditionExpr) condition;
ConditionExprEnum conditionExprEnum = ConditionExprEnum
.fromConditionExprClass(conditionExpr.getClass());
Value left = conditionExpr.getOp1();
Value right = conditionExpr.getOp2();
Interval leftInterval = current.tryGetIntervalForValue(left);
Interval rightInterval = current.tryGetIntervalForValue(right);
LOG.debug("\tLeft Interval: " + leftInterval);
LOG.debug("\tRight Interval: " + rightInterval);
// The constrained interval of the left value when the condition
// holds. It is Interval.BOTTOM if the left value cannot
// possibly satisfy the condition
Interval leftBranchInterval = Interval.cond(leftInterval,
rightInterval, conditionExprEnum);
// The constrained interval of the left value when the condition
// does not hold. It is Interval.BOTTOM if the left value
// certainly satisfies the condition
Interval leftFallInterval = Interval.cond(leftInterval,
rightInterval, conditionExprEnum.getNegation());
// The constrained interval of the right value when the
// condition holds. It is Interval.BOTTOM if the right value
// cannot possibly satisfy the condition
Interval rightBranchInterval = Interval.cond(rightInterval,
leftInterval, conditionExprEnum.getSwapped());
// The constrained interval of the right value when the
// condition does not hold. It is Interval.BOTTOM if the right
// value certainly satisfies the condition
Interval rightFallInterval = Interval.cond(rightInterval,
leftInterval, conditionExprEnum.getSwapped()
.getNegation());
if (leftBranchInterval.isBottom()
&& rightBranchInterval.isBottom()) {
// If no values of the left and right intervals can satisfy
// the condition, mark the branch state as dead
// TODO: Replace this by a disjunction?
branchState.setInDeadCode();
} else if (leftFallInterval.isBottom()
&& rightFallInterval.isBottom()) {
// If no values of the left and right intervals can satisfy
// the negation of the condition, mark the fall through
// state as dead
// TODO: Replace this by disjunction?
fallState.setInDeadCode();
}
if (left instanceof JimpleLocal) {
JimpleLocal leftLocal = (JimpleLocal) left;
String varName = leftLocal.getName();
LOG.debug("\tLeft Branch Interval: "
+ branchState.getIntervalForVar(varName) + " -> "
+ leftBranchInterval);
LOG.debug("\tLeft Fall Interval: "
+ fallState.getIntervalForVar(varName) + " -> "
+ leftFallInterval);
branchState.putIntervalForVar(varName, leftBranchInterval);
fallState.putIntervalForVar(varName, leftFallInterval);
}
if (right instanceof JimpleLocal) {
JimpleLocal rightLocal = (JimpleLocal) right;
String varName = rightLocal.getName();
LOG.debug("\tRight Branch Interval: "
+ branchState.getIntervalForVar(varName) + " -> "
+ rightBranchInterval);
LOG.debug("\tRight Fall Interval: "
+ fallState.getIntervalForVar(varName) + " -> "
+ rightFallInterval);
branchState.putIntervalForVar(varName, rightBranchInterval);
fallState.putIntervalForVar(varName, rightFallInterval);
}
} else {
unhandled("condition");
}
}
// If the statement under inspection is a back-jump statement of a loop,
// apply widening if it has already been handled at least
// LOOP_BACK_JUMP_COUNT_THRESHOLD times.
boolean isWideningNeeded = false;
if (loopBackJumpCountMap.containsKey(stmt)) {
int newCount = loopBackJumpCountMap.get(stmt) + 1;
loopBackJumpCountMap.put(stmt, newCount);
if (newCount > LOOP_BACK_JUMP_COUNT_THRESHOLD) {
isWideningNeeded = true;
+
+ // When there are nested loop and the threshold has been
+ // reached in the case of the inner loop, the intervals
+ // of the inner loop may change when the symbolic execution
+ // moves on to the second element of the outer loop.
+ // Because the threshold of the inner loop is still reached,
+ // another widening is performed, which accidentally affects
+ // the outer loop as well, even though the execution has only
+ // reached its second element.
+ // As a simple measure, reset the counter back to zero.
+ loopBackJumpCountMap.put(stmt, 0);
}
}
for (IntervalPerVar fnext : fallOut) {
if (fallState != null) {
if (isWideningNeeded) {
fnext.copyAndWidenFrom(fallState);
} else {
fnext.copyFrom(fallState);
}
}
}
for (IntervalPerVar fnext : branchOuts) {
if (branchState != null) {
if (isWideningNeeded) {
fnext.copyAndWidenFrom(branchState);
} else {
fnext.copyFrom(branchState);
}
}
}
}
@Override
protected void copy(IntervalPerVar source, IntervalPerVar target) {
target.copyFrom(source);
}
@Override
protected IntervalPerVar entryInitialFlow() {
// TODO: How do you model the entry point?
return new IntervalPerVar();
}
@Override
protected void merge(IntervalPerVar firstSource,
IntervalPerVar secondSource, IntervalPerVar target) {
target.mergeFrom(firstSource, secondSource);
LOG.debug("Merge:");
LOG.debug("\tSource: " + firstSource);
LOG.debug("\tSource: " + secondSource);
LOG.debug("\tResult: " + target);
}
@Override
protected IntervalPerVar newInitialFlow() {
return new IntervalPerVar();
}
public Map<NewArrayExpr, Interval> getAllocationNodeMap() {
return allocationNodeMap;
}
protected boolean isBooleanOrIntType(Type type) {
// TODO: In the case of booleans, one might also return [0, 1] rather
// than Interval.TOP.
return type.equals(IntType.v()) || type.equals(BooleanType.v());
}
}
| false | false | null | null |
diff --git a/src/com/android/browser/NavScreen.java b/src/com/android/browser/NavScreen.java
index 1d2114e0..5df64ded 100644
--- a/src/com/android/browser/NavScreen.java
+++ b/src/com/android/browser/NavScreen.java
@@ -1,265 +1,267 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.browser.NavTabScroller.OnLayoutListener;
import com.android.browser.NavTabScroller.OnRemoveListener;
import com.android.browser.TabControl.OnThumbnailUpdatedListener;
import com.android.browser.UI.ComboViews;
import java.util.HashMap;
public class NavScreen extends RelativeLayout
implements OnClickListener, OnMenuItemClickListener, OnThumbnailUpdatedListener {
UiController mUiController;
PhoneUi mUi;
Tab mTab;
Activity mActivity;
ImageButton mRefresh;
ImageButton mForward;
ImageButton mBookmarks;
ImageButton mMore;
ImageButton mNewTab;
FrameLayout mHolder;
TextView mTitle;
ImageView mFavicon;
ImageButton mCloseTab;
NavTabScroller mScroller;
TabAdapter mAdapter;
int mOrientation;
boolean mNeedsMenu;
HashMap<Tab, View> mTabViews;
public NavScreen(Activity activity, UiController ctl, PhoneUi ui) {
super(activity);
mActivity = activity;
mUiController = ctl;
mUi = ui;
mOrientation = activity.getResources().getConfiguration().orientation;
init();
}
protected void showMenu() {
PopupMenu popup = new PopupMenu(mContext, mMore);
Menu menu = popup.getMenu();
popup.getMenuInflater().inflate(R.menu.browser, menu);
mUiController.updateMenuState(mUiController.getCurrentTab(), menu);
popup.setOnMenuItemClickListener(this);
popup.show();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
return mUiController.onOptionsItemSelected(item);
}
protected float getToolbarHeight() {
return mActivity.getResources().getDimension(R.dimen.toolbar_height);
}
@Override
protected void onConfigurationChanged(Configuration newconfig) {
if (newconfig.orientation != mOrientation) {
int sv = mScroller.getScrollValue();
removeAllViews();
mOrientation = newconfig.orientation;
init();
mScroller.setScrollValue(sv);
mAdapter.notifyDataSetChanged();
}
}
public void refreshAdapter() {
mScroller.handleDataChanged(
mUiController.getTabControl().getTabPosition(mUi.getActiveTab()));
}
private void init() {
LayoutInflater.from(mContext).inflate(R.layout.nav_screen, this);
setContentDescription(mContext.getResources().getString(
R.string.accessibility_transition_navscreen));
mBookmarks = (ImageButton) findViewById(R.id.bookmarks);
mNewTab = (ImageButton) findViewById(R.id.newtab);
mMore = (ImageButton) findViewById(R.id.more);
mBookmarks.setOnClickListener(this);
mNewTab.setOnClickListener(this);
mMore.setOnClickListener(this);
mScroller = (NavTabScroller) findViewById(R.id.scroller);
TabControl tc = mUiController.getTabControl();
mTabViews = new HashMap<Tab, View>(tc.getTabCount());
mAdapter = new TabAdapter(mContext, tc);
mScroller.setOrientation(mOrientation == Configuration.ORIENTATION_LANDSCAPE
? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL);
// update state for active tab
mScroller.setAdapter(mAdapter,
mUiController.getTabControl().getTabPosition(mUi.getActiveTab()));
mScroller.setOnRemoveListener(new OnRemoveListener() {
public void onRemovePosition(int pos) {
Tab tab = mAdapter.getItem(pos);
onCloseTab(tab);
}
});
mNeedsMenu = !ViewConfiguration.get(getContext()).hasPermanentMenuKey();
if (!mNeedsMenu) {
mMore.setVisibility(View.GONE);
}
}
@Override
public void onClick(View v) {
if (mBookmarks == v) {
mUiController.bookmarksOrHistoryPicker(ComboViews.Bookmarks);
} else if (mNewTab == v) {
openNewTab();
} else if (mMore == v) {
showMenu();
}
}
private void onCloseTab(Tab tab) {
if (tab != null) {
if (tab == mUiController.getCurrentTab()) {
mUiController.closeCurrentTab();
} else {
mUiController.closeTab(tab);
}
+ mTabViews.remove(tab);
}
}
private void openNewTab() {
// need to call openTab explicitely with setactive false
final Tab tab = mUiController.openTab(BrowserSettings.getInstance().getHomePage(),
false, false, false);
if (tab != null) {
mUiController.setBlockEvents(true);
final int tix = mUi.mTabControl.getTabPosition(tab);
mScroller.setOnLayoutListener(new OnLayoutListener() {
@Override
public void onLayout(int l, int t, int r, int b) {
mUi.hideNavScreen(tix, true);
switchToTab(tab);
}
});
mScroller.handleDataChanged(tix);
mUiController.setBlockEvents(false);
}
}
private void switchToTab(Tab tab) {
if (tab != mUi.getActiveTab()) {
mUiController.setActiveTab(tab);
}
}
protected void close(int position) {
close(position, true);
}
protected void close(int position, boolean animate) {
mUi.hideNavScreen(position, animate);
}
protected NavTabView getTabView(int pos) {
return mScroller.getTabView(pos);
}
class TabAdapter extends BaseAdapter {
Context context;
TabControl tabControl;
public TabAdapter(Context ctx, TabControl tc) {
context = ctx;
tabControl = tc;
}
@Override
public int getCount() {
return tabControl.getTabCount();
}
@Override
public Tab getItem(int position) {
return tabControl.getTab(position);
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final NavTabView tabview = new NavTabView(mActivity);
final Tab tab = getItem(position);
tabview.setWebView(tab);
mTabViews.put(tab, tabview.mImage);
tabview.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (tabview.isClose(v)) {
mScroller.animateOut(tabview);
+ mTabViews.remove(tab);
} else if (tabview.isTitle(v)) {
switchToTab(tab);
mUi.getTitleBar().setSkipTitleBarAnimations(true);
close(position, false);
mUi.editUrl(false, true);
mUi.getTitleBar().setSkipTitleBarAnimations(false);
} else if (tabview.isWebView(v)) {
close(position);
}
}
});
return tabview;
}
}
@Override
public void onThumbnailUpdated(Tab t) {
View v = mTabViews.get(t);
if (v != null) {
v.invalidate();
}
}
}
| false | false | null | null |
diff --git a/src/net/sf/gogui/utils/StringUtils.java b/src/net/sf/gogui/utils/StringUtils.java
index 98351232..63679916 100644
--- a/src/net/sf/gogui/utils/StringUtils.java
+++ b/src/net/sf/gogui/utils/StringUtils.java
@@ -1,165 +1,168 @@
//----------------------------------------------------------------------------
// $Id$
// $Source$
//----------------------------------------------------------------------------
package net.sf.gogui.utils;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.ArrayList;
//----------------------------------------------------------------------------
/** Static utility functions related to strings. */
public final class StringUtils
{
/** Capitalize the first word and trim whitespaces. */
public static String capitalize(String message)
{
message = message.trim();
if (message.equals(""))
return message;
StringBuffer buffer = new StringBuffer(message);
char first = buffer.charAt(0);
if (! Character.isUpperCase(first))
buffer.setCharAt(0, Character.toUpperCase(first));
return buffer.toString();
}
public static String getDate()
{
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.FULL,
DateFormat.FULL);
Date date = Calendar.getInstance().getTime();
return format.format(date);
}
public static String getDateShort()
{
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT);
Date date = Calendar.getInstance().getTime();
return format.format(date);
}
/** Get default encoding of OutputStreamWriter. */
public static String getDefaultEncoding()
{
// Haven't found another way than constructing one (Java 1.4)
OutputStreamWriter out =
new OutputStreamWriter(new ByteArrayOutputStream());
return out.getEncoding();
}
+ /** Return a number formatter with maximum fraction digits,
+ no grouping, locale ENGLISH.
+ */
public static NumberFormat getNumberFormat(int maximumFractionDigits)
{
- NumberFormat format = NumberFormat.getInstance(new Locale("C"));
+ NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
format.setMaximumFractionDigits(maximumFractionDigits);
format.setGroupingUsed(false);
return format;
}
/** Print exception to standard error.
Prints the class name and message to standard error.
For exceptions of type Error or RuntimeException, a stack trace
is printed in addition.
@return A slightly differently formatted error message
for display in an error dialog.
*/
public static String printException(Throwable exception)
{
String message = exception.getMessage();
boolean hasMessage = (message != null && ! message.trim().equals(""));
String className = exception.getClass().getName();
boolean isSevere = (exception instanceof RuntimeException
|| exception instanceof Error);
String result;
if (exception instanceof ErrorMessage)
result = message;
else if (hasMessage)
result = className + ":\n" + message;
else
result = className;
System.err.println(result);
if (isSevere)
exception.printStackTrace();
return result;
}
/** Split string into tokens. */
public static String[] split(String s, char separator)
{
int count = 1;
int pos = -1;
while ((pos = s.indexOf(separator, pos + 1)) >= 0)
++count;
String result[] = new String[count];
pos = 0;
int newPos;
int i = 0;
while ((newPos = s.indexOf(separator, pos)) >= 0)
{
result[i] = s.substring(pos, newPos);
++i;
pos = newPos + 1;
}
result[i] = s.substring(pos);
return result;
}
/** Split command line into arguments.
Allows " for words containing whitespaces.
*/
public static String[] splitArguments(String string)
{
assert(string != null);
ArrayList vector = new ArrayList();
boolean escape = false;
boolean inString = false;
StringBuffer token = new StringBuffer();
for (int i = 0; i < string.length(); ++i)
{
char c = string.charAt(i);
if (c == '"' && ! escape)
{
if (inString)
{
vector.add(token.toString());
token = new StringBuffer();
}
inString = ! inString;
}
else if (Character.isWhitespace(c) && ! inString)
{
if (token.length() > 0)
{
vector.add(token.toString());
token = new StringBuffer();
}
}
else
token.append(c);
escape = (c == '\\' && ! escape);
}
if (token.length() > 0)
vector.add(token.toString());
int size = vector.size();
String result[] = new String[size];
for (int i = 0; i < size; ++i)
result[i] = (String)vector.get(i);
return result;
}
/** Make constructor unavailable; class is for namespace only. */
private StringUtils()
{
}
}
//----------------------------------------------------------------------------
diff --git a/test/junit/src/net/sf/gogui/utils/StringUtilsTest.java b/test/junit/src/net/sf/gogui/utils/StringUtilsTest.java
index 2e8f66be..513c089a 100644
--- a/test/junit/src/net/sf/gogui/utils/StringUtilsTest.java
+++ b/test/junit/src/net/sf/gogui/utils/StringUtilsTest.java
@@ -1,53 +1,71 @@
//----------------------------------------------------------------------------
// $Id$
// $Source$
//----------------------------------------------------------------------------
package net.sf.gogui.utils;
+import java.text.NumberFormat;
+import java.util.Locale;
+
//----------------------------------------------------------------------------
public class StringUtilsTest
extends junit.framework.TestCase
{
public static void main(String args[])
{
junit.textui.TestRunner.run(suite());
}
public static junit.framework.Test suite()
{
return new junit.framework.TestSuite(StringUtilsTest.class);
}
+ public void testGetNumberFormatLocale()
+ {
+ Locale oldDefault = Locale.getDefault();
+ try
+ {
+ Locale.setDefault(Locale.FRENCH);
+ NumberFormat format = StringUtils.getNumberFormat(1);
+ assertEquals("3.1", format.format(3.1));
+ }
+ finally
+ {
+ Locale.setDefault(oldDefault);
+ }
+ }
+
public void testSplit()
{
String[] s = StringUtils.split("1//23/ ", '/');
assertEquals(s.length, 4);
assertEquals(s[0], "1");
assertEquals(s[1], "");
assertEquals(s[2], "23");
assertEquals(s[3], " ");
}
public void testSplitArguments1()
{
String[] s
= StringUtils.splitArguments("one two \"three four\"");
assertEquals(3, s.length);
assertEquals("one", s[0]);
assertEquals("two", s[1]);
assertEquals("three four", s[2]);
}
public void testSplitArguments2()
{
String[] s
= StringUtils.splitArguments("one \"two \\\"three four\\\"\"");
assertEquals(2, s.length);
assertEquals("one", s[0]);
assertEquals("two \\\"three four\\\"", s[1]);
}
}
//----------------------------------------------------------------------------
| false | false | null | null |
diff --git a/src/main/java/servlet/TestLampServlet.java b/src/main/java/servlet/TestLampServlet.java
index c66296c..a86f3f9 100644
--- a/src/main/java/servlet/TestLampServlet.java
+++ b/src/main/java/servlet/TestLampServlet.java
@@ -1,99 +1,99 @@
package main.java.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
public class TestLampServlet extends HttpServlet {
// Database Connection
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
private static String convertIntToStatus(int data_value_int) {
// Convert int to string
String status_str = "on";
if (data_value_int == 0) {
status_str = "off";
}
return status_str;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT data_value FROM test_lamp ORDER BY time DESC LIMIT 1");
rs.next();
request.setAttribute("data_value", rs.getInt(1) );
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-get.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data_value_str = (String)request.getParameter("data_value");
data_value_str = data_value_str.toLowerCase();
// Convert string to corresponding int 0-off 1-on
int data_value_int;
if (data_value_str == "off") {
data_value_int = 0;
}
else {
data_value_int = 1;
}
try {
Connection connection = getConnection();
// Insert latest test lamp change
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO test_lamp VALUES ('" + data_value_int + "', now())");
// Return the latest status of the test lamp
- ResultSet rs = stmt.executeUpdate("SELECT data_value FROM test_lamp ORDER BY DESC LIMIT 1");
+ ResultSet rs = stmt.executeQuery("SELECT data_value FROM test_lamp ORDER BY DESC LIMIT 1");
rs.next();
// Convert int to string
String lampStatus_str = convertIntToStatus(re.getInt(1));
request.setAttribute("lampStatus", lampStatus_str);
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response);
}
};
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data_value_str = (String)request.getParameter("data_value");
data_value_str = data_value_str.toLowerCase();
// Convert string to corresponding int 0-off 1-on
int data_value_int;
if (data_value_str == "off") {
data_value_int = 0;
}
else {
data_value_int = 1;
}
try {
Connection connection = getConnection();
// Insert latest test lamp change
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO test_lamp VALUES ('" + data_value_int + "', now())");
// Return the latest status of the test lamp
ResultSet rs = stmt.executeUpdate("SELECT data_value FROM test_lamp ORDER BY DESC LIMIT 1");
rs.next();
// Convert int to string
String lampStatus_str = convertIntToStatus(re.getInt(1));
request.setAttribute("lampStatus", lampStatus_str);
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response);
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data_value_str = (String)request.getParameter("data_value");
data_value_str = data_value_str.toLowerCase();
// Convert string to corresponding int 0-off 1-on
int data_value_int;
if (data_value_str == "off") {
data_value_int = 0;
}
else {
data_value_int = 1;
}
try {
Connection connection = getConnection();
// Insert latest test lamp change
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO test_lamp VALUES ('" + data_value_int + "', now())");
// Return the latest status of the test lamp
ResultSet rs = stmt.executeQuery("SELECT data_value FROM test_lamp ORDER BY DESC LIMIT 1");
rs.next();
// Convert int to string
String lampStatus_str = convertIntToStatus(re.getInt(1));
request.setAttribute("lampStatus", lampStatus_str);
}
catch (SQLException e) {
request.setAttribute("SQLException", e.getMessage());
}
catch (URISyntaxException e) {
request.setAttribute("URISyntaxException", e.getMessage());
}
request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response);
}
|
diff --git a/src/com/android/email/activity/MoveMessageToDialog.java b/src/com/android/email/activity/MoveMessageToDialog.java
index 5a6c0677..dbdf2b4b 100644
--- a/src/com/android/email/activity/MoveMessageToDialog.java
+++ b/src/com/android/email/activity/MoveMessageToDialog.java
@@ -1,286 +1,283 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.activity;
import com.android.email.R;
import com.android.email.Utility;
import com.android.email.provider.EmailContent.Account;
import com.android.email.provider.EmailContent.Mailbox;
import com.android.email.provider.EmailContent.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import java.security.InvalidParameterException;
/**
* "Move (messages) to" dialog.
*
* TODO The check logic in MessageCheckerCallback is not efficient. It shouldn't restore full
* Message objects. But we don't bother at this point as the UI is still temporary.
*/
public class MoveMessageToDialog extends DialogFragment implements DialogInterface.OnClickListener {
private static final String BUNDLE_MESSAGE_IDS = "message_ids";
/** Message IDs passed to {@link #newInstance} */
private long[] mMessageIds;
private MailboxesAdapter mAdapter;
/** Account ID is restored by {@link MailboxesLoaderCallbacks} */
private long mAccountId;
private boolean mDestroyed;
/**
* Callback that target fragments, or the owner activity should implement.
*/
public interface Callback {
public void onMoveToMailboxSelected(long newMailboxId, long[] messageIds);
}
/**
* Create and return a new instance.
*
* @param parent owner activity.
* @param messageIds IDs of the messages to be moved.
* @param callbackFragment Fragment that gets a callback. The fragment must implement
* {@link Callback}. If null is passed, then the owner activity is used instead, in which case
* it must implement {@link Callback} instead.
*/
public static MoveMessageToDialog newInstance(Activity parent,
long[] messageIds, Fragment callbackFragment) {
if (messageIds.length == 0) {
throw new InvalidParameterException();
}
MoveMessageToDialog dialog = new MoveMessageToDialog();
Bundle args = new Bundle();
args.putLongArray(BUNDLE_MESSAGE_IDS, messageIds);
dialog.setArguments(args);
if (callbackFragment != null) {
dialog.setTargetFragment(callbackFragment, 0);
}
return dialog;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMessageIds = getArguments().getLongArray(BUNDLE_MESSAGE_IDS);
setStyle(STYLE_NORMAL, android.R.style.Theme_Holo_Light);
}
@Override
public void onDestroy() {
- LoaderManager lm = getActivity().getLoaderManager();
- lm.destroyLoader(ActivityHelper.GLOBAL_LOADER_ID_MOVE_TO_DIALOG_MESSAGE_CHECKER);
- lm.destroyLoader(ActivityHelper.GLOBAL_LOADER_ID_MOVE_TO_DIALOG_MAILBOX_LOADER);
mDestroyed = true;
super.onDestroy();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Activity activity = getActivity();
// Build adapter & dialog
// Make sure to pass Builder's context to the adapter, so that it'll get the correct theme.
AlertDialog.Builder builder = new AlertDialog.Builder(activity)
.setTitle(activity.getResources().getString(R.string.move_to_folder_dialog_title));
mAdapter =
new MailboxesAdapter(builder.getContext(), MailboxesAdapter.MODE_MOVE_TO_TARGET,
new MailboxesAdapter.EmptyCallback());
builder.setSingleChoiceItems(mAdapter, -1, this);
- activity.getLoaderManager().initLoader(
+ getLoaderManager().initLoader(
ActivityHelper.GLOBAL_LOADER_ID_MOVE_TO_DIALOG_MESSAGE_CHECKER,
null, new MessageCheckerCallback());
return builder.show();
}
@Override
public void onClick(DialogInterface dialog, int position) {
final long mailboxId = mAdapter.getItemId(position);
getCallback().onMoveToMailboxSelected(mailboxId, mMessageIds);
dismiss();
}
private Callback getCallback() {
Fragment targetFragment = getTargetFragment();
if (targetFragment != null) {
// If a target is set, it MUST implement Callback.
return (Callback) targetFragment;
}
// If not the parent activity MUST implement Callback.
return (Callback) getActivity();
}
/**
* Delay-call {@link #dismiss()} using a {@link Handler}. Calling {@link #dismiss()} from
* {@link LoaderManager.LoaderCallbacks#onLoadFinished} is not allowed, so we use it instead.
*/
private void dismissAsync() {
new Handler().post(new Runnable() {
@Override
public void run() {
if (!mDestroyed) {
dismiss();
}
}
});
}
/**
* Loader callback for {@link MessageChecker}
*/
private class MessageCheckerCallback implements LoaderManager.LoaderCallbacks<Long> {
@Override
public Loader<Long> onCreateLoader(int id, Bundle args) {
return new MessageChecker(getActivity(), mMessageIds);
}
@Override
public void onLoadFinished(Loader<Long> loader, Long accountId) {
if (mDestroyed) {
return;
}
// accountId shouldn't be null, but I'm paranoia.
if ((accountId == null) || (accountId == -1)) {
// Some of the messages can't be moved. Close the dialog.
dismissAsync();
return;
}
mAccountId = accountId;
- getActivity().getLoaderManager().initLoader(
+ getLoaderManager().initLoader(
ActivityHelper.GLOBAL_LOADER_ID_MOVE_TO_DIALOG_MAILBOX_LOADER,
null, new MailboxesLoaderCallbacks());
}
@Override
public void onLoaderReset(Loader<Long> loader) {
}
}
/**
* Loader callback for destination mailbox list.
*/
private class MailboxesLoaderCallbacks implements LoaderManager.LoaderCallbacks<Cursor> {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return MailboxesAdapter.createLoader(getActivity().getApplicationContext(), mAccountId,
MailboxesAdapter.MODE_MOVE_TO_TARGET);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (mDestroyed) {
return;
}
mAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
/**
* A loader that checks if the messages can be moved, and return the Id of the account that owns
* the messages. (If any of the messages can't be moved, return -1.)
*/
private static class MessageChecker extends AsyncTaskLoader<Long> {
private final Activity mActivity;
private final long[] mMessageIds;
public MessageChecker(Activity activity, long[] messageIds) {
super(activity);
mActivity = activity;
mMessageIds = messageIds;
}
@Override
public Long loadInBackground() {
final Context c = getContext();
long accountId = -1; // -1 == account not found yet.
for (long messageId : mMessageIds) {
// TODO This shouln't restore a full Message object.
final Message message = Message.restoreMessageWithId(c, messageId);
if (message == null) {
continue; // Skip removed messages.
}
// First, check account.
if (accountId == -1) {
// First message -- see if the account supports move.
accountId = message.mAccountKey;
if (!Account.supportsMoveMessages(c, accountId)) {
Utility.showToast(
mActivity, R.string.cannot_move_protocol_not_supported_toast);
return -1L;
}
} else {
// Following messages -- have to belong to the same account
if (message.mAccountKey != accountId) {
Utility.showToast(mActivity, R.string.cannot_move_multiple_accounts_toast);
return -1L;
}
}
// Second, check mailbox.
if (!Mailbox.canMoveFrom(c, message.mMailboxKey)) {
Utility.showToast(mActivity, R.string.cannot_move_special_mailboxes_toast);
return -1L;
}
}
// If all messages have been removed, accountId remains -1, which is what we should
// return here.
return accountId;
}
@Override
protected void onStartLoading() {
cancelLoad();
forceLoad();
}
@Override
protected void onStopLoading() {
cancelLoad();
}
@Override
protected void onReset() {
stopLoading();
}
}
}
| false | false | null | null |
diff --git a/src/main/java/de/tuberlin/dima/presslufthammer/data/ondisk/OnDiskDataStore.java b/src/main/java/de/tuberlin/dima/presslufthammer/data/ondisk/OnDiskDataStore.java
index e16b332..750a61c 100644
--- a/src/main/java/de/tuberlin/dima/presslufthammer/data/ondisk/OnDiskDataStore.java
+++ b/src/main/java/de/tuberlin/dima/presslufthammer/data/ondisk/OnDiskDataStore.java
@@ -1,144 +1,144 @@
package de.tuberlin.dima.presslufthammer.data.ondisk;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import de.tuberlin.dima.presslufthammer.data.SchemaNode;
import de.tuberlin.dima.presslufthammer.data.columnar.DataStore;
import de.tuberlin.dima.presslufthammer.data.columnar.Tablet;
public class OnDiskDataStore implements DataStore {
private final Logger log = LoggerFactory.getLogger(getClass());
private File rootDirectory;
private Map<TabletKey, OnDiskTablet> tablets;
public OnDiskDataStore(File rootDirectory) {
this.rootDirectory = rootDirectory;
tablets = Maps.newHashMap();
log.info("Opening OnDiskDataStore from " + rootDirectory + ".");
}
public static OnDiskDataStore openDataStore(File directory)
throws IOException {
- if (!directory.exists() && directory.isDirectory()) {
+ if (!directory.exists() || !directory.isDirectory()) {
throw new IOException(
"Directory given in openDataStore does not exist or is not a directory.");
}
OnDiskDataStore store = new OnDiskDataStore(directory);
store.openTablets();
return store;
}
public static void removeDataStore(File directory) throws IOException {
if (directory.exists()) {
FileUtils.deleteDirectory(directory);
}
}
public static OnDiskDataStore createDataStore(File directory)
throws IOException {
if (directory.exists()) {
throw new RuntimeException("Directory for tablet already exists: "
+ directory);
}
OnDiskDataStore store = new OnDiskDataStore(directory);
directory.mkdirs();
return store;
}
private void openTablets() throws IOException {
log.debug("Reading tablets from {}.", rootDirectory);
for (File tabletDir : rootDirectory.listFiles()) {
if (!tabletDir.isDirectory()) {
continue;
}
String dirname = tabletDir.getName();
String[] splitted = dirname.split("\\.");
int partitionNum = Integer.parseInt(splitted[1]);
OnDiskTablet tablet = OnDiskTablet.openTablet(tabletDir);
tablets.put(new TabletKey(tablet.getSchema().getName(), partitionNum), tablet);
log.debug("Opened tablet " + tablet.getSchema().getName() + ":"
+ partitionNum);
}
}
public void flush() throws IOException {
for (OnDiskTablet tablet : tablets.values()) {
log.info("Flushing data of tablet " + tablet.getSchema().getName()
+ ".");
tablet.flush();
}
}
@Override
public boolean hasTablet(String tableName, int partition) {
TabletKey key = new TabletKey(tableName, partition);
return tablets.containsKey(key);
}
@Override
public Tablet createOrGetTablet(SchemaNode schema, int partition) throws IOException {
TabletKey key = new TabletKey(schema.getName(), partition);
if (tablets.containsKey(key)) {
return tablets.get(key);
} else {
File tablePath = new File(rootDirectory, schema.getName() + "."
+ partition);
log.info("Creating new tablet " + schema.getName() + ":" + partition);
OnDiskTablet newTablet = OnDiskTablet.createTablet(schema,
tablePath);
tablets.put(key, newTablet);
return newTablet;
}
}
@Override
public Tablet getTablet(String tableName, int partition) throws IOException {
TabletKey key = new TabletKey(tableName, partition);
if (tablets.containsKey(key)) {
return tablets.get(key);
} else {
return null;
}
}
}
class TabletKey {
private String tableName;
private int partition;
public TabletKey(String tableName, int partition) {
this.tableName = tableName;
this.partition = partition;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof TabletKey)) {
return false;
}
TabletKey oKey = (TabletKey) other;
if (!tableName.equals(oKey.tableName)) {
return false;
}
if (!(partition == oKey.partition)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(tableName, partition);
}
}
diff --git a/src/main/java/de/tuberlin/dima/presslufthammer/transport/Leaf.java b/src/main/java/de/tuberlin/dima/presslufthammer/transport/Leaf.java
index 481d344..bf1754b 100644
--- a/src/main/java/de/tuberlin/dima/presslufthammer/transport/Leaf.java
+++ b/src/main/java/de/tuberlin/dima/presslufthammer/transport/Leaf.java
@@ -1,164 +1,164 @@
package de.tuberlin.dima.presslufthammer.transport;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Set;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
import de.tuberlin.dima.presslufthammer.data.SchemaNode;
import de.tuberlin.dima.presslufthammer.data.columnar.InMemoryWriteonlyTablet;
import de.tuberlin.dima.presslufthammer.data.columnar.Tablet;
import de.tuberlin.dima.presslufthammer.data.ondisk.OnDiskDataStore;
import de.tuberlin.dima.presslufthammer.qexec.TabletCopier;
import de.tuberlin.dima.presslufthammer.query.Projection;
import de.tuberlin.dima.presslufthammer.query.Query;
import de.tuberlin.dima.presslufthammer.transport.messages.SimpleMessage;
import de.tuberlin.dima.presslufthammer.transport.messages.Type;
import de.tuberlin.dima.presslufthammer.util.ShutdownStopper;
import de.tuberlin.dima.presslufthammer.util.Stoppable;
/**
* @author feichh
* @author Aljoscha Krettek
*
*/
public class Leaf extends ChannelNode implements Stoppable {
private static final SimpleMessage REGMSG = new SimpleMessage(Type.REGLEAF,
(byte) 0, "Hello".getBytes());
private static int CONNECT_TIMEOUT = 10000;
private final Logger log = LoggerFactory.getLogger(getClass());
private Channel coordinatorChannel;
private ClientBootstrap bootstrap;
private String serverHost;
private int serverPort;
private OnDiskDataStore dataStore;
public Leaf(String serverHost, int serverPort, File dataDirectory) {
this.serverHost = serverHost;
this.serverPort = serverPort;
try {
dataStore = OnDiskDataStore.openDataStore(dataDirectory);
} catch (IOException e) {
- log.warn("Exception caught while while loading datastore: {}", e
- .getCause().getMessage());
+ log.warn("Exception caught while while loading datastore: {}",
+ e.getMessage());
}
}
public void start() {
ChannelFactory factory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
bootstrap = new ClientBootstrap(factory);
bootstrap.setPipelineFactory(new LeafPipelineFac(this));
bootstrap.setOption("connectTimeoutMillis", CONNECT_TIMEOUT);
SocketAddress address = new InetSocketAddress(serverHost, serverPort);
ChannelFuture connectFuture = bootstrap.connect(address);
if (connectFuture.awaitUninterruptibly().isSuccess()) {
coordinatorChannel = connectFuture.getChannel();
coordinatorChannel.write(REGMSG);
log.info("Connected to coordinator at {}:{}", serverHost,
serverPort);
Runtime.getRuntime().addShutdownHook(new ShutdownStopper(this));
} else {
bootstrap.releaseExternalResources();
log.info("Failed to conncet to coordinator at {}:{}", serverHost,
serverPort);
}
}
@Override
public void query(SimpleMessage message) {
Query query = new Query(message.getPayload());
log.info("Received query: " + query);
String table = query.getFrom();
try {
Tablet tablet = dataStore.getTablet(table, query.getPart());
log.debug("Tablet: {}:{}", tablet.getSchema().getName(),
query.getPart());
Set<String> projectedFields = Sets.newHashSet();
for (Projection project : query.getSelect()) {
projectedFields.add(project.getColumn());
}
SchemaNode projectedSchema = null;
if (projectedFields.contains("*")) {
log.debug("Query is a 'select * ...' query.");
projectedSchema = tablet.getSchema();
} else {
projectedSchema = tablet.getSchema().project(projectedFields);
}
InMemoryWriteonlyTablet resultTablet = new InMemoryWriteonlyTablet(
projectedSchema);
TabletCopier copier = new TabletCopier();
copier.copyTablet(projectedSchema, tablet, resultTablet);
SimpleMessage response = new SimpleMessage(Type.INTERNAL_RESULT,
message.getQueryID(), resultTablet.serialize());
coordinatorChannel.write(response);
} catch (IOException e) {
log.warn("Caught exception while creating result: {}",
e.getMessage());
}
}
public void query(Query query) {
// TODO
log.debug("Query received: " + query);
}
@Override
public void stop() {
log.info("Stopping leaf.");
if (coordinatorChannel != null) {
coordinatorChannel.close().awaitUninterruptibly();
}
bootstrap.releaseExternalResources();
log.info("Leaf stopped.");
}
private static void printUsage() {
System.out.println("Usage:");
System.out.println("hostname port data-dir");
}
public static void main(String[] args) throws InterruptedException {
// Print usage if necessary.
if (args.length < 3) {
printUsage();
return;
}
// Parse options.
String host = args[0];
int port = Integer.parseInt(args[1]);
File dataDirectory = new File(args[2]);
Leaf leaf = new Leaf(host, port, dataDirectory);
leaf.start();
}
}
| false | false | null | null |
diff --git a/src/plugins/WebOfTrust/WebOfTrust.java b/src/plugins/WebOfTrust/WebOfTrust.java
index bdba9bd9..7d745b72 100644
--- a/src/plugins/WebOfTrust/WebOfTrust.java
+++ b/src/plugins/WebOfTrust/WebOfTrust.java
@@ -1,3319 +1,3320 @@
/* This code is part of WoT, a plugin for Freenet. It is distributed
* under the GNU General Public License, version 2 (or at your option
* any later version). See http://www.gnu.org/ for details of the GPL. */
package plugins.WebOfTrust;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Random;
import plugins.WebOfTrust.Identity.FetchState;
import plugins.WebOfTrust.Identity.IdentityID;
import plugins.WebOfTrust.Score.ScoreID;
import plugins.WebOfTrust.Trust.TrustID;
import plugins.WebOfTrust.exceptions.DuplicateIdentityException;
import plugins.WebOfTrust.exceptions.DuplicateScoreException;
import plugins.WebOfTrust.exceptions.DuplicateTrustException;
import plugins.WebOfTrust.exceptions.InvalidParameterException;
import plugins.WebOfTrust.exceptions.NotInTrustTreeException;
import plugins.WebOfTrust.exceptions.NotTrustedException;
import plugins.WebOfTrust.exceptions.UnknownIdentityException;
import plugins.WebOfTrust.introduction.IntroductionClient;
import plugins.WebOfTrust.introduction.IntroductionPuzzle;
import plugins.WebOfTrust.introduction.IntroductionPuzzleStore;
import plugins.WebOfTrust.introduction.IntroductionServer;
import plugins.WebOfTrust.introduction.OwnIntroductionPuzzle;
import plugins.WebOfTrust.ui.fcp.FCPInterface;
import plugins.WebOfTrust.ui.web.WebInterface;
import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.defragment.Defragment;
import com.db4o.defragment.DefragmentConfig;
import com.db4o.ext.ExtObjectContainer;
import com.db4o.query.Query;
import com.db4o.reflect.jdk.JdkReflector;
import freenet.keys.FreenetURI;
import freenet.keys.USK;
import freenet.l10n.BaseL10n;
import freenet.l10n.BaseL10n.LANGUAGE;
import freenet.l10n.PluginL10n;
import freenet.node.RequestClient;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginBaseL10n;
import freenet.pluginmanager.FredPluginFCP;
import freenet.pluginmanager.FredPluginL10n;
import freenet.pluginmanager.FredPluginRealVersioned;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginReplySender;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.CurrentTimeUTC;
import freenet.support.Logger;
import freenet.support.Logger.LogLevel;
import freenet.support.SimpleFieldSet;
import freenet.support.SizeUtil;
import freenet.support.api.Bucket;
import freenet.support.io.FileUtil;
/**
* A web of trust plugin based on Freenet.
*
* @author xor ([email protected]), Julien Cornuwel ([email protected])
*/
public class WebOfTrust implements FredPlugin, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginRealVersioned,
FredPluginL10n, FredPluginBaseL10n {
/* Constants */
public static final boolean FAST_DEBUG_MODE = false;
/** The relative path of the plugin on Freenet's web interface */
public static final String SELF_URI = "/WebOfTrust";
/** Package-private method to allow unit tests to bypass some assert()s */
/**
* The "name" of this web of trust. It is included in the document name of identity URIs. For an example, see the SEED_IDENTITIES
* constant below. The purpose of this constant is to allow anyone to create his own custom web of trust which is completely disconnected
* from the "official" web of trust of the Freenet project. It is also used as the session cookie namespace.
*/
public static final String WOT_NAME = "WebOfTrust";
public static final String DATABASE_FILENAME = WOT_NAME + ".db4o";
public static final int DATABASE_FORMAT_VERSION = 2;
/**
* The official seed identities of the WoT plugin: If a newbie wants to download the whole offficial web of trust, he needs at least one
* trust list from an identity which is well-connected to the web of trust. To prevent newbies from having to add this identity manually,
* the Freenet development team provides a list of seed identities - each of them is one of the developers.
*/
private static final String[] SEED_IDENTITIES = new String[] {
"USK@QeTBVWTwBldfI-lrF~xf0nqFVDdQoSUghT~PvhyJ1NE,OjEywGD063La2H-IihD7iYtZm3rC0BP6UTvvwyF5Zh4,AQACAAE/WebOfTrust/1344", // xor
"USK@z9dv7wqsxIBCiFLW7VijMGXD9Gl-EXAqBAwzQ4aq26s,4Uvc~Fjw3i9toGeQuBkDARUV5mF7OTKoAhqOA9LpNdo,AQACAAE/WebOfTrust/1270", // Toad
"USK@o2~q8EMoBkCNEgzLUL97hLPdddco9ix1oAnEa~VzZtg,X~vTpL2LSyKvwQoYBx~eleI2RF6QzYJpzuenfcKDKBM,AQACAAE/WebOfTrust/9379", // Bombe
// "USK@cI~w2hrvvyUa1E6PhJ9j5cCoG1xmxSooi7Nez4V2Gd4,A3ArC3rrJBHgAJV~LlwY9kgxM8kUR2pVYXbhGFtid78,AQACAAE/WebOfTrust/19", // TheSeeker. Disabled because he is using LCWoT and it does not support identity introduction ATM.
"USK@D3MrAR-AVMqKJRjXnpKW2guW9z1mw5GZ9BB15mYVkVc,xgddjFHx2S~5U6PeFkwqO5V~1gZngFLoM-xaoMKSBI8,AQACAAE/WebOfTrust/4959", // zidel
};
/* References from the node */
/** The node's interface to connect the plugin with the node, needed for retrieval of all other interfaces */
private PluginRespirator mPR;
private static PluginL10n l10n;
/* References from the plugin itself */
/* Database & configuration of the plugin */
private ExtObjectContainer mDB;
private Configuration mConfig;
private IntroductionPuzzleStore mPuzzleStore;
/** Used for exporting identities, identity introductions and introduction puzzles to XML and importing them from XML. */
private XMLTransformer mXMLTransformer;
private RequestClient mRequestClient;
/* Worker objects which actually run the plugin */
/**
* Periodically wakes up and inserts any OwnIdentity which needs to be inserted.
*/
private IdentityInserter mInserter;
/**
* Fetches identities when it is told to do so by the plugin:
* - At startup, all known identities are fetched
* - When a new identity is received from a trust list it is fetched
* - When a new identity is received by the IntrouductionServer it is fetched
* - When an identity is manually added it is also fetched.
* - ...
*/
private IdentityFetcher mFetcher;
/**
* Uploads captchas belonging to our own identities which others can solve to get on the trust list of them. Checks whether someone
* uploaded solutions for them periodically and adds the new identities if a solution is received.
*/
private IntroductionServer mIntroductionServer;
/**
* Downloads captchas which the user can solve to announce his identities on other people's trust lists, provides the interface for
* the UI to obtain the captchas and enter solutions. Uploads the solutions if the UI enters them.
*/
private IntroductionClient mIntroductionClient;
/* Actual data of the WoT */
private boolean mFullScoreComputationNeeded = false;
private boolean mTrustListImportInProgress = false;
/* User interfaces */
private WebInterface mWebInterface;
private FCPInterface mFCPInterface;
/* Statistics */
private int mFullScoreRecomputationCount = 0;
private long mFullScoreRecomputationMilliseconds = 0;
private int mIncrementalScoreRecomputationCount = 0;
private long mIncrementalScoreRecomputationMilliseconds = 0;
/* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */
private static transient volatile boolean logDEBUG = false;
private static transient volatile boolean logMINOR = false;
static {
Logger.registerClass(WebOfTrust.class);
}
public void runPlugin(PluginRespirator myPR) {
try {
Logger.normal(this, "Web Of Trust plugin version " + Version.getMarketingVersion() + " starting up...");
/* Catpcha generation needs headless mode on linux */
System.setProperty("java.awt.headless", "true");
mPR = myPR;
/* TODO: This can be used for clean copies of the database to get rid of corrupted internal db4o structures.
/* We should provide an option on the web interface to run this once during next startup and switch to the cloned database */
// cloneDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME), new File(getUserDataDirectory(), DATABASE_FILENAME + ".clone"));
mDB = openDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME));
mConfig = getOrCreateConfig();
if(mConfig.getDatabaseFormatVersion() > WebOfTrust.DATABASE_FORMAT_VERSION)
throw new RuntimeException("The WoT plugin's database format is newer than the WoT plugin which is being used.");
mPuzzleStore = new IntroductionPuzzleStore(this);
upgradeDB(); // Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher while this is executing.
mXMLTransformer = new XMLTransformer(this);
mRequestClient = new RequestClient() {
public boolean persistent() {
return false;
}
public void removeFrom(ObjectContainer container) {
throw new UnsupportedOperationException();
}
public boolean realTimeFlag() {
return false;
}
};
mInserter = new IdentityInserter(this);
mFetcher = new IdentityFetcher(this, getPluginRespirator());
// We only do this if debug logging is enabled since the integrity verification cannot repair anything anyway,
// if the user does not read his logs there is no need to check the integrity.
// TODO: Do this once every few startups and notify the user in the web ui if errors are found.
if(logDEBUG)
verifyDatabaseIntegrity();
// TODO: Only do this once every few startups once we are certain that score computation does not have any serious bugs.
verifyAndCorrectStoredScores();
// Database is up now, integrity is checked. We can start to actually do stuff
// TODO: This can be used for doing backups. Implement auto backup, maybe once a week or month
//backupDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME + ".backup"));
createSeedIdentities();
Logger.normal(this, "Starting fetches of all identities...");
synchronized(this) {
synchronized(mFetcher) {
for(Identity identity : getAllIdentities()) {
if(shouldFetchIdentity(identity)) {
try {
mFetcher.fetch(identity.getID());
}
catch(Exception e) {
Logger.error(this, "Fetching identity failed!", e);
}
}
}
}
}
mInserter.start();
mIntroductionServer = new IntroductionServer(this, mFetcher);
mIntroductionServer.start();
mIntroductionClient = new IntroductionClient(this);
mIntroductionClient.start();
mWebInterface = new WebInterface(this, SELF_URI);
mFCPInterface = new FCPInterface(this);
Logger.normal(this, "Web Of Trust plugin starting up completed.");
}
catch(RuntimeException e){
Logger.error(this, "Error during startup", e);
/* We call it so the database is properly closed */
terminate();
throw e;
}
}
/**
* Constructor for being used by the node and unit tests. Does not do anything.
*/
public WebOfTrust() {
}
/**
* Constructor which does not generate an IdentityFetcher, IdentityInster, IntroductionPuzzleStore, user interface, etc.
* For use by the unit tests to be able to run WoT without a node.
* @param databaseFilename The filename of the database.
*/
public WebOfTrust(String databaseFilename) {
mDB = openDatabase(new File(databaseFilename));
mConfig = getOrCreateConfig();
if(mConfig.getDatabaseFormatVersion() != WebOfTrust.DATABASE_FORMAT_VERSION)
throw new RuntimeException("Database format version mismatch. Found: " + mConfig.getDatabaseFormatVersion() +
"; expected: " + WebOfTrust.DATABASE_FORMAT_VERSION);
mPuzzleStore = new IntroductionPuzzleStore(this);
mFetcher = new IdentityFetcher(this, null);
}
private File getUserDataDirectory() {
final File wotDirectory = new File(mPR.getNode().getUserDir(), WOT_NAME);
if(!wotDirectory.exists() && !wotDirectory.mkdir())
throw new RuntimeException("Unable to create directory " + wotDirectory);
return wotDirectory;
}
private com.db4o.config.Configuration getNewDatabaseConfiguration() {
com.db4o.config.Configuration cfg = Db4o.newConfiguration();
// Required config options:
cfg.reflectWith(new JdkReflector(getPluginClassLoader()));
// TODO: Optimization: We do explicit activation everywhere. We could change this to 0 and test whether everything still works.
// Ideally, we would benchmark both 0 and 1 and make it configurable.
cfg.activationDepth(1);
cfg.updateDepth(1); // This must not be changed: We only activate(this, 1) before store(this).
Logger.normal(this, "Default activation depth: " + cfg.activationDepth());
cfg.exceptionsOnNotStorable(true);
// The shutdown hook does auto-commit. We do NOT want auto-commit: if a transaction hasn't commit()ed, it's not safe to commit it.
cfg.automaticShutDown(false);
// Performance config options:
cfg.callbacks(false); // We don't use callbacks yet. TODO: Investigate whether we might want to use them
cfg.classActivationDepthConfigurable(false);
// Registration of indices (also performance)
// ATTENTION: Also update cloneDatabase() when adding new classes!
@SuppressWarnings("unchecked")
final Class<? extends Persistent>[] persistentClasses = new Class[] {
Configuration.class,
Identity.class,
OwnIdentity.class,
Trust.class,
Score.class,
IdentityFetcher.IdentityFetcherCommand.class,
IdentityFetcher.AbortFetchCommand.class,
IdentityFetcher.StartFetchCommand.class,
IdentityFetcher.UpdateEditionHintCommand.class,
IntroductionPuzzle.class,
OwnIntroductionPuzzle.class
};
for(Class<? extends Persistent> clazz : persistentClasses) {
boolean classHasIndex = clazz.getAnnotation(Persistent.IndexedClass.class) != null;
// TODO: We enable class indexes for all classes to make sure nothing breaks because it is the db4o default, check whether enabling
// them only for the classes where we need them does not cause any harm.
classHasIndex = true;
if(logDEBUG) Logger.debug(this, "Persistent class: " + clazz.getCanonicalName() + "; hasIndex==" + classHasIndex);
// TODO: Make very sure that it has no negative side effects if we disable class indices for some classes
// Maybe benchmark in comparison to a database which has class indices enabled for ALL classes.
cfg.objectClass(clazz).indexed(classHasIndex);
// Check the class' fields for @IndexedField annotations
for(Field field : clazz.getDeclaredFields()) {
if(field.getAnnotation(Persistent.IndexedField.class) != null) {
if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + field.getName());
cfg.objectClass(clazz).objectField(field.getName()).indexed(true);
}
}
// Check whether the class itself has an @IndexedField annotation
final Persistent.IndexedField annotation = clazz.getAnnotation(Persistent.IndexedField.class);
if(annotation != null) {
for(String fieldName : annotation.names()) {
if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + fieldName);
cfg.objectClass(clazz).objectField(fieldName).indexed(true);
}
}
}
// TODO: We should check whether db4o inherits the indexed attribute to child classes, for example for this one:
// Unforunately, db4o does not provide any way to query the indexed() property of fields, you can only set it
// We might figure out whether inheritance works by writing a benchmark.
return cfg;
}
private synchronized void restoreDatabaseBackup(File databaseFile, File backupFile) throws IOException {
Logger.warning(this, "Trying to restore database backup: " + backupFile.getAbsolutePath());
if(mDB != null)
throw new RuntimeException("Database is opened already!");
if(backupFile.exists()) {
try {
FileUtil.secureDelete(databaseFile, mPR.getNode().fastWeakRandom);
} catch(IOException e) {
Logger.warning(this, "Deleting of the database failed: " + databaseFile.getAbsolutePath());
}
if(backupFile.renameTo(databaseFile)) {
Logger.warning(this, "Backup restored!");
} else {
throw new IOException("Unable to rename backup file back to database file: " + databaseFile.getAbsolutePath());
}
} else {
throw new IOException("Cannot restore backup, it does not exist!");
}
}
private synchronized void defragmentDatabase(File databaseFile) throws IOException {
Logger.normal(this, "Defragmenting database ...");
if(mDB != null)
throw new RuntimeException("Database is opened already!");
if(mPR == null) {
Logger.normal(this, "No PluginRespirator found, probably running as unit test, not defragmenting.");
return;
}
final Random random = mPR.getNode().fastWeakRandom;
// Open it first, because defrag will throw if it needs to upgrade the file.
{
final ObjectContainer database = Db4o.openFile(getNewDatabaseConfiguration(), databaseFile.getAbsolutePath());
// Db4o will throw during defragmentation if new fields were added to classes and we didn't initialize their values on existing
// objects before defragmenting. So we just don't defragment if the database format version has changed.
final boolean canDefragment = peekDatabaseFormatVersion(this, database.ext()) == WebOfTrust.DATABASE_FORMAT_VERSION;
while(!database.close());
if(!canDefragment) {
Logger.normal(this, "Not defragmenting, database format version changed!");
return;
}
if(!databaseFile.exists()) {
Logger.error(this, "Database file does not exist after openFile: " + databaseFile.getAbsolutePath());
return;
}
}
final File backupFile = new File(databaseFile.getAbsolutePath() + ".backup");
if(backupFile.exists()) {
Logger.error(this, "Not defragmenting database: Backup file exists, maybe the node was shot during defrag: " + backupFile.getAbsolutePath());
return;
}
final File tmpFile = new File(databaseFile.getAbsolutePath() + ".temp");
FileUtil.secureDelete(tmpFile, random);
/* As opposed to the default, BTreeIDMapping uses an on-disk file instead of in-memory for mapping IDs.
/* Reduces memory usage during defragmentation while being slower.
/* However as of db4o 7.4.63.11890, it is bugged and prevents defragmentation from succeeding for my database, so we don't use it for now. */
final DefragmentConfig config = new DefragmentConfig(databaseFile.getAbsolutePath(),
backupFile.getAbsolutePath()
// ,new BTreeIDMapping(tmpFile.getAbsolutePath())
);
/* Delete classes which are not known to the classloader anymore - We do NOT do this because:
/* - It is buggy and causes exceptions often as of db4o 7.4.63.11890
/* - WOT has always had proper database upgrade code (function upgradeDB()) and does not rely on automatic schema evolution.
/* If we need to get rid of certain objects we should do it in the database upgrade code, */
// config.storedClassFilter(new AvailableClassFilter());
config.db4oConfig(getNewDatabaseConfiguration());
try {
Defragment.defrag(config);
} catch (Exception e) {
Logger.error(this, "Defragment failed", e);
try {
restoreDatabaseBackup(databaseFile, backupFile);
return;
} catch(IOException e2) {
Logger.error(this, "Unable to restore backup", e2);
throw new IOException(e);
}
}
final long oldSize = backupFile.length();
final long newSize = databaseFile.length();
if(newSize <= 0) {
Logger.error(this, "Defrag produced an empty file! Trying to restore old database file...");
databaseFile.delete();
try {
restoreDatabaseBackup(databaseFile, backupFile);
} catch(IOException e2) {
Logger.error(this, "Unable to restore backup", e2);
throw new IOException(e2);
}
} else {
final double change = 100.0 * (((double)(oldSize - newSize)) / ((double)oldSize));
FileUtil.secureDelete(tmpFile, random);
FileUtil.secureDelete(backupFile, random);
Logger.normal(this, "Defragment completed. "+SizeUtil.formatSize(oldSize)+" ("+oldSize+") -> "
+SizeUtil.formatSize(newSize)+" ("+newSize+") ("+(int)change+"% shrink)");
}
}
/**
* ATTENTION: This function is duplicated in the Freetalk plugin, please backport any changes.
*
* Initializes the plugin's db4o database.
*/
private synchronized ExtObjectContainer openDatabase(File file) {
Logger.normal(this, "Opening database using db4o " + Db4o.version());
if(mDB != null)
throw new RuntimeException("Database is opened already!");
try {
defragmentDatabase(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
return Db4o.openFile(getNewDatabaseConfiguration(), file.getAbsolutePath()).ext();
}
/**
* ATTENTION: Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher while this is executing.
* It doesn't synchronize on the IntroductionPuzzleStore and IdentityFetcher because it assumes that they are not being used yet.
* (I didn't upgrade this function to do the locking because it would be much work to test the changes for little benefit)
*/
@SuppressWarnings("deprecation")
private synchronized void upgradeDB() {
int databaseVersion = mConfig.getDatabaseFormatVersion();
if(databaseVersion == WebOfTrust.DATABASE_FORMAT_VERSION)
return;
// Insert upgrade code here. See Freetalk.java for a skeleton.
if(databaseVersion == 1) {
Logger.normal(this, "Upgrading database version " + databaseVersion);
//synchronized(this) { // Already done at function level
//synchronized(mPuzzleStore) { // Normally would be needed for deleteWithoutCommit(Identity) but IntroductionClient/Server are not running yet
//synchronized(mFetcher) { // Normally would be needed for deleteWithoutCommit(Identity) but the IdentityFetcher is not running yet
synchronized(Persistent.transactionLock(mDB)) {
try {
Logger.normal(this, "Generating Score IDs...");
for(Score score : getAllScores()) {
score.generateID();
score.storeWithoutCommit();
}
Logger.normal(this, "Generating Trust IDs...");
for(Trust trust : getAllTrusts()) {
trust.generateID();
trust.storeWithoutCommit();
}
Logger.normal(this, "Searching for identities with mixed up insert/request URIs...");
for(Identity identity : getAllIdentities()) {
try {
USK.create(identity.getRequestURI());
} catch (MalformedURLException e) {
if(identity instanceof OwnIdentity) {
Logger.error(this, "Insert URI specified as request URI for OwnIdentity, not correcting the URIs as the insert URI" +
"might have been published by solving captchas - the identity could be compromised: " + identity);
} else {
Logger.error(this, "Insert URI specified as request URI for non-own Identity, deleting: " + identity);
deleteWithoutCommit(identity);
}
}
}
mConfig.setDatabaseFormatVersion(++databaseVersion);
mConfig.storeAndCommit();
Logger.normal(this, "Upgraded database to version " + databaseVersion);
} catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
//}
}
if(databaseVersion != WebOfTrust.DATABASE_FORMAT_VERSION)
throw new RuntimeException("Your database is too outdated to be upgraded automatically, please create a new one by deleting "
+ DATABASE_FILENAME + ". Contact the developers if you really need your old data.");
}
/**
* DO NOT USE THIS FUNCTION ON A DATABASE WHICH YOU WANT TO CONTINUE TO USE!
*
* Debug function for finding object leaks in the database.
*
* - Deletes all identities in the database - This should delete ALL objects in the database.
* - Then it checks for whether any objects still exist - those are leaks.
*/
private synchronized void checkForDatabaseLeaks() {
Logger.normal(this, "Checking for database leaks... This will delete all identities!");
{
Logger.debug(this, "Checking FetchState leakage...");
final Query query = mDB.query();
query.constrain(FetchState.class);
@SuppressWarnings("unchecked")
ObjectSet<FetchState> result = (ObjectSet<FetchState>)query.execute();
for(FetchState state : result) {
Logger.debug(this, "Checking " + state);
final Query query2 = mDB.query();
query2.constrain(Identity.class);
query.descend("mCurrentEditionFetchState").constrain(state).identity();
@SuppressWarnings("unchecked")
ObjectSet<FetchState> result2 = (ObjectSet<FetchState>)query.execute();
switch(result2.size()) {
case 0:
Logger.error(this, "Found leaked FetchState!");
break;
case 1:
break;
default:
Logger.error(this, "Found re-used FetchState, count: " + result2.size());
break;
}
}
Logger.debug(this, "Finished checking FetchState leakage, amount:" + result.size());
}
Logger.normal(this, "Deleting ALL identities...");
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
beginTrustListImport();
for(Identity identity : getAllIdentities()) {
deleteWithoutCommit(identity);
}
finishTrustListImport();
Persistent.checkedCommit(mDB, this);
} catch(RuntimeException e) {
abortTrustListImport(e);
// abortTrustListImport() does rollback already
// Persistent.checkedRollbackAndThrow(mDB, this, e);
throw e;
}
}
}
}
Logger.normal(this, "Deleting ALL identities finished.");
Query query = mDB.query();
query.constrain(Object.class);
@SuppressWarnings("unchecked")
ObjectSet<Object> result = query.execute();
for(Object leak : result) {
Logger.error(this, "Found leaked object: " + leak);
}
Logger.warning(this, "Finished checking for database leaks. This database is empty now, delete it.");
}
private synchronized boolean verifyDatabaseIntegrity() {
deleteDuplicateObjects();
deleteOrphanObjects();
Logger.debug(this, "Testing database integrity...");
final Query q = mDB.query();
q.constrain(Persistent.class);
boolean result = true;
for(final Persistent p : new Persistent.InitializingObjectSet<Persistent>(this, q)) {
try {
p.startupDatabaseIntegrityTest();
} catch(Exception e) {
result = false;
try {
Logger.error(this, "Integrity test failed for " + p, e);
} catch(Exception e2) {
Logger.error(this, "Integrity test failed for Persistent of class " + p.getClass(), e);
Logger.error(this, "Exception thrown by toString() was:", e2);
}
}
}
Logger.debug(this, "Database integrity test finished.");
return result;
}
/**
* Does not do proper synchronization! Only use it in single-thread-mode during startup.
*
* Does a backup of the database using db4o's backup mechanism.
*
* This will NOT fix corrupted internal structures of databases - use cloneDatabase if you need to fix your database.
*/
private synchronized void backupDatabase(File newDatabase) {
Logger.normal(this, "Backing up database to " + newDatabase.getAbsolutePath());
if(newDatabase.exists())
throw new RuntimeException("Target exists already: " + newDatabase.getAbsolutePath());
WebOfTrust backup = null;
boolean success = false;
try {
mDB.backup(newDatabase.getAbsolutePath());
if(logDEBUG) {
backup = new WebOfTrust(newDatabase.getAbsolutePath());
// We do not throw to make the clone mechanism more robust in case it is being used for creating backups
Logger.debug(this, "Checking database integrity of clone...");
if(backup.verifyDatabaseIntegrity())
Logger.debug(this, "Checking database integrity of clone finished.");
else
Logger.error(this, "Database integrity check of clone failed!");
Logger.debug(this, "Checking this.equals(clone)...");
if(equals(backup))
Logger.normal(this, "Clone is equal!");
else
Logger.error(this, "Clone is not equal!");
}
success = true;
} finally {
if(backup != null)
backup.terminate();
if(!success)
newDatabase.delete();
}
Logger.normal(this, "Backing up database finished.");
}
/**
* Does not do proper synchronization! Only use it in single-thread-mode during startup.
*
* Creates a clone of the source database by reading all objects of it into memory and then writing them out to the target database.
* Does NOT copy the Configuration, the IntroductionPuzzles or the IdentityFetcher command queue.
*
* The difference to backupDatabase is that it does NOT use db4o's backup mechanism, instead it creates the whole database from scratch.
* This is useful because the backup mechanism of db4o does nothing but copying the raw file:
* It wouldn't fix databases which cannot be defragmented anymore due to internal corruption.
* - Databases which were cloned by this function CAN be defragmented even if the original database couldn't.
*
* HOWEVER this function uses lots of memory as the whole database is copied into memory.
*/
private synchronized void cloneDatabase(File sourceDatabase, File targetDatabase) {
Logger.normal(this, "Cloning " + sourceDatabase.getAbsolutePath() + " to " + targetDatabase.getAbsolutePath());
if(targetDatabase.exists())
throw new RuntimeException("Target exists already: " + targetDatabase.getAbsolutePath());
WebOfTrust original = null;
WebOfTrust clone = null;
boolean success = false;
try {
original = new WebOfTrust(sourceDatabase.getAbsolutePath());
// We need to copy all objects into memory and then close & unload the source database before writing the objects to the target one.
// - I tried implementing this function in a way where it directly takes the objects from the source database and stores them
// in the target database while the source is still open. This did not work: Identity objects disappeared magically, resulting
// in Trust objects .storeWithoutCommit throwing "Mandatory object not found" on their associated identities.
final HashSet<Identity> allIdentities = new HashSet<Identity>(original.getAllIdentities());
final HashSet<Trust> allTrusts = new HashSet<Trust>(original.getAllTrusts());
final HashSet<Score> allScores = new HashSet<Score>(original.getAllScores());
for(Identity identity : allIdentities) {
identity.checkedActivate(16);
identity.mWebOfTrust = null;
identity.mDB = null;
}
for(Trust trust : allTrusts) {
trust.checkedActivate(16);
trust.mWebOfTrust = null;
trust.mDB = null;
}
for(Score score : allScores) {
score.checkedActivate(16);
score.mWebOfTrust = null;
score.mDB = null;
}
original.terminate();
original = null;
System.gc();
// Now we write out the in-memory copies ...
clone = new WebOfTrust(targetDatabase.getAbsolutePath());
for(Identity identity : allIdentities) {
identity.initializeTransient(clone);
identity.storeWithoutCommit();
}
Persistent.checkedCommit(clone.getDatabase(), clone);
for(Trust trust : allTrusts) {
trust.initializeTransient(clone);
trust.storeWithoutCommit();
}
Persistent.checkedCommit(clone.getDatabase(), clone);
for(Score score : allScores) {
score.initializeTransient(clone);
score.storeWithoutCommit();
}
Persistent.checkedCommit(clone.getDatabase(), clone);
// And because cloning is a complex operation we do a mandatory database integrity check
Logger.normal(this, "Checking database integrity of clone...");
if(clone.verifyDatabaseIntegrity())
Logger.normal(this, "Checking database integrity of clone finished.");
else
throw new RuntimeException("Database integrity check of clone failed!");
// ... and also test whether the Web Of Trust is equals() to the clone. This does a deep check of all identities, scores & trusts!
original = new WebOfTrust(sourceDatabase.getAbsolutePath());
Logger.normal(this, "Checking original.equals(clone)...");
if(original.equals(clone))
Logger.normal(this, "Clone is equal!");
else
throw new RuntimeException("Clone is not equal!");
success = true;
} finally {
if(original != null)
original.terminate();
if(clone != null)
clone.terminate();
if(!success)
targetDatabase.delete();
}
Logger.normal(this, "Cloning database finished.");
}
/**
* Recomputes the {@link Score} of all identities and checks whether the score which is stored in the database is correct.
* Incorrect scores are corrected & stored.
*
* The function is synchronized and does a transaction, no outer synchronization is needed.
- * ATTENTION: It is NOT synchronized on the IntroductionPuzzleStore or the IdentityFetcher. They must NOT be running yet when using this function!
*/
protected synchronized void verifyAndCorrectStoredScores() {
Logger.normal(this, "Veriying all stored scores ...");
+ synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
} catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
+ }
Logger.normal(this, "Veriying all stored scores finished.");
}
/**
* Debug function for deleting duplicate identities etc. which might have been created due to bugs :)
*/
private synchronized void deleteDuplicateObjects() {
synchronized(mPuzzleStore) { // Needed for deleteIdentity()
synchronized(mFetcher) { // // Needed for deleteIdentity()
synchronized(Persistent.transactionLock(mDB)) {
try {
HashSet<String> deleted = new HashSet<String>();
if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ...");
for(Identity identity : getAllIdentities()) {
Query q = mDB.query();
q.constrain(Identity.class);
q.descend("mID").constrain(identity.getID());
q.constrain(identity).identity().not();
ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q);
for(Identity duplicate : duplicates) {
if(deleted.contains(duplicate.getID()) == false) {
Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI());
deleteWithoutCommit(duplicate);
Persistent.checkedCommit(mDB, this);
}
}
deleted.add(identity.getID());
}
Persistent.checkedCommit(mDB, this);
if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities.");
}
catch(RuntimeException e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
// synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit
synchronized(Persistent.transactionLock(mDB)) {
try {
if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ...");
boolean duplicateTrustFound = false;
for(OwnIdentity truster : getAllOwnIdentities()) {
HashSet<String> givenTo = new HashSet<String>();
for(Trust trust : getGivenTrusts(truster)) {
if(givenTo.contains(trust.getTrustee().getID()) == false)
givenTo.add(trust.getTrustee().getID());
else {
Logger.error(this, "Deleting duplicate given trust:" + trust);
removeTrustWithoutCommit(trust);
duplicateTrustFound = true;
}
}
}
if(duplicateTrustFound) {
computeAllScoresWithoutCommit();
}
Persistent.checkedCommit(mDB, this);
if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects.");
}
catch(RuntimeException e) {
Persistent.checkedRollback(mDB, this, e);
}
} // synchronized(Persistent.transactionLock(mDB)) {
} // synchronized(mFetcher) {
/* TODO: Also delete duplicate score */
}
/**
* Debug function for deleting trusts or scores of which one of the involved partners is missing.
*/
private synchronized void deleteOrphanObjects() {
// synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
boolean orphanTrustFound = false;
Query q = mDB.query();
q.constrain(Trust.class);
q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity());
ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q);
for(Trust trust : orphanTrusts) {
if(trust.getTruster() != null && trust.getTrustee() != null) {
// TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore.
Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust);
continue;
}
Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee());
orphanTrustFound = true;
trust.deleteWithoutCommit();
}
if(orphanTrustFound) {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
}
}
catch(Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
// synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
boolean orphanScoresFound = false;
Query q = mDB.query();
q.constrain(Score.class);
q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity());
ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q);
for(Score score : orphanScores) {
if(score.getTruster() != null && score.getTrustee() != null) {
// TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore.
Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score);
continue;
}
Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee());
orphanScoresFound = true;
score.deleteWithoutCommit();
}
if(orphanScoresFound) {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
}
}
catch(Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
/**
* Warning: This function is not synchronized, use it only in single threaded mode.
* @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist.
*/
@SuppressWarnings("deprecation")
private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) {
final Query query = database.query();
query.constrain(Configuration.class);
@SuppressWarnings("unchecked")
ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute();
switch(result.size()) {
case 1: {
final Configuration config = (Configuration)result.next();
config.initializeTransient(wot, database);
// For the HashMaps to stay alive we need to activate to full depth.
config.checkedActivate(4);
return config.getDatabaseFormatVersion();
}
default:
return -1;
}
}
/**
* Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists.
* @return The config object.
*/
private synchronized Configuration getOrCreateConfig() {
final Query query = mDB.query();
query.constrain(Configuration.class);
final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query);
switch(result.size()) {
case 1: {
final Configuration config = result.next();
// For the HashMaps to stay alive we need to activate to full depth.
config.checkedActivate(4);
config.setDefaultValues(false);
config.storeAndCommit();
return config;
}
case 0: {
final Configuration config = new Configuration(this);
config.initializeTransient(this);
config.storeAndCommit();
return config;
}
default:
throw new RuntimeException("Multiple config objects found: " + result.size());
}
}
/** Capacity is the maximum amount of points an identity can give to an other by trusting it.
*
* Values choice :
* Advogato Trust metric recommends that values decrease by rounded 2.5 times.
* This makes sense, making the need of 3 N+1 ranked people to overpower
* the trust given by a N ranked identity.
*
* Number of ranks choice :
* When someone creates a fresh identity, he gets the seed identity at
* rank 1 and freenet developpers at rank 2. That means that
* he will see people that were :
* - given 7 trust by freenet devs (rank 2)
* - given 17 trust by rank 3
* - given 50 trust by rank 4
* - given 100 trust by rank 5 and above.
* This makes the range small enough to avoid a newbie
* to even see spam, and large enough to make him see a reasonnable part
* of the community right out-of-the-box.
* Of course, as soon as he will start to give trust, he will put more
* people at rank 1 and enlarge his WoT.
*/
protected static final int capacities[] = {
100,// Rank 0 : Own identities
40, // Rank 1 : Identities directly trusted by ownIdenties
16, // Rank 2 : Identities trusted by rank 1 identities
6, // So on...
2,
1 // Every identity above rank 5 can give 1 point
}; // Identities with negative score have zero capacity
/**
* Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much
* trust points an identity can add to the score of identities which it has assigned trust values to.
* The higher the rank of an identity, the less is it's capacity.
*
* If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less
* than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0.
*
* If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value:
* The decision of the truster should always overpower the view of remote identities.
*
* Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity.
*
* @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed
* @param trustee The {@link Identity} of which the capacity shall be computed.
* @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust,
* - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view.
*/
protected int computeCapacity(OwnIdentity truster, Identity trustee, int rank) {
if(truster == trustee)
return 100;
try {
if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit.
assert(rank == Integer.MAX_VALUE);
return 0;
}
} catch(NotTrustedException e) { }
if(rank == -1 || rank == Integer.MAX_VALUE)
return 0;
return (rank < capacities.length) ? capacities[rank] : 1;
}
/**
* Reference-implementation of score computation. This means:<br />
* - It is not used by the real WoT code because its slow<br />
* - It is used by unit tests (and WoT) to check whether the real implementation works<br />
* - It is the function which you should read if you want to understand how WoT works.<br />
*
* Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br />
*
* There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br />
*
* Further, rank values are shortest paths and the path-finding algorithm is not executed from the source
* to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path.
* Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database
* and affect many others. So it is useful to have this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
* </code>
*
* @return True if all stored scores were correct. False if there were any errors in stored scores.
*/
protected boolean computeAllScoresWithoutCommit() {
if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores...");
final long beginTime = CurrentTimeUTC.getInMillis();
boolean returnValue = true;
final ObjectSet<Identity> allIdentities = getAllIdentities();
// Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity.
for(OwnIdentity treeOwner : getAllOwnIdentities()) {
// At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner.
// An identity is visible if there is a trust chain from the owner to it.
// The rank is the distance in trust steps from the treeOwner.
// So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on.
final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2);
// Compute the rank values
{
// For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters.
// The inner loop then pulls out one unprocessed identity and computes the rank of its trustees:
// All trustees which have received positive (> 0) trust will get his rank + 1
// Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE.
// Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all.
// Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none.
//
// Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value:
// The decision of the own identity shall not be overpowered by the view of the remote identities.
//
// The purpose of differentiation between Integer.MAX_VALUE and -1 is:
// Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing
// them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and
// have a way of telling the user "this identity is not trusted" by keeping a score object of them.
// Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where
// we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank
// - and we never import their trust lists.
// We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved
// introduction puzzles cannot inherit their rank to their trustees.
final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>();
// The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE
try {
Score selfScore = getScore(treeOwner, treeOwner);
if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one
rankValues.put(treeOwner, selfScore.getRank());
unprocessedTrusters.addLast(treeOwner);
} else {
rankValues.put(treeOwner, null);
}
} catch(NotInTrustTreeException e) {
// This only happens in unit tests.
}
while(!unprocessedTrusters.isEmpty()) {
final Identity truster = unprocessedTrusters.removeFirst();
final Integer trusterRank = rankValues.get(truster);
// The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all.
if(trusterRank == null || trusterRank == Integer.MAX_VALUE) {
// (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security)
continue;
}
final int trusteeRank = trusterRank + 1;
for(Trust trust : getGivenTrusts(truster)) {
final Identity trustee = trust.getTrustee();
final Integer oldTrusteeRank = rankValues.get(trustee);
if(oldTrusteeRank == null) { // The trustee was not processed yet
if(trust.getValue() > 0) {
rankValues.put(trustee, trusteeRank);
unprocessedTrusters.addLast(trustee);
}
else
rankValues.put(trustee, Integer.MAX_VALUE);
} else {
// Breadth first search will process all rank one identities are processed before any rank two identities, etc.
assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank);
if(oldTrusteeRank == Integer.MAX_VALUE) {
// If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not
// given by the tree owner.
try {
final Trust treeOwnerTrust = getTrust(treeOwner, trustee);
assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct?
} catch(NotTrustedException e) {
if(trust.getValue() > 0) {
rankValues.put(trustee, trusteeRank);
unprocessedTrusters.addLast(trustee);
}
}
}
}
}
}
}
// Rank values of all visible identities are computed now.
// Next step is to compute the scores of all identities
for(Identity target : allIdentities) {
// The score of an identity is the sum of all weighted trust values it has received.
// Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank.
Integer targetScore;
final Integer targetRank = rankValues.get(target);
if(targetRank == null) {
targetScore = null;
} else {
// The treeOwner trusts himself.
if(targetRank == 0) {
targetScore = Integer.MAX_VALUE;
}
else {
// If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score.
try {
targetScore = (int)getTrust(treeOwner, target).getValue();
} catch(NotTrustedException e) {
targetScore = 0;
for(Trust receivedTrust : getReceivedTrusts(target)) {
final Identity truster = receivedTrust.getTruster();
final Integer trusterRank = rankValues.get(truster);
// The capacity is a weight function for trust values which are given from an identity:
// The higher the rank, the less the capacity.
// If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0.
final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1);
targetScore += (receivedTrust.getValue() * capacity) / 100;
}
}
}
}
Score newScore = null;
if(targetScore != null) {
newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank));
}
boolean needToCheckFetchStatus = false;
boolean oldShouldFetch = false;
int oldCapacity = 0;
// Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct.
try {
Score currentStoredScore = getScore(treeOwner, target);
oldCapacity = currentStoredScore.getCapacity();
if(newScore == null) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
currentStoredScore.deleteWithoutCommit();
} else {
if(!newScore.equals(currentStoredScore)) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
currentStoredScore.setRank(newScore.getRank());
currentStoredScore.setCapacity(newScore.getCapacity());
currentStoredScore.setValue(newScore.getScore());
currentStoredScore.storeWithoutCommit();
}
}
} catch(NotInTrustTreeException e) {
oldCapacity = 0;
if(newScore != null) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
newScore.storeWithoutCommit();
}
}
if(needToCheckFetchStatus) {
// If fetch status changed from false to true, we need to start fetching it
// If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot
// cause new identities to be imported from their trust list, capacity > 0 allows this.
// If the fetch status changed from true to false, we need to stop fetching it
if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) {
if(!oldShouldFetch)
if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target);
else
if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target);
target.markForRefetch();
target.storeWithoutCommit();
mFetcher.storeStartFetchCommandWithoutCommit(target);
}
else if(oldShouldFetch && !shouldFetchIdentity(target)) {
if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target);
mFetcher.storeAbortFetchCommandWithoutCommit(target);
}
}
}
}
mFullScoreComputationNeeded = false;
++mFullScoreRecomputationCount;
mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime;
if(logMINOR) {
Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s");
}
return returnValue;
}
private synchronized void createSeedIdentities() {
for(String seedURI : SEED_IDENTITIES) {
Identity seed;
synchronized(Persistent.transactionLock(mDB)) {
try {
seed = getIdentityByURI(seedURI);
if(seed instanceof OwnIdentity) {
OwnIdentity ownSeed = (OwnIdentity)seed;
ownSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
ownSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY,
Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT));
ownSeed.storeAndCommit();
}
else {
try {
seed.setEdition(new FreenetURI(seedURI).getEdition());
seed.storeAndCommit();
} catch(InvalidParameterException e) {
/* We already have the latest edition stored */
}
}
}
catch (UnknownIdentityException uie) {
try {
seed = new Identity(this, seedURI, null, true);
// We have to explicitely set the edition number because the constructor only considers the given edition as a hint.
seed.setEdition(new FreenetURI(seedURI).getEdition());
seed.storeAndCommit();
} catch (Exception e) {
Logger.error(this, "Seed identity creation error", e);
}
}
catch (Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
public void terminate() {
if(logDEBUG) Logger.debug(this, "WoT plugin terminating ...");
/* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */
try {
if(mWebInterface != null)
this.mWebInterface.unload();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mIntroductionClient != null)
mIntroductionClient.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mIntroductionServer != null)
mIntroductionServer.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mInserter != null)
mInserter.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mFetcher != null)
mFetcher.stop();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mDB != null) {
/* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending.
* If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction.
* - All transactions should be committed after obtaining the lock() on the database. */
synchronized(Persistent.transactionLock(mDB)) {
System.gc();
mDB.rollback();
System.gc();
mDB.close();
}
}
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
if(logDEBUG) Logger.debug(this, "WoT plugin terminated.");
}
/**
* Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>.
*/
public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) {
mFCPInterface.handle(replysender, params, data, accesstype);
}
/**
* Loads an own or normal identity from the database, querying on its ID.
*
* @param id The ID of the identity to load
* @return The identity matching the supplied ID.
* @throws DuplicateIdentityException if there are more than one identity with this id in the database
* @throws UnknownIdentityException if there is no identity with this id in the database
*/
public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException {
final Query query = mDB.query();
query.constrain(Identity.class);
query.descend("mID").constrain(id);
final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query);
switch(result.size()) {
case 1: return result.next();
case 0: throw new UnknownIdentityException(id);
default: throw new DuplicateIdentityException(id, result.size());
}
}
/**
* Gets an OwnIdentity by its ID.
*
* @param id The unique identifier to query an OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if there is now OwnIdentity with that id
*/
public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException {
final Query query = mDB.query();
query.constrain(OwnIdentity.class);
query.descend("mID").constrain(id);
final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query);
switch(result.size()) {
case 1: return result.next();
case 0: throw new UnknownIdentityException(id);
default: throw new DuplicateIdentityException(id, result.size());
}
}
/**
* Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI})
*
* @param uri The requestURI of the identity
* @return The identity matching the supplied requestURI
* @throws UnknownIdentityException if there is no identity with this id in the database
*/
public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException {
return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString());
}
/**
* Loads an identity from the database, querying on its requestURI (as String)
*
* @param uri The requestURI of the identity which will be converted to {@link FreenetURI}
* @return The identity matching the supplied requestURI
* @throws UnknownIdentityException if there is no identity with this id in the database
* @throws MalformedURLException if the requestURI isn't a valid FreenetURI
*/
public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException {
return getIdentityByURI(new FreenetURI(uri));
}
/**
* Gets an OwnIdentity by its requestURI (a {@link FreenetURI}).
* The OwnIdentity's unique identifier is extracted from the supplied requestURI.
*
* @param uri The requestURI of the desired OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if the OwnIdentity isn't in the database
*/
public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException {
return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString());
}
/**
* Gets an OwnIdentity by its requestURI (as String).
* The given String is converted to {@link FreenetURI} in order to extract a unique id.
*
* @param uri The requestURI (as String) of the desired OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if the OwnIdentity isn't in the database
* @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI
*/
public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException {
return getOwnIdentityByURI(new FreenetURI(uri));
}
/**
* Returns all identities that are in the database
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all identities present in the database
*/
public ObjectSet<Identity> getAllIdentities() {
final Query query = mDB.query();
query.constrain(Identity.class);
return new Persistent.InitializingObjectSet<Identity>(this, query);
}
public static enum SortOrder {
ByNicknameAscending,
ByNicknameDescending,
ByScoreAscending,
ByScoreDescending,
ByLocalTrustAscending,
ByLocalTrustDescending
}
/**
* Get a filtered and sorted list of identities.
* You have to synchronize on this WoT when calling the function and processing the returned list.
*/
public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) {
Query q = mDB.query();
switch(sortInstruction) {
case ByNicknameAscending:
q.constrain(Identity.class);
q.descend("mNickname").orderAscending();
break;
case ByNicknameDescending:
q.constrain(Identity.class);
q.descend("mNickname").orderDescending();
break;
case ByScoreAscending:
q.constrain(Score.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderAscending();
q = q.descend("mTrustee");
break;
case ByScoreDescending:
// TODO: This excludes identities which have no score
q.constrain(Score.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderDescending();
q = q.descend("mTrustee");
break;
case ByLocalTrustAscending:
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderAscending();
q = q.descend("mTrustee");
break;
case ByLocalTrustDescending:
// TODO: This excludes untrusted identities.
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderDescending();
q = q.descend("mTrustee");
break;
}
if(nickFilter != null) {
nickFilter = nickFilter.trim();
if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like();
}
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all non-own identities that are in the database.
*
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
public ObjectSet<Identity> getAllNonOwnIdentities() {
final Query q = mDB.query();
q.constrain(Identity.class);
q.constrain(OwnIdentity.class).not();
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently
* modified identities will be at the beginning of the list.
*
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* Used by the IntroductionClient for fetching puzzles from recently modified identities.
*/
public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () {
final Query q = mDB.query();
q.constrain(Identity.class);
q.constrain(OwnIdentity.class).not();
/* TODO: As soon as identities announce that they were online every day, uncomment the following line */
/* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */
q.descend("mLastFetchedDate").orderDescending();
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all own identities that are in the database
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all identities present in the database.
*/
public ObjectSet<OwnIdentity> getAllOwnIdentities() {
final Query q = mDB.query();
q.constrain(OwnIdentity.class);
return new Persistent.InitializingObjectSet<OwnIdentity>(this, q);
}
/**
* DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST!
* IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS:
* - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will.
* - Especially it might be an information leak if the trust values of other OwnIdentities are deleted!
* - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption.
*
* The intended purpose of this function is:
* - To specify which objects have to be dealt with when messing with storage of an identity.
* - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them.
* However, the implementations of those functions might cause leaks by forgetting to delete certain object members.
* If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty.
* You then can check whether the database actually IS empty to test for leakage.
*
* You have to lock the WebOfTrust, the IntroductionPuzzleStore and the IdentityFetcher before calling this function.
*/
private void deleteWithoutCommit(Identity identity) {
// We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport.
// If the caller already handles that for us though, we should not call those function again.
// So we check whether the caller already started an import.
boolean trustListImportWasInProgress = mTrustListImportInProgress;
try {
if(!trustListImportWasInProgress)
beginTrustListImport();
if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ...");
if(logDEBUG) Logger.debug(this, "Deleting received scores...");
for(Score score : getScores(identity))
score.deleteWithoutCommit();
if(identity instanceof OwnIdentity) {
if(logDEBUG) Logger.debug(this, "Deleting given scores...");
for(Score score : getGivenScores((OwnIdentity)identity))
score.deleteWithoutCommit();
}
if(logDEBUG) Logger.debug(this, "Deleting received trusts...");
for(Trust trust : getReceivedTrusts(identity))
trust.deleteWithoutCommit();
if(logDEBUG) Logger.debug(this, "Deleting given trusts...");
for(Trust givenTrust : getGivenTrusts(identity)) {
givenTrust.deleteWithoutCommit();
// We call computeAllScores anyway so we do not use removeTrustWithoutCommit()
}
mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us.
if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ...");
mPuzzleStore.onIdentityDeletion(identity);
if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command...");
if(mFetcher != null) { // Can be null if we use this function in upgradeDB()
mFetcher.storeAbortFetchCommandWithoutCommit(identity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
}
if(logDEBUG) Logger.debug(this, "Deleting the identity...");
identity.deleteWithoutCommit();
if(!trustListImportWasInProgress)
finishTrustListImport();
}
catch(RuntimeException e) {
if(!trustListImportWasInProgress)
abortTrustListImport(e);
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
/**
* Gets the score of this identity in a trust tree.
* Each {@link OwnIdentity} has its own trust tree.
*
* @param truster The owner of the trust tree
* @return The {@link Score} of this Identity in the required trust tree
* @throws NotInTrustTreeException if this identity is not in the required trust tree
*/
public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mID").constrain(new ScoreID(truster, trustee).toString());
final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query);
switch(result.size()) {
case 1:
final Score score = result.next();
assert(score.getTruster() == truster);
assert(score.getTrustee() == trustee);
return score;
case 0: throw new NotInTrustTreeException(truster, trustee);
default: throw new DuplicateScoreException(truster, trustee, result.size());
}
}
/**
* Gets a list of all this Identity's Scores.
* You have to synchronize on this WoT around the call to this function and the processing of the returned list!
*
* @return An {@link ObjectSet} containing all {@link Score} this Identity has.
*/
public ObjectSet<Score> getScores(final Identity identity) {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mTrustee").constrain(identity).identity();
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Get a list of all scores which the passed own identity has assigned to other identities.
*
* You have to synchronize on this WoT around the call to this function and the processing of the returned list!
* @return An {@link ObjectSet} containing all {@link Score} this Identity has given.
*/
public ObjectSet<Score> getGivenScores(final OwnIdentity truster) {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mTruster").constrain(truster).identity();
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Gets the best score this Identity has in existing trust trees.
*
* @return the best score this Identity has
* @throws NotInTrustTreeException If the identity has no score in any trusttree.
*/
public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException {
int bestScore = Integer.MIN_VALUE;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
throw new NotInTrustTreeException(identity);
// TODO: Cache the best score of an identity as a member variable.
for(final Score score : scores)
bestScore = Math.max(score.getScore(), bestScore);
return bestScore;
}
/**
* Gets the best capacity this identity has in any trust tree.
* @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0.
*/
public int getBestCapacity(final Identity identity) throws NotInTrustTreeException {
int bestCapacity = 0;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
throw new NotInTrustTreeException(identity);
// TODO: Cache the best score of an identity as a member variable.
for(final Score score : scores)
bestCapacity = Math.max(score.getCapacity(), bestCapacity);
return bestCapacity;
}
/**
* Get all scores in the database.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
public ObjectSet<Score> getAllScores() {
final Query query = mDB.query();
query.constrain(Score.class);
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Checks whether the given identity should be downloaded.
* @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity.
*/
public boolean shouldFetchIdentity(final Identity identity) {
if(identity instanceof OwnIdentity)
return true;
int bestScore = Integer.MIN_VALUE;
int bestCapacity = 0;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
return false;
// TODO: Cache the best score of an identity as a member variable.
for(Score score : scores) {
bestCapacity = Math.max(score.getCapacity(), bestCapacity);
bestScore = Math.max(score.getScore(), bestScore);
if(bestCapacity > 0 || bestScore >= 0)
return true;
}
return false;
}
/**
* Gets non-own Identities matching a specified score criteria.
* TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param truster The owner of the trust tree, null if you want the trusted identities of all owners.
* @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0
* and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0.
* @return an {@link ObjectSet} containing Scores of the identities that match the criteria
*/
public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) {
final Query query = mDB.query();
query.constrain(Score.class);
if(truster != null)
query.descend("mTruster").constrain(truster).identity();
query.descend("mTrustee").constrain(OwnIdentity.class).not();
/* We include 0 in the list of identities with positive score because solving captchas gives no points to score */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0)
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Gets {@link Trust} from a specified truster to a specified trustee.
*
* @param truster The identity that gives trust to this Identity
* @param trustee The identity which receives the trust
* @return The trust given to the trustee by the specified truster
* @throws NotTrustedException if the truster doesn't trust the trustee
*/
public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mID").constrain(new TrustID(truster, trustee).toString());
final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query);
switch(result.size()) {
case 1:
final Trust trust = result.next();
assert(trust.getTruster() == truster);
assert(trust.getTrustee() == trustee);
return trust;
case 0: throw new NotTrustedException(truster, trustee);
default: throw new DuplicateTrustException(truster, trustee, result.size());
}
}
/**
* Gets all trusts given by the given truster.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given.
*/
public ObjectSet<Trust> getGivenTrusts(final Identity truster) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts given by the given truster.
* The result is sorted descending by the time we last fetched the trusted identity.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given.
*/
public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
query.descend("mTrustee").descend("mLastFetchedDate").orderDescending();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets given trust values of an identity matching a specified trust value criteria.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param truster The identity which given the trust values.
* @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0.
* Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0.
* @return an {@link ObjectSet} containing received trust values that match the criteria.
*/
public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
/* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0 )
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts given by the given truster in a trust list with a different edition than the passed in one.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) {
final Query q = mDB.query();
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mTrusterTrustListEdition").constrain(edition).not();
return new Persistent.InitializingObjectSet<Trust>(this, q);
}
/**
* Gets all trusts received by the given trustee.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received.
*/
public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTrustee").constrain(trustee).identity();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets received trust values of an identity matching a specified trust value criteria.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param trustee The identity which has received the trust values.
* @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0.
* Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0.
* @return an {@link ObjectSet} containing received trust values that match the criteria.
*/
public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTrustee").constrain(trustee).identity();
/* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0 )
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received.
*/
public ObjectSet<Trust> getAllTrusts() {
final Query query = mDB.query();
query.constrain(Trust.class);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gives some {@link Trust} to another Identity.
* It creates or updates an existing Trust object and make the trustee compute its {@link Score}.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
* @param truster The Identity that gives the trust
* @param trustee The Identity that receives the trust
* @param newValue Numeric value of the trust
* @param newComment A comment to explain the given value
* @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values.
*/
protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment)
throws InvalidParameterException {
try { // Check if we are updating an existing trust value
final Trust trust = getTrust(truster, trustee);
final Trust oldTrust = trust.clone();
trust.trusterEditionUpdated();
trust.setComment(newComment);
trust.storeWithoutCommit();
if(trust.getValue() != newValue) {
trust.setValue(newValue);
trust.storeWithoutCommit();
if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score.");
updateScoresWithoutCommit(oldTrust, trust);
}
} catch (NotTrustedException e) {
final Trust trust = new Trust(this, truster, trustee, newValue, newComment);
trust.storeWithoutCommit();
if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score.");
updateScoresWithoutCommit(null, trust);
}
truster.updated();
truster.storeWithoutCommit();
}
/**
* Only for being used by WoT internally and by unit tests!
*
* You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function.
*/
void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment)
throws InvalidParameterException {
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
setTrustWithoutCommit(truster, trustee, newValue, newComment);
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
/**
* Deletes a trust object.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
* @param truster
* @param trustee
*/
protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) {
try {
try {
removeTrustWithoutCommit(getTrust(truster, trustee));
} catch (NotTrustedException e) {
Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname());
}
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
/**
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
*/
protected void removeTrustWithoutCommit(Trust trust) {
trust.deleteWithoutCommit();
updateScoresWithoutCommit(trust, null);
}
/**
* Initializes this OwnIdentity's trust tree without commiting the transaction.
* Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities.
*
* The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }
*
* @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen)
*/
private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException {
try {
getScore(identity, identity);
Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity);
return;
} catch (NotInTrustTreeException e) {
final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100);
score.storeWithoutCommit();
}
}
/**
* Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified
* trust tree.
*
* @param truster The OwnIdentity that owns the trust tree
* @param trustee The identity for which the score shall be computed.
* @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster.
* @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen)
*/
private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException {
if(trustee == truster)
return Integer.MAX_VALUE;
int value = 0;
try {
return getTrust(truster, trustee).getValue();
}
catch(NotTrustedException e) { }
for(Trust trust : getReceivedTrusts(trustee)) {
try {
final Score trusterScore = getScore(truster, trust.getTruster());
value += ( trust.getValue() * trusterScore.getCapacity() ) / 100;
} catch (NotInTrustTreeException e) {}
}
return value;
}
/**
* Computes the trustees's rank in the trust tree of the truster.
* It gets its best ranked non-zero-capacity truster's rank, plus one.
* If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite).
* If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1.
*
* If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the
* tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision).
*
* The purpose of differentiation between Integer.MAX_VALUE and -1 is:
* Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them
* in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the
* user "this identity is not trusted" by keeping a score object of them.
* Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we
* hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and
* we never download their trust lists.
*
* Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity.
*
* @param truster The OwnIdentity that owns the trust tree
* @return The new Rank if this Identity
* @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen)
*/
private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException {
if(trustee == truster)
return 0;
int rank = -1;
try {
Trust treeOwnerTrust = getTrust(truster, trustee);
if(treeOwnerTrust.getValue() > 0)
return 1;
else
return Integer.MAX_VALUE;
} catch(NotTrustedException e) { }
for(Trust trust : getReceivedTrusts(trustee)) {
try {
Score score = getScore(truster, trust.getTruster());
if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank
// A truster only gives his rank to a trustee if he has assigned a strictly positive trust value
if(trust.getValue() > 0 ) {
// We give the rank to the trustee if it is better than its current rank or he has no rank yet.
if(rank == -1 || score.getRank() < rank)
rank = score.getRank();
} else {
// If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster.
if(rank == -1)
rank = Integer.MAX_VALUE;
}
}
} catch (NotInTrustTreeException e) {}
}
if(rank == -1)
return -1;
else if(rank == Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return rank+1;
}
/**
* Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress.
* This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called.
*
* ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)}
* for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}
* </code>
*/
protected void beginTrustListImport() {
if(logMINOR) Logger.minor(this, "beginTrustListImport()");
if(mTrustListImportInProgress) {
abortTrustListImport(new RuntimeException("There was already a trust list import in progress!"));
mFullScoreComputationNeeded = true;
computeAllScoresWithoutCommit();
assert(mFullScoreComputationNeeded == false);
}
mTrustListImportInProgress = true;
assert(!mFullScoreComputationNeeded);
assert(computeAllScoresWithoutCommit()); // The database is intact before the import
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Aborts the import of a trust list import and undoes all changes by it.
*
* ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction.
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already }
* }}}
* </code>
*
* @param e The exception which triggered the abort. Will be logged to the Freenet log file.
* @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file.
*/
protected void abortTrustListImport(Exception e, LogLevel logLevel) {
if(logMINOR) Logger.minor(this, "abortTrustListImport()");
assert(mTrustListImportInProgress);
mTrustListImportInProgress = false;
mFullScoreComputationNeeded = false;
Persistent.checkedRollback(mDB, this, e, logLevel);
assert(computeAllScoresWithoutCommit()); // Test rollback.
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Aborts the import of a trust list import and undoes all changes by it.
*
* ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction.
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}
* </code>
*
* @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR}
*/
protected void abortTrustListImport(Exception e) {
abortTrustListImport(e, Logger.LogLevel.ERROR);
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Finishes the import of the current trust list and performs score computation.
*
* ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it!
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}
* </code>
*/
protected void finishTrustListImport() {
if(logMINOR) Logger.minor(this, "finishTrustListImport()");
if(!mTrustListImportInProgress) {
Logger.error(this, "There was no trust list import in progress!");
return;
}
if(mFullScoreComputationNeeded) {
computeAllScoresWithoutCommit();
assert(!mFullScoreComputationNeeded); // It properly clears the flag
assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable
}
else
assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked.
mTrustListImportInProgress = false;
}
/**
* Updates all trust trees which are affected by the given modified score.
* For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()}
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; }
* }}}
*/
private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) {
if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores...");
final long beginTime = CurrentTimeUTC.getInMillis();
// We only include the time measurement if we actually do something.
// If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included.
boolean includeMeasurement = false;
final boolean trustWasCreated = (oldTrust == null);
final boolean trustWasDeleted = (newTrust == null);
final boolean trustWasModified = !trustWasCreated && !trustWasDeleted;
if(trustWasCreated && trustWasDeleted)
throw new NullPointerException("No old/new trust specified.");
if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster())
throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust);
if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee())
throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust);
// We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values
// which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best
// rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity
// then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because
// the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank.
if(trustWasDeleted) {
mFullScoreComputationNeeded = true;
}
if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) {
includeMeasurement = true;
for(OwnIdentity treeOwner : getAllOwnIdentities()) {
try {
// Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score.
if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0)
continue;
} catch(NotInTrustTreeException e) {
continue;
}
// See explanation above "We cannot iteratively REMOVE an inherited rank..."
if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) {
mFullScoreComputationNeeded = true;
break;
}
final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>();
unprocessedEdges.add(newTrust);
while(!unprocessedEdges.isEmpty()) {
final Trust trust = unprocessedEdges.removeFirst();
final Identity trustee = trust.getTrustee();
if(trustee == treeOwner)
continue;
Score currentStoredTrusteeScore;
try {
currentStoredTrusteeScore = getScore(treeOwner, trustee);
} catch(NotInTrustTreeException e) {
currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0);
}
final Score oldScore = currentStoredTrusteeScore.clone();
boolean oldShouldFetch = shouldFetchIdentity(trustee);
final int newScoreValue = computeScoreValue(treeOwner, trustee);
final int newRank = computeRank(treeOwner, trustee);
final int newCapacity = computeCapacity(treeOwner, trustee, newRank);
final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity);
// Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value,
// the rank and capacity are always computed based on the trust value of the own identity so we must also check this here:
if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank
&& (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore
mFullScoreComputationNeeded = true;
break;
}
if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) {
mFullScoreComputationNeeded = true;
break;
}
// We are OK to update it now. We must not update the values of the stored score object before determining whether we need
// a full score computation - the full computation needs the old values of the object.
currentStoredTrusteeScore.setValue(newScore.getScore());
currentStoredTrusteeScore.setRank(newScore.getRank());
currentStoredTrusteeScore.setCapacity(newScore.getCapacity());
// Identities should not get into the queue if they have no rank, see the large if() about 20 lines below
assert(currentStoredTrusteeScore.getRank() >= 0);
if(currentStoredTrusteeScore.getRank() >= 0)
currentStoredTrusteeScore.storeWithoutCommit();
// If fetch status changed from false to true, we need to start fetching it
// If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot
// cause new identities to be imported from their trust list, capacity > 0 allows this.
// If the fetch status changed from true to false, we need to stop fetching it
if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) {
if(!oldShouldFetch)
if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee);
else
if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee);
trustee.markForRefetch();
trustee.storeWithoutCommit();
mFetcher.storeStartFetchCommandWithoutCommit(trustee);
}
else if(oldShouldFetch && !shouldFetchIdentity(trustee)) {
if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee);
mFetcher.storeAbortFetchCommandWithoutCommit(trustee);
}
// If the rank or capacity changed then the trustees might be affected because the could have inherited theirs
if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) {
// If this identity has no capacity or no rank then it cannot affect its trustees:
// (- If it had none and it has none now then there is none which can be inherited, this is obvious)
// - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed
if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) {
// We need to update the trustees of trustee
for(Trust givenTrust : getGivenTrusts(trustee)) {
unprocessedEdges.add(givenTrust);
}
}
}
}
if(mFullScoreComputationNeeded)
break;
}
}
if(includeMeasurement) {
++mIncrementalScoreRecomputationCount;
mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime;
}
if(logMINOR) {
final String time = includeMeasurement ?
("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s")
: ("Time not measured: Computation was aborted before doing anything.");
if(!mFullScoreComputationNeeded)
Logger.minor(this, "Incremental computation of all Scores finished. " + time);
else
Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time);
}
if(!mTrustListImportInProgress) {
if(mFullScoreComputationNeeded) {
// TODO: Optimization: This uses very much CPU and memory. Write a partial computation function...
// TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT
// keep all objects in memory etc.
computeAllScoresWithoutCommit();
assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable
} else {
assert(computeAllScoresWithoutCommit()); // This function worked correctly.
}
} else { // a trust list import is in progress
// We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore
// updateScoresWithoutCommit is called often during import of a single trust list
// assert(computeAllScoresWithoutCommit());
}
}
/* Client interface functions */
public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException {
try {
getIdentityByURI(requestURI);
throw new InvalidParameterException("We already have this identity");
}
catch(UnknownIdentityException e) {
final Identity identity = new Identity(this, requestURI, null, false);
identity.storeAndCommit();
if(logDEBUG) Logger.debug(this, "Created identity " + identity);
// The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher.
// TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust.
return identity;
}
}
public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context)
throws MalformedURLException, InvalidParameterException {
FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME);
return createOwnIdentity(keypair[0], nickName, publishTrustList, context);
}
/**
* @param context A context with which you want to use the identity. Null if you want to add it later.
*/
public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName,
boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException {
synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
OwnIdentity identity;
try {
identity = getOwnIdentityByURI(insertURI);
throw new InvalidParameterException("The URI you specified is already used by the own identity " +
identity.getNickname() + ".");
}
catch(UnknownIdentityException uie) {
identity = new OwnIdentity(this, insertURI, nickName, publishTrustList);
if(context != null)
identity.addContext(context);
if(publishTrustList) {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
}
try {
identity.storeWithoutCommit();
initTrustTreeWithoutCommit(identity);
beginTrustListImport();
// Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation.
mFullScoreComputationNeeded = true;
for(String seedURI : SEED_IDENTITIES) {
try {
setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity.");
} catch(UnknownIdentityException e) {
Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e);
}
}
finishTrustListImport();
Persistent.checkedCommit(mDB, this);
if(mIntroductionClient != null)
mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles.
if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")");
return identity;
}
catch(RuntimeException e) {
abortTrustListImport(e); // Rolls back for us
throw e; // Satisfy the compiler
}
}
}
}
}
/**
* This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}.
*
* The {@link OwnIdentity} is not deleted because this would be a security issue:
* If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target
*
* @param id The {@link Identity.IdentityID} of the identity.
* @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID.
*/
public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException {
Logger.normal(this, "deleteOwnIdentity(): Starting... ");
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
final OwnIdentity oldIdentity = getOwnIdentityByID(id);
try {
Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity);
// We don't need any score computations to happen (explanation will follow below) so we don't need the following:
/* beginTrustListImport(); */
// This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards.
assert(computeAllScoresWithoutCommit());
final Identity newIdentity;
try {
newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList());
} catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen
throw new RuntimeException(e);
} catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen
throw new RuntimeException(e);
}
newIdentity.setContexts(oldIdentity.getContexts());
newIdentity.setProperties(oldIdentity.getProperties());
try {
newIdentity.setEdition(oldIdentity.getEdition());
} catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen
throw new RuntimeException(e);
}
// In theory we do not need to re-fetch the current trust list edition:
// The trust list of an own identity is always stored completely in the database, i.e. all trustees exist.
// HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that
// the current edition of the old OwndIdentity was not fetched yet.
// So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well.
if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) {
newIdentity.onFetched(oldIdentity.getLastFetchedDate());
}
// An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already.
newIdentity.storeWithoutCommit();
// Copy all received trusts.
// We don't have to modify them because they are user-assigned values and the assignment
// of the user does not change just because the type of the identity changes.
for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) {
Trust newReceivedTrust;
try {
newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity,
oldReceivedTrust.getValue(), oldReceivedTrust.getComment());
} catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen
throw new RuntimeException(e);
}
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newReceivedTrust.equals(oldReceivedTrust)); */
oldReceivedTrust.deleteWithoutCommit();
newReceivedTrust.storeWithoutCommit();
}
assert(getReceivedTrusts(oldIdentity).size() == 0);
// Copy all received scores.
// We don't have to modify them because the rating of the identity from the perspective of a
// different own identity should NOT be dependent upon whether it is an own identity or not.
for(Score oldScore : getScores(oldIdentity)) {
Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(),
oldScore.getRank(), oldScore.getCapacity());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newScore.equals(oldScore)); */
oldScore.deleteWithoutCommit();
newScore.storeWithoutCommit();
}
assert(getScores(oldIdentity).size() == 0);
// Delete all given scores:
// Non-own identities do not assign scores to other identities so we can just delete them.
for(Score oldScore : getGivenScores(oldIdentity)) {
final Identity trustee = oldScore.getTrustee();
final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee);
oldScore.deleteWithoutCommit();
// If the OwnIdentity which we are converting was the only source of trust to the trustee
// of this Score value, the should-fetch state of the trustee might change to false.
if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) {
mFetcher.storeAbortFetchCommandWithoutCommit(trustee);
}
}
assert(getGivenScores(oldIdentity).size() == 0);
// Copy all given trusts:
// We don't have to use the removeTrust/setTrust functions because the score graph does not need updating:
// - To the rating of the converted identity in the score graphs of other own identities it is irrelevant
// whether it is an own identity or not. The rating should never depend on whether it is an own identity!
// - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted
// completely and therefore it does not need to be updated.
for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) {
Trust newGivenTrust;
try {
newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(),
oldGivenTrust.getValue(), oldGivenTrust.getComment());
} catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen
throw new RuntimeException(e);
}
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newGivenTrust.equals(oldGivenTrust)); */
oldGivenTrust.deleteWithoutCommit();
newGivenTrust.storeWithoutCommit();
}
mPuzzleStore.onIdentityDeletion(oldIdentity);
mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
oldIdentity.deleteWithoutCommit();
mFetcher.storeStartFetchCommandWithoutCommit(newIdentity);
// This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards.
assert(computeAllScoresWithoutCommit());
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
Logger.normal(this, "deleteOwnIdentity(): Finished.");
}
/**
* NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()}
*/
public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException {
Logger.normal(this, "restoreOwnIdentity(): Starting... ");
OwnIdentity identity;
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
long edition = 0;
try {
edition = Math.max(edition, insertFreenetURI.getEdition());
} catch(IllegalStateException e) {
// The user supplied URI did not have an edition specified
}
try { // Try replacing an existing non-own version of the identity with an OwnIdentity
Identity oldIdentity = getIdentityByURI(insertFreenetURI);
if(oldIdentity instanceof OwnIdentity)
throw new InvalidParameterException("There is already an own identity with the given URI pair.");
Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity);
// Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function.
// But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference
// implementation will fail if two identities with the same ID exist.
// This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph
// but we must also store the own version to be able to modify the trust graph.
beginTrustListImport();
// We already have fetched this identity as a stranger's one. We need to update the database.
identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList());
/* We re-fetch the most recent edition to make sure all trustees are imported */
edition = Math.max(edition, oldIdentity.getEdition());
identity.restoreEdition(edition, oldIdentity.getLastFetchedDate());
identity.setContexts(oldIdentity.getContexts());
identity.setProperties(oldIdentity.getProperties());
identity.storeWithoutCommit();
initTrustTreeWithoutCommit(identity);
// Copy all received trusts.
// We don't have to modify them because they are user-assigned values and the assignment
// of the user does not change just because the type of the identity changes.
for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) {
Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity,
oldReceivedTrust.getValue(), oldReceivedTrust.getComment());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newReceivedTrust.equals(oldReceivedTrust)); */
oldReceivedTrust.deleteWithoutCommit();
newReceivedTrust.storeWithoutCommit();
}
assert(getReceivedTrusts(oldIdentity).size() == 0);
// Copy all received scores.
// We don't have to modify them because the rating of the identity from the perspective of a
// different own identity should NOT be dependent upon whether it is an own identity or not.
for(Score oldScore : getScores(oldIdentity)) {
Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(),
oldScore.getRank(), oldScore.getCapacity());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newScore.equals(oldScore)); */
oldScore.deleteWithoutCommit();
newScore.storeWithoutCommit();
}
assert(getScores(oldIdentity).size() == 0);
// What we do NOT have to deal with is the given scores of the old identity:
// Given scores do NOT exist for non-own identities, so there are no old ones to update.
// Of cause there WILL be scores because it is an own identity now.
// They will be created automatically when updating the given trusts
// - so thats what we will do now.
// Update all given trusts
for(Trust givenTrust : getGivenTrusts(oldIdentity)) {
// TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could:
// - manually delete the old Trust objects from the database
// - manually store the new trust objects
// - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version
// of setTrustWithoutCommit which deals with that.
// But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit:
// To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make
// it only update the parts of the trust graph which are affected.
// Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests.
removeTrustWithoutCommit(givenTrust);
setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment());
}
// We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit
// which would re-create scores of the old identity. We later call it AFTER deleting the old identity.
/* finishTrustListImport(); */
mPuzzleStore.onIdentityDeletion(oldIdentity);
mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
oldIdentity.deleteWithoutCommit();
finishTrustListImport();
} catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it.
identity = new OwnIdentity(this, insertFreenetURI, null, false);
Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity);
identity.restoreEdition(edition, null);
// Store the new identity
identity.storeWithoutCommit();
initTrustTreeWithoutCommit(identity);
}
mFetcher.storeStartFetchCommandWithoutCommit(identity);
// This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards.
assert(computeAllScoresWithoutCommit());
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function
abortTrustListImport(e); // Does rollback for us
throw e;
} else {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
}
Logger.normal(this, "restoreOwnIdentity(): Finished.");
}
public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment)
throws UnknownIdentityException, NumberFormatException, InvalidParameterException {
final OwnIdentity truster = getOwnIdentityByID(ownTrusterID);
Identity trustee = getIdentityByID(trusteeID);
setTrust(truster, trustee, value, comment);
}
public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException {
final OwnIdentity truster = getOwnIdentityByID(ownTrusterID);
final Identity trustee = getIdentityByID(trusteeID);
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
removeTrustWithoutCommit(truster, trustee);
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException {
final Identity identity = getOwnIdentityByID(ownIdentityID);
identity.addContext(newContext);
identity.storeAndCommit();
if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'");
}
public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException {
final Identity identity = getOwnIdentityByID(ownIdentityID);
identity.removeContext(context);
identity.storeAndCommit();
if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'");
}
public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException {
return getIdentityByID(identityID).getProperty(property);
}
public synchronized void setProperty(String ownIdentityID, String property, String value)
throws UnknownIdentityException, InvalidParameterException {
Identity identity = getOwnIdentityByID(ownIdentityID);
identity.setProperty(property, value);
identity.storeAndCommit();
if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'");
}
public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException {
final Identity identity = getOwnIdentityByID(ownIdentityID);
identity.removeProperty(property);
identity.storeAndCommit();
if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'");
}
public String getVersion() {
return Version.getMarketingVersion();
}
public long getRealVersion() {
return Version.getRealVersion();
}
public String getString(String key) {
return getBaseL10n().getString(key);
}
public void setLanguage(LANGUAGE newLanguage) {
WebOfTrust.l10n = new PluginL10n(this, newLanguage);
if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode);
}
public PluginRespirator getPluginRespirator() {
return mPR;
}
public ExtObjectContainer getDatabase() {
return mDB;
}
public Configuration getConfig() {
return mConfig;
}
public IdentityFetcher getIdentityFetcher() {
return mFetcher;
}
public XMLTransformer getXMLTransformer() {
return mXMLTransformer;
}
public IntroductionPuzzleStore getIntroductionPuzzleStore() {
return mPuzzleStore;
}
public IntroductionClient getIntroductionClient() {
return mIntroductionClient;
}
public RequestClient getRequestClient() {
return mRequestClient;
}
/**
* This is where our L10n files are stored.
* @return Path of our L10n files.
*/
public String getL10nFilesBasePath() {
return "plugins/WebOfTrust/l10n/";
}
/**
* This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ...
* @return Mask of the L10n files.
*/
public String getL10nFilesMask() {
return "lang_${lang}.l10n";
}
/**
* Override L10n files are stored on the disk, their names should be explicit
* we put here the plugin name, and the "override" indication. Plugin L10n
* override is not implemented in the node yet.
* @return Mask of the override L10n files.
*/
public String getL10nOverrideFilesMask() {
return "WebOfTrust_lang_${lang}.override.l10n";
}
/**
* Get the ClassLoader of this plugin. This is necessary when getting
* resources inside the plugin's Jar, for example L10n files.
* @return ClassLoader object
*/
public ClassLoader getPluginClassLoader() {
return WebOfTrust.class.getClassLoader();
}
/**
* Access to the current L10n data.
*
* @return L10n object.
*/
public BaseL10n getBaseL10n() {
return WebOfTrust.l10n.getBase();
}
public int getNumberOfFullScoreRecomputations() {
return mFullScoreRecomputationCount;
}
public synchronized double getAverageFullScoreRecomputationTime() {
return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000);
}
public int getNumberOfIncrementalScoreRecomputations() {
return mIncrementalScoreRecomputationCount;
}
public synchronized double getAverageIncrementalScoreRecomputationTime() {
return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000);
}
/**
* Tests whether two WoT are equal.
* This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests.
*/
public synchronized boolean equals(Object obj) {
if(obj == this)
return true;
if(!(obj instanceof WebOfTrust))
return false;
WebOfTrust other = (WebOfTrust)obj;
synchronized(other) {
{ // Compare own identities
final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities();
if(allIdentities.size() != other.getAllOwnIdentities().size())
return false;
for(OwnIdentity identity : allIdentities) {
try {
if(!identity.equals(other.getOwnIdentityByID(identity.getID())))
return false;
} catch(UnknownIdentityException e) {
return false;
}
}
}
{ // Compare identities
final ObjectSet<Identity> allIdentities = getAllIdentities();
if(allIdentities.size() != other.getAllIdentities().size())
return false;
for(Identity identity : allIdentities) {
try {
if(!identity.equals(other.getIdentityByID(identity.getID())))
return false;
} catch(UnknownIdentityException e) {
return false;
}
}
}
{ // Compare trusts
final ObjectSet<Trust> allTrusts = getAllTrusts();
if(allTrusts.size() != other.getAllTrusts().size())
return false;
for(Trust trust : allTrusts) {
try {
Identity otherTruster = other.getIdentityByID(trust.getTruster().getID());
Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID());
if(!trust.equals(other.getTrust(otherTruster, otherTrustee)))
return false;
} catch(UnknownIdentityException e) {
return false;
} catch(NotTrustedException e) {
return false;
}
}
}
{ // Compare scores
final ObjectSet<Score> allScores = getAllScores();
if(allScores.size() != other.getAllScores().size())
return false;
for(Score score : allScores) {
try {
OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID());
Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID());
if(!score.equals(other.getScore(otherTruster, otherTrustee)))
return false;
} catch(UnknownIdentityException e) {
return false;
} catch(NotInTrustTreeException e) {
return false;
}
}
}
}
return true;
}
}
| false | false | null | null |
diff --git a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java
index 1ef8b9fd43..ca07f013ef 100644
--- a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java
+++ b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java
@@ -1,546 +1,548 @@
package org.drools.rule.builder.dialect.java;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.jci.compilers.CompilationResult;
import org.apache.commons.jci.compilers.EclipseJavaCompiler;
import org.apache.commons.jci.compilers.EclipseJavaCompilerSettings;
import org.apache.commons.jci.compilers.JavaCompiler;
import org.apache.commons.jci.compilers.JavaCompilerFactory;
import org.apache.commons.jci.problems.CompilationProblem;
import org.apache.commons.jci.readers.MemoryResourceReader;
import org.apache.commons.jci.readers.ResourceReader;
import org.drools.RuntimeDroolsException;
import org.drools.base.ClassFieldExtractorCache;
import org.drools.base.TypeResolver;
import org.drools.compiler.PackageBuilder;
import org.drools.compiler.PackageBuilderConfiguration;
import org.drools.compiler.RuleError;
import org.drools.compiler.PackageBuilder.ErrorHandler;
import org.drools.compiler.PackageBuilder.FunctionErrorHandler;
import org.drools.compiler.PackageBuilder.RuleErrorHandler;
import org.drools.compiler.PackageBuilder.RuleInvokerErrorHandler;
import org.drools.lang.descr.AccumulateDescr;
import org.drools.lang.descr.AndDescr;
import org.drools.lang.descr.BaseDescr;
import org.drools.lang.descr.CollectDescr;
import org.drools.lang.descr.EvalDescr;
import org.drools.lang.descr.ExistsDescr;
import org.drools.lang.descr.ForallDescr;
import org.drools.lang.descr.FromDescr;
import org.drools.lang.descr.FunctionDescr;
import org.drools.lang.descr.NotDescr;
import org.drools.lang.descr.OrDescr;
import org.drools.lang.descr.PatternDescr;
import org.drools.lang.descr.RuleDescr;
import org.drools.rule.LineMappings;
import org.drools.rule.Package;
import org.drools.rule.Rule;
import org.drools.rule.builder.AccumulateBuilder;
import org.drools.rule.builder.CollectBuilder;
import org.drools.rule.builder.ConditionalElementBuilder;
import org.drools.rule.builder.ConsequenceBuilder;
import org.drools.rule.builder.Dialect;
import org.drools.rule.builder.ForallBuilder;
import org.drools.rule.builder.FromBuilder;
import org.drools.rule.builder.FunctionBuilder;
import org.drools.rule.builder.GroupElementBuilder;
import org.drools.rule.builder.PatternBuilder;
import org.drools.rule.builder.PredicateBuilder;
import org.drools.rule.builder.ReturnValueBuilder;
import org.drools.rule.builder.RuleBuildContext;
import org.drools.rule.builder.RuleClassBuilder;
import org.drools.rule.builder.SalienceBuilder;
import org.drools.rule.builder.dialect.mvel.MVELExprAnalyzer;
import org.drools.rule.builder.dialect.mvel.MVELFromBuilder;
import org.drools.rule.builder.dialect.mvel.MVELSalienceBuilder;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class JavaDialect
implements
Dialect {
// builders
private final PatternBuilder pattern = new PatternBuilder( this );
private final SalienceBuilder salience = new MVELSalienceBuilder();
private final JavaAccumulateBuilder accumulate = new JavaAccumulateBuilder();
private final JavaEvalBuilder eval = new JavaEvalBuilder();
private final JavaPredicateBuilder predicate = new JavaPredicateBuilder();
private final JavaReturnValueBuilder returnValue = new JavaReturnValueBuilder();
private final JavaConsequenceBuilder consequence = new JavaConsequenceBuilder();
private final JavaRuleClassBuilder rule = new JavaRuleClassBuilder();
private final MVELFromBuilder from = new MVELFromBuilder();
private final JavaFunctionBuilder function = new JavaFunctionBuilder();
//
private final KnowledgeHelperFixer knowledgeHelperFixer;
private final DeclarationTypeFixer typeFixer;
private final JavaExprAnalyzer analyzer;
private PackageBuilderConfiguration configuration;
private Package pkg;
private JavaCompiler compiler;
private List generatedClassList;
private MemoryResourceReader src;
private PackageStore packageStoreWrapper;
private Map lineMappings;
private Map errorHandlers;
private List results;
// the class name for the rule
private String ruleClass;
private final TypeResolver typeResolver;
private final ClassFieldExtractorCache classFieldExtractorCache;
// a map of registered builders
private Map builders;
public JavaDialect(final PackageBuilder builder) {
this.pkg = builder.getPackage();
this.configuration = builder.getPackageBuilderConfiguration();
this.typeResolver = builder.getTypeResolver();
this.classFieldExtractorCache = builder.getClassFieldExtractorCache();
this.knowledgeHelperFixer = new KnowledgeHelperFixer();
this.typeFixer = new DeclarationTypeFixer();
this.analyzer = new JavaExprAnalyzer();
if ( pkg != null ) {
init( pkg );
}
initBuilder();
+
+ loadCompiler();
}
public void initBuilder() {
// statically adding all builders to the map
// but in the future we can move that to a configuration
// if we want to
this.builders = new HashMap();
this.builders.put( CollectDescr.class,
new CollectBuilder() );
this.builders.put( ForallDescr.class,
new ForallBuilder() );
final GroupElementBuilder gebuilder = new GroupElementBuilder();
this.builders.put( AndDescr.class,
gebuilder );
this.builders.put( OrDescr.class,
gebuilder );
this.builders.put( NotDescr.class,
gebuilder );
this.builders.put( ExistsDescr.class,
gebuilder );
this.builders.put( PatternDescr.class,
getPatternBuilder() );
this.builders.put( FromDescr.class,
getFromBuilder() );
this.builders.put( AccumulateDescr.class,
getAccumulateBuilder() );
this.builders.put( EvalDescr.class,
getEvalBuilder() );
}
public Map getBuilders() {
return this.builders;
}
public void init(final Package pkg) {
this.pkg = pkg;
this.errorHandlers = new HashMap();
this.results = new ArrayList();
this.src = new MemoryResourceReader();
if ( pkg != null ) {
this.packageStoreWrapper = new PackageStore( pkg.getPackageCompilationData(),
this.results );
this.lineMappings = pkg.getPackageCompilationData().getLineMappings();
}
this.generatedClassList = new ArrayList();
this.packageStoreWrapper = new PackageStore( pkg.getPackageCompilationData(),
this.results );
this.lineMappings = new HashMap();
pkg.getPackageCompilationData().setLineMappings( this.lineMappings );
}
public void init(final RuleDescr ruleDescr) {
final String ruleClassName = getUniqueLegalName( this.pkg.getName(),
ruleDescr.getName(),
"java",
this.src );
ruleDescr.setClassName( ucFirst( ruleClassName ) );
}
public void setRuleClass(final String ruleClass) {
this.ruleClass = ruleClass;
}
public List[] getExpressionIdentifiers(final RuleBuildContext context,
final BaseDescr descr,
final Object content) {
List[] usedIdentifiers = null;
try {
usedIdentifiers = this.analyzer.analyzeExpression( (String) content,
new Set[]{context.getDeclarationResolver().getDeclarations().keySet(), context.getPkg().getGlobals().keySet()} );
} catch ( final Exception e ) {
context.getErrors().add( new RuleError( context.getRule(),
descr,
null,
"Unable to determine the used declarations" ) );
}
return usedIdentifiers;
}
public List[] getBlockIdentifiers(final RuleBuildContext context,
final BaseDescr descr,
final String text) {
List[] usedIdentifiers = null;
try {
usedIdentifiers = this.analyzer.analyzeBlock( text,
new Set[]{context.getDeclarationResolver().getDeclarations().keySet(), context.getPkg().getGlobals().keySet()} );
} catch ( final Exception e ) {
context.getErrors().add( new RuleError( context.getRule(),
descr,
null,
"Unable to determine the used declarations" ) );
}
return usedIdentifiers;
}
/**
* Returns the current type resolver instance
* @return
*/
public TypeResolver getTypeResolver() {
return this.typeResolver;
}
/**
* Returns the cache of field extractors
* @return
*/
public ClassFieldExtractorCache getClassFieldExtractorCache() {
return this.classFieldExtractorCache;
}
/**
* Returns the Knowledge Helper Fixer
* @return
*/
public KnowledgeHelperFixer getKnowledgeHelperFixer() {
return this.knowledgeHelperFixer;
}
/**
* @return the typeFixer
*/
public DeclarationTypeFixer getTypeFixer() {
return this.typeFixer;
}
public Object getBuilder(final Class clazz) {
return this.builders.get( clazz );
}
public PatternBuilder getPatternBuilder() {
return this.pattern;
}
public SalienceBuilder getSalienceBuilder() {
return this.salience;
}
public AccumulateBuilder getAccumulateBuilder() {
return this.accumulate;
}
public ConditionalElementBuilder getEvalBuilder() {
return this.eval;
}
public PredicateBuilder getPredicateBuilder() {
return this.predicate;
}
public ReturnValueBuilder getReturnValueBuilder() {
return this.returnValue;
}
public ConsequenceBuilder getConsequenceBuilder() {
return this.consequence;
}
public RuleClassBuilder getRuleClassBuilder() {
return this.rule;
}
public FunctionBuilder getFunctionBuilder() {
return this.function;
}
public FromBuilder getFromBuilder() {
return this.from;
}
/**
* This actually triggers the compiling of all the resources.
* Errors are mapped back to the element that originally generated the semantic
* code.
*/
public void compileAll() {
if ( this.generatedClassList.isEmpty() ) {
return;
}
final String[] classes = new String[this.generatedClassList.size()];
this.generatedClassList.toArray( classes );
final CompilationResult result = this.compiler.compile( classes,
this.src,
this.packageStoreWrapper,
this.pkg.getPackageCompilationData().getClassLoader() );
//this will sort out the errors based on what class/file they happened in
if ( result.getErrors().length > 0 ) {
for ( int i = 0; i < result.getErrors().length; i++ ) {
final CompilationProblem err = result.getErrors()[i];
final ErrorHandler handler = (ErrorHandler) this.errorHandlers.get( err.getFileName() );
if ( handler instanceof RuleErrorHandler ) {
final RuleErrorHandler rh = (RuleErrorHandler) handler;
}
handler.addError( err );
}
final Collection errors = this.errorHandlers.values();
for ( final Iterator iter = errors.iterator(); iter.hasNext(); ) {
final ErrorHandler handler = (ErrorHandler) iter.next();
if ( handler.isInError() ) {
if ( !(handler instanceof RuleInvokerErrorHandler) ) {
this.results.add( handler.getError() );
} else {
//we don't really want to report invoker errors.
//mostly as they can happen when there is a syntax error in the RHS
//and otherwise, it is a programmatic error in drools itself.
//throw new RuntimeException( "Warning: An error occurred compiling a semantic invoker. Errors should have been reported elsewhere." + handler.getError() );
}
}
}
}
// We've compiled everthing, so clear it for the next set of additions
this.generatedClassList.clear();
}
/**
* This will add the rule for compiling later on.
* It will not actually call the compiler
*/
public void addRule(final RuleBuildContext context) {
// return if there is no ruleclass name;
if ( this.ruleClass == null ) {
return;
}
final Rule rule = context.getRule();
final RuleDescr ruleDescr = context.getRuleDescr();
// The compilation result is for th entire rule, so difficult to associate with any descr
addClassCompileTask( this.pkg.getName() + "." + ruleDescr.getClassName(),
ruleDescr,
this.ruleClass,
this.src,
new RuleErrorHandler( ruleDescr,
rule,
"Rule Compilation error" ) );
for ( final Iterator it = context.getInvokers().keySet().iterator(); it.hasNext(); ) {
final String className = (String) it.next();
// Check if an invoker - returnvalue, predicate, eval or consequence has been associated
// If so we add it to the PackageCompilationData as it will get wired up on compilation
final Object invoker = context.getInvokerLookups().get( className );
if ( invoker != null ) {
this.pkg.getPackageCompilationData().putInvoker( className,
invoker );
}
final String text = (String) context.getInvokers().get( className );
//System.out.println( className + ":\n" + text );
final BaseDescr descr = (BaseDescr) context.getDescrLookups().get( className );
addClassCompileTask( className,
descr,
text,
this.src,
new RuleInvokerErrorHandler( descr,
rule,
"Unable to generate rule invoker." ) );
}
// setup the line mappins for this rule
final String name = this.pkg.getName() + "." + ucFirst( ruleDescr.getClassName() );
final LineMappings mapping = new LineMappings( name );
mapping.setStartLine( ruleDescr.getConsequenceLine() );
mapping.setOffset( ruleDescr.getConsequenceOffset() );
this.lineMappings.put( name,
mapping );
}
public void addFunction(final FunctionDescr functionDescr,
final TypeResolver typeResolver) {
final String functionClassName = this.pkg.getName() + "." + ucFirst( functionDescr.getName() );
this.pkg.addStaticImport( functionClassName + "." + functionDescr.getName() );
functionDescr.setClassName( functionClassName );
this.pkg.addFunction( functionDescr.getName() );
final String functionSrc = getFunctionBuilder().build( this.pkg,
functionDescr,
typeResolver,
this.lineMappings,
this.results );
addClassCompileTask( functionClassName,
functionDescr,
functionSrc,
this.src,
new FunctionErrorHandler( functionDescr,
"Function Compilation error" ) );
final LineMappings mapping = new LineMappings( functionClassName );
mapping.setStartLine( functionDescr.getLine() );
mapping.setOffset( functionDescr.getOffset() );
this.lineMappings.put( functionClassName,
mapping );
}
/**
* This adds a compile "task" for when the compiler of
* semantics (JCI) is called later on with compileAll()\
* which actually does the compiling.
* The ErrorHandler is required to map the errors back to the
* element that caused it.
*/
private void addClassCompileTask(final String className,
final BaseDescr descr,
final String text,
final MemoryResourceReader src,
final ErrorHandler handler) {
final String fileName = className.replace( '.',
'/' ) + ".java";
src.add( fileName,
text.getBytes() );
this.errorHandlers.put( fileName,
handler );
addClassName( fileName );
}
public void addClassName(final String className) {
this.generatedClassList.add( className );
}
private void loadCompiler() {
switch ( this.configuration.getCompiler() ) {
case PackageBuilderConfiguration.JANINO : {
if ( !"1.4".equals( this.configuration.getJavaLanguageLevel() ) ) {
throw new RuntimeDroolsException( "Incompatible Java language level with selected compiler" );
}
this.compiler = JavaCompilerFactory.getInstance().createCompiler( "janino" );
break;
}
case PackageBuilderConfiguration.ECLIPSE :
default : {
final EclipseJavaCompilerSettings eclipseSettings = new EclipseJavaCompilerSettings();
final Map map = eclipseSettings.getMap();
String lngLevel = this.configuration.getJavaLanguageLevel();
map.put( CompilerOptions.OPTION_TargetPlatform,
lngLevel );
if ( lngLevel == "1.4" ) {
// 1.5 is the minimum for source langauge level, so we can use static imports.
lngLevel = "1.5";
}
map.put( CompilerOptions.OPTION_Source,
lngLevel );
this.compiler = new EclipseJavaCompiler( map );
break;
}
}
}
public void addImport(String importEntry) {
// we don't need to do anything here
}
public void addStaticImport(String staticImportEntry) {
// we don't need to do anything here
}
public List getResults() {
return this.results;
}
/**
* Takes a given name and makes sure that its legal and doesn't already exist. If the file exists it increases counter appender untill it is unique.
*
* @param packageName
* @param name
* @param ext
* @return
*/
private String getUniqueLegalName(final String packageName,
final String name,
final String ext,
final ResourceReader src) {
// replaces all non alphanumeric or $ chars with _
String newName = "Rule_" + name.replaceAll( "[[^\\w]$]",
"_" );
// make sure the class name does not exist, if it does increase the counter
int counter = -1;
boolean exists = true;
while ( exists ) {
counter++;
final String fileName = packageName.replaceAll( "\\.",
"/" ) + newName + "_" + counter + ext;
exists = src.isAvailable( fileName );
}
// we have duplicate file names so append counter
if ( counter >= 0 ) {
newName = newName + "_" + counter;
}
return newName;
}
private String ucFirst(final String name) {
return name.toUpperCase().charAt( 0 ) + name.substring( 1 );
}
}
diff --git a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java
index b6718fcff8..86de1a4dff 100644
--- a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java
+++ b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java
@@ -1,286 +1,288 @@
package org.drools.rule.builder.dialect.mvel;
import java.lang.reflect.Method;
import java.nio.channels.UnsupportedAddressTypeException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.drools.base.ClassFieldExtractorCache;
import org.drools.base.TypeResolver;
import org.drools.compiler.PackageBuilder;
import org.drools.compiler.PackageBuilderConfiguration;
import org.drools.compiler.RuleError;
import org.drools.lang.descr.AccumulateDescr;
import org.drools.lang.descr.AndDescr;
import org.drools.lang.descr.BaseDescr;
import org.drools.lang.descr.CollectDescr;
import org.drools.lang.descr.EvalDescr;
import org.drools.lang.descr.ExistsDescr;
import org.drools.lang.descr.ForallDescr;
import org.drools.lang.descr.FromDescr;
import org.drools.lang.descr.FunctionDescr;
import org.drools.lang.descr.NotDescr;
import org.drools.lang.descr.OrDescr;
import org.drools.lang.descr.PatternDescr;
import org.drools.lang.descr.RuleDescr;
import org.drools.rule.Package;
import org.drools.rule.builder.AccumulateBuilder;
import org.drools.rule.builder.CollectBuilder;
import org.drools.rule.builder.ConditionalElementBuilder;
import org.drools.rule.builder.ConsequenceBuilder;
import org.drools.rule.builder.Dialect;
import org.drools.rule.builder.ForallBuilder;
import org.drools.rule.builder.FromBuilder;
import org.drools.rule.builder.GroupElementBuilder;
import org.drools.rule.builder.PatternBuilder;
import org.drools.rule.builder.PredicateBuilder;
import org.drools.rule.builder.ReturnValueBuilder;
import org.drools.rule.builder.RuleBuildContext;
import org.drools.rule.builder.RuleClassBuilder;
import org.drools.rule.builder.SalienceBuilder;
import org.drools.rule.builder.dialect.java.DeclarationTypeFixer;
import org.drools.rule.builder.dialect.java.JavaAccumulateBuilder;
import org.drools.rule.builder.dialect.java.JavaConsequenceBuilder;
import org.drools.rule.builder.dialect.java.JavaEvalBuilder;
import org.drools.rule.builder.dialect.java.JavaExprAnalyzer;
import org.drools.rule.builder.dialect.java.JavaFunctionBuilder;
import org.drools.rule.builder.dialect.java.JavaPredicateBuilder;
import org.drools.rule.builder.dialect.java.JavaReturnValueBuilder;
import org.drools.rule.builder.dialect.java.JavaRuleClassBuilder;
import org.drools.rule.builder.dialect.java.KnowledgeHelperFixer;
import org.mvel.integration.impl.ClassImportResolverFactory;
import org.mvel.integration.impl.StaticMethodImportResolverFactory;
public class MVELDialect
implements
Dialect {
private final PatternBuilder pattern = new PatternBuilder( this );
//private final JavaAccumulateBuilder accumulate = new JavaAccumulateBuilder();
private final SalienceBuilder salience = new MVELSalienceBuilder();
private final MVELEvalBuilder eval = new MVELEvalBuilder();
private final MVELPredicateBuilder predicate = new MVELPredicateBuilder();
private final MVELReturnValueBuilder returnValue = new MVELReturnValueBuilder();
private final MVELConsequenceBuilder consequence = new MVELConsequenceBuilder();
//private final JavaRuleClassBuilder rule = new JavaRuleClassBuilder();
private final MVELFromBuilder from = new MVELFromBuilder();
private List results;
//private final JavaFunctionBuilder function = new JavaFunctionBuilder();
private Package pkg;
private PackageBuilderConfiguration configuration;
private final TypeResolver typeResolver;
private final ClassFieldExtractorCache classFieldExtractorCache;
private final MVELExprAnalyzer analyzer;
private final StaticMethodImportResolverFactory staticImportFactory;
private final ClassImportResolverFactory importFactory;
public void addFunction(FunctionDescr functionDescr,
TypeResolver typeResolver) {
throw new UnsupportedOperationException( "MVEL does not support functions" );
}
// a map of registered builders
private Map builders;
public MVELDialect(final PackageBuilder builder) {
this.pkg = builder.getPackage();
this.configuration = builder.getPackageBuilderConfiguration();
this.typeResolver = builder.getTypeResolver();
this.classFieldExtractorCache = builder.getClassFieldExtractorCache();
this.analyzer = new MVELExprAnalyzer();
if ( pkg != null ) {
init( pkg );
}
+
+ this.results = new ArrayList();
initBuilder();
this.importFactory = new ClassImportResolverFactory();
this.staticImportFactory = new StaticMethodImportResolverFactory();
this.importFactory.setNextFactory( this.staticImportFactory );
}
public void initBuilder() {
// statically adding all builders to the map
// but in the future we can move that to a configuration
// if we want to
this.builders = new HashMap();
final GroupElementBuilder gebuilder = new GroupElementBuilder();
this.builders.put( AndDescr.class,
gebuilder );
this.builders.put( OrDescr.class,
gebuilder );
this.builders.put( NotDescr.class,
gebuilder );
this.builders.put( ExistsDescr.class,
gebuilder );
this.builders.put( PatternDescr.class,
getPatternBuilder() );
this.builders.put( FromDescr.class,
getFromBuilder() );
// this.builders.put( AccumulateDescr.class,
// getAccumulateBuilder() );
this.builders.put( EvalDescr.class,
getEvalBuilder() );
}
public void init(Package pkg) {
this.pkg = pkg;
this.results = new ArrayList();
}
public void init(RuleDescr ruleDescr) {
}
public void addRule(RuleBuildContext context) {
}
public void addImport(String importEntry) {
try {
Class cls = this.configuration.getClassLoader().loadClass( importEntry );
this.importFactory.addClass( cls );
} catch ( ClassNotFoundException e ) {
// @todo: add MVEL error
this.results.add( null );
}
}
public void addStaticImport(String staticImportEntry) {
int index = staticImportEntry.lastIndexOf( '.' );
String className = staticImportEntry.substring( 0, index );
String methodName = staticImportEntry.substring( 0, index + 1 );
try {
Class cls = this.configuration.getClassLoader().loadClass( className );
Method[] methods = cls.getDeclaredMethods();
for ( int i = 0; i < methods.length; i++ ) {
if ( methods[i].equals( "methodName" ) ) {
this.staticImportFactory.createVariable( methodName, methods[i] );
break;
}
}
} catch ( ClassNotFoundException e ) {
// @todo: add MVEL error
this.results.add( null );
}
}
public StaticMethodImportResolverFactory getStaticMethodImportResolverFactory() {
return this.staticImportFactory;
}
public ClassImportResolverFactory getClassImportResolverFactory() {
return this.importFactory;
}
public void compileAll() {
}
public List[] getExpressionIdentifiers(RuleBuildContext context,
BaseDescr descr,
Object content) {
List[] usedIdentifiers = null;
try {
usedIdentifiers = this.analyzer.analyzeExpression( (String) content,
new Set[]{context.getDeclarationResolver().getDeclarations().keySet(), context.getPkg().getGlobals().keySet()} );
} catch ( final Exception e ) {
context.getErrors().add( new RuleError( context.getRule(),
descr,
null,
"Unable to determine the used declarations" ) );
}
return usedIdentifiers;
}
public List[] getBlockIdentifiers(RuleBuildContext context,
BaseDescr descr,
String text) {
List[] usedIdentifiers = null;
try {
usedIdentifiers = this.analyzer.analyzeExpression( text,
new Set[]{context.getDeclarationResolver().getDeclarations().keySet(), context.getPkg().getGlobals().keySet()} );
} catch ( final Exception e ) {
context.getErrors().add( new RuleError( context.getRule(),
descr,
null,
"Unable to determine the used declarations" ) );
}
return usedIdentifiers;
}
public Object getBuilder(final Class clazz) {
return this.builders.get( clazz );
}
public Map getBuilders() {
return this.builders;
}
public ClassFieldExtractorCache getClassFieldExtractorCache() {
return this.classFieldExtractorCache;
}
public PatternBuilder getPatternBuilder() {
return this.pattern;
}
public AccumulateBuilder getAccumulateBuilder() {
throw new UnsupportedOperationException( "MVEL does not yet support accumuate" );
}
public ConsequenceBuilder getConsequenceBuilder() {
return this.consequence;
}
public ConditionalElementBuilder getEvalBuilder() {
return this.eval;
}
public FromBuilder getFromBuilder() {
return this.from;
}
public PredicateBuilder getPredicateBuilder() {
return this.predicate;
}
public SalienceBuilder getSalienceBuilder() {
return this.salience;
}
public List getResults() {
return null;
}
public ReturnValueBuilder getReturnValueBuilder() {
return this.returnValue;
}
public RuleClassBuilder getRuleClassBuilder() {
return null;
}
public TypeResolver getTypeResolver() {
return this.typeResolver;
}
}
| false | false | null | null |
diff --git a/src/com/axelby/podax/PlayerService.java b/src/com/axelby/podax/PlayerService.java
index 5430297..df3f33a 100644
--- a/src/com/axelby/podax/PlayerService.java
+++ b/src/com/axelby/podax/PlayerService.java
@@ -1,597 +1,600 @@
package com.axelby.podax;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import android.bluetooth.BluetoothDevice;
import com.axelby.podax.R.drawable;
public class PlayerService extends Service {
public class PlayerBinder extends Binder {
PlayerService getService() {
return PlayerService.this;
}
}
protected int _lastPosition = 0;
public class UpdatePlayerPositionTimerTask extends TimerTask {
public void run() {
int oldPosition = _lastPosition;
_lastPosition = _player.getCurrentPosition();
if (oldPosition / 1000 != _lastPosition / 1000)
updateActivePodcastPosition();
}
}
protected UpdatePlayerPositionTimerTask _updatePlayerPositionTimerTask;
protected static MediaPlayer _player;
protected PlayerBinder _binder;
protected boolean _onPhone;
protected boolean _pausedForPhone;
protected Timer _updateTimer;
private static final Uri _activePodcastUri = Uri.withAppendedPath(PodcastProvider.URI, "active");
private OnAudioFocusChangeListener _afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
// focusChange could be AUDIOFOCUS_GAIN, AUDIOFOCUS_LOSS,
// _LOSS_TRANSIENT or _LOSS_TRANSIENT_CAN_DUCK
if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
doResume();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
doStop();
}
}
};
private final HeadsetConnectionReceiver _headsetConnectionReceiver = new HeadsetConnectionReceiver();
private final BluetoothConnectionReceiver _bluetoothConnectionReceiver = new BluetoothConnectionReceiver();
@Override
public IBinder onBind(Intent intent) {
handleIntent(intent);
return _binder;
}
public static boolean isPlaying() {
return _player != null && _player.isPlaying();
}
@Override
public void onCreate() {
super.onCreate();
_updateTimer = new Timer();
_binder = new PlayerBinder();
verifyPodcastReady();
// may or may not be creating the service
TelephonyManager _telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
_telephony.listen(new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
_onPhone = (state != TelephonyManager.CALL_STATE_IDLE);
if (_player != null && _onPhone) {
_player.pause();
updateActivePodcastPosition();
_pausedForPhone = true;
}
if (_player != null && !_onPhone && _pausedForPhone) {
_player.start();
updateActivePodcastPosition();
_pausedForPhone = false;
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
_onPhone = (_telephony.getCallState() != TelephonyManager.CALL_STATE_IDLE);
// hook our headset connection and disconnection
this.registerReceiver(_headsetConnectionReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
// hook our bluetooth headset connection and disconnection
//this.registerReceiver(_bluetoothConnectionReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
this.registerReceiver(_bluetoothConnectionReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
}
private void setupMediaPlayer() {
if (_player == null) {
_player = new MediaPlayer();
_player.setAudioStreamType(AudioManager.STREAM_MUSIC);
_pausedForPhone = false;
// handle errors so the onCompletionListener doens't get called
_player.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
PodaxLog.log(PlayerService.this, "mediaplayer error - what: %d, extra: %d", what, extra);
return true;
}
});
_player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer player) {
removeActivePodcastFromQueue();
playNextPodcast();
}
});
}
}
@Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(_headsetConnectionReceiver);
this.unregisterReceiver(_bluetoothConnectionReceiver);
Log.d("Podax", "destroying PlayerService");
}
@Override
public void onStart(Intent intent, int startId) {
handleIntent(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleIntent(intent);
return START_STICKY;
}
private void handleIntent(Intent intent) {
if (intent == null || intent.getExtras() == null)
return;
if (intent.getExtras().containsKey(Constants.EXTRA_PLAYER_COMMAND)) {
switch (intent.getIntExtra(Constants.EXTRA_PLAYER_COMMAND, -1)) {
case -1:
return;
case Constants.PLAYER_COMMAND_SKIPTO:
Log.d("Podax", "PlayerService got a command: skip to");
skipTo(intent.getIntExtra(Constants.EXTRA_PLAYER_COMMAND_ARG, 0));
break;
case Constants.PLAYER_COMMAND_SKIPTOEND:
Log.d("Podax", "PlayerService got a command: skip to end");
removeActivePodcastFromQueue();
playNextPodcast();
break;
case Constants.PLAYER_COMMAND_RESTART:
Log.d("Podax", "PlayerService got a command: restart");
restart();
break;
case Constants.PLAYER_COMMAND_SKIPBACK:
Log.d("Podax", "PlayerService got a command: skip back");
skip(-15);
break;
case Constants.PLAYER_COMMAND_SKIPFORWARD:
Log.d("Podax", "PlayerService got a command: skip forward");
skip(30);
break;
case Constants.PLAYER_COMMAND_PLAYPAUSE:
Log.d("Podax", "PlayerService got a command: playpause");
if (_player != null) {
Log.d("Podax", " stopping the player");
stop();
} else {
Log.d("Podax", " resuming a podcast");
resume();
}
break;
case Constants.PLAYER_COMMAND_PLAY:
Log.d("Podax", "PlayerService got a command: play");
resume();
break;
case Constants.PLAYER_COMMAND_PAUSE:
Log.d("Podax", "PlayerService got a command: pause");
stop();
break;
case Constants.PLAYER_COMMAND_PLAY_SPECIFIC_PODCAST:
Log.d("Podax", "PlayerService got a command: play specific podcast");
int podcastId = intent.getIntExtra(Constants.EXTRA_PLAYER_COMMAND_ARG, -1);
play((long)podcastId);
break;
}
}
}
public void stop() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.abandonAudioFocus(_afChangeListener);
}
doStop();
}
private void doStop() {
Log.d("Podax", "PlayerService stopping");
if (_updatePlayerPositionTimerTask != null)
_updatePlayerPositionTimerTask.cancel();
if (_updateTimer != null)
_updateTimer.cancel();
removeNotification();
if (_player != null)
_player.pause();
updateActivePodcastPosition();
if (_player != null)
_player.stop();
_player = null;
stopSelf();
// tell anything listening to the active podcast to refresh now that we're stopped
ContentValues values = new ContentValues();
getContentResolver().update(_activePodcastUri, values, null, null);
updateWidgets();
}
public void resume() {
if (_player == null)
setupMediaPlayer();
if (_onPhone)
return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = am.requestAudioFocus(_afChangeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED)
stop();
}
doResume();
}
private void doResume() {
PodaxLog.log(this, "PlayerService doResume");
String[] projection = new String[] {
PodcastProvider.COLUMN_ID,
PodcastProvider.COLUMN_MEDIA_URL,
PodcastProvider.COLUMN_LAST_POSITION,
PodcastProvider.COLUMN_DURATION,
PodcastProvider.COLUMN_FILE_SIZE,
};
Cursor c = getContentResolver().query(_activePodcastUri, projection, null, null, null);
try {
PodcastCursor p = new PodcastCursor(this, c);
if (p.isNull())
return;
if (!p.isDownloaded()) {
Toast.makeText(this, R.string.podcast_not_downloaded, Toast.LENGTH_SHORT).show();
return;
}
// don't update the podcast position while the player is reset
if (_updatePlayerPositionTimerTask != null) {
_updatePlayerPositionTimerTask.cancel();
_updatePlayerPositionTimerTask = null;
}
_player.reset();
_player.setDataSource(p.getFilename());
_player.prepare();
_player.seekTo(p.getLastPosition());
// set this podcast as active -- it may have been first in queue
changeActivePodcast(p.getId());
}
catch (IOException ex) {
stop();
} finally {
c.close();
}
// the user will probably try this if the podcast is over and the next one didn't start
if (_player.getCurrentPosition() >= _player.getDuration() - 1000) {
removeActivePodcastFromQueue();
playNextPodcast();
return;
}
_pausedForPhone = false;
_player.start();
showNotification();
_updatePlayerPositionTimerTask = new UpdatePlayerPositionTimerTask();
_updateTimer.schedule(_updatePlayerPositionTimerTask, 250, 250);
updateWidgets();
}
public void play(Long podcastId) {
changeActivePodcast(podcastId);
if (podcastId == null) {
stop();
return;
}
resume();
}
public void skip(int secs) {
if (_player != null) {
_player.seekTo(_player.getCurrentPosition() + secs * 1000);
updateActivePodcastPosition();
} else {
String[] projection = { PodcastProvider.COLUMN_LAST_POSITION };
Cursor c = getContentResolver().query(_activePodcastUri, projection, null, null, null);
try {
if (c.moveToNext()) {
updateActivePodcastPosition(c.getInt(0) + secs * 1000);
}
} finally {
c.close();
}
}
}
public void skipTo(int secs) {
if (_player != null) {
_player.seekTo(secs * 1000);
updateActivePodcastPosition();
} else {
updateActivePodcastPosition(secs * 1000);
}
}
public void restart() {
if (_player != null) {
_player.seekTo(0);
updateActivePodcastPosition();
} else {
updateActivePodcastPosition(0);
}
}
public String getPositionString() {
if (_player.getDuration() == 0)
return "";
return Helper.getTimeString(_player.getCurrentPosition())
+ " / " + Helper.getTimeString(_player.getDuration() - _player.getCurrentPosition());
}
private void playNextPodcast() {
Log.d("Podax", "moving to next podcast");
// stop the player and the updating while we do some administrative stuff
if (_player != null)
_player.pause();
if (_updatePlayerPositionTimerTask != null) {
_updatePlayerPositionTimerTask.cancel();
_updatePlayerPositionTimerTask = null;
}
updateActivePodcastPosition();
Long activePodcastId = moveToNextInQueue();
if (activePodcastId == null) {
Log.d("Podax", "PlayerService queue finished");
stop();
return;
}
resume();
}
public Long findFirstDownloadedInQueue() {
// make sure the active podcast has been downloaded
String[] projection = {
PodcastProvider.COLUMN_ID,
PodcastProvider.COLUMN_FILE_SIZE,
PodcastProvider.COLUMN_MEDIA_URL,
};
Uri queueUri = Uri.withAppendedPath(PodcastProvider.URI, "queue");
Cursor c = getContentResolver().query(queueUri, projection, null, null, null);
try {
while (c.moveToNext()) {
PodcastCursor podcast = new PodcastCursor(this, c);
if (podcast.isDownloaded())
return podcast.getId();
}
return null;
} finally {
c.close();
}
}
public Long moveToNextInQueue() {
Long activePodcastId = findFirstDownloadedInQueue();
if (activePodcastId == null)
stop();
changeActivePodcast(activePodcastId);
return activePodcastId;
}
public void changeActivePodcast(Long activePodcastId) {
ContentValues values = new ContentValues();
values.put(PodcastProvider.COLUMN_ID, activePodcastId);
getContentResolver().update(_activePodcastUri, values, null, null);
// if the podcast has ended and it's back in the queue, restart it
String[] projection = {
PodcastProvider.COLUMN_ID,
PodcastProvider.COLUMN_DURATION,
PodcastProvider.COLUMN_LAST_POSITION,
};
Cursor c = getContentResolver().query(_activePodcastUri, projection, null, null, null);
try {
if (c.moveToNext()) {
PodcastCursor podcast = new PodcastCursor(this, c);
if (podcast.getDuration() > 0 && podcast.getLastPosition() > podcast.getDuration() - 1000)
podcast.setLastPosition(0);
}
} finally {
c.close();
}
}
public Long verifyPodcastReady() {
String[] projection = new String[] { PodcastProvider.COLUMN_ID };
Cursor c = getContentResolver().query(_activePodcastUri, projection, null, null, null);
try {
if (c.moveToNext())
return c.getLong(0);
else
return moveToNextInQueue();
} finally {
c.close();
}
}
private void showNotification() {
String[] projection = new String[] {
PodcastProvider.COLUMN_ID,
PodcastProvider.COLUMN_TITLE,
PodcastProvider.COLUMN_SUBSCRIPTION_TITLE,
};
Cursor c = getContentResolver().query(_activePodcastUri, projection, null, null, null);
if (c.isAfterLast())
return;
PodcastCursor podcast = new PodcastCursor(this, c);
int icon = drawable.icon;
CharSequence tickerText = podcast.getTitle();
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
CharSequence contentTitle = podcast.getTitle();
CharSequence contentText = podcast.getSubscriptionTitle();
Intent notificationIntent = new Intent(this, PodcastDetailActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
startForeground(Constants.NOTIFICATION_PLAYING, notification);
c.close();
}
private void removeNotification() {
stopForeground(true);
}
private void updateWidgets() {
AppWidgetManager widgetManager = AppWidgetManager.getInstance(this);
int[] widgetIds;
widgetIds = widgetManager.getAppWidgetIds(new ComponentName(this, LargeWidgetProvider.class));
if (widgetIds.length > 0) {
AppWidgetProvider provider = (AppWidgetProvider) new LargeWidgetProvider();
provider.onUpdate(this, widgetManager, widgetIds);
}
widgetIds = widgetManager.getAppWidgetIds(new ComponentName(this, SmallWidgetProvider.class));
if (widgetIds.length > 0) {
AppWidgetProvider provider = (AppWidgetProvider) new SmallWidgetProvider();
provider.onUpdate(this, widgetManager, widgetIds);
}
}
public void updateActivePodcastPosition() {
+ if (_player == null)
+ return;
+
ContentValues values = new ContentValues();
values.put(PodcastProvider.COLUMN_LAST_POSITION, _player.getCurrentPosition());
PlayerService.this.getContentResolver().update(_activePodcastUri, values, null, null);
// update widgets
updateWidgets();
}
public void updateActivePodcastPosition(int position) {
ContentValues values = new ContentValues();
values.put(PodcastProvider.COLUMN_LAST_POSITION, position);
PlayerService.this.getContentResolver().update(_activePodcastUri, values, null, null);
// update widgets
updateWidgets();
}
public void removeActivePodcastFromQueue() {
ContentValues values = new ContentValues();
values.put(PodcastProvider.COLUMN_LAST_POSITION, 0);
values.put(PodcastProvider.COLUMN_QUEUE_POSITION, (Integer)null);
PlayerService.this.getContentResolver().update(_activePodcastUri, values, null, null);
}
// static functions for easier controls
public static void play(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_PLAY);
}
public static void pause(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_PAUSE);
}
public static void playpause(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_PLAYPAUSE);
}
public static void skipForward(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_SKIPFORWARD);
}
public static void skipBack(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_SKIPBACK);
}
public static void restart(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_RESTART);
}
public static void skipToEnd(Context context) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_SKIPTOEND);
}
public static void skipTo(Context context, int secs) {
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_SKIPTO, secs);
}
public static void play(Context context, PodcastCursor podcast) {
if (podcast == null)
return;
PlayerService.sendCommand(context, Constants.PLAYER_COMMAND_PLAY_SPECIFIC_PODCAST, (int)(long)podcast.getId());
}
private static void sendCommand(Context context, int command) {
Intent intent = new Intent(context, PlayerService.class);
intent.putExtra(Constants.EXTRA_PLAYER_COMMAND, command);
context.startService(intent);
}
private static void sendCommand(Context context, int command, int arg) {
Intent intent = new Intent(context, PlayerService.class);
intent.putExtra(Constants.EXTRA_PLAYER_COMMAND, command);
intent.putExtra(Constants.EXTRA_PLAYER_COMMAND_ARG, arg);
context.startService(intent);
}
}
| true | false | null | null |
diff --git a/src/com/martinleopold/mode/debug/DebugEditor.java b/src/com/martinleopold/mode/debug/DebugEditor.java
index e29a88d..db9a43c 100644
--- a/src/com/martinleopold/mode/debug/DebugEditor.java
+++ b/src/com/martinleopold/mode/debug/DebugEditor.java
@@ -1,632 +1,633 @@
/*
* Copyright (C) 2012 Martin Leopold <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.martinleopold.mode.debug;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.text.Document;
import processing.app.*;
import processing.app.syntax.JEditTextArea;
import processing.app.syntax.PdeTextAreaDefaults;
import processing.mode.java.JavaEditor;
/**
* Main View Class. Handles the editor window incl. toolbar and menu. Has access
* to the Sketch. Provides line highlighting (for breakpoints and the debuggers
* current line).
*
* @author Martin Leopold <[email protected]>
*/
public class DebugEditor extends JavaEditor implements ActionListener {
// important fields from superclass
//protected Sketch sketch;
//private JMenu fileMenu;
//protected EditorToolbar toolbar;
// highlighting
//public static final Color BREAKPOINT_COLOR = new Color(255, 170, 170); // the background color for highlighting lines
//public static final Color BREAKPOINT_COLOR = new Color(180, 210, 255); // the background color for highlighting lines
public static final Color BREAKPOINT_COLOR = new Color(240, 240, 240); // the background color for highlighting lines
public static final Color CURRENT_LINE_COLOR = new Color(255, 255, 150); // the background color for highlighting lines
public static final String BREAKPOINT_MARKER = "--";
public static final String CURRENT_LINE_MARKER = "->";
public static final Color BREAKPOINT_MARKER_COLOR = new Color(150, 150, 150);
public static final Color CURRENT_LINE_MARKER_COLOR = new Color(226, 117, 0);
protected List<LineHighlight> breakpointedLines = new ArrayList(); // breakpointed lines
protected LineHighlight currentLine; // line the debugger is currently suspended at
// menus
protected JMenu debugMenu;
// debugger control
protected JMenuItem debugMenuItem;
protected JMenuItem continueMenuItem;
protected JMenuItem stopMenuItem;
// breakpoints
protected JMenuItem setBreakpointMenuItem;
protected JMenuItem removeBreakpointMenuItem;
protected JMenuItem listBreakpointsMenuItem;
// stepping
protected JMenuItem stepOverMenuItem;
protected JMenuItem stepIntoMenuItem;
protected JMenuItem stepOutMenuItem;
// info
protected JMenuItem printStackTraceMenuItem;
protected JMenuItem printLocalsMenuItem;
protected JMenuItem printThisMenuItem;
protected JMenuItem printSourceMenuItem;
protected JMenuItem printThreads;
// variable inspector
protected JMenuItem toggleVariableInspectorMenuItem;
protected DebugMode dmode;
protected Debugger dbg;
protected VariableInspector vi;
protected TextArea ta;
public DebugEditor(Base base, String path, EditorState state, Mode mode) {
super(base, path, state, mode);
// add debug menu to editor frame
JMenuBar menuBar = getJMenuBar();
menuBar.add(buildDebugMenu());
dmode = (DebugMode) mode;
// init controller class
dbg = new Debugger(this);
// variable inspector window
vi = new VariableInspector(this);
// access to customized (i.e. subclassed) text area
ta = (TextArea) textarea;
// set action on frame close
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
onWindowClosing(e);
}
});
}
/**
* Event handler called when closing the editor window. Kills the variable
* inspector window.
*
* @param e the event object
*/
protected void onWindowClosing(WindowEvent e) {
System.out.println("closing window");
// remove var.inspector
vi.dispose();
// quit running debug session
dbg.stopDebug();
}
/**
* Creates the debug menu. Includes ActionListeners for the menu items.
* Intended for adding to the menu bar.
*
* @return The debug menu
*/
protected JMenu buildDebugMenu() {
debugMenu = new JMenu("Debug");
debugMenuItem = new JMenuItem("Debug");
debugMenuItem.addActionListener(this);
continueMenuItem = new JMenuItem("Continue");
continueMenuItem.addActionListener(this);
stopMenuItem = new JMenuItem("Stop");
stopMenuItem.addActionListener(this);
setBreakpointMenuItem = new JMenuItem("Set Breakpoint");
setBreakpointMenuItem.addActionListener(this);
removeBreakpointMenuItem = new JMenuItem("Remove Breakpoint");
removeBreakpointMenuItem.addActionListener(this);
listBreakpointsMenuItem = new JMenuItem("List Breakpoints");
listBreakpointsMenuItem.addActionListener(this);
stepOverMenuItem = new JMenuItem("Step Over");
stepOverMenuItem.addActionListener(this);
stepIntoMenuItem = new JMenuItem("Step Into");
stepIntoMenuItem.addActionListener(this);
stepOutMenuItem = new JMenuItem("Step Out");
stepOutMenuItem.addActionListener(this);
printStackTraceMenuItem = new JMenuItem("Print Stack trace");
printStackTraceMenuItem.addActionListener(this);
printLocalsMenuItem = new JMenuItem("Print Locals");
printLocalsMenuItem.addActionListener(this);
printThisMenuItem = new JMenuItem("Print this fields");
printThisMenuItem.addActionListener(this);
printSourceMenuItem = new JMenuItem("Print Source Location");
printSourceMenuItem.addActionListener(this);
printThreads = new JMenuItem("Print Threads");
printThreads.addActionListener(this);
toggleVariableInspectorMenuItem = new JMenuItem("Show/Hide Variable Inspector");
toggleVariableInspectorMenuItem.addActionListener(this);
debugMenu.add(debugMenuItem);
debugMenu.add(continueMenuItem);
debugMenu.add(stopMenuItem);
debugMenu.addSeparator();
debugMenu.add(setBreakpointMenuItem);
debugMenu.add(removeBreakpointMenuItem);
debugMenu.add(listBreakpointsMenuItem);
debugMenu.addSeparator();
debugMenu.add(stepOverMenuItem);
debugMenu.add(stepIntoMenuItem);
debugMenu.add(stepOutMenuItem);
debugMenu.addSeparator();
debugMenu.add(printStackTraceMenuItem);
debugMenu.add(printLocalsMenuItem);
debugMenu.add(printThisMenuItem);
debugMenu.add(printSourceMenuItem);
debugMenu.add(printThreads);
debugMenu.addSeparator();
debugMenu.add(toggleVariableInspectorMenuItem);
return debugMenu;
}
/**
* Callback for menu items. Implementation of Swing ActionListener.
*
* @param ae Action event
*/
@Override
public void actionPerformed(ActionEvent ae) {
//System.out.println("ActionEvent: " + ae.toString());
JMenuItem source = (JMenuItem) ae.getSource();
if (source == debugMenuItem) {
System.out.println("# clicked debug menu item");
//dmode.handleDebug(sketch, this);
dbg.startDebug();
} else if (source == stopMenuItem) {
System.out.println("# clicked stop menu item");
//dmode.handleDebug(sketch, this);
dbg.stopDebug();
} else if (source == continueMenuItem) {
System.out.println("# clicked continue menu item");
//dmode.handleDebug(sketch, this);
dbg.continueDebug();
} else if (source == stepOverMenuItem) {
System.out.println("# clicked step over menu item");
dbg.stepOver();
} else if (source == stepIntoMenuItem) {
System.out.println("# clicked step into menu item");
dbg.stepInto();
} else if (source == stepOutMenuItem) {
System.out.println("# clicked step out menu item");
dbg.stepOut();
} else if (source == printStackTraceMenuItem) {
System.out.println("# clicked print stack trace menu item");
dbg.printStackTrace();
} else if (source == printLocalsMenuItem) {
System.out.println("# clicked print locals menu item");
dbg.printLocals();
} else if (source == printThisMenuItem) {
System.out.println("# clicked print this menu item");
dbg.printThis();
} else if (source == printSourceMenuItem) {
System.out.println("# clicked print source menu item");
dbg.printSource();
} else if (source == printThreads) {
System.out.println("# clicked print threads menu item");
dbg.printThreads();
} else if (source == setBreakpointMenuItem) {
System.out.println("# clicked set breakpoint menu item");
dbg.setBreakpoint();
} else if (source == removeBreakpointMenuItem) {
System.out.println("# clicked remove breakpoint menu item");
dbg.removeBreakpoint();
} else if (source == listBreakpointsMenuItem) {
System.out.println("# clicked list breakpoints menu item");
dbg.listBreakpoints();
} else if (source == toggleVariableInspectorMenuItem) {
System.out.println("# clicked show/hide variable inspector menu item");
toggleVariableInspector();
}
}
// @Override
// public void handleRun() {
// dbg.continueDebug();
// }
/**
* Event handler called when hitting the stop button. Stops a running debug
* session or performs standard stop action if not currently debugging.
*/
@Override
public void handleStop() {
if (dbg.isStarted()) {
dbg.stopDebug();
} else {
super.handleStop();
}
}
/**
* Event handler called when loading another sketch in this editor. Clears
* breakpoints of previous sketch.
*
* @param path
* @return true if a sketch was opened, false if aborted
*/
@Override
protected boolean handleOpenInternal(String path) {
//System.out.println("handleOpen");
boolean didOpen = super.handleOpenInternal(path);
if (didOpen && dbg != null) {
// should already been stopped (open calls handleStop)
dbg.clearBreakpoints();
clearBreakpointedLines(); // force clear breakpoint highlights
variableInspector().clear(); // clear contents of variable inspector
}
return didOpen;
}
/**
* Clear the console.
*/
public void clearConsole() {
console.clear();
}
/**
* Clear current text selection.
*/
public void clearSelection() {
setSelection(getCaretOffset(), getCaretOffset());
}
/**
* Select a line in the current tab.
*
* @param lineIdx 0-based line number
*/
public void selectLine(int lineIdx) {
setSelection(getLineStartOffset(lineIdx), getLineStopOffset(lineIdx));
}
/**
* Set the cursor to the start of a line.
*
* @param lineIdx 0-based line number
*/
public void cursorToLineStart(int lineIdx) {
setSelection(getLineStartOffset(lineIdx), getLineStartOffset(lineIdx));
}
/**
* Set the cursor to the end of a line.
*
* @param lineIdx 0-based line number
*/
public void cursorToLineEnd(int lineIdx) {
setSelection(getLineStopOffset(lineIdx), getLineStopOffset(lineIdx));
}
/**
* Switch to a tab.
*
* @param tabFileName the file name identifying the tab. (as in
* {@link SketchCode#getFileName()})
*/
public void switchToTab(String tabFileName) {
Sketch s = getSketch();
for (int i = 0; i < s.getCodeCount(); i++) {
if (tabFileName.equals(s.getCode(i).getFileName())) {
s.setCurrentCode(i);
break;
}
}
}
/**
* Access the debugger.
*
* @return the debugger controller object
*/
public Debugger dbg() {
return dbg;
}
/**
* Access the mode.
*
* @return the mode object
*/
public DebugMode mode() {
return dmode;
}
/**
* Access the custom text area object.
*
* @return the text area object
*/
public TextArea textArea() {
return ta;
}
/**
* Access variable inspector window.
*
* @return the variable inspector object
*/
public VariableInspector variableInspector() {
return vi;
}
/**
* Show the variable inspector window.
*/
public void showVariableInspector() {
vi.setVisible(true);
}
/**
* Set visibility of the variable inspector window.
*
* @param visible true to set the variable inspector visible, false for
* invisible.
*/
public void showVariableInspector(boolean visible) {
vi.setVisible(visible);
}
/**
* Hide the variable inspector window.
*/
public void hideVariableInspector() {
vi.setVisible(true);
}
/**
* Toggle visibility of the variable inspector window.
*/
public void toggleVariableInspector() {
vi.setVisible(!vi.isVisible());
}
/**
* Text area factory method. Instantiates the customized TextArea.
*
* @return the customized text area object
*/
@Override
protected JEditTextArea createTextArea() {
//System.out.println("overriding creation of text area");
return new TextArea(new PdeTextAreaDefaults(mode));
}
/**
* Set the line to highlight as currently suspended at. Will override the
* breakpoint color, if set. Switches to the appropriate tab and scroll to
* the line by placing the cursor there.
*
* @param line the line to highlight as current suspended line
*/
public void setCurrentLine(LineID line) {
clearCurrentLine();
if (line == null) {
return; // safety, e.g. when no line mapping is found and the null line is used.
}
switchToTab(line.fileName());
// scroll to line, by setting the cursor
cursorToLineStart(line.lineIdx());
// highlight line
currentLine = new LineHighlight(line.lineIdx(), CURRENT_LINE_COLOR, this);
currentLine.setMarker(CURRENT_LINE_MARKER, CURRENT_LINE_MARKER_COLOR);
}
/**
* Clear the highlight for the debuggers current line.
*/
public void clearCurrentLine() {
if (currentLine != null) {
currentLine.clear();
currentLine.dispose();
// revert to breakpoint color if any is set on this line
for (LineHighlight hl : breakpointedLines) {
if (hl.lineID().equals(currentLine.lineID())) {
hl.paint();
break;
}
}
currentLine = null;
}
}
/**
* Add highlight for a breakpointed line. Needs to be on the current tab.
*
* @param lineIdx the line index on the current tab to highlight as
* breakpointed
*/
public void addBreakpointedLine(int lineIdx) {
LineHighlight hl = new LineHighlight(lineIdx, BREAKPOINT_COLOR, this);
hl.setMarker(BREAKPOINT_MARKER, BREAKPOINT_MARKER_COLOR);
breakpointedLines.add(hl);
// repaint current line if it's on this line
if (currentLine != null && currentLine.lineID().equals(getLineIDInCurrentTab(lineIdx))) {
currentLine.paint();
}
}
/**
* Remove a highlight for a breakpointed line. Needs to be on the current
* tab.
*
* @param lineIdx the line index on the current tab to remove a breakpoint
* highlight from
*/
public void removeBreakpointedLine(int lineIdx) {
LineID line = getLineIDInCurrentTab(lineIdx);
//System.out.println("line id: " + line.fileName() + " " + line.lineIdx());
LineHighlight foundLine = null;
for (LineHighlight hl : breakpointedLines) {
if (hl.lineID.equals(line)) {
foundLine = hl;
break;
}
}
if (foundLine != null) {
foundLine.clear();
breakpointedLines.remove(foundLine);
foundLine.dispose();
// repaint current line if it's on this line
if (currentLine != null && currentLine.lineID().equals(line)) {
currentLine.paint();
}
}
}
/**
* Remove all highlights for breakpointed lines.
*/
public void clearBreakpointedLines() {
for (LineHighlight hl : breakpointedLines) {
hl.clear();
hl.dispose();
}
breakpointedLines.clear(); // remove all breakpoints
// fix highlights not being removed when tab names have changed due to opening a new sketch in same editor
ta.clearLineBgColors(); // force clear all highlights
+ ta.clearGutterText();
// repaint current line
if (currentLine != null) {
currentLine.paint();
}
}
/**
* Retrieve a {@link LineID} object for a line on the current tab.
*
* @param lineIdx the line index on the current tab
* @return the {@link LineID} object representing a line index on the
* current tab
*/
public LineID getLineIDInCurrentTab(int lineIdx) {
return new LineID(getSketch().getCurrentCode().getFileName(), lineIdx);
}
/**
* Retrieve line of sketch where the cursor currently resides.
*
* @return the current {@link LineID}
*/
protected LineID getCurrentLineID() {
String tab = getSketch().getCurrentCode().getFileName();
int lineNo = getTextArea().getCaretLine();
return new LineID(tab, lineNo);
}
/**
* Check whether a {@link LineID} is on the current tab.
*
* @param line the {@link LineID}
* @return true, if the {@link LineID} is on the current tab.
*/
public boolean isInCurrentTab(LineID line) {
return line.fileName().equals(getSketch().getCurrentCode().getFileName());
}
/**
* Event handler called when switching between tabs. Loads all line
* background colors set for the tab.
*
* @param code tab to switch to
*/
@Override
protected void setCode(SketchCode code) {
//System.out.println("tab switch: " + code.getFileName());
super.setCode(code); // set the new document in the textarea, etc. need to do this first
// set line background colors for tab
if (ta != null) { // can be null when setCode is called the first time (in constructor)
// clear all line backgrounds
ta.clearLineBgColors();
// clear all gutter text
ta.clearGutterText();
// load appropriate line backgrounds for tab
// first paint breakpoints
for (LineHighlight hl : breakpointedLines) {
if (isInCurrentTab(hl.lineID())) {
hl.paint();
}
}
// now paint current line (if any)
if (currentLine != null) {
if (isInCurrentTab(currentLine.lineID())) {
currentLine.paint();
}
}
}
if (dbg() != null && dbg().isStarted()) {
dbg().startTrackingLineChanges();
}
}
/**
* Get a tab by its file name.
*
* @param fileName the filename to search for.
* @return the {@link SketchCode} object representing the tab, or null if
* not found
*/
public SketchCode getTab(String fileName) {
Sketch s = getSketch();
for (SketchCode c : s.getCode()) {
if (c.getFileName().equals(fileName)) {
return c;
}
}
return null;
}
/**
* Access the currently edited document.
*
* @return the document object
*/
public Document currentDocument() {
return ta.getDocument();
}
/**
* Factory method for the editor toolbar. Instantiates the customized
* toolbar.
*
* @return the toolbar
*/
@Override
public EditorToolbar createToolbar() {
return new DebugToolbar(this, base);
}
}
| true | false | null | null |
diff --git a/src/org/odk/collect/android/activities/FormEntryActivity.java b/src/org/odk/collect/android/activities/FormEntryActivity.java
index 5bdad69..d99c81c 100644
--- a/src/org/odk/collect/android/activities/FormEntryActivity.java
+++ b/src/org/odk/collect/android/activities/FormEntryActivity.java
@@ -1,1489 +1,1489 @@
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.model.xform.XFormsModule;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.PropertyManager;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.FormLoaderTask;
import org.odk.collect.android.tasks.SaveToDiskTask;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.GestureDetector;
import org.odk.collect.android.views.ODKView;
import org.odk.collect.android.widgets.QuestionWidget;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Set;
/**
* FormEntryActivity is responsible for displaying questions, animating transitions between
* questions, and allowing the user to enter data.
*
* @author Carl Hartung ([email protected])
*/
public class FormEntryActivity extends Activity implements AnimationListener, FormLoaderListener,
FormSavedListener {
private static final String t = "FormEntryActivity";
// Defines for FormEntryActivity
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private static final boolean EVALUATE_CONSTRAINTS = true;
private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false;
// Request codes for returning data from specified intent.
public static final int IMAGE_CAPTURE = 1;
public static final int BARCODE_CAPTURE = 2;
public static final int AUDIO_CAPTURE = 3;
public static final int VIDEO_CAPTURE = 4;
public static final int LOCATION_CAPTURE = 5;
public static final int HIERARCHY_ACTIVITY = 6;
public static final int IMAGE_CHOOSER = 7;
public static final int AUDIO_CHOOSER = 8;
public static final int VIDEO_CHOOSER = 9;
// Extra returned from gp activity
public static final String LOCATION_RESULT = "LOCATION_RESULT";
// Identifies the gp of the form used to launch form entry
public static final String KEY_FORMPATH = "formpath";
public static final String KEY_INSTANCEPATH = "instancepath";
public static final String KEY_INSTANCES = "instances";
public static final String KEY_SUCCESS = "success";
public static final String KEY_ERROR = "error";
// Identifies whether this is a new form, or reloading a form after a screen
// rotation (or similar)
private static final String NEWFORM = "newform";
private static final int MENU_DELETE_REPEAT = Menu.FIRST;
private static final int MENU_LANGUAGES = Menu.FIRST + 1;
private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 2;
private static final int MENU_SAVE = Menu.FIRST + 3;
private static final int PROGRESS_DIALOG = 1;
private static final int SAVING_DIALOG = 2;
private String mFormPath;
public static String mInstancePath;
private GestureDetector mGestureDetector;
public static FormController mFormController;
private Animation mInAnimation;
private Animation mOutAnimation;
private RelativeLayout mRelativeLayout;
private View mCurrentView;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private String mErrorMessage;
// used to limit forward/backward swipes to one per question
private boolean mBeenSwiped;
private FormLoaderTask mFormLoaderTask;
private SaveToDiskTask mSaveToDiskTask;
enum AnimationType {
LEFT, RIGHT, FADE
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.form_entry);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.loading_form));
mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
mBeenSwiped = false;
mAlertDialog = null;
mCurrentView = null;
mInAnimation = null;
mOutAnimation = null;
mGestureDetector = new GestureDetector();
// Load JavaRosa modules. needed to restore forms.
new XFormsModule().registerModule();
// needed to override rms property manager
org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager(
getApplicationContext()));
Boolean newForm = true;
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_FORMPATH)) {
mFormPath = savedInstanceState.getString(KEY_FORMPATH);
}
if (savedInstanceState.containsKey(NEWFORM)) {
newForm = savedInstanceState.getBoolean(NEWFORM, true);
}
if (savedInstanceState.containsKey(KEY_ERROR)) {
mErrorMessage = savedInstanceState.getString(KEY_ERROR);
}
}
// If a parse error message is showing then nothing else is loaded
// Dialogs mid form just disappear on rotation.
if (mErrorMessage != null) {
createErrorDialog(mErrorMessage, EXIT);
return;
}
// Check to see if this is a screen flip or a new form load.
Object data = getLastNonConfigurationInstance();
if (data instanceof FormLoaderTask) {
mFormLoaderTask = (FormLoaderTask) data;
} else if (data instanceof SaveToDiskTask) {
mSaveToDiskTask = (SaveToDiskTask) data;
} else if (data == null) {
if (!newForm) {
refreshCurrentView();
return;
}
// Not a restart from a screen orientation change (or other).
mFormController = null;
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if (getContentResolver().getType(uri) == InstanceColumns.CONTENT_ITEM_TYPE) {
Cursor instanceCursor = this.managedQuery(uri, null, null, null, null);
if (instanceCursor.getCount() != 1) {
this.createErrorDialog("Bad URI: " + uri, EXIT);
return;
} else {
instanceCursor.moveToFirst();
mInstancePath =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String jrFormId =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.JR_FORM_ID));
String[] selectionArgs = {
jrFormId
};
String selection = FormsColumns.JR_FORM_ID + " like ?";
Cursor formCursor =
managedQuery(FormsColumns.CONTENT_URI, null, selection, selectionArgs,
null);
if (formCursor.getCount() == 1) {
formCursor.moveToFirst();
mFormPath =
formCursor.getString(formCursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
} else if (formCursor.getCount() < 1) {
this.createErrorDialog("Parent form does not exist", EXIT);
return;
} else if (formCursor.getCount() > 1) {
this.createErrorDialog("More than one possible parent form", EXIT);
return;
}
}
} else if (getContentResolver().getType(uri) == FormsColumns.CONTENT_ITEM_TYPE) {
Cursor c = this.managedQuery(uri, null, null, null, null);
if (c.getCount() != 1) {
this.createErrorDialog("Bad URI: " + uri, EXIT);
return;
} else {
c.moveToFirst();
mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
}
} else {
Log.e(t, "unrecognized URI");
this.createErrorDialog("unrecognized URI: " + uri, EXIT);
return;
}
mFormLoaderTask = new FormLoaderTask();
mFormLoaderTask.execute(mFormPath);
showDialog(PROGRESS_DIALOG);
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_FORMPATH, mFormPath);
outState.putBoolean(NEWFORM, false);
outState.putString(KEY_ERROR, mErrorMessage);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
// request was canceled, so do nothing
return;
}
ContentValues values;
Uri imageURI;
switch (requestCode) {
case BARCODE_CAPTURE:
String sb = intent.getStringExtra("SCAN_RESULT");
((ODKView) mCurrentView).setBinaryData(sb);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case IMAGE_CAPTURE:
/*
* We saved the image to the tempfile_path, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// The intent is empty, but we know we saved the image to the temp file
File fi = new File(Collect.TMPFILE_PATH);
String mInstanceFolder =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String s = mInstanceFolder + "/" + System.currentTimeMillis() + ".jpg";
File nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(t, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath());
}
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, nf.getName());
values.put(Images.Media.DISPLAY_NAME, nf.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, nf.getAbsolutePath());
imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
break;
case IMAGE_CHOOSER:
/*
* We have a saved image somewhere, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// get gp of chosen file
Uri selectedImage = intent.getData();
String[] projection = {
Images.Media.DATA
};
Cursor cursor = managedQuery(selectedImage, projection, null, null, null);
startManagingCursor(cursor);
int column_index = cursor.getColumnIndexOrThrow(Images.Media.DATA);
cursor.moveToFirst();
String sourceImagePath = cursor.getString(column_index);
// Copy file to sdcard
String mInstanceFolder1 =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String destImagePath = mInstanceFolder1 + "/" + System.currentTimeMillis() + ".jpg";
File source = new File(sourceImagePath);
File newImage = new File(destImagePath);
FileUtils.copyFile(source, newImage);
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
imageURI =
getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
} else {
Log.e(t, "NO IMAGE EXISTS at: " + source.getAbsolutePath());
}
refreshCurrentView();
break;
case AUDIO_CAPTURE:
case VIDEO_CAPTURE:
case AUDIO_CHOOSER:
case VIDEO_CHOOSER:
// For audio/video capture/chooser, we get the URI from the content provider
// then the widget copies the file and makes a new entry in the content provider.
Uri media = intent.getData();
((ODKView) mCurrentView).setBinaryData(media);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
break;
case LOCATION_CAPTURE:
String sl = intent.getStringExtra(LOCATION_RESULT);
((ODKView) mCurrentView).setBinaryData(sl);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case HIERARCHY_ACTIVITY:
// We may have jumped to a new index in hierarchy activity, so refresh
refreshCurrentView();
break;
}
}
/**
* Refreshes the current view. the controller and the displayed view can get out of sync due to
* dialogs and restarts caused by screen orientation changes, so they're resynchronized here.
*/
public void refreshCurrentView() {
int event = mFormController.getEvent();
// When we refresh, repeat dialog state isn't maintained, so step back to the previous
// question.
// Also, if we're within a group labeled 'field list', step back to the beginning of that
// group.
// That is, skip backwards over repeat prompts, groups that are not field-lists,
// repeat events, and indexes in field-lists that is not the containing group.
while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| (event == FormEntryController.EVENT_GROUP && !mFormController
.indexIsInFieldList())
|| event == FormEntryController.EVENT_REPEAT
|| (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) {
event = mFormController.stepToPreviousEvent();
}
View current = createView(event);
showView(current, AnimationType.FADE);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.removeItem(MENU_DELETE_REPEAT);
menu.removeItem(MENU_LANGUAGES);
menu.removeItem(MENU_HIERARCHY_VIEW);
menu.removeItem(MENU_SAVE);
menu.add(0, MENU_SAVE, 0, R.string.save_all_answers).setIcon(
android.R.drawable.ic_menu_save);
menu.add(0, MENU_DELETE_REPEAT, 0, getString(R.string.delete_repeat))
.setIcon(R.drawable.ic_menu_clear_playlist)
.setEnabled(mFormController.indexContainsRepeatableGroup() ? true : false);
menu.add(0, MENU_HIERARCHY_VIEW, 0, getString(R.string.view_hierarchy)).setIcon(
R.drawable.ic_menu_goto);
menu.add(0, MENU_LANGUAGES, 0, getString(R.string.change_language))
.setIcon(R.drawable.ic_menu_start_conversation)
.setEnabled(
(mFormController.getLanguages() == null || mFormController.getLanguages().length == 1) ? false
: true);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_LANGUAGES:
createLanguageDialog();
return true;
case MENU_DELETE_REPEAT:
createDeleteRepeatConfirmDialog();
return true;
case MENU_SAVE:
// don't exit
saveDataToDisk(DO_NOT_EXIT, isInstanceComplete());
return true;
case MENU_HIERARCHY_VIEW:
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY);
}
return super.onOptionsItemSelected(item);
}
/**
* @return true if the current View represents a question in the form
*/
private boolean currentPromptIsQuestion() {
return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController
.getEvent() == FormEntryController.EVENT_GROUP);
}
/**
* Attempt to save the answer(s) in the current screen to into the data model.
*
* @param evaluateConstraints
* @return false if any error occurs while saving (constraint violated, etc...), true otherwise.
*/
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) {
// only try to save if the current event is a question or a field-list group
if (mFormController.getEvent() == FormEntryController.EVENT_QUESTION
|| (mFormController.getEvent() == FormEntryController.EVENT_GROUP && mFormController
.indexIsInFieldList())) {
HashMap<FormIndex, IAnswerData> answers = ((ODKView) mCurrentView).getAnswers();
Set<FormIndex> indexKeys = answers.keySet();
for (FormIndex index : indexKeys) {
// Within a group, you can only save for question events
if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) {
int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints);
if (evaluateConstraints && saveStatus != FormEntryController.ANSWER_OK) {
createConstraintToast(mFormController.getQuestionPrompt(index)
.getConstraintText(), saveStatus);
return false;
}
} else {
Log.w(t,
"Attempted to save an index referencing something other than a question: "
+ index.getReference());
}
}
}
return true;
}
/**
* Clears the answer on the screen.
*/
private void clearAnswer(QuestionWidget qw) {
qw.clearAnswer();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, v.getId(), 0, "Clear Answer");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
/*
* We don't have the right view here, so we store the View's ID as the item ID and loop
* through the possible views to find the one the user clicked on.
*/
for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) {
if (item.getItemId() == qw.getId()) {
createClearDialog(qw);
}
}
return super.onContextItemSelected(item);
}
/**
* If we're loading, then we pass the loading thread to our next instance.
*/
@Override
public Object onRetainNonConfigurationInstance() {
// if a form is loading, pass the loader task
if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED)
return mFormLoaderTask;
// if a form is writing to disk, pass the save to disk task
if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)
return mSaveToDiskTask;
// mFormEntryController is static so we don't need to pass it.
if (mFormController != null && currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
return null;
}
/**
* Creates a view given the View type and an event
*
* @param event
* @return newly created View
*/
private View createView(int event) {
setTitle(getString(R.string.app_name) + " > " + mFormController.getFormTitle());
switch (event) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
View startView = View.inflate(this, R.layout.form_entry_start, null);
setTitle(getString(R.string.app_name) + " > " + mFormController.getFormTitle());
((TextView) startView.findViewById(R.id.description)).setText(getString(
R.string.enter_data_description, mFormController.getFormTitle()));
Drawable image = null;
String[] projection = {
FormsColumns.FORM_MEDIA_PATH
};
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String[] selectionArgs = {
mFormPath
};
Cursor c =
managedQuery(FormsColumns.CONTENT_URI, projection, selection, selectionArgs,
null);
String mediaDir = null;
if (c.getCount() < 1) {
createErrorDialog("form Doesn't exist", true);
return new View(this);
} else {
c.moveToFirst();
mediaDir = c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH));
}
BitmapDrawable bitImage = null;
// attempt to load the form-specific logo...
// this is arbitrarily silly
bitImage = new BitmapDrawable(mediaDir + "form_logo.png");
if (bitImage != null && bitImage.getBitmap() != null
&& bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) {
image = bitImage;
}
if (image == null) {
// show the opendatakit zig...
image = getResources().getDrawable(R.drawable.opendatakit_zig);
}
((ImageView) startView.findViewById(R.id.form_start_bling)).setImageDrawable(image);
return startView;
case FormEntryController.EVENT_END_OF_FORM:
View endView = View.inflate(this, R.layout.form_entry_end, null);
((TextView) endView.findViewById(R.id.description)).setText(getString(
R.string.save_enter_data_description, mFormController.getFormTitle()));
// checkbox for if finished or ready to send
final CheckBox instanceComplete =
((CheckBox) endView.findViewById(R.id.mark_finished));
instanceComplete.setChecked(isInstanceComplete());
// Create 'save for later' button
((Button) endView.findViewById(R.id.save_exit_button))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Form is marked as 'saved' here.
saveDataToDisk(EXIT, instanceComplete.isChecked());
}
});
return endView;
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_GROUP:
ODKView odkv = null;
// should only be a group here if the event_group is a field-list
try {
odkv =
new ODKView(this, mFormController.getQuestionPrompts(),
mFormController.getGroupsForCurrentIndex());
Log.i(t, "created view for group");
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
e.printStackTrace();
// this is badness to avoid a crash.
// really a next view should increment the formcontroller, create the view
// if the view is null, then keep the current view and pop an error.
return new View(this);
}
// Makes a "clear answer" menu pop up on long-click
for (QuestionWidget qw : odkv.getWidgets()) {
registerForContextMenu(qw);
}
return odkv;
default:
Log.e(t, "Attempted to create a view that does not exist.");
return null;
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent mv) {
boolean handled = onTouchEvent(mv);
if (!handled) {
return super.dispatchTouchEvent(mv);
}
return handled; // this is always true
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
/*
* constrain the user to only be able to swipe (that causes a view transition) once per
* screen with the mBeenSwiped variable.
*/
boolean handled = false;
if (!mBeenSwiped) {
switch (mGestureDetector.getGesture(motionEvent)) {
case SWIPE_RIGHT:
mBeenSwiped = true;
showPreviousView();
handled = true;
break;
case SWIPE_LEFT:
mBeenSwiped = true;
showNextView();
handled = true;
break;
}
}
return handled;
}
/**
* Determines what should be displayed on the screen. Possible options are: a question, an ask
* repeat dialog, or the submit screen. Also saves answers to the data model after checking
* constraints.
*/
private void showNextView() {
if (currentPromptIsQuestion()) {
if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) {
// A constraint was violated so a dialog should be showing.
return;
}
}
if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) {
int event;
group_skip: do {
event = mFormController.stepToNextEvent(FormController.STEP_INTO_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
View next = createView(event);
showView(next, AnimationType.RIGHT);
break group_skip;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
createRepeatDialog();
break group_skip;
case FormEntryController.EVENT_GROUP:
if (mFormController.indexIsInFieldList()) {
View nextGroupView = createView(event);
showView(nextGroupView, AnimationType.RIGHT);
break group_skip;
}
// otherwise it's not a field-list group, so just skip it
break;
case FormEntryController.EVENT_REPEAT:
Log.i(t, "repeat: " + mFormController.getFormIndex().getReference());
// skip repeats
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ mFormController.getFormIndex().getReference());
// skip repeat junctures until we implement them
break;
default:
Log.w(t,
"JavaRosa added a new EVENT type and didn't tell us... shame on them.");
break;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
} else {
mBeenSwiped = false;
}
}
/**
* Determines what should be displayed between a question, or the start screen and displays the
* appropriate view. Also saves answers to the data model without checking constraints.
*/
private void showPreviousView() {
// The answer is saved on a back swipe, but question constraints are ignored.
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = mFormController.stepToPreviousEvent();
while (event != FormEntryController.EVENT_BEGINNING_OF_FORM
&& event != FormEntryController.EVENT_QUESTION
&& !(event == FormEntryController.EVENT_GROUP && mFormController
.indexIsInFieldList())) {
event = mFormController.stepToPreviousEvent();
}
View next = createView(event);
showView(next, AnimationType.LEFT);
} else {
mBeenSwiped = false;
}
}
/**
* Displays the View specified by the parameter 'next', animating both the current view and next
* appropriately given the AnimationType. Also updates the progress bar.
*/
public void showView(View next, AnimationType from) {
switch (from) {
case RIGHT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out);
break;
case LEFT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out);
break;
case FADE:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
break;
}
if (mCurrentView != null) {
mCurrentView.startAnimation(mOutAnimation);
mRelativeLayout.removeView(mCurrentView);
}
mInAnimation.setAnimationListener(this);
RelativeLayout.LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mCurrentView = next;
mRelativeLayout.addView(mCurrentView, lp);
mCurrentView.startAnimation(mInAnimation);
if (mCurrentView instanceof ODKView)
((ODKView) mCurrentView).setFocus(this);
else {
InputMethodManager inputManager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0);
}
}
// Hopefully someday we can use managed dialogs when the bugs are fixed
/*
* Ideally, we'd like to use Android to manage dialogs with onCreateDialog() and
* onPrepareDialog(), but dialogs with dynamic content are broken in 1.5 (cupcake). We do use
* managed dialogs for our static loading ProgressDialog. The main issue we noticed and are
* waiting to see fixed is: onPrepareDialog() is not called after a screen orientation change.
* http://code.google.com/p/android/issues/detail?id=1639
*/
//
/**
* Creates and displays a dialog displaying the violated constraint.
*/
private void createConstraintToast(String constraintText, int saveStatus) {
switch (saveStatus) {
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
if (constraintText == null) {
constraintText = getString(R.string.invalid_answer_error);
}
break;
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
constraintText = getString(R.string.required_answer_error);
break;
}
showCustomToast(constraintText);
mBeenSwiped = false;
}
/**
* Creates a toast with the specified message.
*
* @param message
*/
private void showCustomToast(String message) {
LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_view, null);
// set the text in the view
TextView tv = (TextView) view.findViewById(R.id.message);
tv.setText(message);
Toast t = new Toast(this);
t.setView(view);
t.setDuration(Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
/**
* Creates and displays a dialog asking the user if they'd like to create a repeat of the
* current group.
*/
private void createRepeatDialog() {
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
DialogInterface.OnClickListener repeatListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // yes, repeat
mFormController.newRepeat();
showNextView();
break;
case DialogInterface.BUTTON2: // no, no repeat
showNextView();
break;
}
}
};
if (mFormController.getLastRepeatCount() > 0) {
mAlertDialog.setTitle(getString(R.string.leaving_repeat_ask));
mAlertDialog.setMessage(getString(R.string.add_another_repeat,
mFormController.getLastGroupText()));
mAlertDialog.setButton(getString(R.string.add_another), repeatListener);
mAlertDialog.setButton2(getString(R.string.leave_repeat_yes), repeatListener);
} else {
mAlertDialog.setTitle(getString(R.string.entering_repeat_ask));
mAlertDialog.setMessage(getString(R.string.add_repeat,
mFormController.getLastGroupText()));
mAlertDialog.setButton(getString(R.string.entering_repeat), repeatListener);
mAlertDialog.setButton2(getString(R.string.add_repeat_no), repeatListener);
}
mAlertDialog.setCancelable(false);
mAlertDialog.show();
mBeenSwiped = false;
}
/**
* Creates and displays dialog with the given errorMsg.
*/
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_alert);
mAlertDialog.setTitle(getString(R.string.error_occured));
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1:
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
/**
* Creates a confirm/cancel dialog for deleting repeats.
*/
private void createDeleteRepeatConfirmDialog() {
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_alert);
String name = mFormController.getLastRepeatedGroupName();
int repeatcount = mFormController.getLastRepeatedGroupRepeatCount();
if (repeatcount != -1) {
name += " (" + (repeatcount + 1) + ")";
}
mAlertDialog.setTitle(getString(R.string.delete_repeat_ask));
mAlertDialog.setMessage(getString(R.string.delete_repeat_confirm, name));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // yes
mFormController.deleteRepeat();
showPreviousView();
break;
case DialogInterface.BUTTON2: // no
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.discard_group), quitListener);
mAlertDialog.setButton2(getString(R.string.delete_repeat_no), quitListener);
mAlertDialog.show();
}
/**
* Called during a 'save and exit' command. The form is not 'done' here.
*/
private boolean saveDataToDisk(boolean exit, boolean complete) {
// save current answer
if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) {
Toast.makeText(this, getString(R.string.data_saved_error), Toast.LENGTH_SHORT).show();
return false;
}
Log.e("Carl", "what? intent? " + getIntent());
if (getIntent() != null) {
Log.e("Carl", "what? data? " + getIntent().getData());
} else {
Log.e("Carl", "but no data");
}
mSaveToDiskTask = new SaveToDiskTask(getIntent().getData());
mSaveToDiskTask.setFormSavedListener(this);
mSaveToDiskTask.setExportVars(exit, complete);
mSaveToDiskTask.execute();
showDialog(SAVING_DIALOG);
return true;
}
/**
* Create a dialog with options to save and exit, save, or quit without saving
*/
private void createQuitDialog() {
String[] items = {
getString(R.string.keep_changes), getString(R.string.do_not_save)
};
mAlertDialog =
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(getString(R.string.quit_application, mFormController.getFormTitle()))
.setNeutralButton(getString(R.string.do_not_exit),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
saveDataToDisk(EXIT, isInstanceComplete());
break;
case 1: // discard changes and exit
String selection =
InstanceColumns.INSTANCE_FILE_PATH + " like '"
+ mInstancePath + "'";
Cursor c =
FormEntryActivity.this.managedQuery(
InstanceColumns.CONTENT_URI, null, selection, null,
null);
// if it's not already saved, erase everything
if (c.getCount() < 1) {
// delete media first
String instanceFolder =
mInstancePath.substring(0,
mInstancePath.lastIndexOf("/") + 1);
Log.i(t, "attempting to delete: " + instanceFolder);
String where =
Images.Media.DATA + " like '" + instanceFolder + "%'";
int images = getContentResolver().delete(
Images.Media.EXTERNAL_CONTENT_URI, where, null);
int audio = getContentResolver().delete(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where,
null);
int video = getContentResolver().delete(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, where,
null);
Log.i(t, "revmoved from content providers: " + images + " image files, "
+ audio + " audio files" + " and "
+ video + " video files.");
File f = new File(instanceFolder);
if (f.exists() && f.isDirectory()) {
for (File del : f.listFiles()) {
Log.i(t, "deleting file: " + del.getAbsolutePath());
del.delete();
}
f.delete();
}
}
finish();
break;
case 2:// do nothing
break;
}
}
}).create();
mAlertDialog.show();
}
/**
* Confirm clear answer dialog
*/
private void createClearDialog(final QuestionWidget qw) {
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_alert);
mAlertDialog.setTitle(getString(R.string.clear_answer_ask));
String question = qw.getPrompt().getLongText();
if (question.length() > 50) {
question = question.substring(0, 50) + "...";
}
mAlertDialog.setMessage(getString(R.string.clearanswer_confirm, question));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // yes
clearAnswer(qw);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case DialogInterface.BUTTON2: // no
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.discard_answer), quitListener);
mAlertDialog.setButton2(getString(R.string.clear_answer_no), quitListener);
mAlertDialog.show();
}
/**
* Creates and displays a dialog allowing the user to set the language for the form.
*/
private void createLanguageDialog() {
final String[] languages = mFormController.getLanguages();
int selected = -1;
if (languages != null) {
String language = mFormController.getLanguage();
for (int i = 0; i < languages.length; i++) {
if (language.equals(languages[i])) {
selected = i;
}
}
}
mAlertDialog =
new AlertDialog.Builder(this)
.setSingleChoiceItems(languages, selected,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
mFormController.setLanguage(languages[whichButton]);
dialog.dismiss();
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
refreshCurrentView();
}
})
.setTitle(getString(R.string.change_language))
.setNegativeButton(getString(R.string.do_not_change),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
}
}).create();
mAlertDialog.show();
}
/**
* We use Android's dialog management for loading/saving progress dialogs
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mFormLoaderTask.setFormLoaderListener(null);
mFormLoaderTask.cancel(true);
finish();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(getString(R.string.loading_form));
mProgressDialog.setMessage(getString(R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel_loading_form),
loadingButtonListener);
return mProgressDialog;
case SAVING_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener savingButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mSaveToDiskTask.setFormSavedListener(null);
mSaveToDiskTask.cancel(true);
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(getString(R.string.saving_form));
mProgressDialog.setMessage(getString(R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel), savingButtonListener);
mProgressDialog.setButton(getString(R.string.cancel_saving_form),
savingButtonListener);
return mProgressDialog;
}
return null;
}
/**
* Dismiss any showing dialogs that we manually manage.
*/
private void dismissDialogs() {
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onPause() {
dismissDialogs();
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
super.onPause();
}
@Override
protected void onResume() {
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(this);
if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
dismissDialog(PROGRESS_DIALOG);
refreshCurrentView();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(this);
}
super.onResume();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
createQuitDialog();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showNextView();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showPreviousView();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
// but only if it's done, otherwise the thread never returns
if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
mFormLoaderTask.cancel(true);
mFormLoaderTask.destroy();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
mSaveToDiskTask.cancel(false);
}
}
mFormController = null;
mInstancePath = null;
super.onDestroy();
}
@Override
public void onAnimationEnd(Animation arg0) {
mBeenSwiped = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
// Added by AnimationListener interface.
}
@Override
public void onAnimationStart(Animation animation) {
// Added by AnimationListener interface.
}
/**
* loadingComplete() is called by FormLoaderTask once it has finished loading a form.
*/
@Override
public void loadingComplete(FormController fc) {
dismissDialog(PROGRESS_DIALOG);
mFormController = fc;
// Set saved answer path
if (mInstancePath == null) {
// Create new answer folder.
String time =
new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
.format(Calendar.getInstance().getTime());
String file =
mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.'));
String path = Collect.INSTANCES_PATH + "/" + file + "_" + time;
if (FileUtils.createFolder(path)) {
mInstancePath = path + "/" + file + "_" + time + ".xml";
}
} else {
// we've just loaded a saved form, so start in the hierarchy view
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivity(i);
return; // so we don't show the intro screen before jumping to the hierarchy
}
refreshCurrentView();
}
/**
* called by the FormLoaderTask if something goes wrong.
*/
@Override
public void loadingError(String errorMsg) {
dismissDialog(PROGRESS_DIALOG);
mErrorMessage = errorMsg;
if (errorMsg != null) {
createErrorDialog(errorMsg, EXIT);
} else {
createErrorDialog(getString(R.string.parse_error), EXIT);
}
}
/**
- * Called by the FormLoaderTask if everything loads correctly.
+ * Called by SavetoDiskTask if everything saves correctly.
*/
@Override
public void savingComplete(int saveStatus) {
dismissDialog(SAVING_DIALOG);
switch (saveStatus) {
case SaveToDiskTask.SAVED:
Toast.makeText(this, getString(R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
break;
case SaveToDiskTask.SAVED_AND_EXIT:
Toast.makeText(this, getString(R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
finish();
break;
case SaveToDiskTask.SAVE_ERROR:
Toast.makeText(this, getString(R.string.data_saved_error), Toast.LENGTH_LONG)
.show();
break;
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
refreshCurrentView();
// an answer constraint was violated, so do a 'swipe' to the next
// question to display the proper toast(s)
next();
break;
}
}
/**
* Attempts to save an answer to the specified index.
*
* @param answer
* @param index
* @param evaluateConstraints
* @return status as determined in FormEntryController
*/
public int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) {
if (evaluateConstraints) {
return mFormController.answerQuestion(index, answer);
} else {
mFormController.saveAnswer(index, answer);
return FormEntryController.ANSWER_OK;
}
}
/**
* Checks the database to determine if the current instance being edited has already been
* 'marked completed'. A form can be 'unmarked' complete and then resaved.
*
* @return true if form has been marked completed, false otherwise.
*/
private boolean isInstanceComplete() {
boolean complete = false;
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = {
mInstancePath
};
Cursor c =
getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs,
null);
startManagingCursor(c);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS));
if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) {
complete = true;
}
}
return complete;
}
public void next() {
if(!mBeenSwiped){
mBeenSwiped = true;
showNextView();
}
}
}
| true | false | null | null |
diff --git a/src/de/craftlancer/serverminimap/AlternativeRenderer.java b/src/de/craftlancer/serverminimap/AlternativeRenderer.java
index 93a925d..05c492e 100644
--- a/src/de/craftlancer/serverminimap/AlternativeRenderer.java
+++ b/src/de/craftlancer/serverminimap/AlternativeRenderer.java
@@ -1,289 +1,289 @@
package de.craftlancer.serverminimap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.TreeMap;
import org.bukkit.Location;
+import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapCursorCollection;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
public class AlternativeRenderer extends MapRenderer implements Listener
{
private Map<Integer, Map<Integer, MapChunk>> cacheMap = new TreeMap<Integer, Map<Integer, MapChunk>>();
protected Queue<Coords> queue = new LinkedList<Coords>();
private RenderTask cacheTask = new RenderTask(this);
private SendTask sendTask = new SendTask();
protected int scale = 0;
protected int cpr = 0;
private int colorlimit;
protected ServerMinimap plugin;
private World world;
public AlternativeRenderer(int scale, int cpr, World world, ServerMinimap plugin)
{
super(true);
this.plugin = plugin;
this.cpr = cpr;
this.world = world;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
this.scale = (scale < 1 || scale > 4) ? 1 : (int) Math.pow(2, scale);
this.colorlimit = (this.scale * this.scale) / 2;
this.cacheTask.runTaskTimer(plugin, plugin.runPerTicks, plugin.runPerTicks);
this.sendTask.runTaskTimer(plugin, plugin.fastTicks, plugin.fastTicks);
}
@Override
public void render(MapView map, MapCanvas canvas, Player player)
{
- if (!player.getWorld().equals(world))
+ if (!player.getWorld().equals(world) || !(player.getItemInHand().getType() == Material.MAP && player.getItemInHand().getDurability() == ServerMinimap.MAPID))
return;
int locX = player.getLocation().getBlockX() / scale - 64;
int locZ = player.getLocation().getBlockZ() / scale - 64;
for (int i = 0; i < 128; i++)
for (int j = 0; j < 128; j++)
{
int x = (int) ((locX + i) / 16D);
if (locX + i < 0 && (locX + i) % 16 != 0)
x--;
int z = (int) ((locZ + j) / 16D);
if (locZ + j < 0 && (locZ + j) % 16 != 0)
z--;
- try
- {
+
+ if(cacheMap.get(x) != null && cacheMap.get(x).get(z) != null)
canvas.setPixel(i, j, (byte) (cacheMap.get(x).get(z).get(Math.abs((locX + i + 16 * Math.abs(x))) % 16, Math.abs((locZ + j + 16 * Math.abs(z))) % 16) % 55));
- }
- catch (NullPointerException e)
+ else
{
canvas.setPixel(i, j, (byte) 0);
if (queue.size() < 200)
addToQueue(x, z, true);
}
}
MapCursorCollection cursors = canvas.getCursors();
while (cursors.size() > 0)
cursors.removeCursor(cursors.getCursor(0));
for (Player p : plugin.getServer().getOnlinePlayers())
{
if (!canSee(player, p))
continue;
float yaw = p.getLocation().getYaw();
if (yaw < 0)
yaw += 360;
byte direction = (byte) ((Math.abs(yaw) + 11.25) / 22.5);
if (direction > 15)
direction = 0;
int x = ((p.getLocation().getBlockX() - player.getLocation().getBlockX()) / scale) * 2;
int z = ((p.getLocation().getBlockZ() - player.getLocation().getBlockZ()) / scale) * 2;
if (Math.abs(x) > 128 || Math.abs(z) > 128)
continue;
byte color = getPlayerColor(player, p);
cursors.addCursor(x, z, direction, color);
}
}
@SuppressWarnings("static-method")
private byte getPlayerColor(Player player, Player p)
{
// TODO Auto-generated method stub
return 0;
}
public void addToQueue(int x, int y, boolean chunk)
{
Coords c = new Coords(x, y, chunk);
if (!queue.contains(c))
queue.offer(c);
}
public void loadData(int x, int z)
{
if (!cacheMap.containsKey(x))
cacheMap.put(x, new TreeMap<Integer, MapChunk>());
if (!cacheMap.get(x).containsKey(z))
cacheMap.get(x).put(z, new MapChunk());
MapChunk map = cacheMap.get(x).get(z);
int initX = x * scale * 16;
int initZ = z * scale * 16;
for (int i = 0; i < 16; i++)
for (int j = 0; j < 16; j++)
map.set(i, j, renderBlock(initX + i * scale, initZ + j * scale));
}
public void loadBlock(int initX, int initZ)
{
int locX = initX / scale;
int locZ = initZ / scale;
int x = (int) (locX / 16D);
if (locX < 0 && locX % 16 != 0)
x--;
int z = (int) (locZ / 16D);
if (locZ < 0 && locZ % 16 != 0)
z--;
int sx = Math.abs((locX + 16 * Math.abs(x))) % 16;
int sz = Math.abs((locZ + 16 * Math.abs(z))) % 16;
if (!cacheMap.containsKey(x))
cacheMap.put(x, new TreeMap<Integer, MapChunk>());
if (!cacheMap.get(x).containsKey(z))
cacheMap.get(x).put(z, new MapChunk());
MapChunk map = cacheMap.get(x).get(z);
map.set(sx, sz, renderBlock((x * 16 + sx) * scale, (z * 16 + sz) * scale));
}
public byte renderBlock(int baseX, int baseZ)
{
byte arr[] = new byte[56];
byte maxpos = 0;
byte max = 0;
for (int k = 0; k < scale; k++)
for (int l = 0; l < scale; l++)
{
Block b = world.getHighestBlockAt(baseX + k, baseZ + l);
if(b.getChunk().isLoaded())
b.getChunk().load();
byte color = plugin.getColor(b.getRelative(0, -1, 0).getTypeId());
arr[color]++;
if (arr[color] >= colorlimit)
return color;
}
if (maxpos == 0)
for (byte h = 0; h < arr.length; h++)
if (arr[h] > max)
{
max = arr[h];
maxpos = h;
}
return maxpos;
}
private boolean canSee(Player viewer, Player p)
{
return viewer.getName().equals(p.getName()) || plugin.canSeeOthers;
}
private void handleBlockEvent(Block e)
{
Location loc = e.getLocation();
if (loc.getBlockY() >= loc.getWorld().getHighestBlockYAt(loc) - 1)
addToQueue(loc.getBlockX(), loc.getBlockZ(), false);
}
// TOTEST every Event handled?
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(BlockPlaceEvent e)
{
handleBlockEvent(e.getBlock());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(BlockFromToEvent e)
{
handleBlockEvent(e.getBlock());
handleBlockEvent(e.getToBlock());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(BlockPhysicsEvent e)
{
switch (e.getChangedType())
{
case LAVA:
case WATER:
case STATIONARY_LAVA:
case STATIONARY_WATER:
handleBlockEvent(e.getBlock()); break;
default:
break;
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(BlockBreakEvent e)
{
handleBlockEvent(e.getBlock());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(BlockBurnEvent e)
{
handleBlockEvent(e.getBlock());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(BlockFadeEvent e)
{
handleBlockEvent(e.getBlock());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(BlockFormEvent e)
{
handleBlockEvent(e.getBlock());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(BlockGrowEvent e)
{
handleBlockEvent(e.getBlock());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(BlockSpreadEvent e)
{
handleBlockEvent(e.getBlock());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockEvent(EntityBlockFormEvent e)
{
handleBlockEvent(e.getBlock());
}
}
diff --git a/src/de/craftlancer/serverminimap/RenderTask.java b/src/de/craftlancer/serverminimap/RenderTask.java
index 6c881f2..ace682b 100644
--- a/src/de/craftlancer/serverminimap/RenderTask.java
+++ b/src/de/craftlancer/serverminimap/RenderTask.java
@@ -1,45 +1,45 @@
package de.craftlancer.serverminimap;
import org.bukkit.scheduler.BukkitRunnable;
public class RenderTask extends BukkitRunnable
{
AlternativeRenderer renderer;
public RenderTask(AlternativeRenderer renderer)
{
this.renderer = renderer;
}
@Override
public void run()
- {
+ {
int chunks = 0;
int blocks = 0;
while (chunks < renderer.cpr)
{
Coords c = renderer.queue.poll();
if (c == null)
break;
if (c.isChunk())
{
renderer.loadData(c.x, c.z);
chunks++;
}
else
{
renderer.loadBlock(c.x, c.z);
blocks++;
if(blocks >= 16 * 16 * renderer.scale * renderer.scale)
{
blocks = 0;
chunks++;
}
}
}
}
}
| false | false | null | null |
diff --git a/MobileClient/src/pl/edu/agh/io/coordinator/ShowUserFragment.java b/MobileClient/src/pl/edu/agh/io/coordinator/ShowUserFragment.java
index 2893cb8..624e928 100644
--- a/MobileClient/src/pl/edu/agh/io/coordinator/ShowUserFragment.java
+++ b/MobileClient/src/pl/edu/agh/io/coordinator/ShowUserFragment.java
@@ -1,168 +1,167 @@
package pl.edu.agh.io.coordinator;
import java.io.InputStream;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ShowUserFragment extends Fragment {
private static final String ARG_USER_NAME = "userName";
private static final String ARG_USER_SURNAME = "userSurname";
private static final String ARG_USER_NICK = "userNick";
private static final String ARG_USER_PHONE = "userPhone";
private static final String ARG_USER_EMAIL = "userEmail";
private static final String ARG_USER_AVATAR = "userAvatar";
private String userName;
private String userSurname;
private String userNick;
private String userPhone;
private String userEmail;
private String userAvatar;
private TextView nameView;
private TextView surnameView;
private TextView nickView;
private TextView telephoneView;
private TextView mailView;
private ImageView avatarView;
private Button callButton;
private Button composeButton;
public static ShowUserFragment newInstance(String userName,
String userSurname, String userNick, String userPhone,
String userEmail, String userAvatar) {
ShowUserFragment fragment = new ShowUserFragment();
Bundle args = new Bundle();
args.putString(ARG_USER_NAME, userName);
args.putString(ARG_USER_SURNAME, userSurname);
args.putString(ARG_USER_NICK, userNick);
args.putString(ARG_USER_PHONE, userPhone);
args.putString(ARG_USER_EMAIL, userEmail);
args.putString(ARG_USER_AVATAR, userAvatar);
fragment.setArguments(args);
return fragment;
}
public ShowUserFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
userName = getArguments().getString(ARG_USER_NAME);
userSurname = getArguments().getString(ARG_USER_SURNAME);
userNick = getArguments().getString(ARG_USER_NICK);
userPhone = getArguments().getString(ARG_USER_PHONE);
userEmail = getArguments().getString(ARG_USER_EMAIL);
userAvatar = getArguments().getString(ARG_USER_AVATAR);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_show_user, container,
false);
nameView = (TextView) (view.findViewById(R.id.userName));
surnameView = (TextView) (view.findViewById(R.id.userSurname));
nickView = (TextView) (view.findViewById(R.id.userNick));
telephoneView = (TextView) (view.findViewById(R.id.userPhone));
mailView = (TextView) (view.findViewById(R.id.userEmail));
avatarView = (ImageView) (view.findViewById(R.id.userAvatar));
callButton = (Button) (view.findViewById(R.id.buttonCall));
composeButton = (Button) (view.findViewById(R.id.buttonCompose));
nameView.setText(userName);
surnameView.setText(userSurname);
nickView.setText(userNick);
telephoneView.setText(userPhone);
mailView.setText(userEmail);
if (telephoneView.getText().equals(""))
callButton.setVisibility(View.INVISIBLE);
else {
callButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String tel = "tel:" + userPhone;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(tel));
startActivity(intent);
}
});
}
if (mailView.getText().equals(""))
composeButton.setVisibility(View.INVISIBLE);
else {
composeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_EMAIL, userEmail);
intent.setData(Uri.parse("mailto:" + userEmail));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
if (!userAvatar.equals(""))
new GetImageInBackground().execute();
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
private class GetImageInBackground extends AsyncTask<Void, Void, Bitmap> {
protected Bitmap doInBackground(Void... urls) {
Bitmap bitmapImage = null;
try {
InputStream in = new java.net.URL(userAvatar).openStream();
bitmapImage = BitmapFactory.decodeStream(in);
} catch (Exception e) {
- Log.e("ShowUserFragment", e.getMessage());
e.printStackTrace();
}
return bitmapImage;
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null)
avatarView.setImageBitmap(bitmap);
}
}
}
diff --git a/MobileClient/src/pl/edu/agh/io/coordinator/utils/layersmenu/LayersMenuState.java b/MobileClient/src/pl/edu/agh/io/coordinator/utils/layersmenu/LayersMenuState.java
index 89bb5e2..39f9df0 100644
--- a/MobileClient/src/pl/edu/agh/io/coordinator/utils/layersmenu/LayersMenuState.java
+++ b/MobileClient/src/pl/edu/agh/io/coordinator/utils/layersmenu/LayersMenuState.java
@@ -1,162 +1,162 @@
package pl.edu.agh.io.coordinator.utils.layersmenu;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import pl.edu.agh.io.coordinator.resources.Group;
import pl.edu.agh.io.coordinator.resources.Layer;
import pl.edu.agh.io.coordinator.resources.User;
import pl.edu.agh.io.coordinator.resources.UserItem;
import android.os.Parcel;
import android.os.Parcelable;
public class LayersMenuState implements Parcelable {
public int expandedGroup;
public Set<UserItem> items;
public Set<User> people;
public Set<Group> groups;
public Set<Layer> layers;
public Map<String, Boolean> itemsChecks;
public Map<String, Boolean> peopleChecks;
public Map<String, Boolean> groupsChecks;
public Map<String, Boolean> layersChecks;
public LayersMenuState() {
this.expandedGroup = -1;
this.items = null;
this.people = null;
this.groups = null;
this.layers = null;
this.itemsChecks = null;
this.peopleChecks = null;
this.groupsChecks = null;
this.layersChecks = null;
}
public static final Creator<LayersMenuState> CREATOR = new Creator<LayersMenuState>() {
@Override
public LayersMenuState createFromParcel(Parcel source) {
LayersMenuState lms = new LayersMenuState();
lms.expandedGroup = source.readInt();
int itemsSize = source.readInt();
lms.items = new HashSet<UserItem>();
for (int i = 0; i < itemsSize; ++i) {
- UserItem ui = source.readParcelable(null);
+ UserItem ui = source.readParcelable(UserItem.class.getClassLoader());
lms.items.add(ui);
}
int peopleSize = source.readInt();
lms.people = new HashSet<User>();
for (int i = 0; i < peopleSize; ++i) {
- User u = source.readParcelable(null);
+ User u = source.readParcelable(User.class.getClassLoader());
lms.people.add(u);
}
int groupsSize = source.readInt();
lms.groups = new HashSet<Group>();
for (int i = 0; i < groupsSize; ++i) {
- Group g = source.readParcelable(null);
+ Group g = source.readParcelable(Group.class.getClassLoader());
lms.groups.add(g);
}
int layersSize = source.readInt();
lms.layers = new HashSet<Layer>();
for (int i = 0; i < layersSize; ++i) {
- Layer l = source.readParcelable(null);
+ Layer l = source.readParcelable(Layer.class.getClassLoader());
lms.layers.add(l);
}
int itemsChecksSize = source.readInt();
lms.itemsChecks = new HashMap<String, Boolean>();
for (int i = 0; i < itemsChecksSize; ++i) {
String s = source.readString();
boolean[] b = new boolean[1];
source.readBooleanArray(b);
lms.itemsChecks.put(s, b[0]);
}
int peopleChecksSize = source.readInt();
lms.peopleChecks = new HashMap<String, Boolean>();
for (int i = 0; i < peopleChecksSize; ++i) {
String s = source.readString();
boolean[] b = new boolean[1];
source.readBooleanArray(b);
lms.peopleChecks.put(s, b[0]);
}
int groupsChecksSize = source.readInt();
lms.groupsChecks = new HashMap<String, Boolean>();
for (int i = 0; i < groupsChecksSize; ++i) {
String s = source.readString();
boolean[] b = new boolean[1];
source.readBooleanArray(b);
lms.groupsChecks.put(s, b[0]);
}
int layersChecksSize = source.readInt();
lms.layersChecks = new HashMap<String, Boolean>();
for (int i = 0; i < layersChecksSize; ++i) {
String s = source.readString();
boolean[] b = new boolean[1];
source.readBooleanArray(b);
lms.layersChecks.put(s, b[0]);
}
return lms;
}
@Override
public LayersMenuState[] newArray(int size) {
return new LayersMenuState[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.expandedGroup);
dest.writeInt(this.items.size());
for (UserItem ui : items) {
dest.writeParcelable(ui, 0);
}
dest.writeInt(this.people.size());
for (User u : people) {
dest.writeParcelable(u, 0);
}
dest.writeInt(this.groups.size());
for (Group g : groups) {
dest.writeParcelable(g, 0);
}
dest.writeInt(this.layers.size());
for (Layer l : layers) {
dest.writeParcelable(l, 0);
}
dest.writeInt(this.itemsChecks.size());
for (String s : itemsChecks.keySet()) {
boolean[] b = new boolean[1];
b[0] = itemsChecks.get(s);
dest.writeString(s);
dest.writeBooleanArray(b);
}
dest.writeInt(this.peopleChecks.size());
for (String s : peopleChecks.keySet()) {
boolean[] b = new boolean[1];
b[0] = peopleChecks.get(s);
dest.writeString(s);
dest.writeBooleanArray(b);
}
dest.writeInt(this.groupsChecks.size());
for (String s : groupsChecks.keySet()) {
boolean[] b = new boolean[1];
b[0] = groupsChecks.get(s);
dest.writeString(s);
dest.writeBooleanArray(b);
}
dest.writeInt(this.layersChecks.size());
for (String s : layersChecks.keySet()) {
boolean[] b = new boolean[1];
b[0] = layersChecks.get(s);
dest.writeString(s);
dest.writeBooleanArray(b);
}
}
}
| false | false | null | null |
diff --git a/ScoreDeviationGroupingToCSV.java b/ScoreDeviationGroupingToCSV.java
index 2bf181d..30f50a4 100755
--- a/ScoreDeviationGroupingToCSV.java
+++ b/ScoreDeviationGroupingToCSV.java
@@ -1,755 +1,755 @@
/*
* Parsing .dev (performance features), .xml (score features) and .apex.xml (structural info)
* and making a single .csv
*
* v 0.7
*
* Elements in the csv file:
* 1. Part OK
* 2. Staff OK
* 3. Measure OK
* 4. Key
* 5. Clef
* 6. Beat position(tactus) OK
* 7. Note number OK
* 8. Note Name
* 9. Duration OK
* 10. Time signature OK
* 11. Slur OK
* 12. Expression marks - dynamics OK
* 13. Expression marks - wedge(cresc, dim.) OK
* 14. Expression marks - tempo(ritardando, accel.) OK
* 15. Articulation - staccato, legato, fermata OK
* 16. Arpeggio
* 17. Ornaments
* 18. Attack Time OK
* 19. Release Time OK
* 20. Tempo OK
* 21. Tempo Deviation OK
* 22. Dynamics OK
* 23. Grouping (reserved)
*
* Taehun Kim
* Audio Communcation Group, TU Berlin
* April 2012
*/
import jp.crestmuse.cmx.commands.*;
import jp.crestmuse.cmx.filewrappers.*;
import java.io.*;
import java.util.*;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.w3c.dom.Element;
import javax.xml.parsers.*;
public class ScoreDeviationGroupingToCSV extends CMXCommand {
private Hashtable<String, List> placeholder;
private Hashtable<Integer, Integer> grouping_indicator_dict;
private String scoreFileName;
private String outputFileName;
private String apexFileName;
private String targetDir;
public boolean isMusicXML; // if this is no, input file is .dev
private MusicXMLWrapper musicxml;
private DeviationInstanceWrapper dev;
private void writeToFile() throws IOException {
// get file pointer of the target file
File outFile = new File(outputFileName);
// make a buffer to write a file
java.io.BufferedWriter writer = new java.io.BufferedWriter(new java.io.FileWriter(outFile));
writer.write("$score_file: "+ scoreFileName);
writer.newLine();
if (!isMusicXML) {
writer.write("$performance_file: "+ dev.getFileName());
} else {
writer.write("$performance_file: NA");
}
writer.newLine();
// write the header
if (musicxml.hasMovementTitle()) {
writer.write("$title: " + musicxml.getMovementTitle());
writer.newLine();
}
double avg_tempo = -1;
if (!isMusicXML) {
avg_tempo = dev.searchNonPartwiseControl(1,0.2, "tempo").value();
}
writer.write("$avg_tempo: " + avg_tempo);
writer.newLine();
writer.write("$legend: Staff,Voice,Key,Clef,Measure,BeatPos,Metric,Notenum,NoteName,Duration,TimeSig,Slur,DynMark,Wedge,TempoMark,Articulation,Arpeggio,Ornaments,*Attack(0),*Release(1),*Tempo(2),*RelTempo(3),*Velocity(4),*GrpStr_Manual(5)");
writer.newLine();
writer.flush();
// write the body
String buffer[] = new String[placeholder.keySet().size()];
for (Enumeration ks = placeholder.keys(); ks.hasMoreElements();) {
// each key has its xpath. the first element is the position of the note
String xpath = (String)(ks.nextElement());
List aList = placeholder.get(xpath);
int note_position = (Integer)(aList.get(0));
String writeLine = "";
for (int j = 1; j < aList.size(); j++) {
writeLine = writeLine+aList.get(j)+",";
}
writeLine = writeLine.substring(0, writeLine.length() - 1); // remove the last comma (,)
buffer[note_position] = writeLine;
}
for (int i = 0; i < buffer.length; i++) {
System.out.println(buffer[i]);
writer.write(buffer[i]);
writer.newLine();
}
// close file writer
writer.write("-EOF-\n");
writer.flush();
writer.close();
}
private void scoreDevToPlaceholder() {
String timeSig = "NA";
String exDyn = "NA";
String exDyn_sf = "NA"; // for sf-family. sf is just for one note!
String exTmp = "NA";
String exWedge = "NA";
String key = "NA";
String clef_sign = "NA";
double avg_tempo = -1.0; // -1 means there is no avg_tempo
if (!isMusicXML) {
avg_tempo = dev.searchNonPartwiseControl(1,0.2, "tempo").value();
}
// getting Partlist
MusicXMLWrapper.Part[] partlist = musicxml.getPartList();
int note_count = 0;
for (MusicXMLWrapper.Part part : partlist) {
MusicXMLWrapper.Measure[] measurelist = part.getMeasureList();
// getting Measurelist
for(MusicXMLWrapper.Measure measure : measurelist) {
MusicXMLWrapper.MusicData[] mdlist = measure.getMusicDataList();
// getting Musicdata
for (MusicXMLWrapper.MusicData md : mdlist) {
// if md is Direction : Direction includes Dynamics, Wedges
if (md instanceof MusicXMLWrapper.Direction) {
MusicXMLWrapper.Direction direction = (MusicXMLWrapper.Direction)md;
MusicXMLWrapper.DirectionType[] directionTypes = direction.getDirectionTypeList();
for (MusicXMLWrapper.DirectionType directionType : directionTypes) {
// getting ff, mf, pp, etc. sf is also handled
if (directionType.name().equals("dynamics")) {
if (directionType.dynamics().contains("sf")) {
exDyn_sf = directionType.dynamics();
if (exDyn_sf.equals("sfp")) exDyn = "p";
} else {
exDyn = directionType.dynamics();
}
}
// getting wedges such as crescendo, diminuendo, rit., acc.
if (directionType.name().equals("wedge")) {
if (directionType.type().equals("crescendo")) {
exWedge = "crescendo";
}
if (directionType.type().equals("diminuendo")) {
exWedge = "diminuendo";
}
if (directionType.type().equals("stop")) {
exWedge = "NA";
}
}
if (directionType.name().equals("words")) {
if (directionType.text().contains("rit")) {
exTmp = "rit";
}
if (directionType.text().contains("rall")) {
exTmp = "rit";
}
if (directionType.text().contains("acc")) {
exTmp = "acc";
}
if (directionType.text().contains("a tempo")) {
exTmp = "NA";
}
if (directionType.text().contains("poco")) {
exTmp = "poco_" + exTmp;
}
if (directionType.text().contains("cresc")) {
exWedge = "crescendo";
}
if (directionType.text().contains("dim")) {
exWedge = "diminuendo";
}
}
} // end of DirectionType loop
} // end of diretion-if-statement
// getting attributes, mainly time signature
if (md instanceof MusicXMLWrapper.Attributes) {
int _beat = ((MusicXMLWrapper.Attributes)md).beats();
int _beatType = ((MusicXMLWrapper.Attributes)md).beatType();
if (_beat != 0 && _beatType != 0) {
timeSig = Integer.toString(_beat)+"/"+Integer.toString(_beatType);
}
clef_sign = ((MusicXMLWrapper.Attributes)md).clef_sign();
int _fifth = ((MusicXMLWrapper.Attributes)md).fifths();
String _mode = ((MusicXMLWrapper.Attributes)md).mode();
if (_fifth > 0) {
// number of sharps
switch (Math.abs(_fifth)) {
case 1:
key = "g";
break;
case 2:
key = "d";
break;
case 3:
key = "a";
break;
case 4:
key = "e";
break;
case 5:
key = "b";
break;
case 6:
key = "fis";
break;
case 7:
key = "cis";
break;
}
} else {
// number of flats
switch (Math.abs(_fifth)) {
case 0:
key = "c";
break;
case 1:
key = "f";
break;
case 2:
key = "bes";
break;
case 3:
key = "es";
break;
case 4:
key = "aes";
break;
case 5:
key = "des";
break;
case 6:
key = "ges";
break;
case 7:
key = "ces";
break;
}
}
}
// getting note info.
if (md instanceof MusicXMLWrapper.Note) {
MusicXMLWrapper.Note note = (MusicXMLWrapper.Note)md;
DeviationInstanceWrapper.NoteDeviation nd = null;
if (!isMusicXML) {
nd = dev.getNoteDeviation(note);
}
String staff = Integer.toString(note.staff());
String voice = Integer.toString(note.voice());
String measureNumber = Integer.toString(measure.number());
String beatPos = Double.toString(note.beat());
String durationActual = Double.toString(note.tiedDuration()); // for a tied note
String xpath = (note.getXPathExpression());
String noteNumber = "R";
String attack = "NA";
String release = "NA";
String dynamic = "NA";
String slur = "NA";
String tie = "NA";
String tuplet = "NA";
String articulation ="NA";
Double tempo_dev = 1.0;
String metric = "NA";
String arpeggiate = "NA";
String ornaments = "NA";
String noteName = "NA";
String [] splitLine = timeSig.split("/");
int beat = Integer.parseInt(splitLine[0]);
int beatType = Integer.parseInt(splitLine[1]);
// estimate metric info
// WE NEED REFACTORING HERE!!!
if (beatType == 4 || beatType == 2) {
if (beat == 4) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "m";
if (note.beat() >= 4.0 && note.beat() < 5.0) metric = "w";
}
if (beat == 3) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "w";
}
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "weak";
}
}
if (beatType == 8) {
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
}
if (beat == 6) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
}
if (beat == 9) {
if (note.beat() >= 1.0 && note.beat() < 1.33) metric = "s";
if (note.beat() >= 1.33 && note.beat() < 1.66) metric = "w";
if (note.beat() >= 1.66 && note.beat() < 2.00) metric = "w";
if (note.beat() >= 2.00 && note.beat() < 2.33) metric = "m";
if (note.beat() >= 2.33 && note.beat() < 2.66) metric = "w";
if (note.beat() >= 2.66 && note.beat() < 3.00) metric = "w";
if (note.beat() >= 3.00 && note.beat() < 3.33) metric = "m";
if (note.beat() >= 3.33 && note.beat() < 3.66) metric = "w";
if (note.beat() >= 3.66 && note.beat() < 4.00) metric = "w";
}
if (beat == 12) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
if (note.beat() >= 4.0 && note.beat() < 4.5) metric = "s";
if (note.beat() >= 4.5 && note.beat() < 5.0) metric = "w";
if (note.beat() >= 5.0 && note.beat() < 5.5) metric = "w";
if (note.beat() >= 5.5 && note.beat() < 6.0) metric = "m";
if (note.beat() >= 6.0 && note.beat() < 6.5) metric = "w";
if (note.beat() >= 6.5 && note.beat() < 7.0) metric = "w";
}
}
String tempoDeviation = "NA";
String tempo = "NA";
if (dev != null && dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2), "tempo-deviation") != null) {
tempo_dev = dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2),
"tempo-deviation").value();
tempoDeviation = Double.toString(tempo_dev);
tempo = Double.toString(avg_tempo*tempo_dev);
}
//get notation
if (((MusicXMLWrapper.Note)md).getFirstNotations() != null) {
if ((note.getFirstNotations().getSlurList()) != null) {
slur = (note.getFirstNotations().getSlurList()).get(0).type();
}
if ((note.getFirstNotations().hasArticulation("staccato")) == true) {
articulation = "staccato";
}
if ((note.getFirstNotations().fermata()) != null) {
articulation = "fermata";
}
if ((note.getFirstNotations().hasArticulation("accent")) == true) {
articulation = "accent";
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
noteName = note.noteName();
//if there exists note deviation info
if (nd != null && nd instanceof DeviationInstanceWrapper.NoteDeviation) {
//calculate relative attack, release respect to actualDuration
if (Double.parseDouble(durationActual) != 0) {
attack = Double.toString(nd.attack());
release = Double.toString((nd.release()+
Double.parseDouble(durationActual))/
Double.parseDouble(durationActual));
}
dynamic = Double.toString(nd.dynamics());
}
}
else {
noteNumber = "R";
attack = "NA";
release = "NA";
dynamic = "NA";
}
MusicXMLWrapper.Notations nt = note.getFirstNotations();
- org.w3c.dom.NodeList childNodes = nt.getTheChildNodes();
+ org.w3c.dom.NodeList childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("arpeggiate")) {
arpeggiate = nodeName;
}
if (nodeName.equals("ornaments")) {
String nodeName2 = childNodes.item(index).getFirstChild().getNodeName();
if (nodeName2.equals("trill-mark")) {
ornaments = "trill_2_X";
}
if (nodeName2.equals("turn")) {
ornaments = "turn_2_-1"; // +2, 0, -2, 0
}
if (nodeName2.equals("inverted-turn")) {
ornaments = "turn_-1_2";
}
if (nodeName2.equals("mordent")) {
ornaments = "mordent_2_X";
}
if (nodeName2.equals("inverted-mordent")) {
ornaments = "mordent_-2_X";
}
}
if (nodeName.equals("slur")) {
slur = nt.getSlurList().get(0).type();
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
if (note.grace()) {
childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("grace")) {
org.w3c.dom.NamedNodeMap attrs = childNodes.item(index).getAttributes();
if (childNodes.item(index).hasAttributes() == false) {
noteNumber = "grace_app_"+noteNumber;
} else {
noteNumber = "grace_acc_"+noteNumber;
}
}
}
if (note.type().equals("32th")) durationActual = "0.125";
else if (note.type().equals("16th")) durationActual = "0.25";
else if (note.type().equals("eighth")) durationActual = "0.5";
else if (note.type().equals("quarter")) durationActual = "1.0";
else if (note.type().equals("half")) durationActual = "2.0";
else if (note.type().equals("whole")) durationActual = "4.0";
else if (note.type().equals("64th")) durationActual = "0.0625";
}
}
String write_exDyn; // for sf-handling
// if duration == 0.0 then the note is a decorative note.
// if tie == "stop" then we skip the note, because tie is already processed
if (!durationActual.equals("0.0") || !tie.equals("stop")) {
// sf-handling
if (!exDyn_sf.equals("NA")) {
write_exDyn = exDyn_sf; exDyn_sf = "NA";
} else {
write_exDyn = exDyn;
}
List<Object> aList = new ArrayList<Object>();
aList.add(note_count); // only for sorting later
aList.add(staff); // 0
aList.add(voice); // 1
aList.add(key); // 2
aList.add(clef_sign); // 3
aList.add(measureNumber); // 4
aList.add(beatPos); // 5
aList.add(metric); // 6
aList.add(noteNumber); // 7
aList.add(noteName); // 8
aList.add(durationActual); // 9
aList.add(timeSig); // 10
aList.add(slur); // 11
aList.add(write_exDyn); // 12
aList.add(exWedge); // 13
aList.add(exTmp); // 14
aList.add(articulation); // 15
aList.add(arpeggiate); // 16
aList.add(ornaments); // 17
aList.add(attack); // 18
aList.add(release); // 19
aList.add(tempo); // 20
aList.add(tempoDeviation); // 21
aList.add(dynamic); // 22
String grouping = "NA";
aList.add(grouping); // 23
placeholder.put(xpath, aList);
note_count++;
}
}
}
}
}
}
private void groupingToPlaceholder() {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document document = null;
try {
document = builder.parse(new FileInputStream(apexFileName));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element rootElement = document.getDocumentElement();
NodeList groups = rootElement.getElementsByTagName(("group"));
for (int i = 0; i < groups.getLength(); i++) {
parseNoteGroupsWithNode(groups.item(i));
}
}
private void parseNoteGroupsWithNode(Node g) {
Element e =(Element)g;
String depth = e.getAttribute("depth");
String grouping_id = getGroupingIdOfDepth(Integer.parseInt(depth));
NodeList notes = g.getChildNodes();
for (int i = 0; i < notes.getLength(); i++) {
// get xpath of the note
if (!(notes.item(i) instanceof Element)) {
continue;
}
Element n = (Element)notes.item(i);
if (n.getTagName().equals("note")) {
String xpath_orig = n.getAttribute("xlink:href");
String xpath = xpath_orig.substring(10, xpath_orig.length()-1);
// find note array with the xpath
List note_array = placeholder.get(xpath);
String grouping = (String)(note_array.get(22)); // 22 is the index of the grouping array
if (grouping.equals("NA")) {
grouping = "";
grouping +=grouping_id;
} else {
grouping = grouping + ":" + grouping_id;
}
note_array.set(22, grouping);
placeholder.remove(xpath);
placeholder.put(xpath, note_array);
} else if (n.getTagName().equals("apex")) {
// Parsing apex info.
// Each group has its own apex point.
// The notes of the apex start will be marked with additional "<"
// The notes of the apex end will be marked with additional ">"
NodeList apex_nodes = n.getChildNodes();
for ( int j = 0; j < apex_nodes.getLength(); j++) {
if (!(apex_nodes.item(j) instanceof Element)) {
continue;
}
Element a = (Element)apex_nodes.item(j);
String xpath_orig = a.getAttribute("xlink:href");
String xpath = xpath_orig.substring(10, xpath_orig.length()-1);
List note_array = placeholder.get(xpath);
System.out.println(note_array);
String grouping = (String)(note_array.get(22)); // 22 is the index of the grouping array
String [] g_split = grouping.split(":");
String target_group = g_split[Integer.parseInt(depth)-1];
if (a.getTagName().equals("start")) {
target_group += "<";
} else if (a.getTagName().equals("stop")) {
target_group += ">";
}
g_split[Integer.parseInt(depth)-1] = target_group;
String newGrouping = "";
for (int m = 0; m < g_split.length; m++) {
newGrouping += g_split[m];
if (m < g_split.length - 1) newGrouping += ":";
}
note_array.set(22, newGrouping);
}
}
}
}
private String getGroupingIdOfDepth(Integer d) {
Integer retVal = -1;
if (grouping_indicator_dict.containsKey(d)) {
Integer value = grouping_indicator_dict.get(d);
Integer newValue = value+1;
grouping_indicator_dict.put(d, newValue);
retVal = newValue;
} else {
// this key is new!
grouping_indicator_dict.put(d, 0);
retVal = 0;
}
return Integer.toString(retVal);
}
protected void run() throws IOException {
if (!isMusicXML) {
dev = (DeviationInstanceWrapper)indata();
//getting target score XML
musicxml = dev.getTargetMusicXML();
// getting score file name and setting output file name
scoreFileName = musicxml.getFileName();
outputFileName = dev.getFileName() + ".apex.csv";
// get apex file name
String [] devFileNameSplit = dev.getFileName().split("\\.(?=[^\\.]+$)");
String devFileNameWithoutExt = devFileNameSplit[0];
String devFileNameWithoutSoundSource;
int string_length = devFileNameWithoutExt.length();
if (devFileNameWithoutExt.charAt(string_length-2) == '-') {
devFileNameWithoutSoundSource = devFileNameWithoutExt.substring(0, string_length-2);
} else {
devFileNameWithoutSoundSource = devFileNameWithoutExt;
}
apexFileName = this.targetDir+devFileNameWithoutSoundSource+".apex.xml";
System.out.println("[LOG] THIS IS DeviationXML FILE.");
System.out.println("[LOG] opening necessary files ...");
System.out.println("ScoreXML: "+scoreFileName+" \nDeviationXML: "+dev.getTargetMusicXMLFileName()+" \nApexXML: "+apexFileName);
System.out.println("OutputCSV: "+outputFileName);
} else {
// this is MusicXML file. so we do not have apex file either!
dev = null;
musicxml = (MusicXMLWrapper)indata();
scoreFileName = musicxml.getFileName();
outputFileName = scoreFileName + ".csv";
System.out.println("[LOG] THIS IS MusicXML FILE.");
System.out.println("[LOG] opening necessary files ...");
System.out.println("ScoreXML: "+scoreFileName);
System.out.println("OutputCSV: "+outputFileName);
}
// Preparing placeholder
placeholder = new Hashtable<String, List>();
// Preparing grouping indicator dicionary
grouping_indicator_dict = new Hashtable<Integer, Integer>();
// Getting score and expressive features from MusicXML into the placeholder
System.out.println("[LOG] parsing score and performance annotations...");
this.scoreDevToPlaceholder();
// Getting structural info form ApexXML into the placeholder
if (!isMusicXML) {
File f = new File(apexFileName);
if (f.exists()) {
System.out.println("[LOG] parsing grouping annotation...");
this.groupingToPlaceholder();
} else {
System.out.println("[LOG] No apex xml is found!");
outputFileName = dev.getFileName()+".csv";
System.out.println("[LOG] new output file name: "+outputFileName);
}
}
// Wrting data in the placeholder into a file
System.out.println("[LOG] writing to the output file...");
this.writeToFile();
}
public static void main(String[] args) {
System.out.println("Score, deviation and grouping annotation parser v 0.7");
System.out.println("Parsing .dev, .xml and .apex.xml and making .csv");
System.out.println("Implemented with CMX API");
System.out.println("Taehun KIM, Audio Communication Group, TU Berlin");
System.out.println("2012");
if (args.length == 0) {
System.out.println("Usage: java ScoreDeviationGroupingToCSV file(s)");
System.out.println("- The input files should have the extension .dev(DeviationXML) or .xml(MusicXML)");
System.exit(1);
}
ScoreDeviationGroupingToCSV c= new ScoreDeviationGroupingToCSV();
// get the target directory
String targetDirArg = args[0];
// check the input file type
c.isMusicXML = targetDirArg.indexOf(".xml") != -1;
String [] split = targetDirArg.split("/");
split[split.length-1] = "";
String result = "";
for (int m = 0; m < split.length; m++) {
result += split[m];
if (m < split.length - 1) result += "/";
}
c.targetDir = result;
try {
c.start(args);
} catch (Exception e) {
c.showErrorMessage(e);
System.exit(1);
}
}
}
| true | true | private void scoreDevToPlaceholder() {
String timeSig = "NA";
String exDyn = "NA";
String exDyn_sf = "NA"; // for sf-family. sf is just for one note!
String exTmp = "NA";
String exWedge = "NA";
String key = "NA";
String clef_sign = "NA";
double avg_tempo = -1.0; // -1 means there is no avg_tempo
if (!isMusicXML) {
avg_tempo = dev.searchNonPartwiseControl(1,0.2, "tempo").value();
}
// getting Partlist
MusicXMLWrapper.Part[] partlist = musicxml.getPartList();
int note_count = 0;
for (MusicXMLWrapper.Part part : partlist) {
MusicXMLWrapper.Measure[] measurelist = part.getMeasureList();
// getting Measurelist
for(MusicXMLWrapper.Measure measure : measurelist) {
MusicXMLWrapper.MusicData[] mdlist = measure.getMusicDataList();
// getting Musicdata
for (MusicXMLWrapper.MusicData md : mdlist) {
// if md is Direction : Direction includes Dynamics, Wedges
if (md instanceof MusicXMLWrapper.Direction) {
MusicXMLWrapper.Direction direction = (MusicXMLWrapper.Direction)md;
MusicXMLWrapper.DirectionType[] directionTypes = direction.getDirectionTypeList();
for (MusicXMLWrapper.DirectionType directionType : directionTypes) {
// getting ff, mf, pp, etc. sf is also handled
if (directionType.name().equals("dynamics")) {
if (directionType.dynamics().contains("sf")) {
exDyn_sf = directionType.dynamics();
if (exDyn_sf.equals("sfp")) exDyn = "p";
} else {
exDyn = directionType.dynamics();
}
}
// getting wedges such as crescendo, diminuendo, rit., acc.
if (directionType.name().equals("wedge")) {
if (directionType.type().equals("crescendo")) {
exWedge = "crescendo";
}
if (directionType.type().equals("diminuendo")) {
exWedge = "diminuendo";
}
if (directionType.type().equals("stop")) {
exWedge = "NA";
}
}
if (directionType.name().equals("words")) {
if (directionType.text().contains("rit")) {
exTmp = "rit";
}
if (directionType.text().contains("rall")) {
exTmp = "rit";
}
if (directionType.text().contains("acc")) {
exTmp = "acc";
}
if (directionType.text().contains("a tempo")) {
exTmp = "NA";
}
if (directionType.text().contains("poco")) {
exTmp = "poco_" + exTmp;
}
if (directionType.text().contains("cresc")) {
exWedge = "crescendo";
}
if (directionType.text().contains("dim")) {
exWedge = "diminuendo";
}
}
} // end of DirectionType loop
} // end of diretion-if-statement
// getting attributes, mainly time signature
if (md instanceof MusicXMLWrapper.Attributes) {
int _beat = ((MusicXMLWrapper.Attributes)md).beats();
int _beatType = ((MusicXMLWrapper.Attributes)md).beatType();
if (_beat != 0 && _beatType != 0) {
timeSig = Integer.toString(_beat)+"/"+Integer.toString(_beatType);
}
clef_sign = ((MusicXMLWrapper.Attributes)md).clef_sign();
int _fifth = ((MusicXMLWrapper.Attributes)md).fifths();
String _mode = ((MusicXMLWrapper.Attributes)md).mode();
if (_fifth > 0) {
// number of sharps
switch (Math.abs(_fifth)) {
case 1:
key = "g";
break;
case 2:
key = "d";
break;
case 3:
key = "a";
break;
case 4:
key = "e";
break;
case 5:
key = "b";
break;
case 6:
key = "fis";
break;
case 7:
key = "cis";
break;
}
} else {
// number of flats
switch (Math.abs(_fifth)) {
case 0:
key = "c";
break;
case 1:
key = "f";
break;
case 2:
key = "bes";
break;
case 3:
key = "es";
break;
case 4:
key = "aes";
break;
case 5:
key = "des";
break;
case 6:
key = "ges";
break;
case 7:
key = "ces";
break;
}
}
}
// getting note info.
if (md instanceof MusicXMLWrapper.Note) {
MusicXMLWrapper.Note note = (MusicXMLWrapper.Note)md;
DeviationInstanceWrapper.NoteDeviation nd = null;
if (!isMusicXML) {
nd = dev.getNoteDeviation(note);
}
String staff = Integer.toString(note.staff());
String voice = Integer.toString(note.voice());
String measureNumber = Integer.toString(measure.number());
String beatPos = Double.toString(note.beat());
String durationActual = Double.toString(note.tiedDuration()); // for a tied note
String xpath = (note.getXPathExpression());
String noteNumber = "R";
String attack = "NA";
String release = "NA";
String dynamic = "NA";
String slur = "NA";
String tie = "NA";
String tuplet = "NA";
String articulation ="NA";
Double tempo_dev = 1.0;
String metric = "NA";
String arpeggiate = "NA";
String ornaments = "NA";
String noteName = "NA";
String [] splitLine = timeSig.split("/");
int beat = Integer.parseInt(splitLine[0]);
int beatType = Integer.parseInt(splitLine[1]);
// estimate metric info
// WE NEED REFACTORING HERE!!!
if (beatType == 4 || beatType == 2) {
if (beat == 4) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "m";
if (note.beat() >= 4.0 && note.beat() < 5.0) metric = "w";
}
if (beat == 3) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "w";
}
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "weak";
}
}
if (beatType == 8) {
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
}
if (beat == 6) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
}
if (beat == 9) {
if (note.beat() >= 1.0 && note.beat() < 1.33) metric = "s";
if (note.beat() >= 1.33 && note.beat() < 1.66) metric = "w";
if (note.beat() >= 1.66 && note.beat() < 2.00) metric = "w";
if (note.beat() >= 2.00 && note.beat() < 2.33) metric = "m";
if (note.beat() >= 2.33 && note.beat() < 2.66) metric = "w";
if (note.beat() >= 2.66 && note.beat() < 3.00) metric = "w";
if (note.beat() >= 3.00 && note.beat() < 3.33) metric = "m";
if (note.beat() >= 3.33 && note.beat() < 3.66) metric = "w";
if (note.beat() >= 3.66 && note.beat() < 4.00) metric = "w";
}
if (beat == 12) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
if (note.beat() >= 4.0 && note.beat() < 4.5) metric = "s";
if (note.beat() >= 4.5 && note.beat() < 5.0) metric = "w";
if (note.beat() >= 5.0 && note.beat() < 5.5) metric = "w";
if (note.beat() >= 5.5 && note.beat() < 6.0) metric = "m";
if (note.beat() >= 6.0 && note.beat() < 6.5) metric = "w";
if (note.beat() >= 6.5 && note.beat() < 7.0) metric = "w";
}
}
String tempoDeviation = "NA";
String tempo = "NA";
if (dev != null && dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2), "tempo-deviation") != null) {
tempo_dev = dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2),
"tempo-deviation").value();
tempoDeviation = Double.toString(tempo_dev);
tempo = Double.toString(avg_tempo*tempo_dev);
}
//get notation
if (((MusicXMLWrapper.Note)md).getFirstNotations() != null) {
if ((note.getFirstNotations().getSlurList()) != null) {
slur = (note.getFirstNotations().getSlurList()).get(0).type();
}
if ((note.getFirstNotations().hasArticulation("staccato")) == true) {
articulation = "staccato";
}
if ((note.getFirstNotations().fermata()) != null) {
articulation = "fermata";
}
if ((note.getFirstNotations().hasArticulation("accent")) == true) {
articulation = "accent";
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
noteName = note.noteName();
//if there exists note deviation info
if (nd != null && nd instanceof DeviationInstanceWrapper.NoteDeviation) {
//calculate relative attack, release respect to actualDuration
if (Double.parseDouble(durationActual) != 0) {
attack = Double.toString(nd.attack());
release = Double.toString((nd.release()+
Double.parseDouble(durationActual))/
Double.parseDouble(durationActual));
}
dynamic = Double.toString(nd.dynamics());
}
}
else {
noteNumber = "R";
attack = "NA";
release = "NA";
dynamic = "NA";
}
MusicXMLWrapper.Notations nt = note.getFirstNotations();
org.w3c.dom.NodeList childNodes = nt.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("arpeggiate")) {
arpeggiate = nodeName;
}
if (nodeName.equals("ornaments")) {
String nodeName2 = childNodes.item(index).getFirstChild().getNodeName();
if (nodeName2.equals("trill-mark")) {
ornaments = "trill_2_X";
}
if (nodeName2.equals("turn")) {
ornaments = "turn_2_-1"; // +2, 0, -2, 0
}
if (nodeName2.equals("inverted-turn")) {
ornaments = "turn_-1_2";
}
if (nodeName2.equals("mordent")) {
ornaments = "mordent_2_X";
}
if (nodeName2.equals("inverted-mordent")) {
ornaments = "mordent_-2_X";
}
}
if (nodeName.equals("slur")) {
slur = nt.getSlurList().get(0).type();
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
if (note.grace()) {
childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("grace")) {
org.w3c.dom.NamedNodeMap attrs = childNodes.item(index).getAttributes();
if (childNodes.item(index).hasAttributes() == false) {
noteNumber = "grace_app_"+noteNumber;
} else {
noteNumber = "grace_acc_"+noteNumber;
}
}
}
if (note.type().equals("32th")) durationActual = "0.125";
else if (note.type().equals("16th")) durationActual = "0.25";
else if (note.type().equals("eighth")) durationActual = "0.5";
else if (note.type().equals("quarter")) durationActual = "1.0";
else if (note.type().equals("half")) durationActual = "2.0";
else if (note.type().equals("whole")) durationActual = "4.0";
else if (note.type().equals("64th")) durationActual = "0.0625";
}
}
String write_exDyn; // for sf-handling
// if duration == 0.0 then the note is a decorative note.
// if tie == "stop" then we skip the note, because tie is already processed
if (!durationActual.equals("0.0") || !tie.equals("stop")) {
// sf-handling
if (!exDyn_sf.equals("NA")) {
write_exDyn = exDyn_sf; exDyn_sf = "NA";
} else {
write_exDyn = exDyn;
}
List<Object> aList = new ArrayList<Object>();
aList.add(note_count); // only for sorting later
aList.add(staff); // 0
aList.add(voice); // 1
aList.add(key); // 2
aList.add(clef_sign); // 3
aList.add(measureNumber); // 4
aList.add(beatPos); // 5
aList.add(metric); // 6
aList.add(noteNumber); // 7
aList.add(noteName); // 8
aList.add(durationActual); // 9
aList.add(timeSig); // 10
aList.add(slur); // 11
aList.add(write_exDyn); // 12
aList.add(exWedge); // 13
aList.add(exTmp); // 14
aList.add(articulation); // 15
aList.add(arpeggiate); // 16
aList.add(ornaments); // 17
aList.add(attack); // 18
aList.add(release); // 19
aList.add(tempo); // 20
aList.add(tempoDeviation); // 21
aList.add(dynamic); // 22
String grouping = "NA";
aList.add(grouping); // 23
placeholder.put(xpath, aList);
note_count++;
}
}
}
}
}
}
| private void scoreDevToPlaceholder() {
String timeSig = "NA";
String exDyn = "NA";
String exDyn_sf = "NA"; // for sf-family. sf is just for one note!
String exTmp = "NA";
String exWedge = "NA";
String key = "NA";
String clef_sign = "NA";
double avg_tempo = -1.0; // -1 means there is no avg_tempo
if (!isMusicXML) {
avg_tempo = dev.searchNonPartwiseControl(1,0.2, "tempo").value();
}
// getting Partlist
MusicXMLWrapper.Part[] partlist = musicxml.getPartList();
int note_count = 0;
for (MusicXMLWrapper.Part part : partlist) {
MusicXMLWrapper.Measure[] measurelist = part.getMeasureList();
// getting Measurelist
for(MusicXMLWrapper.Measure measure : measurelist) {
MusicXMLWrapper.MusicData[] mdlist = measure.getMusicDataList();
// getting Musicdata
for (MusicXMLWrapper.MusicData md : mdlist) {
// if md is Direction : Direction includes Dynamics, Wedges
if (md instanceof MusicXMLWrapper.Direction) {
MusicXMLWrapper.Direction direction = (MusicXMLWrapper.Direction)md;
MusicXMLWrapper.DirectionType[] directionTypes = direction.getDirectionTypeList();
for (MusicXMLWrapper.DirectionType directionType : directionTypes) {
// getting ff, mf, pp, etc. sf is also handled
if (directionType.name().equals("dynamics")) {
if (directionType.dynamics().contains("sf")) {
exDyn_sf = directionType.dynamics();
if (exDyn_sf.equals("sfp")) exDyn = "p";
} else {
exDyn = directionType.dynamics();
}
}
// getting wedges such as crescendo, diminuendo, rit., acc.
if (directionType.name().equals("wedge")) {
if (directionType.type().equals("crescendo")) {
exWedge = "crescendo";
}
if (directionType.type().equals("diminuendo")) {
exWedge = "diminuendo";
}
if (directionType.type().equals("stop")) {
exWedge = "NA";
}
}
if (directionType.name().equals("words")) {
if (directionType.text().contains("rit")) {
exTmp = "rit";
}
if (directionType.text().contains("rall")) {
exTmp = "rit";
}
if (directionType.text().contains("acc")) {
exTmp = "acc";
}
if (directionType.text().contains("a tempo")) {
exTmp = "NA";
}
if (directionType.text().contains("poco")) {
exTmp = "poco_" + exTmp;
}
if (directionType.text().contains("cresc")) {
exWedge = "crescendo";
}
if (directionType.text().contains("dim")) {
exWedge = "diminuendo";
}
}
} // end of DirectionType loop
} // end of diretion-if-statement
// getting attributes, mainly time signature
if (md instanceof MusicXMLWrapper.Attributes) {
int _beat = ((MusicXMLWrapper.Attributes)md).beats();
int _beatType = ((MusicXMLWrapper.Attributes)md).beatType();
if (_beat != 0 && _beatType != 0) {
timeSig = Integer.toString(_beat)+"/"+Integer.toString(_beatType);
}
clef_sign = ((MusicXMLWrapper.Attributes)md).clef_sign();
int _fifth = ((MusicXMLWrapper.Attributes)md).fifths();
String _mode = ((MusicXMLWrapper.Attributes)md).mode();
if (_fifth > 0) {
// number of sharps
switch (Math.abs(_fifth)) {
case 1:
key = "g";
break;
case 2:
key = "d";
break;
case 3:
key = "a";
break;
case 4:
key = "e";
break;
case 5:
key = "b";
break;
case 6:
key = "fis";
break;
case 7:
key = "cis";
break;
}
} else {
// number of flats
switch (Math.abs(_fifth)) {
case 0:
key = "c";
break;
case 1:
key = "f";
break;
case 2:
key = "bes";
break;
case 3:
key = "es";
break;
case 4:
key = "aes";
break;
case 5:
key = "des";
break;
case 6:
key = "ges";
break;
case 7:
key = "ces";
break;
}
}
}
// getting note info.
if (md instanceof MusicXMLWrapper.Note) {
MusicXMLWrapper.Note note = (MusicXMLWrapper.Note)md;
DeviationInstanceWrapper.NoteDeviation nd = null;
if (!isMusicXML) {
nd = dev.getNoteDeviation(note);
}
String staff = Integer.toString(note.staff());
String voice = Integer.toString(note.voice());
String measureNumber = Integer.toString(measure.number());
String beatPos = Double.toString(note.beat());
String durationActual = Double.toString(note.tiedDuration()); // for a tied note
String xpath = (note.getXPathExpression());
String noteNumber = "R";
String attack = "NA";
String release = "NA";
String dynamic = "NA";
String slur = "NA";
String tie = "NA";
String tuplet = "NA";
String articulation ="NA";
Double tempo_dev = 1.0;
String metric = "NA";
String arpeggiate = "NA";
String ornaments = "NA";
String noteName = "NA";
String [] splitLine = timeSig.split("/");
int beat = Integer.parseInt(splitLine[0]);
int beatType = Integer.parseInt(splitLine[1]);
// estimate metric info
// WE NEED REFACTORING HERE!!!
if (beatType == 4 || beatType == 2) {
if (beat == 4) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "m";
if (note.beat() >= 4.0 && note.beat() < 5.0) metric = "w";
}
if (beat == 3) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "s";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "w";
if (note.beat() >= 3.0 && note.beat() < 4.0) metric = "w";
}
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 3.0) metric = "weak";
}
}
if (beatType == 8) {
if (beat == 2) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
}
if (beat == 6) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
}
if (beat == 9) {
if (note.beat() >= 1.0 && note.beat() < 1.33) metric = "s";
if (note.beat() >= 1.33 && note.beat() < 1.66) metric = "w";
if (note.beat() >= 1.66 && note.beat() < 2.00) metric = "w";
if (note.beat() >= 2.00 && note.beat() < 2.33) metric = "m";
if (note.beat() >= 2.33 && note.beat() < 2.66) metric = "w";
if (note.beat() >= 2.66 && note.beat() < 3.00) metric = "w";
if (note.beat() >= 3.00 && note.beat() < 3.33) metric = "m";
if (note.beat() >= 3.33 && note.beat() < 3.66) metric = "w";
if (note.beat() >= 3.66 && note.beat() < 4.00) metric = "w";
}
if (beat == 12) {
if (note.beat() >= 1.0 && note.beat() < 1.5) metric = "s";
if (note.beat() >= 1.5 && note.beat() < 2.0) metric = "w";
if (note.beat() >= 2.0 && note.beat() < 2.5) metric = "w";
if (note.beat() >= 2.5 && note.beat() < 3.0) metric = "m";
if (note.beat() >= 3.0 && note.beat() < 3.5) metric = "w";
if (note.beat() >= 3.5 && note.beat() < 4.0) metric = "w";
if (note.beat() >= 4.0 && note.beat() < 4.5) metric = "s";
if (note.beat() >= 4.5 && note.beat() < 5.0) metric = "w";
if (note.beat() >= 5.0 && note.beat() < 5.5) metric = "w";
if (note.beat() >= 5.5 && note.beat() < 6.0) metric = "m";
if (note.beat() >= 6.0 && note.beat() < 6.5) metric = "w";
if (note.beat() >= 6.5 && note.beat() < 7.0) metric = "w";
}
}
String tempoDeviation = "NA";
String tempo = "NA";
if (dev != null && dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2), "tempo-deviation") != null) {
tempo_dev = dev.searchNonPartwiseControl(measure.number(),
(Math.floor(note.beat())*0.2),
"tempo-deviation").value();
tempoDeviation = Double.toString(tempo_dev);
tempo = Double.toString(avg_tempo*tempo_dev);
}
//get notation
if (((MusicXMLWrapper.Note)md).getFirstNotations() != null) {
if ((note.getFirstNotations().getSlurList()) != null) {
slur = (note.getFirstNotations().getSlurList()).get(0).type();
}
if ((note.getFirstNotations().hasArticulation("staccato")) == true) {
articulation = "staccato";
}
if ((note.getFirstNotations().fermata()) != null) {
articulation = "fermata";
}
if ((note.getFirstNotations().hasArticulation("accent")) == true) {
articulation = "accent";
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
noteName = note.noteName();
//if there exists note deviation info
if (nd != null && nd instanceof DeviationInstanceWrapper.NoteDeviation) {
//calculate relative attack, release respect to actualDuration
if (Double.parseDouble(durationActual) != 0) {
attack = Double.toString(nd.attack());
release = Double.toString((nd.release()+
Double.parseDouble(durationActual))/
Double.parseDouble(durationActual));
}
dynamic = Double.toString(nd.dynamics());
}
}
else {
noteNumber = "R";
attack = "NA";
release = "NA";
dynamic = "NA";
}
MusicXMLWrapper.Notations nt = note.getFirstNotations();
org.w3c.dom.NodeList childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("arpeggiate")) {
arpeggiate = nodeName;
}
if (nodeName.equals("ornaments")) {
String nodeName2 = childNodes.item(index).getFirstChild().getNodeName();
if (nodeName2.equals("trill-mark")) {
ornaments = "trill_2_X";
}
if (nodeName2.equals("turn")) {
ornaments = "turn_2_-1"; // +2, 0, -2, 0
}
if (nodeName2.equals("inverted-turn")) {
ornaments = "turn_-1_2";
}
if (nodeName2.equals("mordent")) {
ornaments = "mordent_2_X";
}
if (nodeName2.equals("inverted-mordent")) {
ornaments = "mordent_-2_X";
}
}
if (nodeName.equals("slur")) {
slur = nt.getSlurList().get(0).type();
}
}
if (!note.rest()) {
noteNumber = Integer.toString(note.notenum());
if (note.grace()) {
childNodes = note.getTheChildNodes();
for (int index = 0; index < childNodes.getLength(); index++) {
String nodeName = childNodes.item(index).getNodeName();
if (nodeName.equals("grace")) {
org.w3c.dom.NamedNodeMap attrs = childNodes.item(index).getAttributes();
if (childNodes.item(index).hasAttributes() == false) {
noteNumber = "grace_app_"+noteNumber;
} else {
noteNumber = "grace_acc_"+noteNumber;
}
}
}
if (note.type().equals("32th")) durationActual = "0.125";
else if (note.type().equals("16th")) durationActual = "0.25";
else if (note.type().equals("eighth")) durationActual = "0.5";
else if (note.type().equals("quarter")) durationActual = "1.0";
else if (note.type().equals("half")) durationActual = "2.0";
else if (note.type().equals("whole")) durationActual = "4.0";
else if (note.type().equals("64th")) durationActual = "0.0625";
}
}
String write_exDyn; // for sf-handling
// if duration == 0.0 then the note is a decorative note.
// if tie == "stop" then we skip the note, because tie is already processed
if (!durationActual.equals("0.0") || !tie.equals("stop")) {
// sf-handling
if (!exDyn_sf.equals("NA")) {
write_exDyn = exDyn_sf; exDyn_sf = "NA";
} else {
write_exDyn = exDyn;
}
List<Object> aList = new ArrayList<Object>();
aList.add(note_count); // only for sorting later
aList.add(staff); // 0
aList.add(voice); // 1
aList.add(key); // 2
aList.add(clef_sign); // 3
aList.add(measureNumber); // 4
aList.add(beatPos); // 5
aList.add(metric); // 6
aList.add(noteNumber); // 7
aList.add(noteName); // 8
aList.add(durationActual); // 9
aList.add(timeSig); // 10
aList.add(slur); // 11
aList.add(write_exDyn); // 12
aList.add(exWedge); // 13
aList.add(exTmp); // 14
aList.add(articulation); // 15
aList.add(arpeggiate); // 16
aList.add(ornaments); // 17
aList.add(attack); // 18
aList.add(release); // 19
aList.add(tempo); // 20
aList.add(tempoDeviation); // 21
aList.add(dynamic); // 22
String grouping = "NA";
aList.add(grouping); // 23
placeholder.put(xpath, aList);
note_count++;
}
}
}
}
}
}
|
diff --git a/src/main/java/com/alexrnl/subtitlecorrector/io/SubtitleReader.java b/src/main/java/com/alexrnl/subtitlecorrector/io/SubtitleReader.java
index cbf1859..9afb057 100644
--- a/src/main/java/com/alexrnl/subtitlecorrector/io/SubtitleReader.java
+++ b/src/main/java/com/alexrnl/subtitlecorrector/io/SubtitleReader.java
@@ -1,111 +1,112 @@
package com.alexrnl.subtitlecorrector.io;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.alexrnl.commons.error.ExceptionUtils;
import com.alexrnl.subtitlecorrector.common.Subtitle;
import com.alexrnl.subtitlecorrector.common.SubtitleFile;
/**
* Abstract class for a subtitle reader.<br />
* @author Alex
*/
public abstract class SubtitleReader {
/** Logger */
private static Logger lg = Logger.getLogger(SubtitleReader.class.getName());
/**
* Constructor #1.<br />
* Default constructor.
*/
public SubtitleReader () {
super();
}
/**
* Read the specified file and return the loaded {@link SubtitleFile}.
* @param file
* the file to read.
* @return the subtitle file, loaded.
* @throws IOException
* if there was a problem while reading the file.
*/
public SubtitleFile readFile (final Path file) throws IOException {
- if (Files.exists(file) || Files.isReadable(file)) {
+ if (!Files.exists(file) || !Files.isReadable(file)) {
lg.warning("File " + file + " does not exists or cannot be read");
+ throw new IllegalArgumentException("The file does not exist or cannot be read");
}
if (lg.isLoggable(Level.INFO)) {
lg.fine("Loading file " + file);
}
SubtitleFile subtitleFile = null;
// TODO check for char set
try (final BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
try {
subtitleFile = readHeader(file, reader);
for (;;) {
subtitleFile.add(readSubtitle(subtitleFile, reader));
}
} catch (final EOFException e) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Finished reading file " + file);
}
readFooter(subtitleFile, reader);
}
} catch (final IOException e) {
lg.warning("Problem while reading subitle file: " + ExceptionUtils.display(e));
throw e;
}
return subtitleFile;
}
/**
* Read the header of the subtitle file and build the {@link SubtitleFile} to hold the data.<br />
* May be override by specific subtitle implementations.
* @param file
* the file being read.
* @param reader
* the reader to use.
* @return the subtitle file to use to store the data.
* @throws IOException
* if there was a problem while reading the file.
*/
protected SubtitleFile readHeader (final Path file, final BufferedReader reader) throws IOException {
return new SubtitleFile(file);
}
/**
* Read the footer of the subtitle file.<br />
* May be override by specific implementations.
* @param subtitleFile
* the subtitle file being read.
* @param reader
* the reader to use.
* @throws IOException
* if there was a problem while reading the file.
*/
protected void readFooter (final SubtitleFile subtitleFile, final BufferedReader reader) throws IOException {
// Do nothing
}
/**
* Read a single subtitle of the file.
* @param subtitleFile
* the subtitle file being read.
* @param reader
* the reader to use.
* @return The subtitle read.
* @throws IOException
* if there was a problem while reading the file.
*/
protected abstract Subtitle readSubtitle (final SubtitleFile subtitleFile, final BufferedReader reader) throws IOException;
}
| false | true | public SubtitleFile readFile (final Path file) throws IOException {
if (Files.exists(file) || Files.isReadable(file)) {
lg.warning("File " + file + " does not exists or cannot be read");
}
if (lg.isLoggable(Level.INFO)) {
lg.fine("Loading file " + file);
}
SubtitleFile subtitleFile = null;
// TODO check for char set
try (final BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
try {
subtitleFile = readHeader(file, reader);
for (;;) {
subtitleFile.add(readSubtitle(subtitleFile, reader));
}
} catch (final EOFException e) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Finished reading file " + file);
}
readFooter(subtitleFile, reader);
}
} catch (final IOException e) {
lg.warning("Problem while reading subitle file: " + ExceptionUtils.display(e));
throw e;
}
return subtitleFile;
}
| public SubtitleFile readFile (final Path file) throws IOException {
if (!Files.exists(file) || !Files.isReadable(file)) {
lg.warning("File " + file + " does not exists or cannot be read");
throw new IllegalArgumentException("The file does not exist or cannot be read");
}
if (lg.isLoggable(Level.INFO)) {
lg.fine("Loading file " + file);
}
SubtitleFile subtitleFile = null;
// TODO check for char set
try (final BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
try {
subtitleFile = readHeader(file, reader);
for (;;) {
subtitleFile.add(readSubtitle(subtitleFile, reader));
}
} catch (final EOFException e) {
if (lg.isLoggable(Level.INFO)) {
lg.info("Finished reading file " + file);
}
readFooter(subtitleFile, reader);
}
} catch (final IOException e) {
lg.warning("Problem while reading subitle file: " + ExceptionUtils.display(e));
throw e;
}
return subtitleFile;
}
|
diff --git a/src/main/java/org/jenkinsci/plugins/pretestedintegration/scminterface/mercurial/PretestedIntegrationSCMMercurial.java b/src/main/java/org/jenkinsci/plugins/pretestedintegration/scminterface/mercurial/PretestedIntegrationSCMMercurial.java
index 4848014..af32207 100644
--- a/src/main/java/org/jenkinsci/plugins/pretestedintegration/scminterface/mercurial/PretestedIntegrationSCMMercurial.java
+++ b/src/main/java/org/jenkinsci/plugins/pretestedintegration/scminterface/mercurial/PretestedIntegrationSCMMercurial.java
@@ -1,258 +1,258 @@
/**
*
*/
package org.jenkinsci.plugins.pretestedintegration.scminterface.mercurial;
import hudson.AbortException;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.BuildListener;
import hudson.model.Node;
import hudson.model.AbstractBuild;
import hudson.model.TaskListener;
import hudson.plugins.mercurial.MercurialInstallation;
import hudson.plugins.mercurial.MercurialSCM;
import hudson.scm.SCM;
import hudson.util.ArgumentListBuilder;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.util.Dictionary;
//import org.jenkinsci.plugins.pretestedintegration.scminterface.mercurial.HgUtils;
import org.jenkinsci.plugins.pretestedintegration.PretestUtils;
import org.jenkinsci.plugins.pretestedintegration.scminterface.PretestedIntegrationSCMCommit;
import org.jenkinsci.plugins.pretestedintegration.scminterface.PretestedIntegrationSCMInterface;
/**
* Implementation of PretestedIntegrationSCMInterface.
* This class adds integration support for mercurial SCM
* @author rel
*
*/
public class PretestedIntegrationSCMMercurial implements
PretestedIntegrationSCMInterface {
private FilePath workingDirectory = null;
final static String LOG_PREFIX = "[PREINT-HG] ";
public void setWorkingDirectory(FilePath workingDirectory){
this.workingDirectory = workingDirectory;
}
/**
* Locate the correct mercurial binary to use for commands
* @param build
* @param listener
* @param allowDebug
* @return An ArgumentListBuilder containing the correct hg binary
* @throws IOException
* @throws InterruptedException
*/
private static ArgumentListBuilder findHgExe(AbstractBuild build, TaskListener listener, boolean allowDebug) throws IOException,
InterruptedException {
//Cast the current SCM to get the methods we want.
//Throw exception on failure
try{
SCM scm = build.getProject().getScm();
MercurialSCM hg = (MercurialSCM) scm;
Node node = build.getBuiltOn();
// Run through Mercurial installations and check if they correspond to
// the one used in this job
for (MercurialInstallation inst
: MercurialInstallation.allInstallations()) {
if (inst.getName().equals(hg.getInstallation())) {
// TODO: what about forEnvironment?
String home = inst.getExecutable().replace("INSTALLATION",
inst.forNode(node, listener).getHome());
ArgumentListBuilder b = new ArgumentListBuilder(home);
if (allowDebug && inst.getDebug()) {
b.add("--debug");
}
return b;
}
}
//Just use the default hg
return new ArgumentListBuilder(hg.getDescriptor().getHgExe());
} catch(ClassCastException e) {
listener.getLogger().println(LOG_PREFIX + " configured scm is not mercurial");
throw new InterruptedException();
}
}
/**
* Invoke a command with mercurial
* @param build
* @param launcher
* @param listener
* @param cmds
* @return The exitcode of command
* @throws IOException
* @throws InterruptedException
*/
public int hg(AbstractBuild build, Launcher launcher, TaskListener listener, String... cmds) throws IOException, InterruptedException{
ArgumentListBuilder hg = findHgExe(build, listener, false);
hg.add(cmds);
//if the working directory has not been manually set use the build workspace
if(workingDirectory == null){
setWorkingDirectory(build.getWorkspace());
}
int exitCode = launcher.launch().cmds(hg).pwd(workingDirectory).join();
return exitCode;
}
/**
* Invoke a command with mercurial
* @param build
* @param launcher
* @param listener
* @param cmds
* @return The exitcode of command
* @throws IOException
* @throws InterruptedException
*/
public int hg(AbstractBuild build, Launcher launcher, TaskListener listener,OutputStream out, String... cmds) throws IOException, InterruptedException{
ArgumentListBuilder hg = findHgExe(build, listener, false);
hg.add(cmds);
//if the working directory has not been manually set use the build workspace
if(workingDirectory == null){
setWorkingDirectory(build.getWorkspace());
}
int exitCode = launcher.launch().cmds(hg).stdout(out).pwd(workingDirectory).join();
return exitCode;
}
/* (non-Javadoc)
* @see org.jenkinsci.plugins.pretestedintegration.scminterface.PretestedIntegrationSCMInterface#hasNextCommit(hudson.model.AbstractBuild, hudson.Launcher, hudson.model.BuildListener)
*/
public void prepareWorkspace(AbstractBuild build, Launcher launcher,
BuildListener listener, PretestedIntegrationSCMCommit commit)
throws AbortException, IOException, IllegalArgumentException {
try {
//Make sure that we are on the integration branch
//TODO: Make it dynamic and not just "default"
hg(build, launcher, listener, "update","default");
//Merge the commit into the integration branch
hg(build, launcher, listener, "merge", commit.getId(),"--tool","internal:merge");
} catch(InterruptedException e){
listener.getLogger().print(LOG_PREFIX + "hg command exited unexpectedly");
throw new AbortException();
}
}
/* (non-Javadoc)
* @see org.jenkinsci.plugins.pretestedintegration.scminterface.PretestedIntegrationSCMInterface#hasNextCommit(hudson.model.AbstractBuild, hudson.Launcher, hudson.model.BuildListener)
*/
public boolean hasNextCommit(AbstractBuild build, Launcher launcher,
BuildListener listener) throws IOException,
IllegalArgumentException {
String revision = "0";
try {
ByteArrayOutputStream logStdout = new ByteArrayOutputStream();
int exitCode = hg(build, launcher, listener,logStdout, new String[]
{"log", "-r", revision+":tip","--template","\"{node}\\n\"" });
if(logStdout.toString().split("\\n").length<2 ){
return false;
}else{
return true;
}
}
catch(IOException e)
{
throw e;
}
catch(InterruptedException e)
{
throw new IOException(e.getMessage());
}
}
/* (non-Javadoc)
* @see org.jenkinsci.plugins.pretestedintegration.scminterface.PretestedIntegrationSCMInterface#popCommit(hudson.model.AbstractBuild, hudson.Launcher, hudson.model.BuildListener)
*/
public PretestedIntegrationSCMCommit popCommit(AbstractBuild build,
Launcher launcher, BuildListener listener) throws IOException,
IllegalArgumentException {
String revision = "0";
- PretestedIntegrationSCMCommit commit = new PretestedIntegrationSCMCommit();
+ //PretestedIntegrationSCMCommit commit = new PretestedIntegrationSCMCommit();
try {
ByteArrayOutputStream logStdout = new ByteArrayOutputStream();
int exitCode = hg(build, launcher, listener,logStdout, new String[]
{"log", "-r", revision+":tip","--template","\"{node}\\n\"" });
if(logStdout.toString().split("\\n").length<2 ){
return null;
}else{
- return true;
+ return null;
}
}
catch(IOException e)
{
throw e;
}
catch(InterruptedException e)
{
throw new IOException(e.getMessage());
}
- return null;
+ //return null;
}
/* (non-Javadoc)
* @see org.jenkinsci.plugins.pretestedintegration.scminterface.PretestedIntegrationSCMInterface#handlePostBuild(hudson.model.AbstractBuild, hudson.Launcher, hudson.model.BuildListener, hudson.model.Result)
*/
public void handlePostBuild(AbstractBuild build, Launcher launcher,
BuildListener listener) throws IOException,
IllegalArgumentException {
try {
ArgumentListBuilder cmd = HgUtils.createArgumentListBuilder(
build, launcher, listener);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//get info regarding which branch that is going to be pushed to company truth
//Dictionary<String, String> newCommitInfo = HgUtils.getNewestCommitInfo(
// build, launcher, listener);
//String sourceBranch = newCommitInfo.get("branch");
//PretestUtils.logMessage(listener, "commit is on this branch: "
// + sourceBranch);
Dictionary<String, String> vars = null;
try {
vars = HgUtils.getNewestCommitInfo(build, launcher, listener);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
HgUtils.runScmCommand(build, launcher, listener,
new String[]{"commit", "-m", vars.get("message")});
HgUtils.runScmCommand(build, launcher, listener,
new String[]{"push", "--new-branch"});
}
catch(AbortException e){
throw e;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| false | false | null | null |
diff --git a/src/com/android/bluetooth/hfp/HeadsetPhoneState.java b/src/com/android/bluetooth/hfp/HeadsetPhoneState.java
index 0f235e9..9b61cc4 100644
--- a/src/com/android/bluetooth/hfp/HeadsetPhoneState.java
+++ b/src/com/android/bluetooth/hfp/HeadsetPhoneState.java
@@ -1,361 +1,365 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.bluetooth.hfp;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
// Note:
// All methods in this class are not thread safe, donot call them from
// multiple threads. Call them from the HeadsetPhoneStateMachine message
// handler only.
class HeadsetPhoneState {
private static final String TAG = "HeadsetPhoneState";
private HeadsetStateMachine mStateMachine;
private TelephonyManager mTelephonyManager;
private ServiceState mServiceState;
// HFP 1.6 CIND service
private int mService = HeadsetHalConstants.NETWORK_STATE_NOT_AVAILABLE;
// Number of active (foreground) calls
private int mNumActive = 0;
// Current Call Setup State
private int mCallState = HeadsetHalConstants.CALL_STATE_IDLE;
// Number of held (background) calls
private int mNumHeld = 0;
// Phone Number
private String mNumber;
// Type of Phone Number
private int mType = 0;
// HFP 1.6 CIND signal
private int mSignal = 0;
// HFP 1.6 CIND roam
private int mRoam = HeadsetHalConstants.SERVICE_TYPE_HOME;
// HFP 1.6 CIND battchg
private int mBatteryCharge = 0;
private int mSpeakerVolume = 0;
private int mMicVolume = 0;
private boolean mListening = false;
HeadsetPhoneState(Context context, HeadsetStateMachine stateMachine) {
mStateMachine = stateMachine;
mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
}
public void cleanup() {
listenForPhoneState(false);
mTelephonyManager = null;
mStateMachine = null;
}
void listenForPhoneState(boolean start) {
if (start) {
if (!mListening) {
mTelephonyManager.listen(mPhoneStateListener,
PhoneStateListener.LISTEN_SERVICE_STATE |
PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
mListening = true;
}
} else {
if (mListening) {
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
mListening = false;
}
}
}
int getService() {
return mService;
}
int getNumActiveCall() {
return mNumActive;
}
void setNumActiveCall(int numActive) {
mNumActive = numActive;
}
int getCallState() {
return mCallState;
}
void setCallState(int callState) {
mCallState = callState;
}
int getNumHeldCall() {
return mNumHeld;
}
void setNumHeldCall(int numHeldCall) {
mNumHeld = numHeldCall;
}
void setNumber(String mNumberCall ) {
mNumber = mNumberCall;
}
String getNumber()
{
return mNumber;
}
void setType(int mTypeCall) {
mType = mTypeCall;
}
int getType() {
return mType;
}
int getSignal() {
return mSignal;
}
int getRoam() {
return mRoam;
}
void setRoam(int roam) {
if (mRoam != roam) {
mRoam = roam;
sendDeviceStateChanged();
}
}
void setBatteryCharge(int batteryLevel) {
if (mBatteryCharge != batteryLevel) {
mBatteryCharge = batteryLevel;
sendDeviceStateChanged();
}
}
int getBatteryCharge() {
return mBatteryCharge;
}
void setSpeakerVolume(int volume) {
mSpeakerVolume = volume;
}
int getSpeakerVolume() {
return mSpeakerVolume;
}
void setMicVolume(int volume) {
mMicVolume = volume;
}
int getMicVolume() {
return mMicVolume;
}
boolean isInCall() {
return (mNumActive >= 1);
}
void sendDeviceStateChanged()
{
+ // When out of service, send signal strength as 0. Some devices don't
+ // use the service indicator, but only the signal indicator
+ int signal = mService == HeadsetHalConstants.NETWORK_STATE_AVAILABLE ? mSignal : 0;
+
Log.d(TAG, "sendDeviceStateChanged. mService="+ mService +
- " mSignal="+mSignal +" mRoam="+mRoam +
+ " mSignal=" + signal +" mRoam="+ mRoam +
" mBatteryCharge=" + mBatteryCharge);
HeadsetStateMachine sm = mStateMachine;
if (sm != null) {
sm.sendMessage(HeadsetStateMachine.DEVICE_STATE_CHANGED,
- new HeadsetDeviceState(mService, mRoam, mSignal, mBatteryCharge));
+ new HeadsetDeviceState(mService, mRoam, signal, mBatteryCharge));
}
}
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
@Override
public void onServiceStateChanged(ServiceState serviceState) {
mServiceState = serviceState;
mService = (serviceState.getState() == ServiceState.STATE_IN_SERVICE) ?
HeadsetHalConstants.NETWORK_STATE_AVAILABLE :
HeadsetHalConstants.NETWORK_STATE_NOT_AVAILABLE;
setRoam(serviceState.getRoaming() ? HeadsetHalConstants.SERVICE_TYPE_ROAMING
: HeadsetHalConstants.SERVICE_TYPE_HOME);
sendDeviceStateChanged();
}
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
int prevSignal = mSignal;
if (signalStrength.isGsm()) {
mSignal = gsmAsuToSignal(signalStrength);
} else {
mSignal = cdmaDbmEcioToSignal(signalStrength);
}
// network signal strength is scaled to BT 1-5 levels.
// This results in a lot of duplicate messages, hence this check
if (prevSignal != mSignal)
sendDeviceStateChanged();
}
/* convert [0,31] ASU signal strength to the [0,5] expected by
* bluetooth devices. Scale is similar to status bar policy
*/
private int gsmAsuToSignal(SignalStrength signalStrength) {
int asu = signalStrength.getGsmSignalStrength();
if (asu >= 16) return 5;
else if (asu >= 8) return 4;
else if (asu >= 4) return 3;
else if (asu >= 2) return 2;
else if (asu >= 1) return 1;
else return 0;
}
/**
* Convert the cdma / evdo db levels to appropriate icon level.
* The scale is similar to the one used in status bar policy.
*
* @param signalStrength
* @return the icon level
*/
private int cdmaDbmEcioToSignal(SignalStrength signalStrength) {
int levelDbm = 0;
int levelEcio = 0;
int cdmaIconLevel = 0;
int evdoIconLevel = 0;
int cdmaDbm = signalStrength.getCdmaDbm();
int cdmaEcio = signalStrength.getCdmaEcio();
if (cdmaDbm >= -75) levelDbm = 4;
else if (cdmaDbm >= -85) levelDbm = 3;
else if (cdmaDbm >= -95) levelDbm = 2;
else if (cdmaDbm >= -100) levelDbm = 1;
else levelDbm = 0;
// Ec/Io are in dB*10
if (cdmaEcio >= -90) levelEcio = 4;
else if (cdmaEcio >= -110) levelEcio = 3;
else if (cdmaEcio >= -130) levelEcio = 2;
else if (cdmaEcio >= -150) levelEcio = 1;
else levelEcio = 0;
cdmaIconLevel = (levelDbm < levelEcio) ? levelDbm : levelEcio;
// STOPSHIP: Change back to getRilVoiceRadioTechnology
if (mServiceState != null &&
(mServiceState.getRadioTechnology() ==
ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_0 ||
mServiceState.getRadioTechnology() ==
ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_A)) {
int evdoEcio = signalStrength.getEvdoEcio();
int evdoSnr = signalStrength.getEvdoSnr();
int levelEvdoEcio = 0;
int levelEvdoSnr = 0;
// Ec/Io are in dB*10
if (evdoEcio >= -650) levelEvdoEcio = 4;
else if (evdoEcio >= -750) levelEvdoEcio = 3;
else if (evdoEcio >= -900) levelEvdoEcio = 2;
else if (evdoEcio >= -1050) levelEvdoEcio = 1;
else levelEvdoEcio = 0;
if (evdoSnr > 7) levelEvdoSnr = 4;
else if (evdoSnr > 5) levelEvdoSnr = 3;
else if (evdoSnr > 3) levelEvdoSnr = 2;
else if (evdoSnr > 1) levelEvdoSnr = 1;
else levelEvdoSnr = 0;
evdoIconLevel = (levelEvdoEcio < levelEvdoSnr) ? levelEvdoEcio : levelEvdoSnr;
}
// TODO(): There is a bug open regarding what should be sent.
return (cdmaIconLevel > evdoIconLevel) ? cdmaIconLevel : evdoIconLevel;
}
};
}
class HeadsetDeviceState {
int mService;
int mRoam;
int mSignal;
int mBatteryCharge;
HeadsetDeviceState(int service, int roam, int signal, int batteryCharge) {
mService = service;
mRoam = roam;
mSignal = signal;
mBatteryCharge = batteryCharge;
}
}
class HeadsetCallState {
int mNumActive;
int mNumHeld;
int mCallState;
String mNumber;
int mType;
public HeadsetCallState(int numActive, int numHeld, int callState, String number, int type) {
mNumActive = numActive;
mNumHeld = numHeld;
mCallState = callState;
mNumber = number;
mType = type;
}
}
class HeadsetClccResponse {
int mIndex;
int mDirection;
int mStatus;
int mMode;
boolean mMpty;
String mNumber;
int mType;
public HeadsetClccResponse(int index, int direction, int status, int mode, boolean mpty,
String number, int type) {
mIndex = index;
mDirection = direction;
mStatus = status;
mMode = mode;
mMpty = mpty;
mNumber = number;
mType = type;
}
}
class HeadsetVendorSpecificResultCode {
String mCommand;
String mArg;
public HeadsetVendorSpecificResultCode(String command, String arg) {
mCommand = command;
mArg = arg;
}
}
| false | false | null | null |
diff --git a/ui/GUIAbout.java b/ui/GUIAbout.java
index 46f2de9..3982be3 100755
--- a/ui/GUIAbout.java
+++ b/ui/GUIAbout.java
@@ -1,263 +1,263 @@
/* GUIAbout.java
*
* This class draws a simple animation for EduMips64 credits.
* (c) 2006 EduMIPS64 project - Rizzo Vanni G.
*
* This file is part of the EduMIPS64 project, and is released under the GNU
* General Public License.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edumips64.ui;
import edumips64.img.*;
import java.net.URL;
import java.awt.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.AffineTransform;
/**
* This class draws the "about us" animation.
*/
public class GUIAbout extends JDialog implements Runnable {
int x=0,y=0, clock;
Thread animazione;
Display lavagna;
boolean running;
boolean click = true;
Container cp;
protected static Image logo;
static String members[] =
{
- "EduMips64 Project",
+ "EduMIPS64 Project",
"http://www.edumips.org",
"MIPS64 Instruction set simulator",
" ",
"Developers:", " ",
"Andrea Spadaccini",
"[email protected]",
"Project Leader - Mantainer",
"Antonella Scandura",
"[email protected]",
"Main GUI - Documentation",
"Salvatore Scellato",
"[email protected]",
"CPU - Core classes",
"Simona Ullo",
"[email protected]",
"CPU - Documentation",
"Vanni Rizzo",
"[email protected]",
"Art Director - Parser",
"Andrea Milazzo",
"[email protected]",
"Wiki admin - Parser - Bug Hunter",
"Massimo Trubia",
"[email protected]",
"Instruction set",
"Daniele Russo",
"[email protected]",
"Instruction set",
"Mirko Musumeci",
"[email protected]",
"GUI Widgets",
"Alessandro Nicolosi",
"[email protected]",
"GUI Widgets",
"Filippo Mondello (Timmy)",
"[email protected]",
"GUI Widgets",
"Giorgio Scibilia",
"[email protected]",
"MIPS32 Instruction set",
"Lorenzo Sciuto",
"[email protected]",
"MIPS32 Instruction set",
"Erik Urzi'",
"[email protected]",
"MIPS32 Instruction set",
" ","Special thanks to: "," ",
"Fabrizio Fazzino",
"[email protected]",
"The Professor"
};
int width=500,height=400;
public GUIAbout(final JFrame owner){
super(owner,"Credits", true);
try{
//MediaTracker mt = new MediaTracker();
logo = IMGLoader.getImage("logo.png");
//mt.addImage(logo,0);
//mt.waitForAll();
}catch(Exception ex){
ex.printStackTrace();
}
//owner.setEnabled(false);
//MediaTracker mt = new MediaTracker(this);
lavagna = new Display(width,height);
getGlassPane().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setVisible(false);
running = false;
//owner.setEnabled(true);
//dispose();
}
});
//setLocation((int)(owner.getSize().getWidth() - width)/2,(int)(owner.getSize().getHeight() - height)/2);
setSize(width,height);
setLocation((getScreenWidth() - getWidth()) / 2, (getScreenHeight() - getHeight()) / 2);
getContentPane().add(lavagna);
//getGlassPane().setVisible(true);
//setAlwaysOnTop(true);
x = 0; y = 10;
running = true;
// setVisible(true);
repaint();
start();
}
public static int getScreenWidth() {
return (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
}
public static int getScreenHeight() {
return (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
}
public void start() {
if (animazione == null) {
animazione = new Thread(this);
animazione.start();
}
}
/**Here start the animation. Setting location for the text. A infinite cycle decrement only the y value and wait for 40ms
*/
public void run() {
x = 120;
y = 300;
while(running) {
if(y<-1100) y = 300; //when the text finish reset y value
y -= 2; //decrementing y
lavagna.repaint();
try { Thread.sleep(40);}
catch (InterruptedException e) { }
}
}
/*In this class there is the Panel that draws the animation.
*/
class Display extends JPanel{
int width,height,head,xg = 0,yg = 0;
Graphics2D G;
BufferedImage I;
Font font_name = new Font("Verdana",Font.BOLD, 20);
Font font_email = new Font("Verdana",Font.ITALIC + Font.BOLD, 15);
Font font_role = new Font("Verdana",Font.BOLD, 13);
GradientPaint gradient;
boolean bigger;
/* The Contructor of the Panel.
* w is the Panel Wiidth, y the Height
*/
public Display(int w,int h){
setBackground(Color.yellow);
setBounds(0,0,w,h);
width = w;
height = h;
xg=width;
I = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); //this is a Buff.Image that give a temp graphics
G = (Graphics2D) I.getGraphics();
head = 98;//logo.getHeight(this);
gradient = new GradientPaint(width/4, height/4, Color.white, width, height, Color.yellow);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
//setting the Rendering Hints to Antialias
G.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//G.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
//sfondo
G.setPaint(gradient);
G.fillRect(0,0,width,height);
//logo image
G.drawImage(logo,new AffineTransform(1,0,0,1,50,0),this);
//HEAD: the width value of the logo image. I use it to know when the text must disappear
G.setColor(new Color(0,0,0));
G.setFont(new Font("Verdana",Font.BOLD, 15));
G.drawString("Version " + edumips64.Main.VERSION + " (" + edumips64.Main.CODENAME + ")",150,92);
head = logo.getHeight(this);
G.setTransform(new AffineTransform(1,0,0,1,0,0));
//inizio stringhe
int alpha,line;
for(int i= 0 ; i < members.length; i++){
//incrementing the line value for printing (and increment i too) and getting the alpha value to use
line = y + i * 25 + head;
alpha = getAlpha(line);
G.setColor(new Color(0,0,0,alpha));
//selecting only the visible text
if(alpha > 0){
//NAME drawing it whith his colour and font
G.setFont(font_name);
G.drawString(members[i] ,x, line);
//incrementing the line value for printing (and increment i too)
line = y + ++i * 25 + head;
//EMAIL
G.setFont(font_email);
G.drawString(members[i],x,line -5);
//incrementing the line value for printing (and increment i too)
line = y + ++i * 25 + head;
//ROLE
G.setFont(font_role);
G.drawString(members[i],x,line -10);
}else i +=2;
}
//per evitare lo sfarfallio applico la grafica appena creata in quella del paint
Graphics2D g2=(Graphics2D)g;
g2.drawImage(I,0,0,null);
}
/** Give the Alpha transparency value knowing the line to draw
* @return (int) the alpha value for the selected line
*/
public int getAlpha(int line){
//border is the value of the height of you wrap of passage from visible to transparent
int border=100;
return (line <= head || line >= height)? // we are out of border?
0 // nothing to draw
: (line> head && line <=border + head)? // else, under text but over the upper border?
(int)((line -head)*255/border) // the transparency depends of the posizion
: (line>=height-border && line<height) ? // on the down border?
(int)((height-line) * 255 / border) // the transparency depends of the posizion
:255; // in the borders: the text must be visible
}
}
}
| true | false | null | null |
diff --git a/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java b/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java
index 72c03e1e..c0d81cbe 100644
--- a/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java
+++ b/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java
@@ -1,45 +1,57 @@
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.test.bpmn.mail;
import org.activiti.engine.impl.test.PluggableActivitiTestCase;
import org.subethamail.wiser.Wiser;
/**
* @author Joram Barrez
*/
public class EmailTestCase extends PluggableActivitiTestCase {
- protected Wiser wiser;
+ protected Wiser wiser;
@Override
protected void setUp() throws Exception {
super.setUp();
- wiser = new Wiser();
- wiser.setPort(5025);
- wiser.start();
+
+ boolean serverUpAndRunning = false;
+ while (!serverUpAndRunning) {
+ wiser = new Wiser();
+ wiser.setPort(5025);
+
+ try {
+ wiser.start();
+ serverUpAndRunning = true;
+ } catch (RuntimeException e) { // Fix for slow port-closing Jenkins
+ if (e.getMessage().toLowerCase().contains("BindException")) {
+ Thread.sleep(250L);
+ }
+ }
+ }
}
@Override
protected void tearDown() throws Exception {
wiser.stop();
// Fix for slow Jenkins
Thread.sleep(250L);
super.tearDown();
}
}
| false | false | null | null |
diff --git a/src/net/m_kawato/tabletpos/Order.java b/src/net/m_kawato/tabletpos/Order.java
index c02ebe9..4645cf7 100644
--- a/src/net/m_kawato/tabletpos/Order.java
+++ b/src/net/m_kawato/tabletpos/Order.java
@@ -1,164 +1,163 @@
package net.m_kawato.tabletpos;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class Order extends Activity implements View.OnClickListener, AdapterView.OnItemSelectedListener, TextView.OnEditorActionListener {
private static final String TAG = "Order";
private Globals globals;
private List<Product> productsInCategory; // products in the selected category
private int selectedPosition;
private ProductListAdapter productListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
globals = (Globals) this.getApplication();
this.productsInCategory = new ArrayList<Product>();
Log.d(TAG, "onCreate: products.size() = " + globals.products.size());
OrderInputHelper orderInputHelper = new OrderInputHelper(this, globals);
// Build ListView for products
this.productListAdapter = new ProductListAdapter(this, this.productsInCategory, this);
ListView productListView = (ListView) findViewById(R.id.list);
LayoutInflater inflater = this.getLayoutInflater();
View header = inflater.inflate(R.layout.order_header, null);
View footer = inflater.inflate(R.layout.order_footer, null);
productListView.addHeaderView(header);
productListView.addFooterView(footer);
productListView.setAdapter(this.productListAdapter);
// Loading sheet number
EditText loadingSheetNumberView = (EditText) findViewById(R.id.loading_sheet_number);
loadingSheetNumberView.setText(globals.loadingSheetNumber);
loadingSheetNumberView.setOnEditorActionListener(this);
Button btnEnter = (Button) findViewById(R.id.btn_enter);
btnEnter.setOnClickListener(this);
// Spinner for route selection
orderInputHelper.buildRouteSelector();
// Spinner for place selection
orderInputHelper.buildPlaceSelector();
// Spinner for category selection
ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
for(String category: globals.categories) {
categoryAdapter.add(category);
}
Spinner spnCategory = (Spinner) findViewById(R.id.spn_category);
spnCategory.setAdapter(categoryAdapter);
spnCategory.setOnItemSelectedListener(this);
// "Confirm" button
Button btnConfirm = (Button) findViewById(R.id.btn_confirm);
btnConfirm.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.order, menu);
return true;
}
// Event handler for TextEdit
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.d(TAG, "onEditorAction: actionId=" + actionId);
if (actionId == EditorInfo.IME_ACTION_GO) {
updateLoadingSheetNumber();
}
return true;
}
// Event handler for spinners
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, String.format("onItemSelected: id=%x, position=%d", parent.getId(), position));
switch (parent.getId()) {
case R.id.spn_category:
changeCategory(globals.categories.get(position));
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d(TAG, "onNothingSelected");
}
// Event handler for "Confirm" button
@Override
public void onClick(View v) {
Intent i;
switch (v.getId()) {
case R.id.btn_enter:
updateLoadingSheetNumber();
break;
case R.id.btn_confirm:
i = new Intent(this, Confirm.class);
startActivity(i);
break;
case R.id.order_checked:
int position = (Integer) v.getTag();
boolean checked = ((CheckBox) v).isChecked();
Log.d(TAG, String.format("onClick: order_checked position=%d, checked=%b", position, checked));
Product p = this.productsInCategory.get(position);
if (checked) {
p.orderItem = new OrderItem(this, this.productsInCategory.get(position), 0);
} else {
p.orderItem = null;
}
break;
}
}
// Update loading sheet number
private void updateLoadingSheetNumber() {
Log.d(TAG, "updateLoadingSheetNumber");
EditText loadingSheetNumberView = (EditText) findViewById(R.id.loading_sheet_number);
String loadingSheetNumber = loadingSheetNumberView.getText().toString();
if (loadingSheetNumber.equals("")) {
return;
}
globals.setLoadingSheetNumber(loadingSheetNumber);
}
// Change selected category of products
private void changeCategory(String category) {
Log.d(TAG, String.format("changeCategory: %s", category));
this.productsInCategory.clear();
for(Product product: globals.products) {
- if (! product.category.equals(category)) {
- continue;
+ if (product.category.equals(category) && product.loaded) {
+ this.productsInCategory.add(product);
}
- this.productsInCategory.add(product);
}
this.productListAdapter.notifyDataSetChanged();
}
}
| false | false | null | null |
diff --git a/org.emftext.sdk.ui/src/org/emftext/sdk/ui/actions/GenerateResourceAction.java b/org.emftext.sdk.ui/src/org/emftext/sdk/ui/actions/GenerateResourceAction.java
index 82bf252bc..18bb2bfd9 100644
--- a/org.emftext.sdk.ui/src/org/emftext/sdk/ui/actions/GenerateResourceAction.java
+++ b/org.emftext.sdk.ui/src/org/emftext/sdk/ui/actions/GenerateResourceAction.java
@@ -1,366 +1,366 @@
package org.emftext.sdk.ui.actions;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.emf.codegen.ecore.generator.Generator;
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
import org.eclipse.emf.codegen.ecore.genmodel.generator.GenBaseGeneratorAdapter;
import org.eclipse.emf.common.util.BasicMonitor;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.emftext.runtime.ui.MarkerHelper;
import org.emftext.sdk.codegen.ICodeGenOptions;
import org.emftext.sdk.codegen.ManifestGenerator;
import org.emftext.sdk.codegen.OptionManager;
import org.emftext.sdk.codegen.PluginXMLGenerator;
import org.emftext.sdk.codegen.PutEverywhereSyntaxExtender;
import org.emftext.sdk.codegen.ResourcePackage;
import org.emftext.sdk.codegen.ResourcePackageGenerator;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
import org.emftext.sdk.concretesyntax.Import;
/**
* An action that calls the generator and in addition generates a
* <code><plugin.xml</code> and <code>MANIFEST.MF</code> file.
*
* @author jj2
*
*/
public class GenerateResourceAction extends AbstractConcreteSyntaxAction
implements IObjectActionDelegate {
// these must add up to 100
protected static final int TICKS_CREATE_PROJECT = 2;
protected static final int TICKS_OPEN_PROJECT = 2;
protected static final int TICKS_SET_CLASSPATH = 2;
protected static final int TICKS_CREATE_META_FOLDER = 2;
protected static final int TICKS_CREATE_MANIFEST = 2;
protected static final int TICKS_CREATE_PLUGIN_XML = 2;
protected static final int TICKS_CREATE_MODELS_FOLDER = 2;
protected static final int TICKS_GENERATE_RESOURCE = 26;
protected static final int TICKS_GENERATE_METAMODEL_CODE = 40;
protected static final int TICKS_REFRESH_PROJECT = 20;
private ISelection selection;
/**
* Calls {@link #process(IFile)} for all selected <i>cs</i> files .
*/
public void run(IAction action) {
if (selection instanceof IStructuredSelection) {
for (Iterator<?> i = ((IStructuredSelection) selection).iterator(); i
.hasNext();) {
Object o = i.next();
if (o instanceof IFile) {
IFile file = (IFile) o;
if (file.getFileExtension().startsWith("cs")) {
process(file);
}
}
}
}
}
/**
* Creates a new Java project in the Workspace and calls the generators,
*
* @param file
* The file that contains the concrete syntax definition.
*/
public void process(final IFile file) {
try {
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
try {
SubMonitor progress = SubMonitor.convert(monitor, 100);
Resource csResource = getResource(file);
MarkerHelper.unmark(csResource);
if (containsProblems(csResource)) {
MarkerHelper.mark(csResource);
return;
}
final ConcreteSyntax concreteSyntax = (ConcreteSyntax) csResource
.getContents().get(0);
new PutEverywhereSyntaxExtender().generatePutEverywhereExtensions(concreteSyntax);
final String csPackageName = getPackageName(concreteSyntax);
final String projectName = csPackageName;
if (projectName == null) {
return;
}
// create a project
IProject project = createProject(progress, projectName);
// generate the resource class, parser, and printer
ResourcePackage pck = new ResourcePackage(
concreteSyntax, csPackageName,
getSrcFolder(project));
ResourcePackageGenerator.generate(pck, progress
.newChild(TICKS_GENERATE_RESOURCE));
// errors from parser generator?
if (containsProblems(csResource)) {
MarkerHelper.mark(csResource);
}
createMetaFolder(progress, project);
createManifest(progress, concreteSyntax, projectName, project, pck);
createPluginXML(progress, concreteSyntax, projectName, project, file);
markErrors(concreteSyntax);
createMetaModelCode(progress, concreteSyntax);
project.refreshLocal(IProject.DEPTH_INFINITE, progress
.newChild(TICKS_REFRESH_PROJECT));
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
private String getPackageName(final ConcreteSyntax cSyntax) {
return (cSyntax.getPackage().getBasePackage() == null ? ""
: cSyntax.getPackage().getBasePackage() + ".")
+ cSyntax.getPackage().getEcorePackage().getName()
+ ".resource." + cSyntax.getName();
}
};
PlatformUI.getWorkbench().getProgressService().busyCursorWhile(
runnable);
} catch (InvocationTargetException e) {
e.getTargetException().printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void generateMetaModelCode(GenPackage genPackage,
IProgressMonitor monitor) {
monitor.setTaskName("generating metamodel code...");
GenModel genModel = genPackage.getGenModel();
genModel.setCanGenerate(true);
// generate the code
Generator generator = new Generator();
generator.setInput(genModel);
generator.generate(genModel,
GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE,
new BasicMonitor.EclipseSubProgress(monitor, 100));
}
private IProject createProject(SubMonitor progress, String projectName)
throws CoreException, JavaModelException {
IJavaProject javaProject = createJavaProject(progress, projectName);
IProject project = javaProject.getProject();
setClasspath(javaProject, progress);
return project;
}
private void createMetaModelCode(SubMonitor progress,
final ConcreteSyntax cSyntax) {
// do not generate code for genmodels imported from deployed plugins
if (cSyntax.getPackage().eResource().getURI().segments()[0].equals("plugin")) {
return;
}
// call EMF code generator if specified
if (OptionManager.INSTANCE.getBooleanOption(cSyntax, ICodeGenOptions.GENERATE_CODE_FROM_GENERATOR_MODEL)) {
generateMetaModelCode(cSyntax.getPackage(), progress
.newChild(TICKS_GENERATE_METAMODEL_CODE));
} else {
progress.internalWorked(TICKS_GENERATE_METAMODEL_CODE);
}
}
private IJavaProject createJavaProject(SubMonitor progress,
String projectName) throws CoreException, JavaModelException {
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(
projectName);
if (!project.exists()) {
project.create(progress.newChild(TICKS_CREATE_PROJECT));
} else {
progress.internalWorked(TICKS_CREATE_PROJECT);
}
project.open(progress.newChild(TICKS_OPEN_PROJECT));
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { JavaCore.NATURE_ID,
"org.eclipse.pde.PluginNature" });
ICommand command1 = description.newCommand();
command1.setBuilderName("org.eclipse.jdt.core.javabuilder");
ICommand command2 = description.newCommand();
command2.setBuilderName("org.eclipse.pde.ManifestBuilder");
ICommand command3 = description.newCommand();
command3.setBuilderName("org.eclipse.pde.SchemaBuilder");
description
.setBuildSpec(new ICommand[] { command1, command2, command3 });
project.setDescription(description, null);
IJavaProject javaProject = JavaCore.create(project);
return javaProject;
}
private IFolder getSrcFolder(IProject project) {
return project.getFolder("/src");
}
private IFolder getOutFolder(IProject project) {
return project.getFolder("/bin");
}
private void setClasspath(IJavaProject javaProject, SubMonitor progress)
throws JavaModelException {
IFolder srcFolder = getSrcFolder(javaProject.getProject());
IFolder outFolder = getOutFolder(javaProject.getProject());
javaProject.setRawClasspath(new IClasspathEntry[] {
JavaCore.newSourceEntry(srcFolder.getFullPath()),
- JavaRuntime.getJREVariableEntry(),
+ JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)),
JavaCore.newContainerEntry(new Path(
"org.eclipse.pde.core.requiredPlugins")) }, outFolder
.getFullPath(), progress.newChild(TICKS_SET_CLASSPATH));
}
private void createMetaFolder(SubMonitor progress, IProject project)
throws CoreException {
IFolder metaFolder = project.getFolder("/META-INF");
if (!metaFolder.exists()) {
metaFolder.create(true, true, progress
.newChild(TICKS_CREATE_META_FOLDER));
} else {
progress.internalWorked(TICKS_CREATE_META_FOLDER);
}
}
private void createManifest(SubMonitor progress,
final ConcreteSyntax cSyntax, String projectName,
IProject project,
ResourcePackage resourcePackage) throws CoreException {
boolean overrideManifest = OptionManager.INSTANCE.getBooleanOption(cSyntax, ICodeGenOptions.OVERRIDE_MANIFEST);
IFile manifestMFFile = project.getFile("/META-INF/MANIFEST.MF");
if (manifestMFFile.exists()) {
if (overrideManifest) {
ManifestGenerator mGenerator = new ManifestGenerator(cSyntax, projectName, resourcePackage, isGenerateTestActionEnabled(cSyntax));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mGenerator.generate(new PrintWriter(outputStream));
manifestMFFile.setContents(new ByteArrayInputStream(
outputStream.toByteArray()), true, true,
progress.newChild(TICKS_CREATE_MANIFEST));
} else {
progress.internalWorked(TICKS_CREATE_MANIFEST);
}
} else {
ManifestGenerator mGenerator = new ManifestGenerator(cSyntax, projectName, resourcePackage, isGenerateTestActionEnabled(cSyntax));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mGenerator.generate(new PrintWriter(outputStream));
manifestMFFile.create(new ByteArrayInputStream(outputStream.toByteArray()), true,
progress.newChild(TICKS_CREATE_MANIFEST));
}
}
private void createPluginXML(SubMonitor progress,
final ConcreteSyntax cSyntax, String projectName,
IProject project, IFile file)
throws CoreException {
boolean overridePluginXML = OptionManager.INSTANCE.getBooleanOption(cSyntax, ICodeGenOptions.OVERRIDE_PLUGIN_XML);
IFile pluginXMLFile = project.getFile("/plugin.xml");
if (pluginXMLFile.exists()) {
if (overridePluginXML) {
PluginXMLGenerator pluginXMLGenerator = new PluginXMLGenerator(
cSyntax, projectName, file,
isGenerateTestActionEnabled(cSyntax)
);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
pluginXMLGenerator.generate(new PrintWriter(outputStream));
pluginXMLFile.setContents(new ByteArrayInputStream(
outputStream.toByteArray()), true, true, progress
.newChild(TICKS_CREATE_PLUGIN_XML));
} else {
progress.internalWorked(TICKS_CREATE_PLUGIN_XML);
}
} else {
PluginXMLGenerator pluginXMLGenerator = new PluginXMLGenerator(
cSyntax, projectName, file,
isGenerateTestActionEnabled(cSyntax)
);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
pluginXMLGenerator.generate(new PrintWriter(outputStream));
pluginXMLFile.create(new ByteArrayInputStream(outputStream.toByteArray()), true, progress
.newChild(TICKS_CREATE_PLUGIN_XML));
}
}
private boolean isGenerateTestActionEnabled(ConcreteSyntax syntax) {
return OptionManager.INSTANCE.getBooleanOption(syntax, ICodeGenOptions.GENERATE_TEST_ACTION);
}
private void markErrors(final ConcreteSyntax cSyntax) throws CoreException {
// also mark errors on imported concrete syntaxes
for (Import aImport : cSyntax.getImports()) {
ConcreteSyntax importedCS = aImport.getConcreteSyntax();
if (importedCS != null) {
MarkerHelper.unmark(importedCS.eResource());
MarkerHelper.mark(aImport.eResource());
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
* .IAction, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.
* action.IAction, org.eclipse.ui.IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
// this.part = targetPart;
}
}
| true | false | null | null |
diff --git a/test/sun/misc/Version/Version.java b/test/sun/misc/Version/Version.java
index 6e7d3626d..16ecd1ea9 100644
--- a/test/sun/misc/Version/Version.java
+++ b/test/sun/misc/Version/Version.java
@@ -1,156 +1,162 @@
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 6994413
* @summary Check the JDK and JVM version returned by sun.misc.Version
* matches the versions defined in the system properties
* @compile -XDignore.symbol.file Version.java
* @run main Version
*/
import static sun.misc.Version.*;
public class Version {
public static void main(String[] args) throws Exception {
VersionInfo jdk = newVersionInfo(System.getProperty("java.runtime.version"));
VersionInfo v1 = new VersionInfo(jdkMajorVersion(),
jdkMinorVersion(),
jdkMicroVersion(),
jdkUpdateVersion(),
jdkSpecialVersion(),
jdkBuildNumber());
System.out.println("JDK version = " + jdk + " " + v1);
if (!jdk.equals(v1)) {
throw new RuntimeException("Unmatched version: " + jdk + " vs " + v1);
}
VersionInfo jvm = newVersionInfo(System.getProperty("java.vm.version"));
VersionInfo v2 = new VersionInfo(jvmMajorVersion(),
jvmMinorVersion(),
jvmMicroVersion(),
jvmUpdateVersion(),
jvmSpecialVersion(),
jvmBuildNumber());
System.out.println("JVM version = " + jvm + " " + v2);
if (!jvm.equals(v2)) {
throw new RuntimeException("Unmatched version: " + jvm + " vs " + v2);
}
}
static class VersionInfo {
final int major;
final int minor;
final int micro;
final int update;
final String special;
final int build;
VersionInfo(int major, int minor, int micro,
int update, String special, int build) {
this.major = major;
this.minor = minor;
this.micro = micro;
this.update = update;
this.special = special;
this.build = build;
}
public boolean equals(VersionInfo v) {
return (this.major == v.major && this.minor == v.minor &&
this.micro == v.micro && this.update == v.update &&
this.special.equals(v.special) && this.build == v.build);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(major + "." + minor + "." + micro);
if (update > 0) {
sb.append("_" + update);
}
if (!special.isEmpty()) {
sb.append(special);
}
sb.append("-b" + build);
return sb.toString();
}
}
private static VersionInfo newVersionInfo(String version) throws Exception {
// valid format of the version string is:
// n.n.n[_uu[c]][-<identifer>]-bxx
int major = 0;
int minor = 0;
int micro = 0;
int update = 0;
String special = "";
int build = 0;
CharSequence cs = version;
if (cs.length() >= 5) {
if (Character.isDigit(cs.charAt(0)) && cs.charAt(1) == '.' &&
Character.isDigit(cs.charAt(2)) && cs.charAt(3) == '.' &&
Character.isDigit(cs.charAt(4))) {
major = Character.digit(cs.charAt(0), 10);
minor = Character.digit(cs.charAt(2), 10);
micro = Character.digit(cs.charAt(4), 10);
cs = cs.subSequence(5, cs.length());
} else if (Character.isDigit(cs.charAt(0)) &&
Character.isDigit(cs.charAt(1)) && cs.charAt(2) == '.' &&
Character.isDigit(cs.charAt(3))) {
// HSX has nn.n (major.minor) version
major = Integer.valueOf(version.substring(0, 2)).intValue();
minor = Character.digit(cs.charAt(3), 10);
cs = cs.subSequence(4, cs.length());
}
if (cs.charAt(0) == '_' && cs.length() >= 3 &&
Character.isDigit(cs.charAt(1)) &&
Character.isDigit(cs.charAt(2))) {
int nextChar = 3;
String uu = cs.subSequence(1, 3).toString();
update = Integer.valueOf(uu).intValue();
if (cs.length() >= 4) {
char c = cs.charAt(3);
if (c >= 'a' && c <= 'z') {
special = Character.toString(c);
nextChar++;
}
}
cs = cs.subSequence(nextChar, cs.length());
}
if (cs.charAt(0) == '-') {
// skip the first character
// valid format: <identifier>-bxx or bxx
// non-product VM will have -debug|-release appended
cs = cs.subSequence(1, cs.length());
String[] res = cs.toString().split("-");
- for (String s : res) {
+ for (int i = res.length - 1; i >= 0; i--) {
+ String s = res[i];
if (s.charAt(0) == 'b') {
- build =
- Integer.valueOf(s.substring(1, s.length())).intValue();
- break;
+ try {
+ build = Integer.parseInt(s.substring(1, s.length()));
+ break;
+ } catch (NumberFormatException nfe) {
+ // ignore
+ }
}
}
}
}
- return new VersionInfo(major, minor, micro, update, special, build);
+ VersionInfo vi = new VersionInfo(major, minor, micro, update, special, build);
+ System.out.printf("newVersionInfo: input=%s output=%s\n", version, vi);
+ return vi;
}
}
| false | true | private static VersionInfo newVersionInfo(String version) throws Exception {
// valid format of the version string is:
// n.n.n[_uu[c]][-<identifer>]-bxx
int major = 0;
int minor = 0;
int micro = 0;
int update = 0;
String special = "";
int build = 0;
CharSequence cs = version;
if (cs.length() >= 5) {
if (Character.isDigit(cs.charAt(0)) && cs.charAt(1) == '.' &&
Character.isDigit(cs.charAt(2)) && cs.charAt(3) == '.' &&
Character.isDigit(cs.charAt(4))) {
major = Character.digit(cs.charAt(0), 10);
minor = Character.digit(cs.charAt(2), 10);
micro = Character.digit(cs.charAt(4), 10);
cs = cs.subSequence(5, cs.length());
} else if (Character.isDigit(cs.charAt(0)) &&
Character.isDigit(cs.charAt(1)) && cs.charAt(2) == '.' &&
Character.isDigit(cs.charAt(3))) {
// HSX has nn.n (major.minor) version
major = Integer.valueOf(version.substring(0, 2)).intValue();
minor = Character.digit(cs.charAt(3), 10);
cs = cs.subSequence(4, cs.length());
}
if (cs.charAt(0) == '_' && cs.length() >= 3 &&
Character.isDigit(cs.charAt(1)) &&
Character.isDigit(cs.charAt(2))) {
int nextChar = 3;
String uu = cs.subSequence(1, 3).toString();
update = Integer.valueOf(uu).intValue();
if (cs.length() >= 4) {
char c = cs.charAt(3);
if (c >= 'a' && c <= 'z') {
special = Character.toString(c);
nextChar++;
}
}
cs = cs.subSequence(nextChar, cs.length());
}
if (cs.charAt(0) == '-') {
// skip the first character
// valid format: <identifier>-bxx or bxx
// non-product VM will have -debug|-release appended
cs = cs.subSequence(1, cs.length());
String[] res = cs.toString().split("-");
for (String s : res) {
if (s.charAt(0) == 'b') {
build =
Integer.valueOf(s.substring(1, s.length())).intValue();
break;
}
}
}
}
return new VersionInfo(major, minor, micro, update, special, build);
}
| private static VersionInfo newVersionInfo(String version) throws Exception {
// valid format of the version string is:
// n.n.n[_uu[c]][-<identifer>]-bxx
int major = 0;
int minor = 0;
int micro = 0;
int update = 0;
String special = "";
int build = 0;
CharSequence cs = version;
if (cs.length() >= 5) {
if (Character.isDigit(cs.charAt(0)) && cs.charAt(1) == '.' &&
Character.isDigit(cs.charAt(2)) && cs.charAt(3) == '.' &&
Character.isDigit(cs.charAt(4))) {
major = Character.digit(cs.charAt(0), 10);
minor = Character.digit(cs.charAt(2), 10);
micro = Character.digit(cs.charAt(4), 10);
cs = cs.subSequence(5, cs.length());
} else if (Character.isDigit(cs.charAt(0)) &&
Character.isDigit(cs.charAt(1)) && cs.charAt(2) == '.' &&
Character.isDigit(cs.charAt(3))) {
// HSX has nn.n (major.minor) version
major = Integer.valueOf(version.substring(0, 2)).intValue();
minor = Character.digit(cs.charAt(3), 10);
cs = cs.subSequence(4, cs.length());
}
if (cs.charAt(0) == '_' && cs.length() >= 3 &&
Character.isDigit(cs.charAt(1)) &&
Character.isDigit(cs.charAt(2))) {
int nextChar = 3;
String uu = cs.subSequence(1, 3).toString();
update = Integer.valueOf(uu).intValue();
if (cs.length() >= 4) {
char c = cs.charAt(3);
if (c >= 'a' && c <= 'z') {
special = Character.toString(c);
nextChar++;
}
}
cs = cs.subSequence(nextChar, cs.length());
}
if (cs.charAt(0) == '-') {
// skip the first character
// valid format: <identifier>-bxx or bxx
// non-product VM will have -debug|-release appended
cs = cs.subSequence(1, cs.length());
String[] res = cs.toString().split("-");
for (int i = res.length - 1; i >= 0; i--) {
String s = res[i];
if (s.charAt(0) == 'b') {
try {
build = Integer.parseInt(s.substring(1, s.length()));
break;
} catch (NumberFormatException nfe) {
// ignore
}
}
}
}
}
VersionInfo vi = new VersionInfo(major, minor, micro, update, special, build);
System.out.printf("newVersionInfo: input=%s output=%s\n", version, vi);
return vi;
}
|
diff --git a/src/edu/cmu/cs/diamond/wholeslide/gui/Demo.java b/src/edu/cmu/cs/diamond/wholeslide/gui/Demo.java
index e3c6387..00cf0a1 100644
--- a/src/edu/cmu/cs/diamond/wholeslide/gui/Demo.java
+++ b/src/edu/cmu/cs/diamond/wholeslide/gui/Demo.java
@@ -1,67 +1,67 @@
package edu.cmu.cs.diamond.wholeslide.gui;
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import edu.cmu.cs.diamond.wholeslide.Wholeslide;
public class Demo {
public static void main(String[] args) {
- JFrame jf = new JFrame("zzz");
+ JFrame jf = new JFrame("Wholeslide");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
switch (args.length) {
case 0:
- System.out.println("oops");
+ System.out.println("Give 1 or 2 files");
return;
case 1:
WholeslideView wv = new WholeslideView(new Wholeslide(new File(args[0])));
wv.setBorder(BorderFactory.createTitledBorder(args[0]));
jf.getContentPane().add(wv);
break;
case 2:
final WholeslideView w1 = new WholeslideView(new Wholeslide(
new File(args[0])));
final WholeslideView w2 = new WholeslideView(new Wholeslide(
new File(args[1])));
Box b = Box.createHorizontalBox();
b.add(w1);
b.add(w2);
jf.getContentPane().add(b);
JToggleButton linker = new JToggleButton("Link");
jf.getContentPane().add(linker, BorderLayout.SOUTH);
linker.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
switch(e.getStateChange()) {
case ItemEvent.SELECTED:
w1.linkWithOther(w2);
break;
case ItemEvent.DESELECTED:
w1.unlinkOther();
break;
}
}
});
break;
default:
return;
}
- jf.setSize(800, 600);
+ jf.setSize(900, 700);
jf.setVisible(true);
}
}
| false | true | public static void main(String[] args) {
JFrame jf = new JFrame("zzz");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
switch (args.length) {
case 0:
System.out.println("oops");
return;
case 1:
WholeslideView wv = new WholeslideView(new Wholeslide(new File(args[0])));
wv.setBorder(BorderFactory.createTitledBorder(args[0]));
jf.getContentPane().add(wv);
break;
case 2:
final WholeslideView w1 = new WholeslideView(new Wholeslide(
new File(args[0])));
final WholeslideView w2 = new WholeslideView(new Wholeslide(
new File(args[1])));
Box b = Box.createHorizontalBox();
b.add(w1);
b.add(w2);
jf.getContentPane().add(b);
JToggleButton linker = new JToggleButton("Link");
jf.getContentPane().add(linker, BorderLayout.SOUTH);
linker.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
switch(e.getStateChange()) {
case ItemEvent.SELECTED:
w1.linkWithOther(w2);
break;
case ItemEvent.DESELECTED:
w1.unlinkOther();
break;
}
}
});
break;
default:
return;
}
jf.setSize(800, 600);
jf.setVisible(true);
}
| public static void main(String[] args) {
JFrame jf = new JFrame("Wholeslide");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
switch (args.length) {
case 0:
System.out.println("Give 1 or 2 files");
return;
case 1:
WholeslideView wv = new WholeslideView(new Wholeslide(new File(args[0])));
wv.setBorder(BorderFactory.createTitledBorder(args[0]));
jf.getContentPane().add(wv);
break;
case 2:
final WholeslideView w1 = new WholeslideView(new Wholeslide(
new File(args[0])));
final WholeslideView w2 = new WholeslideView(new Wholeslide(
new File(args[1])));
Box b = Box.createHorizontalBox();
b.add(w1);
b.add(w2);
jf.getContentPane().add(b);
JToggleButton linker = new JToggleButton("Link");
jf.getContentPane().add(linker, BorderLayout.SOUTH);
linker.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
switch(e.getStateChange()) {
case ItemEvent.SELECTED:
w1.linkWithOther(w2);
break;
case ItemEvent.DESELECTED:
w1.unlinkOther();
break;
}
}
});
break;
default:
return;
}
jf.setSize(900, 700);
jf.setVisible(true);
}
|
diff --git a/src/com/statichiss/recordio/ConfirmDetailsActivity.java b/src/com/statichiss/recordio/ConfirmDetailsActivity.java
index 31e32ea..5a76ef9 100644
--- a/src/com/statichiss/recordio/ConfirmDetailsActivity.java
+++ b/src/com/statichiss/recordio/ConfirmDetailsActivity.java
@@ -1,146 +1,149 @@
package com.statichiss.recordio;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
+
import com.statichiss.R;
import com.statichiss.recordio.utils.StringUtils;
import java.io.IOException;
public class ConfirmDetailsActivity extends Activity implements View.OnClickListener {
private static final String TAG = "com.statichiss.recordio.ConfirmDetailsActivity";
private int MODE;
private long radioDetailsId;
private final int ADD_NEW_MODE = 0;
private final int EDIT_MODE = 1;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.edit_fav_pop_up);
Bundle bundle = this.getIntent().getExtras();
RadioDetails radioDetails = null;
if (bundle.getLong(getString(R.string.edit_favourite_id)) > 0) {
// Edit mode
MODE = EDIT_MODE;
DatabaseHelper dbHelper = new DatabaseHelper(this);
try {
dbHelper.openDataBase();
radioDetails = dbHelper.getFavourite(bundle.getLong(getString(R.string.edit_favourite_id)));
radioDetailsId = bundle.getLong(getString(R.string.edit_favourite_id));
} catch (IOException e) {
Log.e(TAG, "IOException thrown when trying to access DB", e);
} finally {
dbHelper.close();
}
} else {
// New mode
MODE = ADD_NEW_MODE;
radioDetails = bundle.getParcelable(getString(R.string.radio_details_key));
}
EditText txtName = (EditText) findViewById(R.id.edit_fav_pop_up_txt_name);
EditText txtUrl = (EditText) findViewById(R.id.edit_fav_pop_up_txt_url);
if (radioDetails != null) {
txtName.setText(radioDetails.getStationName());
if (StringUtils.IsNullOrEmpty(radioDetails.getPlaylistUrl())) {
txtUrl.setText(radioDetails.getStreamUrl());
} else {
txtUrl.setText(radioDetails.getPlaylistUrl());
}
radioDetails.setStationName(txtName.getText().toString());
radioDetails.setStreamUrl(txtUrl.getText().toString());
}
Button cancelButton = (Button) findViewById(R.id.edit_fav_pop_up_btn_cancel);
Button saveButton = (Button) findViewById(R.id.edit_fav_pop_up_btn_save);
cancelButton.setOnClickListener(this);
saveButton.setOnClickListener(this);
}
public void onClick(View view) {
Intent intent = new Intent(ConfirmDetailsActivity.this, RadioActivity.class);
String txtName = ((EditText) findViewById(R.id.edit_fav_pop_up_txt_name)).getText().toString();
String txtUrl = ((EditText) findViewById(R.id.edit_fav_pop_up_txt_url)).getText().toString();
RadioDetails radioDetails = new RadioDetails(radioDetailsId, txtName, null, null);
if (txtUrl.endsWith(".pls") || txtUrl.endsWith(".m3u")) {
radioDetails.setPlaylistUrl(txtUrl);
} else {
radioDetails.setStreamUrl(txtUrl);
}
+ InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+
switch (view.getId()) {
case R.id.edit_fav_pop_up_btn_save:
if (txtName.equals("")) {
Toast.makeText(this, "Please enter a name before saving", Toast.LENGTH_SHORT).show();
return;
}
if (txtUrl.equals("")) {
Toast.makeText(this, "Please enter a URL before saving", Toast.LENGTH_SHORT).show();
return;
}
DatabaseHelper dbHelper = new DatabaseHelper(this);
try {
dbHelper.openDataBase();
switch (MODE) {
case EDIT_MODE:
dbHelper.updateFavourite(radioDetails);
break;
case ADD_NEW_MODE:
dbHelper.addFavourite(radioDetails);
break;
}
} catch (IOException e) {
Log.e(TAG, "IOException thrown when trying to access DB", e);
} finally {
dbHelper.close();
}
- InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(findViewById(R.id.edit_fav_pop_up_txt_name).getWindowToken(), 0);
finish();
break;
case R.id.edit_fav_pop_up_btn_cancel:
onBackPressed();
+ imm.hideSoftInputFromWindow(findViewById(R.id.edit_fav_pop_up_txt_name).getWindowToken(), 0);
break;
}
}
@Override
public void onBackPressed() {
Intent RadioActivityIntent = new Intent(ConfirmDetailsActivity.this, RadioActivity.class);
startActivity(RadioActivityIntent);
finish();
}
}
| false | false | null | null |
diff --git a/src/jar/resolver-store/java/org/mulgara/store/statement/xa/TripleAVLFile.java b/src/jar/resolver-store/java/org/mulgara/store/statement/xa/TripleAVLFile.java
index c41bc51c..0e629221 100644
--- a/src/jar/resolver-store/java/org/mulgara/store/statement/xa/TripleAVLFile.java
+++ b/src/jar/resolver-store/java/org/mulgara/store/statement/xa/TripleAVLFile.java
@@ -1,2230 +1,2230 @@
/*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is the Kowari Metadata Store.
*
* The Initial Developer of the Original Code is Plugged In Software Pty
* Ltd (http://www.pisoftware.com, mailto:[email protected]). Portions
* created by Plugged In Software Pty Ltd are Copyright (C) 2001,2002
* Plugged In Software Pty Ltd. All Rights Reserved.
*
* Contributor(s): N/A.
*
* [NOTE: The text of this Exhibit A may differ slightly from the text
* of the notices in the Source Code files of the Original Code. You
* should use the text of this Exhibit A rather than the text found in the
* Original Code Source Code for Your Modifications.]
*
*/
package org.mulgara.store.statement.xa;
// Java 2 standard packages
import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
// Third party packages
import org.apache.log4j.Logger;
// Locally written packages
import org.mulgara.query.Constraint;
import org.mulgara.query.Cursor;
import org.mulgara.query.TuplesException;
import org.mulgara.query.Variable;
import org.mulgara.store.statement.*;
import org.mulgara.store.tuples.*;
import org.mulgara.store.xa.*;
import org.mulgara.util.Constants;
import org.mulgara.util.StackTrace;
/**
* @created 2001-10-13
*
* @author David Makepeace
* @author Paul Gearon
*
* @version $Revision: 1.9 $
*
* @modified $Date: 2005/05/16 11:07:08 $ @maintenanceAuthor $Author: amuys $
*
* @company <A href="mailto:[email protected]">Plugged In Software</A>
*
* @copyright © 2001-2003 <A href="http://www.PIsoftware.com/">Plugged In
* Software Pty Ltd</A>
*
* @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
*/
public final class TripleAVLFile {
/**
* Logger.
*/
private final static Logger logger = Logger.getLogger(TripleAVLFile.class);
/**
* Get line separator.
*/
private static final String eol = System.getProperty("line.separator");
private final static String BLOCKFILE_EXT = "_tb";
private final static int SIZEOF_TRIPLE = 4;
private final static int BLOCK_SIZE = 8 * 1024;
private final static int MAX_TRIPLES =
BLOCK_SIZE / Constants.SIZEOF_LONG / SIZEOF_TRIPLE;
private final static int IDX_NR_TRIPLES_I = 1;
private final static int IDX_LOW_TRIPLE = 1;
private final static int IDX_HIGH_TRIPLE = IDX_LOW_TRIPLE + SIZEOF_TRIPLE;
private final static int IDX_BLOCK_ID = IDX_HIGH_TRIPLE + SIZEOF_TRIPLE;
private final static int PAYLOAD_SIZE = IDX_BLOCK_ID + 1;
@SuppressWarnings("unused")
private File file;
private AVLFile avlFile;
private ManagedBlockFile blockFile;
private Phase currentPhase;
private TripleWriteThread tripleWriteThread;
private int order0;
private int order1;
private int order2;
private int order3;
private int[] sortOrder;
private AVLComparator avlComparator;
private TripleComparator tripleComparator;
/**
* CONSTRUCTOR TripleAVLFile TO DO
*
* @param file PARAMETER TO DO
* @param sortOrder PARAMETER TO DO
* @throws IOException EXCEPTION TO DO
*/
public TripleAVLFile(File file, int[] sortOrder) throws IOException {
this.file = file;
this.sortOrder = sortOrder;
order0 = sortOrder[0];
order1 = sortOrder[1];
order2 = sortOrder[2];
order3 = sortOrder[3];
avlFile = new AVLFile(file, PAYLOAD_SIZE);
blockFile = new ManagedBlockFile(file + BLOCKFILE_EXT, BLOCK_SIZE, BlockFile.IOType.DEFAULT);
avlComparator = new TripleAVLComparator(sortOrder);
tripleComparator = new TripleComparator(sortOrder);
tripleWriteThread = new TripleWriteThread(file);
}
/**
* CONSTRUCTOR TripleAVLFile TO DO
*
* @param fileName PARAMETER TO DO
* @param sortOrder PARAMETER TO DO
* @throws IOException EXCEPTION TO DO
*/
public TripleAVLFile(String fileName, int[] sortOrder) throws IOException {
this(new File(fileName), sortOrder);
}
/**
* Binary search for a triple given a range to work within.
*
* @param triples The int buffer holding the triples to search on.
* @param comp The comparator to use based on the ordering within <i>triples
* </i>.
* @param left The start of the range to search in (inclusive).
* @param right The end of the range to search in (exclusive).
* @param triple The triple to search for.
* @return The index of the found triple in the int buffer, or if not found
* then -index-1 of the triple above the point where the triple would be.
*/
private static int binarySearch(
Block triples, TripleComparator comp,
int left, int right, long[] triple
) {
for (;;) {
// if the range is zero then the node was not found.
// return the next node up.
if (left >= right) {
return -right - 1;
}
// find the middle of this range
- int middle = (left + right) / 2;
+ int middle = (left + right) >>> 1;
// determine if the required triple is above or below the middle
int c = comp.compare(triple, triples, middle);
// if it's in the middle then return it
if (c == 0) {
return middle;
}
if (c < 0) {
// if it's below the middle then search there
right = middle;
} else {
// if it's below the middle then search there
left = middle + 1;
}
}
}
/**
* METHOD TO DO
*
* @param triples PARAMETER TO DO
* @param nrTriples PARAMETER TO DO
* @param index PARAMETER TO DO
* @param triple PARAMETER TO DO
*/
private static void insertTripleInBlock(
Block triples, int nrTriples, int index, long[] triple
) {
if (index < nrTriples) {
triples.put(
(index + 1) * SIZEOF_TRIPLE * Constants.SIZEOF_LONG,
triples, index * SIZEOF_TRIPLE * Constants.SIZEOF_LONG,
(nrTriples - index) * SIZEOF_TRIPLE * Constants.SIZEOF_LONG
);
}
//triples.put(index * SIZEOF_TRIPLE, triple);
int pos = index * SIZEOF_TRIPLE;
triples.putLong(pos++, triple[0]);
triples.putLong(pos++, triple[1]);
triples.putLong(pos++, triple[2]);
triples.putLong(pos, triple[3]);
}
/**
* METHOD TO DO
*
* @param triples PARAMETER TO DO
* @param nrTriples PARAMETER TO DO
* @param index PARAMETER TO DO
*/
private static void removeTripleFromBlock(
Block triples, int nrTriples, int index
) {
if (index + 1 < nrTriples) {
triples.put(
index * SIZEOF_TRIPLE * Constants.SIZEOF_LONG,
triples, (index + 1) * SIZEOF_TRIPLE * Constants.SIZEOF_LONG,
(nrTriples - index - 1) * SIZEOF_TRIPLE * Constants.SIZEOF_LONG
);
}
}
/**
* Truncates the file to zero length.
*
* @throws IOException if an I/O error occurs.
*/
public void clear() throws IOException {
avlFile.clear();
blockFile.clear();
}
/**
* Ensures that all data for this BlockFile is stored in persistent storage
* before returning.
*
* @throws IOException if an I/O error occurs.
*/
public void force() throws IOException {
avlFile.force();
blockFile.force();
}
/**
* METHOD TO DO
*/
public synchronized void unmap() {
if (tripleWriteThread != null) {
tripleWriteThread.close();
tripleWriteThread = null;
}
if (avlFile != null) {
avlFile.unmap();
}
if (blockFile != null) {
blockFile.unmap();
}
}
/**
* Closes the block file.
*
* @throws IOException EXCEPTION TO DO
*/
public synchronized void close() throws IOException {
try {
if (avlFile != null) {
avlFile.close();
}
} finally {
if (blockFile != null) {
blockFile.close();
}
}
}
/**
* Closes and deletes the block file.
*
* @throws IOException EXCEPTION TO DO
*/
public synchronized void delete() throws IOException {
try {
try {
if (avlFile != null) {
avlFile.delete();
}
} finally {
if (blockFile != null) {
blockFile.delete();
}
}
} finally {
avlFile = null;
blockFile = null;
}
}
private final static class TripleLocation {
public AVLNode node;
public int offset;
/**
* CONSTRUCTOR TripleLocation TO DO
*
* @param node PARAMETER TO DO
* @param offset PARAMETER TO DO
*/
TripleLocation(AVLNode node, int offset) {
this.node = node;
this.offset = offset;
}
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
TripleLocation tl;
try {
tl = (TripleLocation) o;
} catch (ClassCastException ex) {
return false;
}
return tl.node == null && node == null || (
tl.node != null && node != null &&
tl.node.getId() == node.getId() &&
tl.offset == offset
);
}
public int hashCode() {
return node == null ? 0 : ((int) node.getId() + 1) * 17 + offset;
}
}
private static final class TripleAVLComparator implements AVLComparator {
private TripleComparator tripleComparator;
/**
* CONSTRUCTOR TripleAVLComparator TO DO
*
* @param sortOrder PARAMETER TO DO
*/
TripleAVLComparator(int[] sortOrder) {
this.tripleComparator = new TripleComparator(
AVLNode.IDX_PAYLOAD + IDX_LOW_TRIPLE, sortOrder
);
}
public int compare(long[] key, AVLNode node) {
Block block = node.getBlock();
if (tripleComparator.compare(key, block, 0) < 0) {
return -1;
}
if (tripleComparator.compare(key, block, 1) > 0) {
return 1;
}
return 0;
}
}
/**
* Inner class to compare two triples in an int buffer, using a given ordering
* for each of the node columns.
*/
private final static class TripleComparator implements Comparator {
private int offset;
/**
* The required ordering of node columns.
*/
private int c0, c1, c2, c3;
/**
* Construct a comparator according to requested ordering.
*
* @param offset PARAMETER TO DO
* @param sortOrder The order of the columns to sort on
*/
TripleComparator(int offset, int[] sortOrder) {
this.offset = offset;
c0 = sortOrder[0];
c1 = sortOrder[1];
c2 = sortOrder[2];
c3 = sortOrder[3];
}
/**
* Construct a comparator according to requested ordering.
*
* @param sortOrder The order of the columns to sort on
*/
TripleComparator(int[] sortOrder) {
this(0, sortOrder);
}
/**
* Compare triples in 2 int buffers.
*
* @param key PARAMETER TO DO
* @param b PARAMETER TO DO
* @param i PARAMETER TO DO
* @return -1 If the first triple is smaller than the second, 1 if the first
* triple is larger than the second, and 0 if they are equal.
*/
public int compare(long[] key, Block b, int i) {
// calculate the offset into the buffers of each triple
int index = offset + i * SIZEOF_TRIPLE;
int c;
if (
(c = XAUtils.compare(key[c0], b.getLong(index + c0))) == 0 &&
(c = XAUtils.compare(key[c1], b.getLong(index + c1))) == 0 &&
(c = XAUtils.compare(key[c2], b.getLong(index + c2))) == 0
) {
c = XAUtils.compare(key[c3], b.getLong(index + c3));
}
return c;
}
/**
* Compare triples in 2 int arrays.
*
* @param t1 The array holding the first triple.
* @param t2 The array holding the second triple.
* @return -1 If the first triple is smaller than the second, 1 if the first
* triple is larger than the second, and 0 if they are equal.
*/
public int compare(long[] t1, long[] t2) {
int c;
if (
(c = XAUtils.compare(t1[c0], t2[c0])) == 0 &&
(c = XAUtils.compare(t1[c1], t2[c1])) == 0 &&
(c = XAUtils.compare(t1[c2], t2[c2])) == 0
) {
c = XAUtils.compare(t1[c3], t2[c3]);
}
return c;
}
/**
* Compare triples in 2 long arrays.
*
* @param t1 The array holding the first triple.
* @param t2 The array holding the second triple.
* @return -1 If the first triple is smaller than the second, 1 if the first
* triple is larger than the second, and 0 if they are equal.
*/
public int compare(Object t1, Object t2) {
return compare((long[])t1, (long[])t2);
}
}
static String toString(long[] la) {
StringBuffer sb = new StringBuffer("[");
for (int i = 0; i < la.length; ++i) {
if (i != 0) sb.append(',');
sb.append(la[i]);
}
sb.append(']');
return sb.toString();
}
static String toString(int[] ia) {
StringBuffer sb = new StringBuffer("[");
for (int i = 0; i < ia.length; ++i) {
if (i != 0) sb.append(',');
sb.append(ia[i]);
}
sb.append(']');
return sb.toString();
}
public final class Phase implements PersistableMetaRoot {
// in longs
private final static int HEADER_SIZE = 1;
public final static int RECORD_SIZE =
HEADER_SIZE + AVLFile.Phase.RECORD_SIZE +
ManagedBlockFile.Phase.RECORD_SIZE;
private final static int IDX_NR_FILE_TRIPLES = 0;
private long nrFileTriples;
private AVLFile.Phase avlFilePhase;
private ManagedBlockFile.Phase blockFilePhase;
private AVLNode cachedNode = null;
private Block cachedBlock = null;
/**
* CONSTRUCTOR Phase TO DO
*
* @throws IOException EXCEPTION TO DO
*/
public Phase() throws IOException {
if (tripleWriteThread != null) tripleWriteThread.drain();
if (currentPhase == null) {
nrFileTriples = 0;
} else {
nrFileTriples = currentPhase.nrFileTriples;
}
avlFilePhase = avlFile.new Phase();
blockFilePhase = blockFile.new Phase();
check();
if (tripleWriteThread != null) tripleWriteThread.setPhase(this);
currentPhase = this;
}
/**
* CONSTRUCTOR Phase TO DO
*
* @throws IOException EXCEPTION TO DO
*/
public Phase(Phase p) throws IOException {
assert p != null;
if (tripleWriteThread != null) {
if (p == currentPhase) tripleWriteThread.drain();
else tripleWriteThread.abort();
}
nrFileTriples = p.nrFileTriples;
avlFilePhase = avlFile.new Phase(p.avlFilePhase);
blockFilePhase = blockFile.new Phase(p.blockFilePhase);
check();
if (tripleWriteThread != null) tripleWriteThread.setPhase(this);
currentPhase = this;
}
/**
* CONSTRUCTOR Phase TO DO
*
* @param b PARAMETER TO DO
* @param offset PARAMETER TO DO
* @throws IOException EXCEPTION TO DO
*/
public Phase(Block b, int offset) throws IOException {
if (tripleWriteThread != null) tripleWriteThread.drain();
nrFileTriples = b.getLong(offset++);
avlFilePhase = avlFile.new Phase(b, offset);
offset += AVLFile.Phase.RECORD_SIZE;
blockFilePhase = blockFile.new Phase(b, offset);
check();
if (tripleWriteThread != null) tripleWriteThread.setPhase(this);
currentPhase = this;
}
public long getNrTriples() {
if (this == currentPhase && tripleWriteThread != null)
tripleWriteThread.drain();
return nrFileTriples;
}
public boolean isInUse() {
return blockFilePhase.isInUse();
}
public boolean isEmpty() {
if (this == currentPhase && tripleWriteThread != null)
tripleWriteThread.drain();
return avlFilePhase.isEmpty();
}
/**
* Writes this PersistableMetaRoot to the specified Block. The ints are
* written at the specified offset.
*
* @param b the Block.
* @param offset PARAMETER TO DO
*/
public void writeToBlock(Block b, int offset) {
if (tripleWriteThread != null) tripleWriteThread.drain();
check();
b.putLong(offset++, nrFileTriples);
avlFilePhase.writeToBlock(b, offset);
offset += AVLFile.Phase.RECORD_SIZE;
blockFilePhase.writeToBlock(b, offset);
}
/**
* Adds a triple to the graph.
*
* @param node0 The 0 node of the triple.
* @param node1 The 1 node of the triple.
* @param node2 The 2 node of the triple.
* @param node3 The 3 node of the triple.
* @throws IOException EXCEPTION TO DO
*/
public void addTriple(long node0, long node1, long node2, long node3) throws IOException {
addTriple(new long[] {node0, node1, node2, node3});
}
/**
* Adds a triple to the graph.
*
* @param triple The triple to add
* @throws IOException EXCEPTION TO DO
*/
void addTriple(long[] triple) throws IOException {
if (this != currentPhase) throw new IllegalStateException("Attempt to modify a read-only phase.");
if (tripleWriteThread != null) tripleWriteThread.drain();
try {
syncAddTriple(triple);
} finally {
releaseCache();
}
}
/**
* Adds multiple triples to the graph.
*
* @param triples The triples to add
* @throws IOException EXCEPTION TO DO
*/
void syncAddTriples(long[][] triples) throws IOException {
if (this != currentPhase) throw new IllegalStateException("Attempt to modify a read-only phase.");
Arrays.sort(triples, tripleComparator);
try {
for (int i = 0; i < triples.length; ++i) {
long[] triple = triples[i];
triples[i] = null; // Allow early garbage collection.
// Add the triple to the TripleAVLFile and check that the triple
// wasn't already there.
syncAddTriple(triple);
}
} finally {
releaseCache();
}
}
private void releaseCache() throws IOException {
try {
if (cachedNode != null) cachedNode.release();
if (cachedBlock != null) {
cachedBlock.write();
}
} finally {
cachedNode = null;
cachedBlock = null;
}
}
private void releaseBlockToCache(Block block) throws IOException {
if (cachedBlock != null) {
cachedBlock.write();
}
cachedBlock = block;
}
private Block getCachedBlock(long blockId) {
if (cachedBlock != null && blockId == cachedBlock.getBlockId()) {
// Block is cached. Remove from cache and return it.
Block block = cachedBlock;
cachedBlock = null;
return block;
}
return null;
}
private void releaseNodeToCache(AVLNode node) {
if (cachedNode != null) cachedNode.release();
cachedNode = node;
}
/**
* Adds a triple to the graph.
*
* @param triple The triple to add
* @throws IOException EXCEPTION TO DO
*/
private void syncAddTriple(long[] triple) throws IOException {
AVLNode startNode;
if (cachedNode == null) {
startNode = avlFilePhase.getRootNode();
} else {
startNode = cachedNode;
cachedNode = null;
}
AVLNode[] findResult = AVLNode.find(startNode, avlComparator, triple);
if (startNode != null) startNode.release();
if (findResult == null) {
// Tree is empty. Create a node and allocate a triple block.
Block newTripleBlock = blockFilePhase.allocateBlock();
AVLNode newNode = avlFilePhase.newAVLNodeInstance();
newNode.putPayloadLong(IDX_LOW_TRIPLE, triple[0]);
newNode.putPayloadLong(IDX_LOW_TRIPLE + 1, triple[1]);
newNode.putPayloadLong(IDX_LOW_TRIPLE + 2, triple[2]);
newNode.putPayloadLong(IDX_LOW_TRIPLE + 3, triple[3]);
newNode.putPayloadLong(IDX_HIGH_TRIPLE, triple[0]);
newNode.putPayloadLong(IDX_HIGH_TRIPLE + 1, triple[1]);
newNode.putPayloadLong(IDX_HIGH_TRIPLE + 2, triple[2]);
newNode.putPayloadLong(IDX_HIGH_TRIPLE + 3, triple[3]);
newNode.putPayloadInt(IDX_NR_TRIPLES_I, 1);
newNode.putPayloadLong(
IDX_BLOCK_ID, newTripleBlock.getBlockId()
);
newNode.write();
newTripleBlock.put(0, triple);
//newTripleBlock.write();
releaseBlockToCache(newTripleBlock);
avlFilePhase.insertFirst(newNode);
releaseNodeToCache(newNode);
incNrTriples();
return;
}
AVLNode node;
if (findResult.length == 1 || findResult[1] == null) {
node = findResult[0];
} else if (findResult[0] == null) {
node = findResult[1];
} else {
// Between two nodes.
//// Choose the node with the smaller number of triples.
//if (
// findResult[0].getPayloadInt(IDX_NR_TRIPLES_I) <=
// findResult[1].getPayloadInt(IDX_NR_TRIPLES_I)
//) {
// node = findResult[0];
//} else {
// node = findResult[1];
//}
// Preferentially choose the lower node.
if (
findResult[0].getPayloadInt(IDX_NR_TRIPLES_I) < MAX_TRIPLES ||
findResult[1].getPayloadInt(IDX_NR_TRIPLES_I) == MAX_TRIPLES
) {
node = findResult[0];
} else {
node = findResult[1];
}
}
node.incRefCount();
Block tripleBlock = null;
boolean tripleBlockDirty = false;
try {
int nrTriples = node.getPayloadInt(IDX_NR_TRIPLES_I);
if (findResult.length == 1) {
// Found the node. See if it matches the high or low triple.
if (
// Low triple.
node.getPayloadLong(IDX_LOW_TRIPLE) == triple[0] &&
node.getPayloadLong(IDX_LOW_TRIPLE + 1) == triple[1] &&
node.getPayloadLong(IDX_LOW_TRIPLE + 2) == triple[2] &&
node.getPayloadLong(IDX_LOW_TRIPLE + 3) == triple[3]
) return;
if (
nrTriples > 1 &&
// High triple.
node.getPayloadLong(IDX_HIGH_TRIPLE) == triple[0] &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 1) == triple[1] &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 2) == triple[2] &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 3) == triple[3]
) return;
}
// Get the triple block.
long blockId = node.getPayloadLong(IDX_BLOCK_ID);
tripleBlock = getCachedBlock(blockId);
if (tripleBlock == null) {
tripleBlock = blockFilePhase.readBlock(blockId);
} else {
// Blocks in the cache are always dirty.
tripleBlockDirty = true;
}
int index;
if (findResult.length == 2) {
index = node == findResult[0] ? nrTriples : 0;
} else {
// Find the triple or where the triple should be inserted.
index = binarySearch(
tripleBlock, tripleComparator, 0, nrTriples, triple
);
if (index >= 0) return;
index = -index - 1;
// Make index positive.
}
// Tell the node that it will be modified.
node.modify();
// Split the node if the triple block is full.
if (nrTriples == MAX_TRIPLES) {
// Split the block. Allocate a new node and block to take the upper
// portion of the current block.
//int splitPoint = MAX_TRIPLES / 2;
int splitPoint = index == 0 ? 0 : (
index == MAX_TRIPLES ? MAX_TRIPLES : MAX_TRIPLES / 2
);
assert splitPoint > 0 || index == 0;
assert splitPoint < MAX_TRIPLES || index == MAX_TRIPLES;
Block newTripleBlock = blockFilePhase.allocateBlock();
AVLNode newNode = avlFilePhase.newAVLNodeInstance();
// Low triple.
if (splitPoint < MAX_TRIPLES) {
int pos = splitPoint * SIZEOF_TRIPLE;
newNode.putPayloadLong(
IDX_LOW_TRIPLE, tripleBlock.getLong(pos++)
);
newNode.putPayloadLong(
IDX_LOW_TRIPLE + 1, tripleBlock.getLong(pos++)
);
newNode.putPayloadLong(
IDX_LOW_TRIPLE + 2, tripleBlock.getLong(pos++)
);
newNode.putPayloadLong(
IDX_LOW_TRIPLE + 3, tripleBlock.getLong(pos)
);
}
// High triple.
if (index < MAX_TRIPLES) {
int pos = IDX_HIGH_TRIPLE;
newNode.putPayloadLong(
IDX_HIGH_TRIPLE, node.getPayloadLong(pos++)
);
newNode.putPayloadLong(
IDX_HIGH_TRIPLE + 1, node.getPayloadLong(pos++)
);
newNode.putPayloadLong(
IDX_HIGH_TRIPLE + 2, node.getPayloadLong(pos++)
);
newNode.putPayloadLong(
IDX_HIGH_TRIPLE + 3, node.getPayloadLong(pos)
);
}
if (index < MAX_TRIPLES && index <= splitPoint) {
newNode.putPayloadInt(IDX_NR_TRIPLES_I, MAX_TRIPLES - splitPoint);
newNode.putPayloadLong(
IDX_BLOCK_ID, newTripleBlock.getBlockId()
);
}
// Update existing node's high triple unless it will be updated
// later or will not change.
if (index != splitPoint) {
// If splitPoint is zero then index must also be zero.
// If splitPoint is MAX_TRIPLES then index is also MAX_TRIPLES.
// If splitPoint is MAX_TRIPLES then no change is required.
int pos = (splitPoint - 1) * SIZEOF_TRIPLE;
node.putPayloadLong(
IDX_HIGH_TRIPLE, tripleBlock.getLong(pos++)
);
node.putPayloadLong(
IDX_HIGH_TRIPLE + 1, tripleBlock.getLong(pos++)
);
node.putPayloadLong(
IDX_HIGH_TRIPLE + 2, tripleBlock.getLong(pos++)
);
node.putPayloadLong(
IDX_HIGH_TRIPLE + 3, tripleBlock.getLong(pos)
);
}
// Copy the top portion of the full block to the new block.
if (splitPoint < MAX_TRIPLES) {
newTripleBlock.put(
0, tripleBlock,
splitPoint * SIZEOF_TRIPLE * Constants.SIZEOF_LONG,
(MAX_TRIPLES - splitPoint) * SIZEOF_TRIPLE *
Constants.SIZEOF_LONG
);
}
// Update the number of triples unless it will be updated later or
// will not change.
if (index > splitPoint) {
node.putPayloadInt(IDX_NR_TRIPLES_I, splitPoint);
}
// Insert the new node into the tree.
if (findResult.length == 1 || findResult[0] == null) {
node.incRefCount();
AVLFile.release(findResult);
findResult = null;
findResult = new AVLNode[] {
node, node.getNextNode()
};
}
int li = avlFile.leafIndex(findResult);
findResult[li].insert(newNode, 1 - li);
if (index == MAX_TRIPLES || index > splitPoint) {
nrTriples = MAX_TRIPLES - splitPoint;
index -= splitPoint;
if (tripleBlockDirty) tripleBlock.write();
tripleBlock = newTripleBlock;
node.write();
node.release();
node = newNode;
} else {
nrTriples = splitPoint;
newTripleBlock.write();
newNode.write();
newNode.release();
}
// In case nodes are written by insert().
node.modify();
}
// Duplicate the triple block.
tripleBlock.modify();
node.putPayloadLong(IDX_BLOCK_ID, tripleBlock.getBlockId());
insertTripleInBlock(tripleBlock, nrTriples, index, triple);
//tripleBlock.write();
tripleBlockDirty = true;
node.putPayloadInt(IDX_NR_TRIPLES_I, nrTriples + 1);
if (index == nrTriples) {
node.putPayloadLong(IDX_HIGH_TRIPLE, triple[0]);
node.putPayloadLong(IDX_HIGH_TRIPLE + 1, triple[1]);
node.putPayloadLong(IDX_HIGH_TRIPLE + 2, triple[2]);
node.putPayloadLong(IDX_HIGH_TRIPLE + 3, triple[3]);
}
if (index == 0) {
node.putPayloadLong(IDX_LOW_TRIPLE, triple[0]);
node.putPayloadLong(IDX_LOW_TRIPLE + 1, triple[1]);
node.putPayloadLong(IDX_LOW_TRIPLE + 2, triple[2]);
node.putPayloadLong(IDX_LOW_TRIPLE + 3, triple[3]);
}
node.write();
incNrTriples();
return;
} finally {
if (tripleBlock != null) {
if (tripleBlockDirty) releaseBlockToCache(tripleBlock);
}
AVLFile.release(findResult);
releaseNodeToCache(node);
}
}
/**
* Asynchronously adds a triple to the graph.
*
* @param triple The triple to add
*/
public void asyncAddTriple(long[] triple) {
if (this != currentPhase) {
throw new IllegalStateException("Attempt to modify a read-only phase.");
}
tripleWriteThread.addTriple(triple);
}
/**
* Remove a triple from the graph.
*
* @param node0 The 0 node of the triple to remove.
* @param node1 The 1 node of the triple to remove.
* @param node2 The 2 node of the triple to remove.
* @param node3 PARAMETER TO DO
* @throws IOException EXCEPTION TO DO
*/
public void removeTriple(long node0, long node1, long node2, long node3) throws IOException {
if (this != currentPhase) {
throw new IllegalStateException("Attempt to modify a read-only phase.");
}
long[] triple = new long[] {node0, node1, node2, node3};
if (tripleWriteThread != null) tripleWriteThread.drain();
AVLNode[] findResult = avlFilePhase.find(avlComparator, triple);
if (findResult == null || findResult.length == 2) {
if (findResult != null) AVLFile.release(findResult);
// Triple not found
return;
}
// Found the node.
AVLNode node = findResult[0];
node.incRefCount();
AVLFile.release(findResult);
int nrTriples = node.getPayloadInt(IDX_NR_TRIPLES_I);
if (nrTriples == 1) {
// Free the triple block and the avl node.
blockFilePhase.freeBlock(node.getPayloadLong(IDX_BLOCK_ID));
node.remove();
decNrTriples();
return;
}
if (nrTriples == 2) {
// Special case. If the triple matches the high triple and there are
// only two triples in this node then we can simply set the high triple
// to the low triple and decrement the number of triples.
if (
// High triple.
node.getPayloadLong(IDX_HIGH_TRIPLE) == node0 &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 1) == node1 &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 2) == node2 &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 3) == node3
) {
node.modify();
node.putPayloadLong(
IDX_HIGH_TRIPLE, node.getPayloadLong(IDX_LOW_TRIPLE)
);
node.putPayloadLong(
IDX_HIGH_TRIPLE + 1, node.getPayloadLong(IDX_LOW_TRIPLE + 1)
);
node.putPayloadLong(
IDX_HIGH_TRIPLE + 2, node.getPayloadLong(IDX_LOW_TRIPLE + 2)
);
node.putPayloadLong(
IDX_HIGH_TRIPLE + 3, node.getPayloadLong(IDX_LOW_TRIPLE + 3)
);
node.putPayloadInt(IDX_NR_TRIPLES_I, 1);
node.write();
node.release();
decNrTriples();
return;
}
}
// Get the triple block.
Block tripleBlock = blockFilePhase.readBlock(node.getPayloadLong(IDX_BLOCK_ID));
try {
// Find the triple.
int index = binarySearch(tripleBlock, tripleComparator, 0, nrTriples, triple);
// If triple not found
if (index < 0) return;
// Duplicate both the AVLNode and the triple block.
node.modify();
tripleBlock.modify();
node.putPayloadLong(IDX_BLOCK_ID, tripleBlock.getBlockId());
removeTripleFromBlock(tripleBlock, nrTriples, index);
tripleBlock.write();
node.putPayloadInt(IDX_NR_TRIPLES_I, nrTriples - 1);
if (index == nrTriples - 1) {
int pos = (index - 1) * SIZEOF_TRIPLE;
node.putPayloadLong(IDX_HIGH_TRIPLE, tripleBlock.getLong(pos++));
node.putPayloadLong(IDX_HIGH_TRIPLE + 1, tripleBlock.getLong(pos++));
node.putPayloadLong(IDX_HIGH_TRIPLE + 2, tripleBlock.getLong(pos++));
node.putPayloadLong(IDX_HIGH_TRIPLE + 3, tripleBlock.getLong(pos));
} else if (index == 0) {
node.putPayloadLong(IDX_LOW_TRIPLE, tripleBlock.getLong(0));
node.putPayloadLong(IDX_LOW_TRIPLE + 1, tripleBlock.getLong(1));
node.putPayloadLong(IDX_LOW_TRIPLE + 2, tripleBlock.getLong(2));
node.putPayloadLong(IDX_LOW_TRIPLE + 3, tripleBlock.getLong(3));
}
node.write();
decNrTriples();
return;
} finally {
node.release();
}
}
public StoreTuples findTuples(long node0) throws IOException {
long[] startTriple = new long[SIZEOF_TRIPLE];
long[] endTriple = new long[SIZEOF_TRIPLE];
startTriple[order0] = node0;
endTriple[order0] = node0 + 1;
return new TuplesImpl(startTriple, endTriple, 1);
}
public StoreTuples findTuples(long node0, long node1) throws IOException {
long[] startTriple = new long[SIZEOF_TRIPLE];
long[] endTriple = new long[SIZEOF_TRIPLE];
startTriple[order0] = node0;
startTriple[order1] = node1;
endTriple[order0] = node0;
endTriple[order1] = node1 + 1;
return new TuplesImpl(startTriple, endTriple, 2);
}
public StoreTuples findTuples(long node0, long node1, long node2) throws IOException {
long[] startTriple = new long[SIZEOF_TRIPLE];
long[] endTriple = new long[SIZEOF_TRIPLE];
startTriple[order0] = node0;
startTriple[order1] = node1;
startTriple[order2] = node2;
endTriple[order0] = node0;
endTriple[order1] = node1;
endTriple[order2] = node2 + 1;
return new TuplesImpl(startTriple, endTriple, 3);
}
public StoreTuples allTuples() {
return new TuplesImpl();
}
public boolean existsTriples(long node0) throws IOException {
long[] triple = new long[SIZEOF_TRIPLE];
triple[order0] = node0;
if (this == currentPhase && tripleWriteThread != null) tripleWriteThread.drain();
AVLNode[] findResult = avlFilePhase.find(avlComparator, triple);
// If Triplestore is empty.
if (findResult == null) return false;
try {
// Found the node.
AVLNode node = findResult[findResult.length == 1 ? 0 : 1];
// If Triple is less than the minimum or greater than the maximum.
if (node == null) return false;
int nrTriples = node.getPayloadInt(IDX_NR_TRIPLES_I);
// If exact match on a node that only contains one triple.
if (findResult.length == 1 && nrTriples == 1) return true;
// See if it matches the high or low triple.
if (node.getPayloadLong(IDX_LOW_TRIPLE + order0) == node0) return true;
// If this triple's value falls between two nodes.
if (findResult.length == 2) return false;
if (node.getPayloadLong(IDX_HIGH_TRIPLE + order0) == node0) return true;
// Check if there is no point looking inside the triple block since we have
// already checked the only two triples for this node.
if (nrTriples == 2) return false;
// Get the triple block.
Block tripleBlock = blockFilePhase.readBlock(node.getPayloadLong(IDX_BLOCK_ID));
// Find the triple.
int index = binarySearch(tripleBlock, tripleComparator, 0, nrTriples, triple);
boolean exists;
if (index >= 0) {
exists = true;
} else {
index = -index - 1;
exists = index < nrTriples && tripleBlock.getLong(index * SIZEOF_TRIPLE + order0) == node0;
}
return exists;
} finally {
AVLFile.release(findResult);
}
}
public boolean existsTriples(long node0, long node1) throws IOException {
long[] triple = new long[SIZEOF_TRIPLE];
triple[order0] = node0;
triple[order1] = node1;
if (this == currentPhase && tripleWriteThread != null)tripleWriteThread.drain();
AVLNode[] findResult = avlFilePhase.find(avlComparator, triple);
// If Triplestore is empty.
if (findResult == null) return false;
try {
// Found the node.
AVLNode node = findResult[findResult.length == 1 ? 0 : 1];
// Check if Triple is less than the minimum or greater than the maximum.
if (node == null) return false;
int nrTriples = node.getPayloadInt(IDX_NR_TRIPLES_I);
// Check if exact match on a node that only contains one triple.
if (nrTriples == 1) return true;
// See if it matches the high or low triple.
if (
node.getPayloadLong(IDX_LOW_TRIPLE + order0) == node0 &&
node.getPayloadLong(IDX_LOW_TRIPLE + order1) == node1
) {
return true;
}
// Check if this triple's value falls between two nodes.
if (findResult.length == 2) return false;
if (
node.getPayloadLong(IDX_HIGH_TRIPLE + order0) == node0 &&
node.getPayloadLong(IDX_HIGH_TRIPLE + order1) == node1
) {
return true;
}
// Check if there is no point looking inside the triple block since we have
// already checked the only two triples for this node.
if (nrTriples == 2) return false;
// Get the triple block.
Block tripleBlock = blockFilePhase.readBlock(node.getPayloadLong(IDX_BLOCK_ID));
// Find the triple.
int index = binarySearch(tripleBlock, tripleComparator, 0, nrTriples, triple);
boolean exists;
if (index >= 0) {
exists = true;
} else {
index = -index - 1;
exists = index < nrTriples &&
tripleBlock.getLong(index * SIZEOF_TRIPLE + order0) == node0 &&
tripleBlock.getLong(index * SIZEOF_TRIPLE + order1) == node1;
}
return exists;
} finally {
AVLFile.release(findResult);
}
}
public boolean existsTriples(long node0, long node1, long node2) throws IOException {
long[] triple = new long[SIZEOF_TRIPLE];
triple[order0] = node0;
triple[order1] = node1;
triple[order2] = node2;
if (this == currentPhase && tripleWriteThread != null) tripleWriteThread.drain();
AVLNode[] findResult = avlFilePhase.find(avlComparator, triple);
// Check if Triplestore is empty.
if (findResult == null) return false;
try {
// Found the node.
AVLNode node = findResult[findResult.length == 1 ? 0 : 1];
// Check if Triple is less than the minimum or greater than the maximum.
if (node == null) return false;
int nrTriples = node.getPayloadInt(IDX_NR_TRIPLES_I);
// Check if exact match on a node that only contains one triple.
if (nrTriples == 1) return true;
// See if it matches the high or low triple.
if (
node.getPayloadLong(IDX_LOW_TRIPLE + order0) == node0 &&
node.getPayloadLong(IDX_LOW_TRIPLE + order1) == node1 &&
node.getPayloadLong(IDX_LOW_TRIPLE + order2) == node2
) {
return true;
}
// Check if this triple's value falls between two nodes.
if (findResult.length == 2) return false;
if (
node.getPayloadLong(IDX_HIGH_TRIPLE + order0) == node0 &&
node.getPayloadLong(IDX_HIGH_TRIPLE + order1) == node1 &&
node.getPayloadLong(IDX_HIGH_TRIPLE + order2) == node2
) {
return true;
}
// Check if there is no point looking inside the triple block since we have
// already checked the only two triples for this node.
if (nrTriples == 2) return false;
// Get the triple block.
Block tripleBlock = blockFilePhase.readBlock(node.getPayloadLong(IDX_BLOCK_ID));
// Find the triple.
int index = binarySearch(tripleBlock, tripleComparator, 0, nrTriples, triple);
boolean exists;
if (index >= 0) {
exists = true;
} else {
index = -index - 1;
exists = index < nrTriples &&
tripleBlock.getLong(index * SIZEOF_TRIPLE + order0) == node0 &&
tripleBlock.getLong(index * SIZEOF_TRIPLE + order1) == node1 &&
tripleBlock.getLong(index * SIZEOF_TRIPLE + order2) == node2;
}
return exists;
} finally {
AVLFile.release(findResult);
}
}
public boolean existsTriple(long node0, long node1, long node2, long node3) throws IOException {
long[] triple = new long[SIZEOF_TRIPLE];
triple[order0] = node0;
triple[order1] = node1;
triple[order2] = node2;
triple[order3] = node3;
return existsTriple(triple);
}
public Token use() {
return new Token();
}
long checkIntegrity() {
if (this == currentPhase && tripleWriteThread != null)
tripleWriteThread.drain();
AVLNode node = avlFilePhase.getRootNode();
if (node == null) return 0;
node = node.getMinNode_R();
long[] prevTriple = new long[] {0, 0, 0, 0};
long[] triple = new long[SIZEOF_TRIPLE];
long nodeIndex = 0;
long totalNrTriples = 0;
do {
int nrTriples = node.getPayloadInt(IDX_NR_TRIPLES_I);
if (nrTriples < 1 || nrTriples > MAX_TRIPLES) {
throw new Error(
"NR_TRIPLES (" + nrTriples + ") is out of bounds in node: " +
node.getId() + " (index " + nodeIndex + ")"
);
}
triple[0] = node.getPayloadLong(IDX_LOW_TRIPLE);
triple[1] = node.getPayloadLong(IDX_LOW_TRIPLE + 1);
triple[2] = node.getPayloadLong(IDX_LOW_TRIPLE + 2);
triple[3] = node.getPayloadLong(IDX_LOW_TRIPLE + 3);
if (tripleComparator.compare(prevTriple, triple) >= 0) {
throw new Error(
"LOW_TRIPLE (" +
triple[0] + " " + triple[1] + " " +
triple[2] + " " + triple[3] +
") is not greater than prevTriple (" +
prevTriple[0] + " " + prevTriple[1] + " " +
prevTriple[2] + " " + prevTriple[3] +
") in node: " + node.getId() + " (index " + nodeIndex + ")"
);
}
Block block;
try {
block = blockFilePhase.readBlock(node.getPayloadLong(IDX_BLOCK_ID));
} catch (IOException ex) {
throw new Error("I/O Error", ex);
}
if (tripleComparator.compare(triple, block, 0) != 0) {
long[] firstTriple = new long[SIZEOF_TRIPLE];
block.get(0, firstTriple);
throw new Error(
"LOW_TRIPLE (" +
triple[0] + " " + triple[1] + " " +
triple[2] + " " + triple[3] +
") is not equal to the first triple (" +
firstTriple[0] + " " +
firstTriple[1] + " " +
firstTriple[2] + " " +
firstTriple[3] + ") in node: " + node.getId() +
" (index " + nodeIndex + ")"
);
}
System.arraycopy(triple, 0, prevTriple, 0, SIZEOF_TRIPLE);
for (int i = 1; i < nrTriples; ++i) {
block.get(i * SIZEOF_TRIPLE, triple);
if (tripleComparator.compare(prevTriple, triple) >= 0) {
throw new Error(
"Triple #" + i + " (" +
" not greater than previous triple in block in node: " +
node.getId() + " (index " + nodeIndex + ")"
);
}
System.arraycopy(triple, 0, prevTriple, 0, SIZEOF_TRIPLE);
}
triple[0] = node.getPayloadLong(IDX_HIGH_TRIPLE);
triple[1] = node.getPayloadLong(IDX_HIGH_TRIPLE + 1);
triple[2] = node.getPayloadLong(IDX_HIGH_TRIPLE + 2);
triple[3] = node.getPayloadLong(IDX_HIGH_TRIPLE + 3);
if (tripleComparator.compare(triple, prevTriple) != 0) {
throw new Error(
"HIGH_TRIPLE (" +
triple[0] + " " + triple[1] + " " +
triple[2] + " " + triple[3] +
") is not equal to the last triple (" +
prevTriple[0] + " " + prevTriple[1] + " " +
prevTriple[2] + " " + prevTriple[3] +
") in node: " + node.getId() + " (index " + nodeIndex + ")"
);
}
++nodeIndex;
totalNrTriples += nrTriples;
} while ((node = node.getNextNode_R()) != null);
if (totalNrTriples != nrFileTriples) {
throw new Error(
"nrFileTriples (" + nrFileTriples +
") does not match actual number of triples (" + totalNrTriples +
") in: " + order0 + order1 + order2 + order3
);
}
return totalNrTriples;
}
private void check() {
assert !isEmpty() || nrFileTriples == 0 :
"AVLFile not empty but nrFileTriples == 0";
assert isEmpty() || nrFileTriples > 0 :
"AVLFile is empty but nrFileTriples == " + nrFileTriples;
}
private void incNrTriples() {
++nrFileTriples;
}
private void decNrTriples() {
assert nrFileTriples > 0;
--nrFileTriples;
}
private boolean existsTriple(long[] triple)
throws IOException {
if (this == currentPhase && tripleWriteThread != null)
tripleWriteThread.drain();
AVLNode[] findResult = avlFilePhase.find(avlComparator, triple);
// Check if Triplestore is empty.
if (findResult == null) return false;
try {
// Check if triple not found.
if (findResult.length == 2) return false;
// Found the node.
AVLNode node = findResult[0];
int nrTriples = node.getPayloadInt(IDX_NR_TRIPLES_I);
if (nrTriples == 1) return true;
// See if it matches the high or low triple.
if (
(
// Low triple.
node.getPayloadLong(IDX_LOW_TRIPLE) == triple[0] &&
node.getPayloadLong(IDX_LOW_TRIPLE + 1) == triple[1] &&
node.getPayloadLong(IDX_LOW_TRIPLE + 2) == triple[2] &&
node.getPayloadLong(IDX_LOW_TRIPLE + 3) == triple[3]
) || (
// High triple.
node.getPayloadLong(IDX_HIGH_TRIPLE) == triple[0] &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 1) == triple[1] &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 2) == triple[2] &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 3) == triple[3]
)
) {
return true;
}
if (nrTriples == 2) {
return false;
}
// Get the triple block.
Block tripleBlock = blockFilePhase.readBlock(node.getPayloadLong(IDX_BLOCK_ID));
// Find the triple.
int index = binarySearch(tripleBlock, tripleComparator, 0, nrTriples, triple);
return index >= 0;
} finally {
AVLFile.release(findResult);
}
}
private TripleLocation findTriple(long[] triple) throws IOException {
AVLNode[] findResult = avlFilePhase.find(avlComparator, triple);
if (findResult == null) return null;
AVLNode node;
if (findResult.length == 2) {
node = findResult[1];
if (node != null) node.incRefCount();
AVLFile.release(findResult);
return new TripleLocation(node, 0);
}
// Found the node.
node = findResult[0];
node.incRefCount();
AVLFile.release(findResult);
int nrTriples = node.getPayloadInt(IDX_NR_TRIPLES_I);
if (nrTriples == 1) {
return new TripleLocation(node, 0);
}
// See if it matches the low triple.
if (
// Low triple.
node.getPayloadLong(IDX_LOW_TRIPLE) == triple[0] &&
node.getPayloadLong(IDX_LOW_TRIPLE + 1) == triple[1] &&
node.getPayloadLong(IDX_LOW_TRIPLE + 2) == triple[2] &&
node.getPayloadLong(IDX_LOW_TRIPLE + 3) == triple[3]
) {
return new TripleLocation(node, 0);
}
if (nrTriples == 2) {
return new TripleLocation(node, 1);
}
// See if it matches the high triple.
if (
// High triple.
node.getPayloadLong(IDX_HIGH_TRIPLE) == triple[0] &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 1) == triple[1] &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 2) == triple[2] &&
node.getPayloadLong(IDX_HIGH_TRIPLE + 3) == triple[3]
) {
return new TripleLocation(node, nrTriples - 1);
}
// Get the triple block.
Block tripleBlock = blockFilePhase.readBlock(node.getPayloadLong(IDX_BLOCK_ID));
// Find the triple.
int index = binarySearch(tripleBlock, tripleComparator, 0, nrTriples, triple);
if (index < 0) index = -index - 1;
return new TripleLocation(node, index);
}
public final class Token {
private AVLFile.Phase.Token avlFileToken;
private ManagedBlockFile.Phase.Token blockFileToken;
private Phase phase = Phase.this;
/**
* CONSTRUCTOR Token TO DO
*/
Token() {
avlFileToken = avlFilePhase.use();
blockFileToken = blockFilePhase.use();
}
public Phase getPhase() {
assert avlFileToken != null : "Invalid Token";
assert blockFileToken != null : "Invalid Token";
return phase;
}
public void release() {
assert avlFileToken != null : "Invalid Token";
assert blockFileToken != null : "Invalid Token";
avlFileToken.release();
avlFileToken = null;
blockFileToken.release();
blockFileToken = null;
phase = null;
}
}
private final class TuplesImpl implements StoreTuples {
// keep a stack trace of the instantiation of this object
@SuppressWarnings("unused")
private StackTrace stack = logger.isDebugEnabled() ? new StackTrace() : null;
private List<Integer> objectIds = new ArrayList<Integer>();
private long[] startTriple;
private TripleLocation start;
private long[] endTriple;
private TripleLocation end;
private Token token;
private long nrTriples;
private boolean nrTriplesValid = false;
@SuppressWarnings("unused")
private int prefixLength;
private int[] columnMap;
private Variable[] variables;
private long[] tmpTriple = new long[SIZEOF_TRIPLE];
private AVLNode node;
private boolean beforeStart;
private int nrBlockTriples = 0;
private Block tripleBlock = null;
private int offset;
private long endBlockId = Block.INVALID_BLOCK_ID;
private int endOffset = 0;
private long[] prefix = null;
private int rowCardinality = -1;
/**
* CONSTRUCTOR TuplesImpl TO DO
*
* @param startTriple PARAMETER TO DO
* @param endTriple PARAMETER TO DO
* @param prefixLength PARAMETER TO DO
* @throws IOException EXCEPTION TO DO
*/
TuplesImpl(
long[] startTriple, long[] endTriple,
int prefixLength
) throws IOException {
assert prefixLength >= 1 && prefixLength < SIZEOF_TRIPLE;
if (Phase.this == currentPhase && tripleWriteThread != null) tripleWriteThread.drain();
this.startTriple = startTriple;
this.endTriple = endTriple;
this.prefixLength = prefixLength;
int nrColumns = SIZEOF_TRIPLE - prefixLength;
// Set up a column order which moves the prefix columns to the end.
columnMap = new int[nrColumns];
for (int i = 0; i < nrColumns; ++i) {
columnMap[i] = sortOrder[(i + prefixLength) % SIZEOF_TRIPLE];
}
variables = new Variable[nrColumns];
for (int i = 0; i < nrColumns; ++i) {
variables[i] = StatementStore.VARIABLES[columnMap[i]];
}
start = findTriple(startTriple);
end = findTriple(endTriple);
if (end != null && end.node != null) {
endBlockId = end.node.getId();
endOffset = end.offset;
}
if (start != null && start.node != null && (start.node.getId() != endBlockId || start.offset < endOffset)) {
token = use();
beforeStart = true;
} else {
close();
}
}
/**
* CONSTRUCTOR TuplesImpl TO DO
*/
TuplesImpl() {
if (Phase.this == currentPhase && tripleWriteThread != null) tripleWriteThread.drain();
this.nrTriples = Phase.this.nrFileTriples;
this.nrTriplesValid = true;
columnMap = sortOrder;
this.variables = new Variable[] {
StatementStore.VARIABLES[order0],
StatementStore.VARIABLES[order1],
StatementStore.VARIABLES[order2],
StatementStore.VARIABLES[order3]
};
startTriple = new long[SIZEOF_TRIPLE];
endTriple = new long[] { Constants.MASK63, Constants.MASK63, Constants.MASK63, Constants.MASK63 };
prefixLength = 0;
AVLNode node = avlFilePhase.getRootNode();
if (node != null) {
start = new TripleLocation(node.getMinNode_R(), 0);
token = use();
end = new TripleLocation(null, 0);
beforeStart = true;
} else {
close();
}
}
public int[] getColumnOrder() {
return (int[])columnMap.clone();
}
public long getRawColumnValue(int column) throws TuplesException {
return getColumnValue(column);
}
public long getColumnValue(int column) throws TuplesException {
try {
return tripleBlock.getLong(offset * SIZEOF_TRIPLE + columnMap[column]);
} catch (ArrayIndexOutOfBoundsException ex) {
if (column < 0 || column >= variables.length) {
throw new TuplesException("Column index out of range: " + column);
}
throw ex;
} catch (NullPointerException ex) {
if (beforeStart || node == null) {
throw new TuplesException("No current row. Before start: " + beforeStart + " node: " + node);
}
throw ex;
}
}
public Variable[] getVariables() {
return (Variable[])variables.clone();
}
public int getNumberOfVariables() {
return variables.length;
}
public long getRowCount() throws TuplesException {
if (nrTriplesValid) return nrTriples;
nrTriplesValid = true;
if (start == null) return nrTriples = 0;
long n = endOffset - start.offset;
AVLNode curNode = start.node;
curNode.incRefCount();
while (curNode != null && curNode.getId() != endBlockId) {
n += curNode.getPayloadInt(IDX_NR_TRIPLES_I);
curNode = curNode.getNextNode_R();
}
if (curNode != null) {
curNode.release();
}
return nrTriples = n;
}
public long getRowUpperBound() throws TuplesException {
return getRowCount();
}
public int getRowCardinality() throws TuplesException {
if (rowCardinality != -1) return rowCardinality;
Tuples temp = (Tuples)this.clone();
temp.beforeFirst();
if (!temp.next()) {
rowCardinality = Cursor.ZERO;
} else if (!temp.next()) {
rowCardinality = Cursor.ONE;
} else {
rowCardinality = Cursor.MANY;
}
temp.close();
return rowCardinality;
}
public int getColumnIndex(Variable variable) throws TuplesException {
for (int i = 0; i < variables.length; ++i) {
if (variables[i].equals(variable)) return i;
}
throw new TuplesException("variable doesn't match any column");
}
public boolean isColumnEverUnbound(int column) {
return false;
}
public boolean isMaterialized() {
return true;
}
public boolean isUnconstrained() {
return false;
}
public RowComparator getComparator() {
return DefaultRowComparator.getInstance();
}
public List getOperands() {
return new ArrayList(0);
}
public boolean isEmpty() {
return start == null;
}
public boolean next() throws TuplesException {
if (prefix.length > variables.length) throw new TuplesException("prefix too long: " + prefix.length);
// Move to the next row.
if (!advance()) {
return false;
}
if (prefix.length == 0) return true;
// See if the current row matches the prefix.
RowComparator comparator = getComparator();
int c = comparator.compare(prefix, this);
if (c == 0) return true;
closeIterator();
if (c < 0) return false;
// Reorder the prefix to create a triple.
System.arraycopy(startTriple, 0, tmpTriple, 0, SIZEOF_TRIPLE);
for (int i = 0; i < prefix.length; ++i) tmpTriple[columnMap[i]] = prefix[i];
// Check if the prefix is past the end triple.
if (tripleComparator.compare(tmpTriple, endTriple) >= 0) return false;
// Locate the first triple greater than or equal to the prefix.
TripleLocation tLoc;
try {
tLoc = findTriple(tmpTriple);
} catch (IOException ex) {
throw new TuplesException("I/O error", ex);
}
if (tLoc.node != null) {
if (tLoc.node.getId() != endBlockId || tLoc.offset < endOffset) {
node = tLoc.node;
offset = tLoc.offset;
readTripleBlock();
return comparator.compare(prefix, this) == 0;
} else {
tLoc.node.release();
}
}
return false;
}
public void beforeFirst(long[] prefix, int suffixTruncation) throws TuplesException {
if (prefix == null) throw new IllegalArgumentException("Null \"prefix\" parameter");
if (suffixTruncation != 0) throw new TuplesException("Suffix truncation not implemented");
beforeStart = true;
this.prefix = prefix;
}
public void beforeFirst() {
beforeStart = true;
prefix = Tuples.NO_PREFIX;
}
public boolean hasNoDuplicates() {
return true;
}
/**
* Renames the variables which label the tuples if they have the "magic"
* names such as "Subject", "Predicate", "Object" and "Meta".
*
* @param constraint PARAMETER TO DO
*/
public void renameVariables(Constraint constraint) {
if (logger.isDebugEnabled()) {
logger.debug("Renaming variables. before: " + Arrays.asList(variables) + " constraint: " + constraint);
}
for (int i = 0; i < columnMap.length; ++i) variables[i] = (Variable) constraint.getElement(columnMap[i]);
if (logger.isDebugEnabled()) {
logger.debug("Renaming variables. after: " + Arrays.asList(variables));
}
}
public String toString() {
Tuples cloned = (Tuples) clone();
NumberFormat formatter = new DecimalFormat("000000");
try {
StringBuffer buffer = new StringBuffer(eol + "{");
Variable[] variables = cloned.getVariables();
for (int i = 0; i < variables.length; i++) {
buffer.append(variables[i]);
for (int j = 0; j < (6 - variables[i].toString().length()); j++) buffer.append(" ");
buffer.append(" ");
}
if (cloned.isMaterialized()) {
buffer.append("(");
buffer.append(cloned.getRowCount());
buffer.append(" rows)" + eol);
} else {
buffer.append("(unevaluated, ");
buffer.append(cloned.getRowCount());
buffer.append(" rows max)" + eol);
}
cloned.beforeFirst();
int rowNo = 0;
while (cloned.next()) {
if (++rowNo > 20) {
buffer.append("..." + eol);
break;
}
buffer.append("[");
for (int i = 0; i < variables.length; i++) {
buffer.append(formatter.format(cloned.getColumnValue(i)));
buffer.append(" ");
}
buffer.append("]" + eol);
}
buffer.append("}");
return buffer.toString();
} catch (TuplesException e) {
return e.toString();
} finally {
try {
cloned.close();
} catch (Exception e) {
logger.warn("Failed to close tuples after serializing", e);
}
}
}
public Object clone() {
try {
TuplesImpl copy = (TuplesImpl) super.clone();
tmpTriple = new long[SIZEOF_TRIPLE];
if (start != null) {
start.node.incRefCount();
if (end.node != null) end.node.incRefCount();
copy.token = use();
copy.tripleBlock = null;
copy.node = null;
copy.beforeFirst();
}
copy.variables = getVariables();
copy.stack = logger.isDebugEnabled() ? new StackTrace() : null;
copy.objectIds = new ArrayList<Integer>(objectIds);
copy.objectIds.add(new Integer(System.identityHashCode(this)));
return copy;
} catch (CloneNotSupportedException ex) {
throw new Error();
}
}
public void close() {
closeIterator();
if (token != null) {
token.release();
token = null;
}
startTriple = null;
if (start != null) {
if (start.node != null) start.node.release();
start = null;
}
endTriple = null;
if (end != null) {
if (end.node != null) end.node.release();
end = null;
}
stack = null;
}
/* Don't enable this in production unless you want a significant increase in heap usage,
* out-of-heap errors, and 60% slow-down of the queries.
public void finalize() {
if (logger.isDebugEnabled()) {
if (stack != null) {
logger.debug("TuplesImpl not closed (" + System.identityHashCode(this) + ")\n" + stack);
logger.debug("----Provenance : " + objectIds);
}
}
}
*/
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) return true;
// Make sure the object is a Tuples.
Tuples t;
try {
t = (Tuples) o;
} catch (ClassCastException ex) {
return false;
}
Tuples t1 = null;
Tuples t2 = null;
try {
if (getRowCount() != t.getRowCount()) return false;
if (getRowCount() == 0) return true;
// Return false if the column variable names don't match or the number
// of columns differ.
if (!Arrays.asList(getVariables()).equals(Arrays.asList(t.getVariables()))) return false;
// Clone the two Tuples objects.
t1 = (Tuples) this.clone();
t2 = (Tuples) t.clone();
// Get the default comparator.
RowComparator comp = getComparator();
t1.beforeFirst();
t2.beforeFirst();
while (t1.next()) {
if (!t2.next() || comp.compare(t1, t2) != 0) return false;
}
return !t2.next();
} catch (TuplesException ex) {
throw new RuntimeException(ex.toString(), ex);
} finally {
try {
if (t1 != null) t1.close();
if (t2 != null) t2.close();
} catch (TuplesException ex) {
throw new RuntimeException(ex.toString(), ex);
}
}
}
private boolean advance() throws TuplesException {
if (beforeStart) {
// Reset the iterator position to the start.
beforeStart = false;
if (start != null) {
// Tuples is not empty. Reset to first triple.
closeIterator();
node = start.node;
node.incRefCount();
offset = start.offset;
}
} else if (node != null) {
if (++offset == nrBlockTriples) {
offset = 0;
tripleBlock = null;
node = node.getNextNode_R();
}
if (
node != null && node.getId() == endBlockId && offset >= endOffset
) {
closeIterator();
}
}
readTripleBlock();
return node != null;
}
private void closeIterator() {
if (tripleBlock != null) tripleBlock = null;
if (node != null) {
node.release();
node = null;
}
}
private void readTripleBlock() throws TuplesException {
if (tripleBlock == null && node != null) {
nrBlockTriples = node.getPayloadInt(IDX_NR_TRIPLES_I);
try {
tripleBlock = blockFilePhase.readBlock(node.getPayloadLong(IDX_BLOCK_ID));
} catch (IOException ex) {
throw new TuplesException("I/O error", ex);
}
}
}
/**
* Copied from AbstractTuples
*/
public Annotation getAnnotation(Class annotationClass) throws TuplesException {
return null;
}
}
}
}
| true | false | null | null |
diff --git a/MasterMindSolver/src/org/hitzemann/mms/solver/DefaultErgebnisBerechner.java b/MasterMindSolver/src/org/hitzemann/mms/solver/DefaultErgebnisBerechner.java
index d3a77b8..613b318 100644
--- a/MasterMindSolver/src/org/hitzemann/mms/solver/DefaultErgebnisBerechner.java
+++ b/MasterMindSolver/src/org/hitzemann/mms/solver/DefaultErgebnisBerechner.java
@@ -1,70 +1,70 @@
/**
*
*/
package org.hitzemann.mms.solver;
import java.util.HashMap;
import java.util.Map;
import org.hitzemann.mms.model.ErgebnisKombination;
import org.hitzemann.mms.model.SpielKombination;
/**
* @author simon
*
*/
public class DefaultErgebnisBerechner implements IErgebnisBerechnung {
/* (non-Javadoc)
* @see org.hitzemann.mms.solver.IErgebnisBerechnung#berechneErgebnis(org.hitzemann.mms.model.SpielKombination, org.hitzemann.mms.model.SpielKombination)
*/
@Override
public ErgebnisKombination berechneErgebnis(SpielKombination geheim,
SpielKombination geraten) {
// Fallback, nix richtig
int korrekt = 0;
int position = 0;
// Trivial: beide gleich
- if (geheim.getSpielSteineCount() != geraten.getSpielSteineCount()) {
- throw new IllegalArgumentException("Spielsteine haben unterschiedliche Größen!");
+ if (geheim == null || geraten == null || geheim.getSpielSteineCount() != geraten.getSpielSteineCount() ) {
+ throw new IllegalArgumentException();
}
if (geheim.equals(geraten)) {
korrekt = geheim.getSpielSteineCount();
position = 0;
} else {
// 2 Maps um zu tracken, welche Steine schon "benutzt" wurden
final Map<Integer, Boolean> geheimMap = new HashMap<Integer, Boolean>();
final Map<Integer, Boolean> geratenMap = new HashMap<Integer, Boolean>();
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
geheimMap.put(n, true);
geratenMap.put(n, true);
}
// Berechne korrekte Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
if (geheimMap.get(n)
&& geratenMap.get(n)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(n))) {
geheimMap.put(n, false);
geratenMap.put(n, false);
korrekt++;
}
}
// Berechne korrekte Farben und falsche Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
for (int m = 0; m < geheim.getSpielSteineCount(); m++) {
if (m != n) {
if (geheimMap.get(n)
&& geratenMap.get(m)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(m))) {
geheimMap.put(n, false);
geratenMap.put(m, false);
position++;
}
}
}
}
}
return new ErgebnisKombination(korrekt, position);
}
}
| true | true | public ErgebnisKombination berechneErgebnis(SpielKombination geheim,
SpielKombination geraten) {
// Fallback, nix richtig
int korrekt = 0;
int position = 0;
// Trivial: beide gleich
if (geheim.getSpielSteineCount() != geraten.getSpielSteineCount()) {
throw new IllegalArgumentException("Spielsteine haben unterschiedliche Größen!");
}
if (geheim.equals(geraten)) {
korrekt = geheim.getSpielSteineCount();
position = 0;
} else {
// 2 Maps um zu tracken, welche Steine schon "benutzt" wurden
final Map<Integer, Boolean> geheimMap = new HashMap<Integer, Boolean>();
final Map<Integer, Boolean> geratenMap = new HashMap<Integer, Boolean>();
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
geheimMap.put(n, true);
geratenMap.put(n, true);
}
// Berechne korrekte Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
if (geheimMap.get(n)
&& geratenMap.get(n)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(n))) {
geheimMap.put(n, false);
geratenMap.put(n, false);
korrekt++;
}
}
// Berechne korrekte Farben und falsche Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
for (int m = 0; m < geheim.getSpielSteineCount(); m++) {
if (m != n) {
if (geheimMap.get(n)
&& geratenMap.get(m)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(m))) {
geheimMap.put(n, false);
geratenMap.put(m, false);
position++;
}
}
}
}
}
return new ErgebnisKombination(korrekt, position);
}
| public ErgebnisKombination berechneErgebnis(SpielKombination geheim,
SpielKombination geraten) {
// Fallback, nix richtig
int korrekt = 0;
int position = 0;
// Trivial: beide gleich
if (geheim == null || geraten == null || geheim.getSpielSteineCount() != geraten.getSpielSteineCount() ) {
throw new IllegalArgumentException();
}
if (geheim.equals(geraten)) {
korrekt = geheim.getSpielSteineCount();
position = 0;
} else {
// 2 Maps um zu tracken, welche Steine schon "benutzt" wurden
final Map<Integer, Boolean> geheimMap = new HashMap<Integer, Boolean>();
final Map<Integer, Boolean> geratenMap = new HashMap<Integer, Boolean>();
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
geheimMap.put(n, true);
geratenMap.put(n, true);
}
// Berechne korrekte Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
if (geheimMap.get(n)
&& geratenMap.get(n)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(n))) {
geheimMap.put(n, false);
geratenMap.put(n, false);
korrekt++;
}
}
// Berechne korrekte Farben und falsche Positionen
for (int n = 0; n < geheim.getSpielSteineCount(); n++) {
for (int m = 0; m < geheim.getSpielSteineCount(); m++) {
if (m != n) {
if (geheimMap.get(n)
&& geratenMap.get(m)
&& geheim.getSpielStein(n).equals(
geraten.getSpielStein(m))) {
geheimMap.put(n, false);
geratenMap.put(m, false);
position++;
}
}
}
}
}
return new ErgebnisKombination(korrekt, position);
}
|
diff --git a/src/com/owncloud/android/ui/activity/FileDisplayActivity.java b/src/com/owncloud/android/ui/activity/FileDisplayActivity.java
index 0401b07..0b97c68 100644
--- a/src/com/owncloud/android/ui/activity/FileDisplayActivity.java
+++ b/src/com/owncloud/android/ui/activity/FileDisplayActivity.java
@@ -1,891 +1,892 @@
/* ownCloud Android client application
* Copyright (C) 2011 Bartek Przybylski
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.ui.activity;
import java.io.File;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.owncloud.android.AccountUtils;
import com.owncloud.android.CrashHandler;
import com.owncloud.android.authenticator.AccountAuthenticator;
import com.owncloud.android.datamodel.DataStorageManager;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
import com.owncloud.android.files.OwnCloudFileObserver;
import com.owncloud.android.files.services.FileDownloader;
import com.owncloud.android.files.services.FileObserverService;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.network.OwnCloudClientUtils;
import com.owncloud.android.syncadapter.FileSyncService;
import com.owncloud.android.ui.fragment.FileDetailFragment;
import com.owncloud.android.ui.fragment.OCFileListFragment;
import com.owncloud.android.R;
import eu.alefzero.webdav.WebdavClient;
/**
* Displays, what files the user has available in his ownCloud.
*
* @author Bartek Przybylski
*
*/
public class FileDisplayActivity extends SherlockFragmentActivity implements
OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener {
private ArrayAdapter<String> mDirectories;
private OCFile mCurrentDir;
private DataStorageManager mStorageManager;
private SyncBroadcastReceiver mSyncBroadcastReceiver;
private UploadFinishReceiver mUploadFinishReceiver;
private DownloadFinishReceiver mDownloadFinishReceiver;
private OCFileListFragment mFileList;
private boolean mDualPane;
private static final int DIALOG_SETUP_ACCOUNT = 0;
private static final int DIALOG_CREATE_DIR = 1;
private static final int DIALOG_ABOUT_APP = 2;
public static final int DIALOG_SHORT_WAIT = 3;
private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;
private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
private static final String TAG = "FileDisplayActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(getClass().toString(), "onCreate() start");
super.onCreate(savedInstanceState);
//Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
/// saved instance state: keep this always before initDataFromCurrentAccount()
if(savedInstanceState != null) {
mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
}
if (!AccountUtils.accountsAreSetup(this)) {
/// no account available: FORCE ACCOUNT CREATION
mStorageManager = null;
createFirstAccount();
} else { /// at least an account is available
initDataFromCurrentAccount();
}
// PIN CODE request ; best location is to decide, let's try this first
if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
requestPinCode();
}
// file observer
- Intent observer_intent = new Intent(this, FileObserverService.class);
+ /*Intent observer_intent = new Intent(this, FileObserverService.class);
observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
startService(observer_intent);
+ */
/// USER INTERFACE
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
// Drop-down navigation
mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
OCFile currFile = mCurrentDir;
while(currFile != null && currFile.getFileName() != OCFile.PATH_SEPARATOR) {
mDirectories.add(currFile.getFileName());
currFile = mStorageManager.getFileById(currFile.getParentId());
}
mDirectories.add(OCFile.PATH_SEPARATOR);
// Inflate and set the layout view
setContentView(R.layout.files);
mFileList = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
mDualPane = (findViewById(R.id.file_details_container) != null);
if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
transaction.commit();
}
// Action bar setup
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getParentId() != 0);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(mDirectories, this);
setSupportProgressBarIndeterminateVisibility(false); // always AFTER setContentView(...) ; to workaround bug in its implementation
Log.d(getClass().toString(), "onCreate() end");
}
/**
* Launches the account creation activity. To use when no ownCloud account is available
*/
private void createFirstAccount() {
Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
startActivity(intent); // the new activity won't be created until this.onStart() and this.onResume() are finished;
}
/**
* Load of state dependent of the existence of an ownCloud account
*/
private void initDataFromCurrentAccount() {
/// Storage manager initialization - access to local database
mStorageManager = new FileDataStorageManager(
AccountUtils.getCurrentOwnCloudAccount(this),
getContentResolver());
/// State recovery - CURRENT DIRECTORY ; priority: 1/ getIntent(), 2/ savedInstanceState (in onCreate()), 3/ root dir
if(getIntent().hasExtra(FileDetailFragment.EXTRA_FILE)) {
mCurrentDir = (OCFile) getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
if(mCurrentDir != null && !mCurrentDir.isDirectory()){
mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
}
// clear intent extra, so rotating the screen will not return us to this directory
getIntent().removeExtra(FileDetailFragment.EXTRA_FILE);
}
if (mCurrentDir == null)
mCurrentDir = mStorageManager.getFileByPath("/"); // this will return NULL if the database has not ever synchronized
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSherlock().getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean retval = true;
switch (item.getItemId()) {
case R.id.createDirectoryItem: {
showDialog(DIALOG_CREATE_DIR);
break;
}
case R.id.startSync: {
ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE); // cancel the current synchronizations of any ownCloud account
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(
AccountUtils.getCurrentOwnCloudAccount(this),
AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);
break;
}
case R.id.action_upload: {
showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
break;
}
case R.id.action_settings: {
Intent settingsIntent = new Intent(this, Preferences.class);
startActivity(settingsIntent);
break;
}
case R.id.about_app : {
showDialog(DIALOG_ABOUT_APP);
break;
}
case android.R.id.home: {
if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
onBackPressed();
}
break;
}
default:
retval = false;
}
return retval;
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
int i = itemPosition;
while (i-- != 0) {
onBackPressed();
}
// the next operation triggers a new call to this method, but it's necessary to
// ensure that the name exposed in the action bar is the current directory when the
// user selected it in the navigation list
if (itemPosition != 0)
getSupportActionBar().setSelectedNavigationItem(0);
return true;
}
/**
* Called, when the user selected something for uploading
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && resultCode == RESULT_OK) {
requestSimpleUpload(data);
} else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && resultCode == RESULT_OK) {
requestMultipleUpload(data);
}
}
private void requestMultipleUpload(Intent data) {
String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
if (filePaths != null) {
String[] remotePaths = new String[filePaths.length];
String remotePathBase = "";
for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
}
if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
remotePathBase += OCFile.PATH_SEPARATOR;
for (int j = 0; j< remotePaths.length; j++) {
remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
}
Intent i = new Intent(this, FileUploader.class);
i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
startService(i);
} else {
Log.d("FileDisplay", "User clicked on 'Update' with no selection");
Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
t.show();
return;
}
}
private void requestSimpleUpload(Intent data) {
String filepath = null;
try {
Uri selectedImageUri = data.getData();
String filemanagerstring = selectedImageUri.getPath();
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null)
filepath = selectedImagePath;
else
filepath = filemanagerstring;
} catch (Exception e) {
Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
e.printStackTrace();
} finally {
if (filepath == null) {
Log.e("FileDisplay", "Couldnt resolve path to file");
Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
t.show();
return;
}
}
Intent i = new Intent(this, FileUploader.class);
i.putExtra(FileUploader.KEY_ACCOUNT,
AccountUtils.getCurrentOwnCloudAccount(this));
String remotepath = new String();
for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
}
if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
remotepath += OCFile.PATH_SEPARATOR;
remotepath += new File(filepath).getName();
i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
startService(i);
}
@Override
public void onBackPressed() {
if (mDirectories.getCount() <= 1) {
finish();
return;
}
popDirname();
mFileList.onNavigateUp();
mCurrentDir = mFileList.getCurrentFile();
if (mDualPane) {
// Resets the FileDetailsFragment on Tablets so that it always displays
FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
if (fileDetails != null && !fileDetails.isEmpty()) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.remove(fileDetails);
transaction.add(R.id.file_details_container, new FileDetailFragment(null, null));
transaction.commit();
}
}
if(mCurrentDir.getParentId() == 0){
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
Log.d(getClass().toString(), "onSaveInstanceState() start");
super.onSaveInstanceState(outState);
outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
Log.d(getClass().toString(), "onSaveInstanceState() end");
}
@Override
protected void onResume() {
Log.d(getClass().toString(), "onResume() start");
super.onResume();
if (AccountUtils.accountsAreSetup(this)) {
if (mStorageManager == null) {
// this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
initDataFromCurrentAccount();
}
// Listen for sync messages
IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
mSyncBroadcastReceiver = new SyncBroadcastReceiver();
registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
// Listen for upload messages
IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
mUploadFinishReceiver = new UploadFinishReceiver();
registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
// Listen for download messages
IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
mDownloadFinishReceiver = new DownloadFinishReceiver();
registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
// List current directory
mFileList.listDirectory(mCurrentDir);
} else {
mStorageManager = null; // an invalid object will be there if all the ownCloud accounts are removed
showDialog(DIALOG_SETUP_ACCOUNT);
}
Log.d(getClass().toString(), "onResume() end");
}
@Override
protected void onPause() {
Log.d(getClass().toString(), "onPause() start");
super.onPause();
if (mSyncBroadcastReceiver != null) {
unregisterReceiver(mSyncBroadcastReceiver);
mSyncBroadcastReceiver = null;
}
if (mUploadFinishReceiver != null) {
unregisterReceiver(mUploadFinishReceiver);
mUploadFinishReceiver = null;
}
if (mDownloadFinishReceiver != null) {
unregisterReceiver(mDownloadFinishReceiver);
mDownloadFinishReceiver = null;
}
if (!AccountUtils.accountsAreSetup(this)) {
dismissDialog(DIALOG_SETUP_ACCOUNT);
}
getIntent().putExtra(FileDetailFragment.EXTRA_FILE, mCurrentDir);
Log.d(getClass().toString(), "onPause() end");
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder;
switch (id) {
case DIALOG_SETUP_ACCOUNT: {
builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.main_tit_accsetup);
builder.setMessage(R.string.main_wrn_accsetup);
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
createFirstAccount();
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.common_exit, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
//builder.setNegativeButton(android.R.string.cancel, this);
dialog = builder.create();
break;
}
case DIALOG_ABOUT_APP: {
builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.about_title));
PackageInfo pkg;
try {
pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
builder.setMessage("ownCloud android client\n\nversion: " + pkg.versionName );
builder.setIcon(android.R.drawable.ic_menu_info_details);
dialog = builder.create();
} catch (NameNotFoundException e) {
builder = null;
dialog = null;
Log.e(TAG, "Error while showing about dialog", e);
}
break;
}
case DIALOG_CREATE_DIR: {
builder = new Builder(this);
final EditText dirNameInput = new EditText(getBaseContext());
builder.setView(dirNameInput);
builder.setTitle(R.string.uploader_info_dirname);
int typed_color = getResources().getColor(R.color.setup_text_typed);
dirNameInput.setTextColor(typed_color);
builder.setPositiveButton(android.R.string.ok,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String directoryName = dirNameInput.getText().toString();
if (directoryName.trim().length() == 0) {
dialog.cancel();
return;
}
// Figure out the path where the dir needs to be created
String path;
if (mCurrentDir == null) {
// this is just a patch; we should ensure that mCurrentDir never is null
if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
mStorageManager.saveFile(file);
}
mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
}
path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
// Create directory
path += directoryName + OCFile.PATH_SEPARATOR;
Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
thread.start();
dialog.dismiss();
showDialog(DIALOG_SHORT_WAIT);
}
});
builder.setNegativeButton(R.string.common_cancel,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog = builder.create();
break;
}
case DIALOG_SHORT_WAIT: {
ProgressDialog working_dialog = new ProgressDialog(this);
working_dialog.setMessage(getResources().getString(
R.string.wait_a_moment));
working_dialog.setIndeterminate(true);
working_dialog.setCancelable(false);
dialog = working_dialog;
break;
}
case DIALOG_CHOOSE_UPLOAD_SOURCE: {
final String [] items = { getString(R.string.actionbar_upload_files),
getString(R.string.actionbar_upload_from_apps) };
builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.actionbar_upload);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
//if (!mDualPane) {
Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
//} else {
// TODO create and handle new fragment LocalFileListFragment
//}
} else if (item == 1) {
Intent action = new Intent(Intent.ACTION_GET_CONTENT);
action = action.setType("*/*")
.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(
Intent.createChooser(action, getString(R.string.upload_chooser_title)),
ACTION_SELECT_CONTENT_FROM_APPS);
}
}
});
dialog = builder.create();
break;
}
default:
dialog = null;
}
return dialog;
}
/**
* Translates a content URI of an image to a physical path
* on the disk
* @param uri The URI to resolve
* @return The path to the image or null if it could not be found
*/
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return null;
}
/**
* Pushes a directory to the drop down list
* @param directory to push
* @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
*/
public void pushDirname(OCFile directory) {
if(!directory.isDirectory()){
throw new IllegalArgumentException("Only directories may be pushed!");
}
mDirectories.insert(directory.getFileName(), 0);
mCurrentDir = directory;
}
/**
* Pops a directory name from the drop down list
* @return True, unless the stack is empty
*/
public boolean popDirname() {
mDirectories.remove(mDirectories.getItem(0));
return !mDirectories.isEmpty();
}
private class DirectoryCreator implements Runnable {
private String mTargetPath;
private Account mAccount;
private AccountManager mAm;
private Handler mHandler;
public DirectoryCreator(String targetPath, Account account, Handler handler) {
mTargetPath = targetPath;
mAccount = account;
mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
mHandler = handler;
}
@Override
public void run() {
WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
boolean created = wdc.createDirectory(mTargetPath);
if (created) {
mHandler.post(new Runnable() {
@Override
public void run() {
dismissDialog(DIALOG_SHORT_WAIT);
// Save new directory in local database
OCFile newDir = new OCFile(mTargetPath);
newDir.setMimetype("DIR");
newDir.setParentId(mCurrentDir.getFileId());
mStorageManager.saveFile(newDir);
// Display the new folder right away
mFileList.listDirectory(mCurrentDir);
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
dismissDialog(DIALOG_SHORT_WAIT);
try {
Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
msg.show();
} catch (NotFoundException e) {
Log.e(TAG, "Error while trying to show fail message " , e);
}
}
});
}
}
}
// Custom array adapter to override text colors
private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
super(ctx, view);
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
((TextView) v).setTextColor(getResources().getColorStateList(
android.R.color.white));
return v;
}
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View v = super.getDropDownView(position, convertView, parent);
((TextView) v).setTextColor(getResources().getColorStateList(
android.R.color.white));
return v;
}
}
private class SyncBroadcastReceiver extends BroadcastReceiver {
/**
* {@link BroadcastReceiver} to enable syncing feedback in UI
*/
@Override
public void onReceive(Context context, Intent intent) {
boolean inProgress = intent.getBooleanExtra(
FileSyncService.IN_PROGRESS, false);
String accountName = intent
.getStringExtra(FileSyncService.ACCOUNT_NAME);
Log.d("FileDisplay", "sync of account " + accountName
+ " is in_progress: " + inProgress);
if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
boolean fillBlankRoot = false;
if (mCurrentDir == null) {
mCurrentDir = mStorageManager.getFileByPath("/");
fillBlankRoot = (mCurrentDir != null);
}
if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
|| fillBlankRoot ) {
if (!fillBlankRoot)
mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
.findFragmentById(R.id.fileList);
if (fileListFragment != null) {
fileListFragment.listDirectory(mCurrentDir);
}
}
setSupportProgressBarIndeterminateVisibility(inProgress);
}
}
}
private class UploadFinishReceiver extends BroadcastReceiver {
/**
* Once the file upload has finished -> update view
* @author David A. Velasco
* {@link BroadcastReceiver} to enable upload feedback in UI
*/
@Override
public void onReceive(Context context, Intent intent) {
long parentDirId = intent.getLongExtra(FileUploader.EXTRA_PARENT_DIR_ID, -1);
OCFile parentDir = mStorageManager.getFileById(parentDirId);
String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
parentDir != null &&
( (mCurrentDir == null && parentDir.getFileName().equals("/")) ||
parentDir.equals(mCurrentDir)
)
) {
OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
if (fileListFragment != null) {
fileListFragment.listDirectory();
}
}
}
}
/**
* Once the file download has finished -> update view
*/
private class DownloadFinishReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
mCurrentDir != null && mCurrentDir.getFileId() == mStorageManager.getFileByPath(downloadedRemotePath).getParentId()) {
OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
if (fileListFragment != null) {
fileListFragment.listDirectory();
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public DataStorageManager getStorageManager() {
return mStorageManager;
}
/**
* {@inheritDoc}
*/
@Override
public void onDirectoryClick(OCFile directory) {
pushDirname(directory);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
if (mDualPane) {
// Resets the FileDetailsFragment on Tablets so that it always displays
FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
if (fileDetails != null && !fileDetails.isEmpty()) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.remove(fileDetails);
transaction.add(R.id.file_details_container, new FileDetailFragment(null, null));
transaction.commit();
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void onFileClick(OCFile file) {
// If we are on a large device -> update fragment
if (mDualPane) {
// buttons in the details view are problematic when trying to reuse an existing fragment; create always a new one solves some of them, BUT no all; downloads are 'dangerous'
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
} else { // small or medium screen device -> new Activity
Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
showDetailsIntent.putExtra(FileDownloader.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
startActivity(showDetailsIntent);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onFileStateChanged() {
OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
if (fileListFragment != null) {
fileListFragment.listDirectory();
}
}
/**
* Launch an intent to request the PIN code to the user before letting him use the app
*/
private void requestPinCode() {
boolean pinStart = false;
SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pinStart = appPrefs.getBoolean("set_pincode", false);
if (pinStart) {
Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
startActivity(i);
}
}
}
diff --git a/src/com/owncloud/android/ui/fragment/FileDetailFragment.java b/src/com/owncloud/android/ui/fragment/FileDetailFragment.java
index d251883..4772ddf 100644
--- a/src/com/owncloud/android/ui/fragment/FileDetailFragment.java
+++ b/src/com/owncloud/android/ui/fragment/FileDetailFragment.java
@@ -1,1141 +1,1143 @@
/* ownCloud Android client application
* Copyright (C) 2011 Bartek Przybylski
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.ui.fragment;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.jackrabbit.webdav.client.methods.DavMethodBase;
import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
import org.json.JSONException;
import org.json.JSONObject;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Point;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockFragment;
import com.owncloud.android.AccountUtils;
import com.owncloud.android.DisplayUtils;
import com.owncloud.android.authenticator.AccountAuthenticator;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.files.services.FileDownloader;
import com.owncloud.android.files.services.FileObserverService;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.network.OwnCloudClientUtils;
import com.owncloud.android.ui.activity.FileDetailActivity;
import com.owncloud.android.ui.activity.FileDisplayActivity;
import com.owncloud.android.utils.OwnCloudVersion;
import com.owncloud.android.R;
import eu.alefzero.webdav.WebdavClient;
import eu.alefzero.webdav.WebdavUtils;
/**
* This Fragment is used to display the details about a file.
*
* @author Bartek Przybylski
*
*/
public class FileDetailFragment extends SherlockFragment implements
OnClickListener, ConfirmationDialogFragment.ConfirmationDialogFragmentListener {
public static final String EXTRA_FILE = "FILE";
public static final String EXTRA_ACCOUNT = "ACCOUNT";
private FileDetailFragment.ContainerActivity mContainerActivity;
private int mLayout;
private View mView;
private OCFile mFile;
private Account mAccount;
private ImageView mPreview;
private DownloadFinishReceiver mDownloadFinishReceiver;
private UploadFinishReceiver mUploadFinishReceiver;
private static final String TAG = "FileDetailFragment";
public static final String FTAG = "FileDetails";
public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
/**
* Creates an empty details fragment.
*
* It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
*/
public FileDetailFragment() {
mFile = null;
mAccount = null;
mLayout = R.layout.file_details_empty;
}
/**
* Creates a details fragment.
*
* When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
*
* @param fileToDetail An {@link OCFile} to show in the fragment
* @param ocAccount An ownCloud account; needed to start downloads
*/
public FileDetailFragment(OCFile fileToDetail, Account ocAccount){
mFile = fileToDetail;
mAccount = ocAccount;
mLayout = R.layout.file_details_empty;
if(fileToDetail != null && ocAccount != null) {
mLayout = R.layout.file_details_fragment;
}
}
/**
* {@inheritDoc}
*/
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mContainerActivity = (ContainerActivity) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement FileListFragment.ContainerActivity");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (savedInstanceState != null) {
mFile = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
mAccount = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_ACCOUNT);
}
View view = null;
view = inflater.inflate(mLayout, container, false);
mView = view;
if (mLayout == R.layout.file_details_fragment) {
mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
//mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
}
updateFileDetails();
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
Log.i(getClass().toString(), "onSaveInstanceState() start");
super.onSaveInstanceState(outState);
outState.putParcelable(FileDetailFragment.EXTRA_FILE, mFile);
outState.putParcelable(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
Log.i(getClass().toString(), "onSaveInstanceState() end");
}
@Override
public void onResume() {
super.onResume();
mDownloadFinishReceiver = new DownloadFinishReceiver();
IntentFilter filter = new IntentFilter(
FileDownloader.DOWNLOAD_FINISH_MESSAGE);
getActivity().registerReceiver(mDownloadFinishReceiver, filter);
mUploadFinishReceiver = new UploadFinishReceiver();
filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
getActivity().registerReceiver(mUploadFinishReceiver, filter);
mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
}
@Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(mDownloadFinishReceiver);
mDownloadFinishReceiver = null;
getActivity().unregisterReceiver(mUploadFinishReceiver);
mUploadFinishReceiver = null;
if (mPreview != null) {
mPreview = null;
}
}
@Override
public View getView() {
return super.getView() == null ? mView : super.getView();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fdDownloadBtn: {
Intent i = new Intent(getActivity(), FileDownloader.class);
i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());
i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());
// update ui
setButtonsForTransferring();
getActivity().startService(i);
mContainerActivity.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
break;
}
case R.id.fdKeepInSync: {
CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
mFile.setKeepInSync(cb.isChecked());
FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
fdsm.saveFile(mFile);
if (mFile.keepInSync()) {
onClick(getView().findViewById(R.id.fdDownloadBtn));
} else {
mContainerActivity.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
}
+ /*
Intent intent = new Intent(getActivity().getApplicationContext(),
FileObserverService.class);
intent.putExtra(FileObserverService.KEY_FILE_CMD,
(cb.isChecked()?
FileObserverService.CMD_ADD_OBSERVED_FILE:
FileObserverService.CMD_DEL_OBSERVED_FILE));
intent.putExtra(FileObserverService.KEY_CMD_ARG, mFile.getStoragePath());
getActivity().startService(intent);
+ */
break;
}
case R.id.fdRenameBtn: {
EditNameFragment dialog = EditNameFragment.newInstance(mFile.getFileName());
dialog.show(getFragmentManager(), "nameeditdialog");
dialog.setOnDismissListener(this);
break;
}
case R.id.fdRemoveBtn: {
ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
R.string.confirmation_remove_alert,
new String[]{mFile.getFileName()},
mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
mFile.isDown() ? R.string.confirmation_remove_local : -1,
R.string.common_cancel);
confDialog.setOnConfirmationListener(this);
confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
break;
}
case R.id.fdOpenBtn: {
String storagePath = mFile.getStoragePath();
String encodedStoragePath = WebdavUtils.encodePath(storagePath);
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(i);
} catch (Throwable t) {
Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
boolean toastIt = true;
String mimeType = "";
try {
Intent i = new Intent(Intent.ACTION_VIEW);
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(i);
toastIt = false;
}
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
} catch (Throwable th) {
Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
} finally {
if (toastIt) {
Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
}
}
}
break;
}
default:
Log.e(TAG, "Incorrect view clicked!");
}
/* else if (v.getId() == R.id.fdShareBtn) {
Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
t.start();
}*/
}
@Override
public void onConfirmation(String callerTag) {
if (callerTag.equals(FTAG_CONFIRMATION)) {
FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
if (fdsm.getFileById(mFile.getFileId()) != null) {
new Thread(new RemoveRunnable(mFile, mAccount, new Handler())).start();
boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
}
}
}
@Override
public void onNeutral(String callerTag) {
FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
File f = null;
if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
f.delete();
mFile.setStoragePath(null);
fdsm.saveFile(mFile);
updateFileDetails(mFile, mAccount);
}
}
@Override
public void onCancel(String callerTag) {
Log.d(TAG, "REMOVAL CANCELED");
}
/**
* Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
*
* @return True when the fragment was created with the empty layout.
*/
public boolean isEmpty() {
return mLayout == R.layout.file_details_empty;
}
/**
* Can be used to get the file that is currently being displayed.
* @return The file on the screen.
*/
public OCFile getDisplayedFile(){
return mFile;
}
/**
* Use this method to signal this Activity that it shall update its view.
*
* @param file : An {@link OCFile}
*/
public void updateFileDetails(OCFile file, Account ocAccount) {
mFile = file;
mAccount = ocAccount;
updateFileDetails();
}
/**
* Updates the view with all relevant details about that file.
*/
public void updateFileDetails() {
if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {
// set file details
setFilename(mFile.getFileName());
setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile
.getMimetype()));
setFilesize(mFile.getFileLength());
if(ocVersionSupportsTimeCreated()){
setTimeCreated(mFile.getCreationTimestamp());
}
setTimeModified(mFile.getModificationTimestamp());
CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
cb.setChecked(mFile.keepInSync());
// configure UI for depending upon local state of the file
if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
setButtonsForTransferring();
} else if (mFile.isDown()) {
// Update preview
if (mFile.getMimetype().startsWith("image/")) {
BitmapLoader bl = new BitmapLoader();
bl.execute(new String[]{mFile.getStoragePath()});
}
setButtonsForDown();
} else {
setButtonsForRemote();
}
}
}
/**
* Updates the filename in view
* @param filename to set
*/
private void setFilename(String filename) {
TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
if (tv != null)
tv.setText(filename);
}
/**
* Updates the MIME type in view
* @param mimetype to set
*/
private void setFiletype(String mimetype) {
TextView tv = (TextView) getView().findViewById(R.id.fdType);
if (tv != null)
tv.setText(mimetype);
}
/**
* Updates the file size in view
* @param filesize in bytes to set
*/
private void setFilesize(long filesize) {
TextView tv = (TextView) getView().findViewById(R.id.fdSize);
if (tv != null)
tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
}
/**
* Updates the time that the file was created in view
* @param milliseconds Unix time to set
*/
private void setTimeCreated(long milliseconds){
TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
if(tv != null){
tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
tv.setVisibility(View.VISIBLE);
tvLabel.setVisibility(View.VISIBLE);
}
}
/**
* Updates the time that the file was last modified
* @param milliseconds Unix time to set
*/
private void setTimeModified(long milliseconds){
TextView tv = (TextView) getView().findViewById(R.id.fdModified);
if(tv != null){
tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
}
}
/**
* Enables or disables buttons for a file being downloaded
*/
private void setButtonsForTransferring() {
if (!isEmpty()) {
Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
//downloadButton.setText(R.string.filedetails_download_in_progress); // ugly
downloadButton.setEnabled(false); // TODO replace it with a 'cancel download' button
// let's protect the user from himself ;)
((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);
((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);
}
}
/**
* Enables or disables buttons for a file locally available
*/
private void setButtonsForDown() {
if (!isEmpty()) {
Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
//downloadButton.setText(R.string.filedetails_redownload); // ugly
downloadButton.setEnabled(true);
((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);
((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
}
}
/**
* Enables or disables buttons for a file not locally available
*/
private void setButtonsForRemote() {
if (!isEmpty()) {
Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
//downloadButton.setText(R.string.filedetails_download); // unnecessary
downloadButton.setEnabled(true);
((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
}
}
/**
* In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
* the time that the file was created. There is a chance that this will
* be fixed in future versions. Use this method to check if this version of
* ownCloud has this fix.
* @return True, if ownCloud the ownCloud version is supporting creation time
*/
private boolean ocVersionSupportsTimeCreated(){
/*if(mAccount != null){
AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
return true;
}
}*/
return false;
}
/**
* Interface to implement by any Activity that includes some instance of FileDetailFragment
*
* @author David A. Velasco
*/
public interface ContainerActivity {
/**
* Callback method invoked when the detail fragment wants to notice its container
* activity about a relevant state the file shown by the fragment.
*
* Added to notify to FileDisplayActivity about the need of refresh the files list.
*
* Currently called when:
* - a download is started;
* - a rename is completed;
* - a deletion is completed;
* - the 'inSync' flag is changed;
*/
public void onFileStateChanged();
}
/**
* Once the file download has finished -> update view
* @author Bartek Przybylski
*/
private class DownloadFinishReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
if (!isEmpty() && accountName.equals(mAccount.name)) {
boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
if (mFile.getRemotePath().equals(downloadedRemotePath)) {
if (downloadWasFine) {
mFile.setStoragePath(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH)); // updates the local object without accessing the database again
}
updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
}
}
}
}
/**
* Once the file upload has finished -> update view
*
* Being notified about the finish of an upload is necessary for the next sequence:
* 1. Upload a big file.
* 2. Force a synchronization; if it finished before the upload, the file in transfer will be included in the local database and in the file list
* of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
* 3. Click the file in the list to see its details.
* 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
*/
private class UploadFinishReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
if (!isEmpty() && accountName.equals(mAccount.name)) {
boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
if (mFile.getRemotePath().equals(uploadRemotePath)) {
if (uploadWasFine) {
FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
mFile = fdsm.getFileByPath(mFile.getRemotePath());
}
updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
}
}
}
}
// this is a temporary class for sharing purposes, it need to be replaced in transfer service
private class ShareRunnable implements Runnable {
private String mPath;
public ShareRunnable(String path) {
mPath = path;
}
public void run() {
AccountManager am = AccountManager.get(getActivity());
Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
Log.d("share", "sharing for version " + ocv.toString());
if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
String APPS_PATH = "/apps/files_sharing/";
String SHARE_PATH = "ajax/share.php";
String SHARED_PATH = "/apps/files_sharing/get.php?token=";
final String WEBDAV_SCRIPT = "webdav.php";
final String WEBDAV_FILES_LOCATION = "/files/";
WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
//wc.getParams().setParameter("http.protocol.single-cookie-header", true);
//wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
Log.d("share", mPath+"");
formparams.add(new BasicNameValuePair("sources",mPath));
formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
formparams.add(new BasicNameValuePair("permissions", "0"));
post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
int status;
try {
PropFindMethod find = new PropFindMethod(url+"/");
find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
Log.d("sharer", ""+ url+"/");
for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
Log.d("sharer-h", a.getName() + ":"+a.getValue());
}
int status2 = wc.executeMethod(find);
Log.d("sharer", "propstatus "+status2);
GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
status2 = wc.executeMethod(get);
Log.d("sharer", "getstatus "+status2);
Log.d("sharer", "" + get.getResponseBodyAsString());
for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
Log.d("sharer", a.getName() + ":"+a.getValue());
}
status = wc.executeMethod(post);
for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
Log.d("sharer-h", a.getName() + ":"+a.getValue());
}
for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
Log.d("sharer", a.getName() + ":"+a.getValue());
}
String resp = post.getResponseBodyAsString();
Log.d("share", ""+post.getURI().toString());
Log.d("share", "returned status " + status);
Log.d("share", " " +resp);
if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
return;
}
JSONObject jsonObject = new JSONObject (resp);
String jsonStatus = jsonObject.getString("status");
if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
String token = jsonObject.getString("data");
String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
Log.d("Actions:shareFile ok", "url: " + uri);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
}
}
}
public void onDismiss(EditNameFragment dialog) {
if (dialog instanceof EditNameFragment) {
if (((EditNameFragment)dialog).getResult()) {
String newFilename = ((EditNameFragment)dialog).getNewFilename();
Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
if (!newFilename.equals(mFile.getFileName())) {
FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
if (fdsm.getFileById(mFile.getFileId()) != null) {
OCFile newFile = new OCFile(fdsm.getFileById(mFile.getParentId()).getRemotePath() + newFilename);
newFile.setCreationTimestamp(mFile.getCreationTimestamp());
newFile.setFileId(mFile.getFileId());
newFile.setFileLength(mFile.getFileLength());
newFile.setKeepInSync(mFile.keepInSync());
newFile.setLastSyncDate(mFile.getLastSyncDate());
newFile.setMimetype(mFile.getMimetype());
newFile.setModificationTimestamp(mFile.getModificationTimestamp());
newFile.setParentId(mFile.getParentId());
boolean localRenameFails = false;
if (mFile.isDown()) {
File f = new File(mFile.getStoragePath());
Log.e(TAG, f.getAbsolutePath());
localRenameFails = !(f.renameTo(new File(f.getParent() + File.separator + newFilename)));
Log.e(TAG, f.getParent() + File.separator + newFilename);
newFile.setStoragePath(f.getParent() + File.separator + newFilename);
}
if (localRenameFails) {
Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
msg.show();
} else {
new Thread(new RenameRunnable(mFile, newFile, mAccount, new Handler())).start();
boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
}
}
}
}
} else {
Log.e(TAG, "Unknown dialog instance passed to onDismissDalog: " + dialog.getClass().getCanonicalName());
}
}
private class RenameRunnable implements Runnable {
Account mAccount;
OCFile mOld, mNew;
Handler mHandler;
public RenameRunnable(OCFile oldFile, OCFile newFile, Account account, Handler handler) {
mOld = oldFile;
mNew = newFile;
mAccount = account;
mHandler = handler;
}
public void run() {
WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
AccountManager am = AccountManager.get(getSherlockActivity());
String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
String webdav_path = AccountUtils.getWebdavPath(ocv);
Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()));
Log.e("ASD", Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));
LocalMoveMethod move = new LocalMoveMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()),
Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));
boolean success = false;
try {
int status = wc.executeMethod(move);
success = move.succeeded();
move.getResponseBodyAsString(); // exhaust response, although not interesting
Log.d(TAG, "Move returned status: " + status);
} catch (HttpException e) {
Log.e(TAG, "HTTP Exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(), e);
} catch (IOException e) {
Log.e(TAG, "I/O Exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(), e);
} catch (Exception e) {
Log.e(TAG, "Unexpected exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(), e);
} finally {
move.releaseConnection();
}
if (success) {
FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
fdsm.removeFile(mOld, false);
fdsm.saveFile(mNew);
mFile = mNew;
mHandler.post(new Runnable() {
@Override
public void run() {
boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
updateFileDetails(mFile, mAccount);
mContainerActivity.onFileStateChanged();
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
// undo the local rename
if (mNew.isDown()) {
File f = new File(mNew.getStoragePath());
if (!f.renameTo(new File(mOld.getStoragePath()))) {
// the local rename undoing failed; last chance: save the new local storage path in the old file
mFile.setStoragePath(mNew.getStoragePath());
FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
fdsm.saveFile(mFile);
}
}
boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
try {
Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
msg.show();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
});
}
}
private class LocalMoveMethod extends DavMethodBase {
public LocalMoveMethod(String uri, String dest) {
super(uri);
addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest));
}
@Override
public String getName() {
return "MOVE";
}
@Override
protected boolean isSuccess(int status) {
return status == 201 || status == 204;
}
}
}
private static class EditNameFragment extends SherlockDialogFragment implements OnClickListener {
private String mNewFilename;
private boolean mResult;
private FileDetailFragment mListener;
static public EditNameFragment newInstance(String filename) {
EditNameFragment f = new EditNameFragment();
Bundle args = new Bundle();
args.putString("filename", filename);
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.edit_box_dialog, container, false);
String currentName = getArguments().getString("filename");
if (currentName == null)
currentName = "";
((Button)v.findViewById(R.id.cancel)).setOnClickListener(this);
((Button)v.findViewById(R.id.ok)).setOnClickListener(this);
((TextView)v.findViewById(R.id.user_input)).setText(currentName);
((TextView)v.findViewById(R.id.user_input)).requestFocus();
getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
mResult = false;
return v;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.ok: {
mNewFilename = ((TextView)getView().findViewById(R.id.user_input)).getText().toString();
mResult = true;
}
case R.id.cancel: { // fallthought
dismiss();
mListener.onDismiss(this);
}
}
}
void setOnDismissListener(FileDetailFragment listener) {
mListener = listener;
}
public String getNewFilename() {
return mNewFilename;
}
// true if user click ok
public boolean getResult() {
return mResult;
}
}
private class RemoveRunnable implements Runnable {
Account mAccount;
OCFile mFileToRemove;
Handler mHandler;
public RemoveRunnable(OCFile fileToRemove, Account account, Handler handler) {
mFileToRemove = fileToRemove;
mAccount = account;
mHandler = handler;
}
public void run() {
WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
AccountManager am = AccountManager.get(getSherlockActivity());
String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
String webdav_path = AccountUtils.getWebdavPath(ocv);
Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));
DeleteMethod delete = new DeleteMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));
boolean success = false;
int status = -1;
try {
status = wc.executeMethod(delete);
success = (delete.succeeded());
delete.getResponseBodyAsString(); // exhaust the response, although not interesting
Log.d(TAG, "Delete: returned status " + status);
} catch (HttpException e) {
Log.e(TAG, "HTTP Exception removing file " + mFileToRemove.getRemotePath(), e);
} catch (IOException e) {
Log.e(TAG, "I/O Exception removing file " + mFileToRemove.getRemotePath(), e);
} catch (Exception e) {
Log.e(TAG, "Unexpected exception removing file " + mFileToRemove.getRemotePath(), e);
} finally {
delete.releaseConnection();
}
if (success) {
FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
fdsm.removeFile(mFileToRemove, true);
mHandler.post(new Runnable() {
@Override
public void run() {
boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
try {
Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
msg.show();
if (inDisplayActivity) {
// double pane
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
transaction.commit();
mContainerActivity.onFileStateChanged();
} else {
getActivity().finish();
}
} catch (NotFoundException e) {
e.printStackTrace();
}
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
try {
Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
msg.show();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
});
}
}
}
class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
@SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
@Override
protected Bitmap doInBackground(String... params) {
Bitmap result = null;
if (params.length != 1) return result;
String storagePath = params[0];
try {
BitmapFactory.Options options = new Options();
options.inScaled = true;
options.inPurgeable = true;
options.inJustDecodeBounds = true;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
options.inPreferQualityOverSpeed = false;
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
options.inMutable = false;
}
result = BitmapFactory.decodeFile(storagePath, options);
options.inJustDecodeBounds = false;
int width = options.outWidth;
int height = options.outHeight;
int scale = 1;
if (width >= 2048 || height >= 2048) {
scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
options.inSampleSize = scale;
}
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
int screenwidth;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
display.getSize(size);
screenwidth = size.x;
} else {
screenwidth = display.getWidth();
}
Log.e("ASD", "W " + width + " SW " + screenwidth);
if (width > screenwidth) {
scale = (int) Math.ceil((float)width / screenwidth);
options.inSampleSize = scale;
}
result = BitmapFactory.decodeFile(storagePath, options);
Log.e("ASD", "W " + options.outWidth + " SW " + options.outHeight);
} catch (OutOfMemoryError e) {
result = null;
Log.e(TAG, "Out of memory occured for file with size " + storagePath);
} catch (NoSuchFieldError e) {
result = null;
Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);
} catch (Throwable t) {
result = null;
Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);
}
return result;
}
@Override
protected void onPostExecute(Bitmap result) {
if (result != null && mPreview != null) {
mPreview.setImageBitmap(result);
}
}
}
}
| false | false | null | null |
diff --git a/client/web/src/test/java/org/sagebionetworks/web/client/GwtTestSuite.java b/client/web/src/test/java/org/sagebionetworks/web/client/GwtTestSuite.java
index f290fc2f9..db29ee7b1 100644
--- a/client/web/src/test/java/org/sagebionetworks/web/client/GwtTestSuite.java
+++ b/client/web/src/test/java/org/sagebionetworks/web/client/GwtTestSuite.java
@@ -1,220 +1,224 @@
package org.sagebionetworks.web.client;
import java.util.Date;
import java.util.Map;
import org.junit.Test;
import org.sagebionetworks.gwt.client.schema.adapter.JSONObjectGwt;
import org.sagebionetworks.repo.model.Agreement;
import org.sagebionetworks.repo.model.Analysis;
import org.sagebionetworks.repo.model.Dataset;
import org.sagebionetworks.repo.model.Eula;
import org.sagebionetworks.repo.model.Layer;
import org.sagebionetworks.repo.model.Project;
import org.sagebionetworks.repo.model.Step;
import org.sagebionetworks.schema.FORMAT;
import org.sagebionetworks.schema.ObjectSchema;
import org.sagebionetworks.schema.TYPE;
import org.sagebionetworks.schema.adapter.JSONEntity;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.transform.NodeModelCreatorImpl;
import org.sagebionetworks.web.shared.exceptions.RestServiceException;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Since the GWT test are so slow to start and we could not get the GWTTestSuite to work,
* we put all GWT tests in one class.
* @author jmhill
*
*/
public class GwtTestSuite extends GWTTestCase {
/**
* Must refer to a valid module that sources this class.
*/
public String getModuleName() {
return "org.sagebionetworks.web.Portal";
}
@Override
public void gwtSetUp() {
// Create a dataset with all fields filled in
}
@Test
public void testNodeModelCreatorImpl_createDataset() throws JSONObjectAdapterException, RestServiceException{
Dataset populatedDataset = new Dataset();
initilaizedJSONEntityFromSchema(populatedDataset);
assertNotNull(populatedDataset);
// Get the JSON for the populate dataset
JSONObjectAdapter adapter = populatedDataset.writeToJSONObject(JSONObjectGwt.createNewAdapter());
String json = adapter.toJSONString();
assertNotNull(json);
// Use the factor to create a clone
NodeModelCreatorImpl modelCreator = new NodeModelCreatorImpl(null,null); // jsonadapter and entitytypeprovider not needed for this deprecated model creation
Dataset clone = modelCreator.createDataset(json);
assertNotNull(clone);
assertEquals(populatedDataset, clone);
}
@Test
public void testNodeModelCreatorImpl_createLayer() throws JSONObjectAdapterException, RestServiceException{
Layer populatedLayer = new Layer();
initilaizedJSONEntityFromSchema(populatedLayer);
assertNotNull(populatedLayer);
// Get the JSON for the populate dataset
JSONObjectAdapter adapter = populatedLayer.writeToJSONObject(JSONObjectGwt.createNewAdapter());
String json = adapter.toJSONString();
assertNotNull(json);
// Use the factor to create a clone
NodeModelCreatorImpl modelCreator = new NodeModelCreatorImpl(null,null); // jsonadapter and entitytypeprovider not needed for this deprecated model creation
Layer clone = modelCreator.createLayer(json);
assertNotNull(clone);
assertEquals(populatedLayer, clone);
}
@Test
public void testNodeModelCreatorImpl_createProject() throws JSONObjectAdapterException, RestServiceException{
Project populatedProject = new Project();
initilaizedJSONEntityFromSchema(populatedProject);
assertNotNull(populatedProject);
// Get the JSON for the populate dataset
JSONObjectAdapter adapter = populatedProject.writeToJSONObject(JSONObjectGwt.createNewAdapter());
String json = adapter.toJSONString();
assertNotNull(json);
// Use the factor to create a clone
NodeModelCreatorImpl modelCreator = new NodeModelCreatorImpl(null,null); // jsonadapter and entitytypeprovider not needed for this deprecated model creation
Project clone = modelCreator.createProject(json);
assertNotNull(clone);
assertEquals(populatedProject, clone);
}
@Test
public void testNodeModelCreatorImpl_createEULA() throws JSONObjectAdapterException, RestServiceException{
Eula populatedEula = new Eula();
initilaizedJSONEntityFromSchema(populatedEula);
assertNotNull(populatedEula);
// Get the JSON for the populate dataset
JSONObjectAdapter adapter = populatedEula.writeToJSONObject(JSONObjectGwt.createNewAdapter());
String json = adapter.toJSONString();
assertNotNull(json);
// Use the factor to create a clone
NodeModelCreatorImpl modelCreator = new NodeModelCreatorImpl(null,null); // jsonadapter and entitytypeprovider not needed for this deprecated model creation
Eula clone = modelCreator.createEULA(json);
assertNotNull(clone);
assertEquals(populatedEula, clone);
}
@Test
public void testNodeModelCreatorImpl_Agreement() throws JSONObjectAdapterException, RestServiceException{
Agreement populatedAgreement = new Agreement();
initilaizedJSONEntityFromSchema(populatedAgreement);
assertNotNull(populatedAgreement);
// Get the JSON for the populate dataset
JSONObjectAdapter adapter = populatedAgreement.writeToJSONObject(JSONObjectGwt.createNewAdapter());
String json = adapter.toJSONString();
assertNotNull(json);
// Use the factor to create a clone
NodeModelCreatorImpl modelCreator = new NodeModelCreatorImpl(null,null); // jsonadapter and entitytypeprovider not needed for this deprecated model creation
Agreement clone = modelCreator.createAgreement(json);
assertNotNull(clone);
assertEquals(populatedAgreement, clone);
// Make sure we can go back to json
String jsonClone = modelCreator.createAgreementJSON(clone);
assertEquals(json, jsonClone);
}
@Test
public void testNodeModelCreatorImpl_createAnalysis() throws JSONObjectAdapterException, RestServiceException{
Analysis populatedAnalysis = new Analysis();
initilaizedJSONEntityFromSchema(populatedAnalysis);
assertNotNull(populatedAnalysis);
// Get the JSON for the populate dataset
JSONObjectAdapter adapter = populatedAnalysis.writeToJSONObject(JSONObjectGwt.createNewAdapter());
String json = adapter.toJSONString();
assertNotNull(json);
// Use the factor to create a clone
NodeModelCreatorImpl modelCreator = new NodeModelCreatorImpl(null,null); // jsonadapter and entitytypeprovider not needed for this deprecated model creation
Analysis clone = modelCreator.createAnalysis(json);
assertNotNull(clone);
assertEquals(populatedAnalysis, clone);
}
@Test
public void testNodeModelCreatorImpl_createStep() throws JSONObjectAdapterException, RestServiceException{
Step populatedStep = new Step();
initilaizedJSONEntityFromSchema(populatedStep);
assertNotNull(populatedStep);
// Get the JSON for the populate dataset
JSONObjectAdapter adapter = populatedStep.writeToJSONObject(JSONObjectGwt.createNewAdapter());
String json = adapter.toJSONString();
assertNotNull(json);
// Use the factor to create a clone
NodeModelCreatorImpl modelCreator = new NodeModelCreatorImpl(null,null); // jsonadapter and entitytypeprovider not needed for this deprecated model creation
Step clone = modelCreator.createStep(json);
assertNotNull(clone);
assertEquals(populatedStep, clone);
}
/**
* Populate a given entity using all of the fields from the schema.
* @param toPopulate
* @throws JSONObjectAdapterException
*/
private void initilaizedJSONEntityFromSchema(JSONEntity toPopulate) throws JSONObjectAdapterException{
JSONObjectAdapter adapter = JSONObjectGwt.createNewAdapter().createNew(toPopulate.getJSONSchema());
ObjectSchema schema = new ObjectSchema(adapter);
// This adapter will be used to populate the entity
JSONObjectAdapter adapterToPopulate = JSONObjectGwt.createNewAdapter();
Map<String, ObjectSchema> properteis = schema.getProperties();
assertNotNull(properteis);
int index = 0;
for(String propertyName: properteis.keySet()){
ObjectSchema propertySchema = properteis.get(propertyName);
if(TYPE.STRING == propertySchema.getType()){
// This could be a date or an enumeration.
String value = "StringValue for "+propertyName;
if(propertySchema.getFormat() == null && propertySchema.getEnum() == null){
// This is just a normal string
value = "StringValue for "+propertyName;
}else if(FORMAT.DATE_TIME == propertySchema.getFormat()){
value = adapter.convertDateToString(FORMAT.DATE_TIME, new Date());
}else if(propertySchema.getEnum() != null){
int enumIndex = propertySchema.getEnum().length % index;
value = propertySchema.getEnum()[enumIndex];
}else{
if(propertySchema.isRequired()){
throw new IllegalArgumentException("Unknown FORMAT: "+propertySchema.getFormat()+" for required property");
}
}
// Set the string value
adapterToPopulate.put(propertyName, value);
}else if(TYPE.BOOLEAN == propertySchema.getType()){
Boolean value = index % 2 == 0;
adapterToPopulate.put(propertyName, value);
}else if(TYPE.INTEGER == propertySchema.getType()){
Long value = new Long(123+index);
adapterToPopulate.put(propertyName, value);
}else if(TYPE.NUMBER == propertySchema.getType()){
Double value = new Double(456.0909+index);
adapterToPopulate.put(propertyName, value);
}else{
if(propertySchema.isRequired()){
throw new IllegalArgumentException("Unknown type:"+propertySchema.getType()+" for required property");
}
}
index++;
}
// Now populate it with data
toPopulate.initializeFromJSONObject(adapterToPopulate);
}
+
+ public void testCreateAdapter(){
+ JSONObjectGwt adapter = new JSONObjectGwt();
+ }
@Override
public String toString() {
return "GwtTestSuite for Module: "+getModuleName();
}
}
| true | false | null | null |
diff --git a/plugins/org.eclipse.m2m.atl.emftvm.launcher/src/org/eclipse/m2m/atl/emftvm/launcher/debug/LocalObjectReference.java b/plugins/org.eclipse.m2m.atl.emftvm.launcher/src/org/eclipse/m2m/atl/emftvm/launcher/debug/LocalObjectReference.java
index 7d400f1c..9813f2bb 100644
--- a/plugins/org.eclipse.m2m.atl.emftvm.launcher/src/org/eclipse/m2m/atl/emftvm/launcher/debug/LocalObjectReference.java
+++ b/plugins/org.eclipse.m2m.atl.emftvm.launcher/src/org/eclipse/m2m/atl/emftvm/launcher/debug/LocalObjectReference.java
@@ -1,309 +1,312 @@
/*******************************************************************************
* Copyright (c) 2004 INRIA.
* Copyright (c) 2011 Vrije Universiteit Brussel.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Frederic Jouault (INRIA) - initial API and implementation
* Dennis Wagelaar, Vrije Universiteit Brussel
*******************************************************************************/
package org.eclipse.m2m.atl.emftvm.launcher.debug;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.m2m.atl.common.ATLLogger;
import org.eclipse.m2m.atl.debug.core.adwp.ADWP;
import org.eclipse.m2m.atl.debug.core.adwp.BooleanValue;
import org.eclipse.m2m.atl.debug.core.adwp.IntegerValue;
import org.eclipse.m2m.atl.debug.core.adwp.NullValue;
import org.eclipse.m2m.atl.debug.core.adwp.ObjectReference;
import org.eclipse.m2m.atl.debug.core.adwp.RealValue;
import org.eclipse.m2m.atl.debug.core.adwp.StringValue;
import org.eclipse.m2m.atl.debug.core.adwp.Value;
import org.eclipse.m2m.atl.emftvm.CodeBlock;
+import org.eclipse.m2m.atl.emftvm.EmftvmFactory;
import org.eclipse.m2m.atl.emftvm.ExecEnv;
import org.eclipse.m2m.atl.emftvm.Field;
import org.eclipse.m2m.atl.emftvm.Operation;
import org.eclipse.m2m.atl.emftvm.launcher.EmftvmLauncherPlugin;
import org.eclipse.m2m.atl.emftvm.util.EMFTVMUtil;
import org.eclipse.m2m.atl.emftvm.util.StackFrame;
import org.eclipse.m2m.atl.emftvm.util.VMException;
/**
* The local implementation of an object reference.
* Adapted from org.eclipse.m2m.atl.engine.emfvm.launch.debug.LocalObjectReference.
* @author <a href="mailto:[email protected]">Dennis Wagelaar</a>
* @author <a href="mailto:[email protected]">Frederic Jouault</a>
*/
public class LocalObjectReference extends ObjectReference {
+ private static final CodeBlock EMPTY_CB = EmftvmFactory.eINSTANCE.createCodeBlock();
+
private static Map<List<Object>, ObjectReference> values = new HashMap<List<Object>, ObjectReference>();
private static Map<Integer, ObjectReference> valuesById = new HashMap<Integer, ObjectReference>();
private static int idGenerator;
protected Object object;
protected NetworkDebugger debugger;
/**
* Creates a new LocalObjectReference.
*
* @param object
* the object
* @param id
* the objecct id
* @param debugger
* the debugger
*/
protected LocalObjectReference(Object object, int id, NetworkDebugger debugger) {
super(id);
this.object = object;
this.debugger = debugger;
}
public Object getObject() {
return object;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.debug.core.adwp.ObjectReference#toString()
*/
@Override
public String toString() {
return object.toString();
}
/**
* Returns the object reference matching the given id.
*
* @param objectId
* the object id
* @return the object reference matching the given id
*/
public static ObjectReference valueOf(int objectId) {
Integer id = Integer.valueOf(objectId);
ObjectReference ret = valuesById.get(id);
assert ret != null;
return ret;
}
/**
* Returns an object reference for the given object.
*
* @param object
* the object
* @param debugger
* the current debugger
* @return the object reference
*/
public static ObjectReference valueOf(Object object, NetworkDebugger debugger) {
final List<Object> key = new ArrayList<Object>();
key.add(object);
key.add(debugger);
ObjectReference ret = values.get(key);
if (ret == null) {
int id = idGenerator++;
ret = new LocalObjectReference(object, id, debugger);
values.put(key, ret);
valuesById.put(Integer.valueOf(id), ret);
}
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.debug.core.adwp.ObjectReference#get(java.lang.String)
*/
@Override
public Value get(final String propName) {
Value ret = null;
final StackFrame frame = debugger.getLastFrame();
final ExecEnv env = debugger.getExecEnv();
try {
final Object type = getType();
final Field field = env.findField(type, propName);
if (field != null) {
ret = object2value(field.getValue(object, frame));
} else if (object instanceof EObject) {
assert type instanceof EClass;
final EStructuralFeature sf = ((EClass)type).getEStructuralFeature(propName);
if (sf != null) {
ret = object2value(EMFTVMUtil.uncheckedGet(env, (EObject)object, sf));
}
}
} catch (Exception e) {
EmftvmLauncherPlugin.log(e);
}
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.debug.core.adwp.ObjectReference#set(java.lang.String,
* org.eclipse.m2m.atl.debug.core.adwp.Value)
*/
@Override
public void set(final String propName, final Value value) {
final ExecEnv env = debugger.getExecEnv();
final Object realValue = value2object(value);
final Object type = getType();
final Field field = env.findField(type, propName);
if (field != null) {
field.setValue(object, realValue);
} else if (object instanceof EObject) {
assert type instanceof EClass;
final EStructuralFeature sf = ((EClass)type).getEStructuralFeature(propName);
if (sf != null) {
EMFTVMUtil.set(env, (EObject)object, sf, realValue);
}
}
}
/**
* Converts <code>value</code> to a regular object.
* @param value the {@link org.eclipse.m2m.atl.debug.core.adwp.ADWP} value to convert
* @return the regular object
*/
private Object value2object(Value value) {
Object ret = null;
if (value instanceof LocalObjectReference) {
ret = ((LocalObjectReference)value).object;
} else if (value instanceof StringValue) {
ret = ((StringValue)value).getValue();
} else if (value instanceof IntegerValue) {
ret = ((IntegerValue)value).getValue();
} else if (value instanceof RealValue) {
ret = ((RealValue)value).getValue();
} else if (value instanceof BooleanValue) {
ret = ((BooleanValue)value).getValue();
}
return ret;
}
/**
* Returns the type of this object.
* @return the type
*/
private Object getType() {
if (object instanceof EObject) {
return ((EObject)object).eClass();
}
return object == null ? Void.TYPE : object.getClass();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.debug.core.adwp.ObjectReference#call(java.lang.String, java.util.List)
*/
@Override
public Value call(String opName, List<Value> args) {
final boolean debug = false;
final ExecEnv execEnv = debugger.getExecEnv();
Value ret = null;
final Object type = getType();
final Object[] realArgs = getRealArgs(args);
final EList<Object> argTypes = EMFTVMUtil.getArgumentTypes(realArgs);
final Operation op = execEnv.findOperation(type, opName, argTypes);
if (op == null) {
try {
- final StackFrame frame = new StackFrame(execEnv, null);
+ final StackFrame frame = new StackFrame(execEnv, EMPTY_CB);
ret = object2value(EMFTVMUtil.invokeNative(frame, object, opName, realArgs));
} catch (VMException e) {
ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
} catch (UnsupportedOperationException e) {
ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
} else {
if (debug) {
ATLLogger.info(object + " : " + type + "." + opName + "("); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
for (Iterator<Value> i = args.iterator(); i.hasNext();) {
Value v = i.next();
ATLLogger.info(v + ((i.hasNext()) ? ", " : "")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
final CodeBlock body = op.getBody();
final StackFrame frame = new StackFrame(execEnv, body);
frame.setLocals(object, realArgs);
final Object o = body.execute(frame);
ret = object2value(o);
if (debug) {
ATLLogger.info(") = " + o); //$NON-NLS-1$
ATLLogger.info(" => " + ret); //$NON-NLS-1$
}
}
return ret;
}
/**
* Returns the real arguments wrapped as {@link Value}s inside the given <code>args</code>.
* @param args the wrapped arguments
* @return the real arguments
*/
private Object[] getRealArgs(List<Value> args) {
final Object[] realArgs = new Object[args.size()];
for (int i = 0; i < realArgs.length; i++) {
realArgs[i] = value2object(args.get(i));
}
return realArgs;
}
/**
* Converts a regular object into an {@link ADWP} value.
* @param o the regular object to convert
* @return the {@link ADWP} value
*/
private Value object2value(Object o) {
return object2value(o, debugger);
}
/**
* Converts an Object into a {@link Value}.
*
* @param o
* the object
* @param debugger
* the current debugger
* @return the {@link Value}
*/
public static Value object2value(Object o, NetworkDebugger debugger) {
Value ret = null;
if (o instanceof String) {
ret = StringValue.valueOf((String)o);
} else if (o instanceof Integer) {
ret = IntegerValue.valueOf((Integer)o);
} else if (o instanceof Double) {
ret = RealValue.valueOf((Double)o);
} else if (o instanceof Boolean) {
ret = BooleanValue.valueOf((Boolean)o);
} else if (o == null) {
ret = new NullValue();
} else {
ret = valueOf(o, debugger);
}
return ret;
}
}
| false | false | null | null |
diff --git a/src/cs2114/tiletraveler/TileTravelerScreen.java b/src/cs2114/tiletraveler/TileTravelerScreen.java
index 7ccecca..d102f13 100644
--- a/src/cs2114/tiletraveler/TileTravelerScreen.java
+++ b/src/cs2114/tiletraveler/TileTravelerScreen.java
@@ -1,675 +1,677 @@
package cs2114.tiletraveler;
import java.util.Locale;
import sofia.graphics.Shape;
import sofia.app.OptionsMenu;
import sofia.util.Timer;
import sofia.graphics.Anchor;
import sofia.app.ShapeScreen;
import android.widget.TextView;
import sofia.graphics.RectangleShape;
import sofia.graphics.Color;
// -------------------------------------------------------------------------
/**
* Screen class to set up the tile traveler game screen
*
* @author Luciano Biondi (lbiondi)
* @author Ezra Richards (MrZchuck)
* @author Jacob Stenzel (sjacob95)
* @version 2013.12.08
*/
@OptionsMenu
public class TileTravelerScreen
extends ShapeScreen
{
private float tileSize;
private Map currentMap;
private EnemyMap currentEnMap;
private Stage currentStage;
private static final int SCREENDIM = 15; // tile size of one
// side in a single view
private int mapDim;
private Player player;
private Timer enemyTimer;
private TextView status;
/**
* the map location currently at the bottom left of the screen
*/
private Location origin = new Location(0, 0);
public void initialize()
{
getCoordinateSystem().origin(Anchor.BOTTOM_LEFT).flipY();
tileSize = Math.min(getWidth(), getHeight()) / SCREENDIM;
currentStage = new Stage1(tileSize);
reset();
}
// ------------------------------------------------------------------------
// MENU OPTIONS
// ------------------------------------------------------------------------
/**
* Loads Stage 1 when the appropriate menu item is clicked
*/
public void stage1Clicked()
{
currentStage = new Stage1(tileSize);
reset();
}
/**
* Loads Stage 2 when the appropriate menu item is clicked
*/
public void stage2Clicked()
{
currentStage = new Stage2(tileSize);
reset();
}
/**
* Loads Stage 2 when the appropriate menu item is clicked
*/
public void stage3Clicked()
{
currentStage = new Stage3(tileSize);
reset();
}
// -------------------------------------------------------------------------
// BUTTONS
// -------------------------------------------------------------------------
// ----------------------------------------------------------
/**
* Moves the Player west when the left button is clicked
*/
public void leftClicked()
{
player.act(Direction.WEST);
}
// ----------------------------------------------------------
/**
* Moves the Player east when the right button is clicked
*/
public void rightClicked()
{
player.act(Direction.EAST);
}
// ----------------------------------------------------------
/**
* Moves the Player north when the up button is clicked
*/
public void upClicked()
{
player.act(Direction.NORTH);
}
// ----------------------------------------------------------
/**
* Moves the Player south when the down button is clicked
*/
public void downClicked()
{
player.act(Direction.SOUTH);
}
// ----------------------------------------------------------
/**
* Resets the Stage when reset is clicked
*/
public void resetClicked()
{
reset();
}
/**
* Recenters the screen when Center Screen is clicked
*/
public void centerScreenClicked()
{
if (!player.isMoving() && player.isAlive())
{
Location loc = player.getLocation();
origin =
new Location(loc.x() - (SCREENDIM / 2), loc.y()
- (SCREENDIM / 2));
redraw();
}
}
// -------------------------------------------------------------------------
// SCREEN METHODS
// -------------------------------------------------------------------------
// ----------------------------------------------------------
/**
* Completely resets the Stage
*/
public void reset()
{
if (enemyTimer != null)
{
enemyTimer.stop();
}
currentStage = currentStage.reset(tileSize);
currentMap = currentStage.getMap();
currentEnMap = currentStage.getEnemyMap();
mapDim = currentMap.getMapDim();
player = new Player(currentStage.getStartLoc(), tileSize, currentStage);
status.setText("Using the arrow buttons, escape the dungeon!");
centerScreenClicked();
redraw();
enemyTimer = Timer.callRepeatedly(this, "moveEnemies", 0, MovingEnemy.getMoveTime());
}
// ----------------------------------------------------------
/**
* Draws the screen and adds the Player to the screen and begins observing
* it
*/
public void draw()
{
drawScreen();
add(player.getShape());
player.addObserver(this);
addEnemies();
checkOrigin();
}
// ----------------------------------------------------------
/**
* Adds all Enemies to the screen
*/
public void addEnemies()
{
for (int x = 0; x < currentEnMap.getMapDim(); x++)
{
for (int y = 0; y < currentEnMap.getMapDim(); y++)
{
Enemy tempEnemy = currentEnMap.getEnemy(x, y);
if (tempEnemy != null)
{
add(tempEnemy.getShape());
tempEnemy.addObserver(this);
}
}
}
}
// ----------------------------------------------------------
/**
* Redraws all Enemies (Does not add to screen; consult drawEnemies)
*/
public void redrawEnemies()
{
for (int x = 0; x < currentEnMap.getMapDim(); x++)
{
for (int y = 0; y < currentEnMap.getMapDim(); y++)
{
Enemy tempEnemy = currentEnMap.getEnemy(x, y);
if (tempEnemy != null)
{
remove(tempEnemy.getShape());
tempEnemy.redrawShape(origin);
}
}
}
}
// ----------------------------------------------------------
/**
* Redraws all Enemies (Does not add to screen; consult drawEnemies)
*/
public void adjustEnemies()
{
for (int x = 0; x < currentEnMap.getMapDim(); x++)
{
for (int y = 0; y < currentEnMap.getMapDim(); y++)
{
Enemy tempEnemy = currentEnMap.getEnemy(x, y);
if (tempEnemy != null)
{
adjustEntity(tempEnemy);
}
}
}
}
// ----------------------------------------------------------
/**
* Redraws the Player and the Stage
*/
public void redraw()
{
remove(player.getShape());
player.redrawShape(origin);
redrawEnemies();
draw();
}
/**
* Adjusts the Entity's position to correct timing/lag related problems
*
* @param entity
* The Entity
*/
public void adjustEntity(Entity entity)
{
entity.getShape().setLeft(
(entity.getLocation().x() - origin.x()) * tileSize);
entity.getShape().setTop(
(entity.getLocation().y() - origin.y()) * tileSize);
}
/**
* Adjusts the Player's position to correct timing/lag related problems
*/
public void adjustPlayer()
{
player.getShape().setLeft(
(player.getLocation().x() - origin.x()) * tileSize);
player.getShape().setTop(
(player.getLocation().y() - origin.y()) * tileSize);
if (player.isAlive())
{
checkOrigin();
}
}
/**
* Redraws an Entity
*
* @param entity
* The Entity to be redrawn
*/
public void redrawEntity(Entity entity)
{
entity.getShape().setLeft(
(entity.getLocation().x() - origin.x()) * tileSize);
entity.getShape().setTop(
(entity.getLocation().y() - origin.y()) * tileSize);
}
/**
* Draws the Map according to the value of origin
*/
public void drawScreen()
{
clear();
RectangleShape background =
new RectangleShape(0, 0, getWidth(), getHeight());
background.setFillColor(Color.black);
add(background);
for (int y = 0; y < mapDim; y++)
{
for (int x = 0; x < mapDim; x++)
{
drawTile(x, y);
}
}
}
/**
* Draws a Tile
*
* @param x
* the x coordinate of the Tile to be drawn
* @param y
* the y coordinate of the Tile to be drawn
*/
public void drawTile(int x, int y)
{
Tile tile = currentMap.getTile(x, y);
if (tile == null)
return;
switch (tile)
{
case DOOR:
add(new Door((x - origin.x()), (y - origin.y()), tileSize));
break;
case FLOOR:
add(new Floor((x - origin.x()), (y - origin.y()), tileSize));
break;
case LILY:
add(new Water((x - origin.x()), (y - origin.y()), tileSize));
add(new Lily((x - origin.x()), (y - origin.y()), tileSize));
break;
case PILLAR:
add(new Pillar((x - origin.x()), (y - origin.y()), tileSize));
break;
case WALL:
add(new Wall((x - origin.x()), (y - origin.y()), tileSize));
break;
case WATER:
add(new Water((x - origin.x()), (y - origin.y()), tileSize));
break;
default:
break;
}
}
// ----------------------------------------------------------
/**
* @return the Tile size in pixels
*/
public float getTileSize()
{
return tileSize;
}
// ----------------------------------------------------------
/**
* Checks whether or not the player has moved outside the bounds set by
* SCREENDIM. If this is the case, the screen shifts by SCREENDIM Tiles in
* the direction of the Player
*/
public void checkOrigin()
{
if (player.isAlive())
{
+ Location tempOrigin = origin;
boolean changed = false;
if (player.getLocation().y() - origin.y() < 0)
{
- origin = origin.south(SCREENDIM);
+ tempOrigin = origin.south(SCREENDIM);
changed = true;
}
else if (player.getLocation().x() - origin.x() < 0)
{
- origin = origin.west(SCREENDIM);
+ tempOrigin = origin.west(SCREENDIM);
changed = true;
}
else if (player.getLocation().y() - origin.y() >= SCREENDIM)
{
- origin = origin.north(SCREENDIM);
+ tempOrigin = origin.north(SCREENDIM);
changed = true;
}
else if (player.getLocation().x() - origin.x() >= SCREENDIM)
{
- origin = origin.east(SCREENDIM);
+ tempOrigin = origin.east(SCREENDIM);
changed = true;
}
if (changed && !player.isJumping())
{
+ origin = tempOrigin;
redraw();
}
}
}
/**
* Moves all Enemies and then checks whether or not they have killed the Player
*/
public void moveEnemies()
{
EnemyMap tempMap = new EnemyMap(mapDim);
MovingEnemy lastMovingEnemy = null;
for (int x = 0; x < currentEnMap.getMapDim(); x++)
{
for (int y = 0; y < currentEnMap.getMapDim(); y++)
{
Enemy tempEnemy = currentEnMap.getEnemy(x, y);
if (tempEnemy instanceof MovingEnemy)
{
lastMovingEnemy = (MovingEnemy)tempEnemy;
lastMovingEnemy.move();
tempMap.addEnemy(lastMovingEnemy);
}
}
}
currentStage.setEnemyMap(tempMap);
currentEnMap = tempMap;
player.checkEnemyCollision();
}
// -------------------------------------------------------------------------
// MOVINGENEMY OBSERVER METHODS
// -------------------------------------------------------------------------
// ----------------------------------------------------------
/**
* Moves a MovingEnemy
*
* @param entity
* The MovingEnemy to be moved
* @param fractionMoveTime
* The fraction of the MovingEnemy's MoveTime that this move will take
* to execute
* @param x
* The x coordinate to be moved to
* @param y
* The y coordinate to be moved to
*/
public void changeWasObserved(
MovingEnemy entity,
double fractionMoveTime,
int x,
int y)
{
Shape.Animator<?> anim =
entity
.getShape()
.animate(MovingEnemy.getMoveTime() * Math.round(fractionMoveTime))
.position(
(float)((x - origin.x() +.5) * tileSize),
(float)((y - origin.y() + .5) * tileSize));
anim.play();
entity.setLastAnimation(anim);
}
// -------------------------------------------------------------------------
// PLAYER OBSERVER METHODS
// -------------------------------------------------------------------------
// ----------------------------------------------------------
/**
* Checks whether or not the player is alive and responds appropriately
*
* @param entity
* The player
* @param alive
* Whether or not he or she is alive
*/
public void changeWasObserved(Player entity, boolean alive)
{
if (!alive)
{
status.setText("You are died!");
}
else if (alive)
{
status.setText("You did the win!");
}
}
// ----------------------------------------------------------
/**
* Moves the Player
*
* @param entity
* The player
* @param fractionMoveTime
* The fraction of the player's MoveTime that this move will take
* to execute
* @param x
* The x distance to be traveled
* @param y
* The y distance to be traveled
*/
public void changeWasObserved(
Player entity,
double fractionMoveTime,
int x,
int y)
{
Shape.Animator<?> anim =
player.getShape()
.animate((long)(player.getMoveTime() * (fractionMoveTime)))
.moveBy(x * getTileSize(), y * getTileSize());
anim.play();
while (anim.isPlaying())
{
// intentionally blank
}
adjustPlayer();
}
// ----------------------------------------------------------
/**
* Calls the screen method associated with the Player method specified by
* methodName after a delay, calls the adjustPlayer() method to fix any
* offset to lag, and then calls the checkOrigin() method to make sure the
* Player stays within the screen's bounds
*
* @param entity
* The Player
* @param methodName
* The name of the Player method to be called
* @param fractionMoveTime
* The fraction of the Player's MoveTime that the method's delay
* will take
*/
public void changeWasObserved(
Player entity,
String methodName,
double fractionMoveTime)
{
StringBuilder thisMethodName = new StringBuilder();
thisMethodName.append("callPlayer");
thisMethodName.append(methodName.substring(0, 1).toUpperCase(Locale.US));
thisMethodName.append(methodName.substring(1, methodName.length()));
Timer.callOnce(
this,
thisMethodName.toString(),
((long)(entity.getMoveTime() * (fractionMoveTime))));
Timer.callOnce(
this,
"checkOrigin",
((long)(entity.getMoveTime() * (fractionMoveTime))));
}
// -------------------------------------------------------------------------
// PLAYER CALL METHODS
// -------------------------------------------------------------------------
// ----------------------------------------------------------
/**
* Calls the player's resumeInput() method
*/
public void callPlayerResumeInput()
{
player.resumeInput();
}
// ----------------------------------------------------------
/**
* Calls the player's movingStopped() method
*/
public void callPlayerMovingStopped()
{
player.movingStopped();
}
// ----------------------------------------------------------
/**
* Calls the player's checkAndMove() method
*/
public void callPlayerCheckAndMove()
{
player.checkAndMove();
}
// ----------------------------------------------------------
/**
* Calls the player's incJumpCount() method
*/
public void callPlayerIncJumpCount()
{
player.incJumpCount();
}
// ----------------------------------------------------------
/**
* Calls the player's nextMove() method
*/
public void callPlayerNextMove()
{
player.nextMove();
}
// ----------------------------------------------------------
/**
* Calls the player's setRestImage() method
*/
public void callPlayerSetRestImage()
{
player.setRestImage();
}
// ----------------------------------------------------------
/**
* Calls the player's setWalkImage() method
*/
public void callPlayerSetWalkImage()
{
player.setWalkImage();
}
// ----------------------------------------------------------
/**
* Calls the player's setJumpImage() method
*/
public void callPlayerSetJumpImage()
{
player.setJumpImage();
}
}
| false | false | null | null |
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxAttr.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxAttr.java
index 4b5da84c7..9b93f33d6 100755
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxAttr.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxAttr.java
@@ -1,3958 +1,3961 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import javax.lang.model.element.ElementKind;
import javax.tools.JavaFileObject;
import com.sun.javafx.api.tree.ForExpressionInClauseTree;
import com.sun.javafx.api.tree.Tree.JavaFXKind;
import com.sun.javafx.api.tree.TypeTree.Cardinality;
import com.sun.tools.javac.code.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Flags.ANNOTATION;
import static com.sun.tools.javac.code.Flags.BLOCK;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type.*;
import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.code.TypeTags.WILDCARD;
import com.sun.tools.javac.comp.*;
import com.sun.tools.javac.jvm.ByteCodes;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javafx.code.*;
import com.sun.tools.javafx.tree.*;
import com.sun.tools.javafx.util.MsgSym;
import static com.sun.tools.javafx.code.JavafxFlags.SCRIPT_LEVEL_SYNTH_STATIC;
import com.sun.tools.javafx.comp.JavafxCheck.WriteKind;
/** This is the main context-dependent analysis phase in GJC. It
* encompasses name resolution, type checking and constant folding as
* subtasks. Some subtasks involve auxiliary classes.
* @see Check
* @see Resolve
* @see ConstFold
* @see Infer
*
* This class is interleaved with {@link JavafxMemberEnter}, which is used
* to enter declarations into a local scope.
*
* <p><b>This is NOT part of any API supported by Sun Microsystems. If
* you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class JavafxAttr implements JavafxVisitor {
protected static final Context.Key<JavafxAttr> javafxAttrKey =
new Context.Key<JavafxAttr>();
/*
* modules imported by context
*/
private final JavafxDefs defs;
private final Name.Table names;
private final Log log;
private final JavafxResolve rs;
private final JavafxSymtab syms;
private final JavafxCheck chk;
private final JavafxMemberEnter memberEnter;
private final JavafxTreeMaker fxmake;
private final ConstFold cfolder;
private final JavafxEnter enter;
private final Target target;
private final JavafxTypes types;
private final Annotate annotate;
/*
* other instance information
*/
private final Source source;
Map<JavafxVarSymbol, JFXVar> varSymToTree =
new HashMap<JavafxVarSymbol, JFXVar>();
Map<MethodSymbol, JFXFunctionDefinition> methodSymToTree =
new HashMap<MethodSymbol, JFXFunctionDefinition>();
public static JavafxAttr instance(Context context) {
JavafxAttr instance = context.get(javafxAttrKey);
if (instance == null)
instance = new JavafxAttr(context);
return instance;
}
protected JavafxAttr(Context context) {
context.put(javafxAttrKey, this);
defs = JavafxDefs.instance(context);
syms = (JavafxSymtab)JavafxSymtab.instance(context);
names = Name.Table.instance(context);
log = Log.instance(context);
rs = JavafxResolve.instance(context);
chk = JavafxCheck.instance(context);
memberEnter = JavafxMemberEnter.instance(context);
fxmake = (JavafxTreeMaker)JavafxTreeMaker.instance(context);
enter = JavafxEnter.instance(context);
cfolder = ConstFold.instance(context);
target = Target.instance(context);
types = JavafxTypes.instance(context);
annotate = Annotate.instance(context);
Options options = Options.instance(context);
source = Source.instance(context);
allowGenerics = source.allowGenerics();
allowVarargs = source.allowVarargs();
allowBoxing = source.allowBoxing();
allowCovariantReturns = source.allowCovariantReturns();
allowAnonOuterThis = source.allowAnonOuterThis();
relax = (options.get("-retrofit") != null ||
options.get("-relax") != null);
inBindContext = false;
}
/** Switch: relax some constraints for retrofit mode.
*/
private boolean relax;
/** Switch: support generics?
*/
private boolean allowGenerics;
/** Switch: allow variable-arity methods.
*/
private boolean allowVarargs;
/** Switch: support boxing and unboxing?
*/
private boolean allowBoxing;
/** Switch: support covariant result types?
*/
private boolean allowCovariantReturns;
/** Switch: allow references to surrounding object from anonymous
* objects during constructor call?
*/
private boolean allowAnonOuterThis;
enum Sequenceness {
DISALLOWED,
PERMITTED,
REQUIRED
}
/** Check kind and type of given tree against protokind and prototype.
* If check succeeds, store type in tree and return it.
* If check fails, store errType in tree and return it.
* No checks are performed if the prototype is a method type.
* Its not necessary in this case since we know that kind and type
* are correct. WRONG - see JFXC-2199.
*
* @param tree The tree whose kind and type is checked
* @param owntype The computed type of the tree
* @param ownkind The computed kind of the tree
* @param pkind The expected kind (or: protokind) of the tree
* @param pt The expected type (or: prototype) of the tree
*/
Type check(JFXTree tree, Type owntype, int ownkind, int pkind, Type pt, Sequenceness pSequenceness) {
if (owntype != null && owntype != syms.javafx_UnspecifiedType && owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
// if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
if ((pkind & VAL) != 0 && ownkind == MTH) {
ownkind = VAL;
if (owntype instanceof MethodType) {
owntype = chk.checkFunctionType(tree.pos(), (MethodType)owntype);
}
}
if ((ownkind & ~pkind) == 0) {
owntype = chk.checkType(tree.pos(), owntype, pt, pSequenceness);
} else {
log.error(tree.pos(), MsgSym.MESSAGE_UNEXPECTED_TYPE,
Resolve.kindNames(pkind),
Resolve.kindName(ownkind));
owntype = syms.errType;
}
}
tree.type = owntype;
return owntype;
}
/** Is this symbol a type?
*/
static boolean isType(Symbol sym) {
return sym != null && sym.kind == TYP;
}
/** The current `this' symbol.
* @param env The current environment.
*/
Symbol thisSym(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env) {
return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
}
/* ************************************************************************
* Visitor methods
*************************************************************************/
/** Visitor argument: the current environment.
*/
private JavafxEnv<JavafxAttrContext> env;
/** Visitor argument: the currently expected proto-kind.
*/
int pkind;
/** Visitor argument: the currently expected proto-type.
*/
Type pt;
/** Visitor argument: is a sequence permitted
*/
private Sequenceness pSequenceness;
/** Visitor argument: bind context
*/
private boolean inBindContext;
/** Visitor result: the computed type.
*/
private Type result;
/** Visitor method: attribute a tree, catching any completion failure
* exceptions. Return the tree's type.
*
* @param tree The tree to be visited.
* @param env The environment visitor argument.
* @param pkind The protokind visitor argument.
* @param pt The prototype visitor argument.
*/
Type attribTree(JFXTree tree, JavafxEnv<JavafxAttrContext> env, int pkind, Type pt) {
return attribTree(tree, env, pkind, pt, this.pSequenceness, this.inBindContext);
}
Type attribTree(JFXTree tree, JavafxEnv<JavafxAttrContext> env, int pkind, Type pt, Sequenceness pSequenceness) {
return attribTree(tree, env, pkind, pt, pSequenceness, this.inBindContext);
}
Type attribTree(JFXTree tree, JavafxEnv<JavafxAttrContext> env, int pkind, Type pt, Sequenceness pSequenceness, boolean inBindContext) {
JavafxEnv<JavafxAttrContext> prevEnv = this.env;
int prevPkind = this.pkind;
Type prevPt = this.pt;
Sequenceness prevSequenceness = this.pSequenceness;
boolean wasInBindContext = this.inBindContext;
this.inBindContext = inBindContext;
try {
this.env = env;
this.pkind = pkind;
this.pt = pt;
this.pSequenceness = pSequenceness;
if (tree != null )tree.accept(this);
if (tree == breakTree)
throw new BreakAttr(env);
if (pSequenceness == Sequenceness.REQUIRED && result.tag != ERROR
&& ! types.isSequence(result)) {
result = chk.typeTagError(tree, types.sequenceType(syms.unknownType), result);
}
return result;
} catch (CompletionFailure ex) {
tree.type = syms.errType;
return chk.completionError(tree.pos(), ex);
} finally {
this.env = prevEnv;
this.pkind = prevPkind;
this.pt = prevPt;
this.pSequenceness = prevSequenceness;
this.inBindContext = wasInBindContext;
}
}
/** Derived visitor method: attribute an expression tree.
*/
Type attribExpr(JFXTree tree, JavafxEnv<JavafxAttrContext> env, Type pt, Sequenceness pSequenceness) {
return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType, pt.tag != ERROR ? pSequenceness : Sequenceness.PERMITTED);
}
/** Derived visitor method: attribute an expression tree.
* allow a sequence if no proto-type is specified, the proto-type is a seqeunce,
* or the proto-type is an error.
*/
Type attribExpr(JFXTree tree, JavafxEnv<JavafxAttrContext> env, Type pt) {
return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType,
(pt.tag == ERROR || pt == Type.noType || types.isSequence(pt))?
Sequenceness.PERMITTED :
Sequenceness.DISALLOWED);
}
/** Derived visitor method: attribute an expression tree with
* no constraints on the computed type.
*/
Type attribExpr(JFXTree tree, JavafxEnv<JavafxAttrContext> env) {
return attribTree(tree, env, VAL, Type.noType, Sequenceness.PERMITTED);
}
/** Derived visitor method: attribute a type tree.
*/
Type attribType(JFXTree tree, JavafxEnv<JavafxAttrContext> env) {
Type localResult = attribTree(tree, env, TYP, Type.noType, Sequenceness.DISALLOWED);
return localResult;
}
/** Derived visitor method: attribute a statement or definition tree.
*/
public Type attribDecl(JFXTree tree, JavafxEnv<JavafxAttrContext> env) {
return attribTree(tree, env, NIL, Type.noType, Sequenceness.DISALLOWED);
}
public Type attribVar(JFXVar tree, JavafxEnv<JavafxAttrContext> env) {
memberEnter.memberEnter(tree, env);
return attribExpr(tree, env);
}
/** Attribute a list of expressions, returning a list of types.
*/
List<Type> attribExprs(List<JFXExpression> trees, JavafxEnv<JavafxAttrContext> env, Type pt) {
ListBuffer<Type> ts = new ListBuffer<Type>();
for (List<JFXExpression> l = trees; l.nonEmpty(); l = l.tail)
ts.append(attribExpr(l.head, env, pt));
return ts.toList();
}
/** Attribute the arguments in a method call, returning a list of types.
*/
List<Type> attribArgs(List<JFXExpression> trees, JavafxEnv<JavafxAttrContext> env) {
ListBuffer<Type> argtypes = new ListBuffer<Type>();
for (List<JFXExpression> l = trees; l.nonEmpty(); l = l.tail)
argtypes.append(chk.checkNonVoid(
l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
return argtypes.toList();
}
/** Does tree represent a static reference to an identifier?
* It is assumed that tree is either a SELECT or an IDENT.
* We have to weed out selects from non-type names here.
* @param tree The candidate tree.
*/
boolean isStaticReference(JFXTree tree) {
if (tree.getFXTag() == JavafxTag.SELECT) {
Symbol lsym = JavafxTreeInfo.symbol(((JFXSelect) tree).selected);
if (lsym == null || lsym.kind != TYP) {
return false;
}
}
return true;
}
/** Attribute a list of statements, returning nothing.
*/
<T extends JFXTree> void attribDecls(List<T> trees, JavafxEnv<JavafxAttrContext> env) {
for (List<T> l = trees; l.nonEmpty(); l = l.tail)
attribDecl(l.head, env);
}
/** Attribute a type argument list, returning a list of types.
*/
List<Type> attribTypes(List<JFXExpression> trees, JavafxEnv<JavafxAttrContext> env) {
ListBuffer<Type> argtypes = new ListBuffer<Type>();
for (List<JFXExpression> l = trees; l.nonEmpty(); l = l.tail)
argtypes.append(chk.checkRefType(l.head.pos(), attribType(l.head, env)));
return argtypes.toList();
}
/** Attribute type reference in an `extends' or `implements' clause.
*
* @param tree The tree making up the type reference.
* @param env The environment current at the reference.
* @param classExpected true if only a class is expected here.
* @param interfaceExpected true if only an interface is expected here.
*/
Type attribBase(JFXTree tree,
JavafxEnv<JavafxAttrContext> env,
boolean classExpected,
boolean interfaceExpected,
boolean checkExtensible) {
Type t = attribType(tree, env);
return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
}
Type checkBase(Type t,
JFXTree tree,
JavafxEnv<JavafxAttrContext> env,
boolean classExpected,
boolean interfaceExpected,
boolean checkExtensible) {
if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
// check that type variable is already visible
if (t.getUpperBound() == null) {
log.error(tree.pos(), MsgSym.MESSAGE_ILLEGAL_FORWARD_REF);
return syms.errType;
}
} else {
t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
}
if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
log.error(tree.pos(), MsgSym.MESSAGE_INTF_EXPECTED_HERE);
// return errType is necessary since otherwise there might
// be undetected cycles which cause attribution to loop
return syms.errType;
} else if (checkExtensible &&
classExpected &&
(t.tsym.flags() & INTERFACE) != 0) {
log.error(tree.pos(), MsgSym.MESSAGE_NO_INTF_EXPECTED_HERE);
return syms.errType;
}
if (checkExtensible &&
((t.tsym.flags() & FINAL) != 0)) {
log.error(tree.pos(),
MsgSym.MESSAGE_CANNOT_INHERIT_FROM_FINAL, t.tsym);
}
chk.checkNonCyclic(tree.pos(), t);
return t;
}
private JavafxEnv<JavafxAttrContext> newLocalEnv(JFXTree tree) {
JavafxEnv<JavafxAttrContext> localEnv =
env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
localEnv.outer = env;
localEnv.info.scope.owner = new MethodSymbol(BLOCK, names.empty, null, env.enclClass.sym);
return localEnv;
}
@Override
public void visitTypeCast(JFXTypeCast tree) {
Type clazztype = attribType(tree.clazz, env);
Type reqType = tree.expr instanceof JFXLiteral ? clazztype : Infer.anyPoly;
Type exprtype = attribExpr(tree.expr, env, reqType);
if (clazztype.isPrimitive() && ! exprtype.isPrimitive())
clazztype = types.boxedClass(clazztype).type;
Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
if (exprtype.constValue() != null)
owntype = cfolder.coerce(exprtype, owntype);
result = check(tree, capture(owntype), VAL, pkind, pt, Sequenceness.DISALLOWED);
}
@Override
public void visitInstanceOf(JFXInstanceOf tree) {
Type exprtype = attribExpr(tree.expr, env);
+ Type type = attribType(tree.clazz, env);
+ if (type.isPrimitive())
+ type = types.boxedClass(type).type;
Type clazztype = chk.checkReifiableReferenceType(
- tree.clazz.pos(), attribType(tree.clazz, env));
+ tree.clazz.pos(), type);
chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
result = check(tree, syms.booleanType, VAL, pkind, pt, Sequenceness.DISALLOWED);
}
private void checkTypeCycle(JFXTree tree, Symbol sym) {
if (sym.type == null) {
JFXVar var = varSymToTree.get(sym);
if (var != null)
log.note(var, MsgSym.MESSAGE_JAVAFX_TYPE_INFER_CYCLE_VAR_DECL, sym.name);
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_TYPE_INFER_CYCLE_VAR_REF, sym.name);
sym.type = syms.objectType;
}
else if (sym.type instanceof MethodType &&
sym.type.getReturnType() == syms.unknownType) {
JFXFunctionDefinition fun = methodSymToTree.get(sym);
if (fun != null)
log.note(fun, MsgSym.MESSAGE_JAVAFX_TYPE_INFER_CYCLE_FUN_DECL, sym.name);
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_TYPE_INFER_CYCLE_VAR_REF, sym.name);
if (pt instanceof MethodType)
((MethodType)pt).restype = new ErrorType();
sym.type = syms.objectType;
}
}
@Override
public void visitIdent(JFXIdent tree) {
Symbol sym;
boolean varArgs = false;
// Find symbol
if (tree.sym != null && tree.sym.kind != VAR) {
sym = tree.sym;
} else {
sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind, pt);
}
tree.sym = sym;
sym.complete();
checkTypeCycle(tree, sym);
// (1) Also find the environment current for the class where
// sym is defined (`symEnv').
// Only for pre-tiger versions (1.4 and earlier):
// (2) Also determine whether we access symbol out of an anonymous
// class in a this or super call. This is illegal for instance
// members since such classes don't carry a this$n link.
// (`noOuterThisPath').
JavafxEnv<JavafxAttrContext> symEnv = env;
boolean noOuterThisPath = false;
if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
(sym.kind & (VAR | MTH | TYP)) != 0 &&
sym.owner.kind == TYP &&
tree.name != names._this && tree.name != names._super) {
// Find environment in which identifier is defined.
while (symEnv.outer != null &&
!sym.isMemberOf(symEnv.enclClass.sym, types)) {
if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
noOuterThisPath = !allowAnonOuterThis;
symEnv = symEnv.outer;
}
}
// In a constructor body,
// if symbol is a field or instance method, check that it is
// not accessed before the supertype constructor is called.
if ((symEnv.info.isSelfCall || noOuterThisPath) &&
(sym.kind & (VAR | MTH)) != 0 &&
sym.owner.kind == TYP &&
(sym.flags() & STATIC) == 0) {
chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
}
JavafxEnv<JavafxAttrContext> env1 = env;
if (sym.kind != ERR && sym.owner != null && sym.owner != env1.enclClass.sym) {
// If the found symbol is inaccessible, then it is
// accessed through an enclosing instance. Locate this
// enclosing instance:
while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
env1 = env1.outer;
}
// If symbol is a variable, ...
if (sym.kind == VAR) {
VarSymbol v = (VarSymbol)sym;
// ..., evaluate its initializer, if it has one, and check for
// illegal forward reference.
checkInit(tree, env, v);
checkForward(tree, env, v);
// If we are expecting a variable (as opposed to a value), check
// that the variable is assignable in the current environment.
if (pkind == VAR)
chk.checkAssignable(tree.pos(), v, null, env1.enclClass.sym.type, env, WriteKind.ASSIGN);
}
result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, pSequenceness, varArgs);
}
@Override
public void visitSelect(JFXSelect tree) {
// Determine the expected kind of the qualifier expression.
int skind = 0;
if (tree.name == names._this || tree.name == names._super ||
tree.name == names._class)
{
skind = TYP;
} else {
if ((pkind & PCK) != 0) skind = skind | PCK;
if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
}
boolean inSelectPrev = env.info.inSelect;
env.info.inSelect = true;
// Attribute the qualifier expression, and determine its symbol (if any).
Type site = attribTree(tree.selected, env, skind,
Infer.anyPoly, Sequenceness.PERMITTED);
boolean wasPrimitive = site.isPrimitive();
if (wasPrimitive) {
site = types.boxedClass(site).type;
}
env.info.inSelect = inSelectPrev;
if ((pkind & (PCK | TYP)) == 0)
site = capture(site); // Capture field access
// don't allow T.class T[].class, etc
if (skind == TYP) {
Type elt = site;
while (elt.tag == ARRAY)
elt = ((ArrayType)elt).elemtype;
if (elt.tag == TYPEVAR) {
log.error(tree.pos(), MsgSym.MESSAGE_TYPE_VAR_CANNOT_BE_DEREF);
result = syms.errType;
return;
}
}
// If qualifier symbol is a type or `super', assert `selectSuper'
// for the selection. This is relevant for determining whether
// protected symbols are accessible.
Symbol sitesym = JavafxTreeInfo.symbol(tree.selected);
boolean selectSuperPrev = env.info.selectSuper;
env.info.selectSuper =
sitesym != null &&
sitesym.name == names._super;
// If selected expression is polymorphic, strip
// type parameters and remember in env.info.tvars, so that
// they can be added later (in Attr.checkId and Infer.instantiateMethod).
if (tree.selected.type.tag == FORALL) {
ForAll pstype = (ForAll)tree.selected.type;
env.info.tvars = pstype.tvars;
site = tree.selected.type = pstype.qtype;
}
// Determine the symbol represented by the selection.
env.info.varArgs = false;
if (sitesym instanceof ClassSymbol &&
env.enclClass.sym.isSubClass(sitesym, types))
env.info.selectSuper = true;
Symbol sym = selectSym(tree, site, env, pt, pkind);
sym.complete();
if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
site = capture(site);
sym = selectSym(tree, site, env, pt, pkind);
}
boolean varArgs = env.info.varArgs;
tree.sym = sym;
if (wasPrimitive && sym.isStatic() && tree.selected instanceof JFXIdent)
tree.selected.type = site;
checkTypeCycle(tree, sym);
if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR)
site = capture(site.getUpperBound());
// If that symbol is a variable, ...
if (sym.kind == VAR) {
VarSymbol v = (VarSymbol)sym;
// ..., evaluate its initializer, if it has one, and check for
// illegal forward reference.
checkInit(tree, env, v);
// If we are expecting a variable (as opposed to a value), check
// that the variable is assignable in the current environment.
if (pkind == VAR)
chk.checkAssignable(tree.pos(), v, tree.selected, site, env, WriteKind.ASSIGN);
}
// Disallow selecting a type from an expression
if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
tree.type = check(tree.selected, pt,
sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt, pSequenceness);
}
if (isType(sitesym)) {
if (sym.name == names._this) {
// If `C' is the currently compiled class, check that
// C.this' does not appear in a call to a super(...)
if (env.info.isSelfCall &&
site.tsym == env.enclClass.sym) {
chk.earlyRefError(tree.pos(), sym);
}
}
else if (! sym.isStatic()) {
for (JavafxEnv<JavafxAttrContext> env1 = env; ; env1 = env1.outer) {
if (env1 == null) {
rs.access(rs.new StaticError(sym),
tree.pos(), site, sym.name, true);
break;
}
if (env1.tree instanceof JFXClassDeclaration &&
types.isSubtype(((JFXClassDeclaration) env1.tree).sym.type, site)) {
break;
}
}
}
}
// If we are selecting an instance member via a `super', ...
if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
// Check that super-qualified symbols are not abstract (JLS)
rs.checkNonAbstract(tree.pos(), sym);
if (site.isRaw()) {
// Determine argument types for site.
Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
if (site1 != null) site = site1;
}
}
env.info.selectSuper = selectSuperPrev;
result = checkId(tree, site, sym, env, pkind, pt, pSequenceness, varArgs);
env.info.tvars = List.nil();
}
//where
/** Determine symbol referenced by a Select expression,
*
* @param tree The select tree.
* @param site The type of the selected expression,
* @param env The current environment.
* @param pt The current prototype.
* @param pkind The expected kind(s) of the Select expression.
*/
@SuppressWarnings("fallthrough")
private Symbol selectSym(JFXSelect tree,
Type site,
JavafxEnv<JavafxAttrContext> env,
Type pt,
int pkind) {
DiagnosticPosition pos = tree.pos();
Name name = tree.name;
Symbol sym;
switch (site.tag) {
case PACKAGE:
return rs.access(
rs.findIdentInPackage(env, site.tsym, name, pkind),
pos, site, name, true);
case ARRAY:
case CLASS:
if (pt.tag == METHOD || pt.tag == FORALL) {
return rs.resolveQualifiedMethod(pos, env, site, name, pt);
} else if (name == names._this || name == names._super) {
return rs.resolveSelf(pos, env, site.tsym, name);
} else if (name == names._class) {
// In this case, we have already made sure in
// visitSelect that qualifier expression is a type.
Type t = syms.classType;
List<Type> typeargs = allowGenerics
? List.of(types.erasure(site))
: List.<Type>nil();
t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
return new VarSymbol(
STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
} else {
// We are seeing a plain identifier as selector.
sym = rs.findIdentInType(env, site, name, pkind);
if ((pkind & ERRONEOUS) == 0)
sym = rs.access(sym, pos, site, name, true);
return sym;
}
case WILDCARD:
throw new AssertionError(tree);
case TYPEVAR:
// Normally, site.getUpperBound() shouldn't be null.
// It should only happen during memberEnter/attribBase
// when determining the super type which *must* be
// done before attributing the type variables. In
// other words, we are seeing this illegal program:
// class B<T> extends A<T.foo> {}
sym = (site.getUpperBound() != null)
? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
: null;
if (sym == null || isType(sym)) {
log.error(pos, MsgSym.MESSAGE_TYPE_VAR_CANNOT_BE_DEREF);
return syms.errSymbol;
} else {
return sym;
}
case ERROR:
// preserve identifier names through errors
return new ErrorType(name, site.tsym).tsym;
default:
// The qualifier expression is of a primitive type -- only
// .class is allowed for these.
if (name == names._class) {
// In this case, we have already made sure in Select that
// qualifier expression is a type.
Type t = syms.classType;
Type arg = types.boxedClass(site).type;
t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
return new VarSymbol(
STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
} else {
log.error(pos, MsgSym.MESSAGE_CANNOT_DEREF, site);
return syms.errSymbol;
}
}
}
@Override
public void visitParens(JFXParens tree) {
Type owntype = attribTree(tree.expr, env, pkind, pt);
result = check(tree, owntype, pkind, pkind, pt, pSequenceness);
Symbol sym = JavafxTreeInfo.symbol(tree);
if (sym != null && (sym.kind&(TYP|PCK)) != 0)
log.error(tree.pos(), MsgSym.MESSAGE_ILLEGAL_START_OF_TYPE);
}
@Override
public void visitAssign(JFXAssign tree) {
Type owntype = null;
JavafxEnv<JavafxAttrContext> dupEnv = env.dup(tree);
dupEnv.outer = env;
owntype = attribTree(tree.lhs, dupEnv, VAR, Type.noType);
boolean hasLhsType;
if (owntype == null || owntype == syms.javafx_UnspecifiedType) {
owntype = attribExpr(tree.rhs, env, Type.noType);
hasLhsType = false;
}
else {
hasLhsType = true;
}
Type capturedType = capture(owntype);
Symbol lhsSym = JavafxTreeInfo.symbol(tree.lhs);
if (lhsSym == null) {
log.error(tree, MsgSym.MESSAGE_JAVAFX_INVALID_ASSIGNMENT);
return;
}
if (hasLhsType) {
attribExpr(tree.rhs, dupEnv, owntype);
}
else {
if (tree.lhs.getFXTag() == JavafxTag.SELECT) {
JFXSelect fa = (JFXSelect)tree.lhs;
fa.type = owntype;
}
else if (tree.lhs.getFXTag() == JavafxTag.IDENT) {
JFXIdent id = (JFXIdent)tree.lhs;
id.type = owntype;
}
attribTree(tree.lhs, dupEnv, VAR, owntype);
lhsSym.type = owntype;
}
result = check(tree, capturedType, VAL, pkind, pt, pSequenceness);
if (tree.rhs != null && tree.lhs.getFXTag() == JavafxTag.IDENT) {
JFXVar lhsVar = varSymToTree.get(lhsSym);
if (lhsVar != null && (lhsVar.getJFXType() instanceof JFXTypeUnknown)) {
if (lhsVar.type == null ||
lhsVar.type == syms.javafx_AnyType/* ??? */ ||
lhsVar.type == syms.javafx_UnspecifiedType) {
if (tree.rhs.type != null && lhsVar.type != tree.rhs.type) {
lhsVar.type = lhsSym.type = types.upperBound(tree.rhs.type);
JFXExpression jcExpr = fxmake.at(tree.pos()).Ident(lhsSym);
lhsVar.setJFXType(fxmake.at(tree.pos()).TypeClass(jcExpr, lhsVar.getJFXType().getCardinality()));
}
}
}
}
}
public void finishVar(JFXVar tree, JavafxEnv<JavafxAttrContext> env) {
VarSymbol v = tree.sym;
// The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
// because the annotations were not available at the time the env was created. Therefore,
// we look up the environment chain for the first enclosing environment for which the
// lint value is set. Typically, this is the parent env, but might be further if there
// are any envs created as a result of TypeParameter nodes.
JavafxEnv<JavafxAttrContext> lintEnv = env;
while (lintEnv.info.lint == null)
lintEnv = lintEnv.next;
Lint lint = lintEnv.info.lint.augment(v.attributes_field, v.flags());
Lint prevLint = chk.setLint(lint);
JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
try {
Type declType = attribType(tree.getJFXType(), env);
declType = chk.checkNonVoid(tree.getJFXType(), declType);
if (declType != syms.javafx_UnspecifiedType) {
result = tree.type = v.type = declType;
}
// Check that the variable's declared type is well-formed.
// chk.validate(tree.vartype);
Type initType;
if (tree.init == null && (tree.getModifiers().flags & JavafxFlags.IS_DEF) != 0) {
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_DEF_MUST_HAVE_INIT, v);
}
if (tree.init != null) {
if (tree.init.getJavaFXKind() == JavaFXKind.INSTANTIATE_OBJECT_LITERAL &&
(tree.getModifiers().flags & JavafxFlags.IS_DEF) != 0)
v.flags_field |= JavafxFlags.OBJ_LIT_INIT;
// Attribute initializer in a new environment.
// Check that initializer conforms to variable's declared type.
Scope initScope = new Scope(new MethodSymbol(BLOCK, v.name, null, env.enclClass.sym));
initScope.next = env.info.scope;
JavafxEnv<JavafxAttrContext> initEnv =
env.dup(tree, env.info.dup(initScope));
initEnv.outer = env;
initEnv.info.lint = lint;
if ((tree.getModifiers().flags & STATIC) != 0)
initEnv.info.staticLevel++;
// In order to catch self-references, we set the variable's
// declaration position to maximal possible value, effectively
// marking the variable as undefined.
v.pos = Position.MAXPOS;
boolean wasInBindContext = this.inBindContext;
this.inBindContext |= tree.isBound();
initType = attribExpr(tree.init, initEnv, declType);
this.inBindContext = wasInBindContext;
initType = chk.checkNonVoid(tree.pos(), initType);
if (declType.tag <= LONG && initType.tag >= LONG && initType.tag <= DOUBLE) {
// Temporary kludge to supress duplicate warnings.
// (The kludge won't be needed if we make Number->Integer and error.)
}
else
chk.checkType(tree.pos(), initType, declType, Sequenceness.DISALLOWED);
if (initType == syms.botType
|| initType == syms.unreachableType)
initType = syms.objectType;
else if (initType == syms.javafx_EmptySequenceType)
initType = types.sequenceType(syms.objectType);
else if (types.isArray(initType)) {
Type elemType = types.elemtype(initType);
initType = types.sequenceType(elemType);
}
chk.checkBidiBind(tree.init, tree.getBindStatus(), initEnv, v.type);
}
else if (tree.type != null)
initType = tree.type;
else
initType = syms.objectType; // nothing to go on, so we assume Object
if (declType == syms.javafx_UnspecifiedType && v.type == null)
result = tree.type = v.type = types.upperBound(initType);
//chk.validateAnnotations(tree.mods.annotations, v);
}
finally {
chk.setLint(prevLint);
log.useSource(prev);
v.pos = tree.pos;
}
}
@Override
public void visitVarScriptInit(JFXVarScriptInit tree) {
result = tree.type = attribExpr(tree.getVar(), env);
}
@Override
public void visitVar(JFXVar tree) {
long flags = tree.getModifiers().flags;
Symbol sym = tree.sym;
if (sym == null) {
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_VAR_NOT_SUPPORTED_HERE, (flags & JavafxFlags.IS_DEF) == 0 ? "var" : "def", tree.getName());
return;
}
sym.complete();
boolean isClassVar = env.info.scope.owner.kind == TYP;
if (isClassVar && (flags & STATIC) == 0L) {
// Check that instance variables don't override
chk.checkVarOverride(tree, (VarSymbol)sym);
}
JFXOnReplace onReplace = tree.getOnReplace();
if (onReplace != null) {
JFXVar oldValue = onReplace.getOldValue();
if (oldValue != null && oldValue.type == null) {
oldValue.type = tree.type;
}
JFXVar newElements = onReplace.getNewElements();
if (newElements != null && newElements.type == null)
newElements.type = tree.type;
if (isClassVar) {
// let the owner of the environment be a freshly
// created BLOCK-method.
JavafxEnv<JavafxAttrContext> localEnv = newLocalEnv(tree);
if ((flags & STATIC) != 0) {
localEnv.info.staticLevel++;
}
attribDecl(onReplace, localEnv);
} else {
// Create a new local environment with a local scope.
JavafxEnv<JavafxAttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
attribDecl(onReplace, localEnv);
localEnv.info.scope.leave();
}
}
warnOnStaticUse(tree.pos(), tree.getModifiers(), sym);
// type is the type of the variable unless the variable is bound
result = tree.isBound()? syms.voidType : tree.type;
}
private void warnOnStaticUse(DiagnosticPosition pos, JFXModifiers mods, Symbol sym) {
// temporary warning for the use of 'static'
if ((mods.flags & (STATIC | SCRIPT_LEVEL_SYNTH_STATIC)) == STATIC) {
log.warning(pos, MsgSym.MESSAGE_JAVAFX_STATIC_DEPRECATED, sym);
}
}
/**
* OK, this is a not really "finish" as in the completer, at least not now.
* But it does finish the attribution of the override by attributing the
* default initialization.
*
* @param tree
* @param env
*/
public void finishOverrideAttribute(JFXOverrideClassVar tree, JavafxEnv<JavafxAttrContext> env) {
VarSymbol v = tree.sym;
Type declType = tree.getId().type;
result = tree.type = declType;
// The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
// because the annotations were not available at the time the env was created. Therefore,
// we look up the environment chain for the first enclosing environment for which the
// lint value is set. Typically, this is the parent env, but might be further if there
// are any envs created as a result of TypeParameter nodes.
JavafxEnv<JavafxAttrContext> lintEnv = env;
while (lintEnv.info.lint == null) {
lintEnv = lintEnv.next;
}
Lint lint = lintEnv.info.lint.augment(v.attributes_field, v.flags());
Lint prevLint = chk.setLint(lint);
JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
if ((v.flags() & JavafxFlags.IS_DEF) != 0L) {
log.error(tree.getId().pos(), MsgSym.MESSAGE_JAVAFX_CANNOT_OVERRIDE_DEF, tree.getId().name);
} else if (!rs.isAccessibleForWrite(env, env.enclClass.type, v)) {
log.error(tree.getId().pos(), MsgSym.MESSAGE_JAVAFX_CANNOT_OVERRIDE, tree.getId().name);
}
boolean wasInBindContext = this.inBindContext;
this.inBindContext |= tree.isBound();
try {
JFXExpression init = tree.getInitializer();
if (init != null) {
// Attribute initializer in a new environment/
// Check that initializer conforms to variable's declared type.
Scope initScope = new Scope(new MethodSymbol(BLOCK, v.name, null, env.enclClass.sym));
initScope.next = env.info.scope;
JavafxEnv<JavafxAttrContext> initEnv =
env.dup(tree, env.info.dup(initScope));
initEnv.outer = env;
// In order to catch self-references, we set the variable's
// declaration position to maximal possible value, effectively
// marking the variable as undefined.
v.pos = Position.MAXPOS;
chk.checkNonVoid(init, attribExpr(init, initEnv, declType));
chk.checkBidiBind(tree.getInitializer(), tree.getBindStatus(), initEnv, v.type);
}
} finally {
chk.setLint(prevLint);
log.useSource(prev);
this.inBindContext = wasInBindContext;
}
}
@Override
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
//TODO: handle static triggers
JFXIdent id = tree.getId();
JFXOnReplace onr = tree.getOnReplace();
// let the owner of the environment be a freshly
// created BLOCK-method.
JavafxEnv<JavafxAttrContext> localEnv = newLocalEnv(tree);
Type type = attribExpr(id, localEnv);
tree.type = type;
Symbol sym = id.sym;
if (onr != null) {
JFXVar oldValue = onr.getOldValue();
if (oldValue != null && oldValue.type == null) {
oldValue.type = type;
}
JFXVar newElements = onr.getNewElements();
if (newElements != null && newElements.type == null) {
newElements.type = type;
}
attribDecl(onr, localEnv);
}
// Must reference an attribute
if (sym.kind != VAR) {
log.error(id.pos(), MsgSym.MESSAGE_JAVAFX_MUST_BE_AN_ATTRIBUTE, id.name);
} else {
VarSymbol v = (VarSymbol) sym;
tree.sym = v;
finishOverrideAttribute(tree, env);
}
}
@Override
public void visitOnReplace(JFXOnReplace tree) {
JavafxEnv<JavafxAttrContext> localEnv = env.dup(tree);
localEnv.outer = env;
JFXVar lastIndex = tree.getLastIndex();
if (lastIndex != null) {
lastIndex.mods.flags |= Flags.FINAL;
attribVar(lastIndex, localEnv);
lastIndex.sym.type = syms.intType;
}
JFXVar newElements = tree.getNewElements();
if (newElements != null) {
newElements.mods.flags |= Flags.FINAL;
attribVar(newElements, localEnv);
}
JFXVar firstIndex = tree.getFirstIndex();
if (firstIndex != null) {
firstIndex.mods.flags |= Flags.FINAL;
attribVar(firstIndex, localEnv);
firstIndex.sym.type = syms.intType;
}
JFXVar oldValue = tree.getOldValue();
if (oldValue != null) {
oldValue.mods.flags |= Flags.FINAL;
attribVar(oldValue, localEnv);
}
attribExpr(tree.getBody(), localEnv);
}
private ArrayList<JFXForExpressionInClause> forClauses = null;
@Override
public void visitForExpression(JFXForExpression tree) {
JavafxEnv<JavafxAttrContext> forExprEnv =
env.dup(tree, env.info.dup(env.info.scope.dup()));
if (forClauses == null)
forClauses = new ArrayList<JFXForExpressionInClause>();
int forClausesOldSize = forClauses.size();
for (ForExpressionInClauseTree cl : tree.getInClauses()) {
// Don't try to examine erroneous in clauses. We don't wish to
// place the entire for expression into error nodes, just because
// one or more in clauses was in error, so we jsut skip any
// erroneous ones.
//
if (cl instanceof JFXErroneousForExpressionInClause) continue;
JFXForExpressionInClause clause = (JFXForExpressionInClause)cl;
forClauses.add(clause);
JFXVar var = clause.getVar();
// Don't try to examine erroneous loop controls, such as
// when a variable was missing. Again, this is because the IDE may
// try to attribute a node that is mostly correct, but contains
// one or more components that are in error.
//
if (var == null || var instanceof JFXErroneousVar) continue;
Type declType = attribType(var.getJFXType(), forExprEnv);
JFXExpression expr = (JFXExpression)clause.getSequenceExpression();
Type exprType = types.upperBound(attribExpr(expr, forExprEnv));
attribVar(var, forExprEnv);
chk.checkNonVoid(((JFXTree)clause).pos(), exprType);
Type elemtype;
// must implement Sequence<T>?
Type base = types.asSuper(exprType, syms.javafx_SequenceType.tsym);
if (base == null)
base = types.asSuper(exprType, syms.iterableType.tsym);
if (base == null) {
log.warning(expr, MsgSym.MESSAGE_JAVAFX_ITERATING_NON_SEQUENCE);
elemtype = exprType;
} else {
List<Type> iterableParams = base.allparams();
if (iterableParams.isEmpty()) {
elemtype = syms.objectType;
} else {
elemtype = types.upperBound(iterableParams.last());
}
}
if (elemtype == syms.errType) {
log.error(((JFXTree)(clause.getSequenceExpression())).pos(), MsgSym.MESSAGE_FOREACH_NOT_APPLICABLE_TO_TYPE);
} else if (elemtype == syms.botType || elemtype == syms.unreachableType) {
elemtype = syms.objectType;
} else {
// if it is a primitive type, unbox it
Type unboxed = types.unboxedType(elemtype);
if (unboxed != Type.noType) {
elemtype = unboxed;
}
chk.checkType(clause.getSequenceExpression().pos(), elemtype, declType, Sequenceness.DISALLOWED);
}
if (declType == syms.javafx_UnspecifiedType) {
var.type = elemtype;
var.sym.type = elemtype;
}
if (clause.getWhereExpression() != null) {
attribExpr(clause.getWhereExpression(), env, syms.booleanType);
}
}
forExprEnv.tree = tree; // before, we were not in loop!
attribTree(tree.getBodyExpression(), forExprEnv, VAL, pt.tag != ERROR ? pt : Type.noType, Sequenceness.PERMITTED);
Type bodyType = tree.getBodyExpression().type;
if (bodyType == syms.unreachableType)
log.error(tree.getBodyExpression(), MsgSym.MESSAGE_UNREACHABLE_STMT);
Type owntype = (bodyType == null || bodyType == syms.voidType)?
syms.voidType :
types.isSequence(bodyType) ?
bodyType :
types.sequenceType(bodyType);
while (forClauses.size() > forClausesOldSize)
forClauses.remove(forClauses.size()-1);
forExprEnv.info.scope.leave();
result = check(tree, owntype, VAL, pkind, pt, pSequenceness);
}
@Override
public void visitForExpressionInClause(JFXForExpressionInClause that) {
// Do not assert that we cannot reach here as this unit can
// be visited by virtue of visiting JFXErronous which
// will attempt to visit each Erroneous node that it has
// encapsualted.
//
}
public void visitIndexof(JFXIndexof tree) {
for (int n = forClauses == null ? 0 : forClauses.size(); ; ) {
if (--n < 0) {
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_INDEXOF_NOT_FOUND, tree.fname.name);
break;
}
JFXForExpressionInClause clause = forClauses.get(n);
// Don't try to examine erroneous in clauses. We don't wish to
// place the entire for expression into error nodes, just because
// one or more in clauses was in error, so we jsut skip any
// erroneous ones.
//
if (clause == null || clause instanceof JFXErroneousForExpressionInClause) continue;
JFXVar v = clause.getVar();
// Don't try to deal with Erroneous or missing variables
//
if (v == null || v instanceof JFXErroneousVar) continue;
if (clause.getVar().getName() == tree.fname.name) {
tree.clause = clause;
tree.fname.sym = clause.getVar().sym;
clause.setIndexUsed(true);
break;
}
}
result = check(tree, syms.javafx_IntegerType, VAL,
pkind, pt, pSequenceness);
}
@Override
public void visitSkip(JFXSkip tree) {
result = syms.voidType;
tree.type = result;
}
@Override
public void visitBlockExpression(JFXBlock tree) {
// Create a new local environment with a local scope.
JavafxEnv<JavafxAttrContext> localEnv;
if (env.info.scope.owner.kind == TYP) {
// Block is a static or instance initializer;
// let the owner of the environment be a freshly
// created BLOCK-method.
localEnv = newLocalEnv(tree);
if ((tree.flags & STATIC) != 0) {
localEnv.info.staticLevel++;
}
} else {
Scope localScope = new Scope(env.info.scope.owner);
localScope.next = env.info.scope;
localEnv = env.dup(tree, env.info.dup(localScope));
localEnv.outer = env;
if (env.tree instanceof JFXFunctionDefinition) {
if (env.enclClass.runMethod == env.tree)
env.enclClass.runBodyScope = localEnv.info.scope;
localEnv.info.scope.owner = env.info.scope.owner;
}
else {
localEnv.info.scope.owner = new MethodSymbol(BLOCK, names.empty, null, env.enclClass.sym);
}
}
memberEnter.memberEnter(tree.getStmts(), localEnv);
if (tree.getValue() != null) {
memberEnter.memberEnter(tree.getValue(), localEnv);
}
boolean canReturn = true;
boolean unreachableReported = false;
tree.type = syms.javafx_UnspecifiedType;
for (List<JFXExpression> l = tree.stats; l.nonEmpty(); l = l.tail) {
if (! canReturn && ! unreachableReported) {
unreachableReported = true;
log.error(l.head.pos(), MsgSym.MESSAGE_UNREACHABLE_STMT);
}
Type stype = attribExpr(l.head, localEnv);
if (stype == syms.unreachableType)
canReturn = false;
if (inBindContext && (l.head.getFXTag() != JavafxTag.VAR_DEF)) {
log.error(l.head.pos(), MsgSym.MESSAGE_JAVAFX_NOT_ALLOWED_IN_BIND_CONTEXT, l.head.toString());
}
}
Type owntype = null;
if (tree.value != null) {
if (!canReturn && !unreachableReported) {
log.error(tree.value.pos(), MsgSym.MESSAGE_UNREACHABLE_STMT);
}
Type valueType = attribExpr(tree.value, localEnv, pt, pSequenceness);
owntype = valueType != syms.unreachableType ?
unionType(tree.pos(), tree.type, valueType) :
syms.unreachableType;
}
if (owntype == null) {
owntype = syms.voidType;
}
if (!canReturn) {
owntype = syms.unreachableType;
}
owntype = owntype.baseType();
result = check(tree, owntype, VAL, pkind, pt, pSequenceness);
if (env.info.scope.owner.kind != TYP)
localEnv.info.scope.leave();
}
/**
* @param tree
*/
@Override
public void visitWhileLoop(JFXWhileLoop tree) {
attribExpr(tree.cond, env, syms.booleanType);
attribExpr(tree.body, env.dup(tree));
result = syms.voidType;
tree.type = result;
}
@Override
public void visitInstanciate(JFXInstanciate tree) {
Type owntype = syms.errType;
// The local environment of a class creation is
// a new environment nested in the current one.
JavafxEnv<JavafxAttrContext> localEnv = newLocalEnv(tree);
List<JFXVar> vars = tree.getLocalvars();
memberEnter.memberEnter(vars, localEnv);
for (List<JFXVar> l = vars; l.nonEmpty(); l = l.tail)
attribExpr(l.head, localEnv);
// The anonymous inner class definition of the new expression,
// if one is defined by it.
JFXClassDeclaration cdef = tree.getClassBody();
// If enclosing class is given, attribute it, and
// complete class name to be fully qualified
JFXExpression clazz = tree.getIdentifier(); // Class field following new
// Attribute clazz expression and store
// symbol + type back into the attributed tree.
Type clazztype = chk.checkClassType(
clazz.pos(), attribType(clazz, env), true);
chk.validate(clazz);
if (!clazztype.tsym.isInterface() &&
clazztype.getEnclosingType().tag == CLASS) {
// Check for the existence of an apropos outer instance
rs.resolveImplicitThis(tree.pos(), env, clazztype);
}
// Attribute constructor arguments.
List<Type> argtypes = attribArgs(tree.getArgs(), localEnv);
// If we have made no mistakes in the class type...
if (clazztype.tag == CLASS) {
// Check that class is not abstract
if (cdef == null &&
(clazztype.tsym.flags() & (ABSTRACT | INTERFACE | JavafxFlags.MIXIN)) != 0) {
log.error(tree.pos(), MsgSym.MESSAGE_ABSTRACT_CANNOT_BE_INSTANTIATED,
clazztype.tsym);
} else if (cdef != null && clazztype.tsym.isInterface()) {
// Check that no constructor arguments are given to
// anonymous classes implementing an interface
if (!argtypes.isEmpty())
log.error(tree.getArgs().head.pos(), MsgSym.MESSAGE_ANON_CLASS_IMPL_INTF_NO_ARGS);
// Error recovery: pretend no arguments were supplied.
argtypes = List.nil();
}
// Resolve the called constructor under the assumption
// that we are referring to a superclass instance of the
// current instance (JLS ???).
else {
localEnv.info.selectSuper = cdef != null;
localEnv.info.varArgs = false;
if (! types.isJFXClass(clazztype.tsym))
tree.constructor = rs.resolveConstructor(
tree.pos(), localEnv, clazztype, argtypes, null);
/**
List<Type> emptyTypeargtypes = List.<Type>nil();
tree.constructor = rs.resolveConstructor(
tree.pos(), localEnv, clazztype, argtypes, emptyTypeargtypes);
Type ctorType = checkMethod(clazztype,
tree.constructor,
localEnv,
tree.getArguments(),
argtypes,
emptyTypeargtypes,
localEnv.info.varArgs);
if (localEnv.info.varArgs)
assert ctorType.isErroneous();
* ***/
}
if (((ClassSymbol) clazztype.tsym).fullname == defs.javalangThreadName) {
log.warning(tree.pos(), MsgSym.MESSAGE_JAVAFX_EXPLICIT_THREAD);
}
if (cdef != null) {
// We are seeing an anonymous class instance creation.
// In this case, the class instance creation
// expression
//
// E.new <typeargs1>C<typargs2>(args) { ... }
//
// is represented internally as
//
// E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
//
// This expression is then *transformed* as follows:
//
// (1) add a STATIC flag to the class definition
// if the current environment is static
// (2) add an extends or implements clause
// (3) add a constructor.
//
// For instance, if C is a class, and ET is the type of E,
// the expression
//
// E.new <typeargs1>C<typargs2>(args) { ... }
//
// is translated to (where X is a fresh name and typarams is the
// parameter list of the super constructor):
//
// new <typeargs1>X(<*nullchk*>E, args) where
// X extends C<typargs2> {
// <typarams> X(ET e, args) {
// e.<typeargs1>super(args)
// }
// ...
// }
// if (JavafxResolve.isStatic(env)) cdef.mods.flags |= STATIC;
// always need to be static, because they will have generated static members
cdef.mods.flags |= STATIC;
// now handled in class processing
// if (clazztype.tsym.isInterface()) {
// cdef.implementing = List.of(clazz);
// } else {
// cdef.extending = clazz;
// }
if (cdef.sym == null)
enter.classEnter(cdef, env);
attribDecl(cdef, localEnv);
attribClass(cdef.pos(), null, cdef.sym);
// Reassign clazztype and recompute constructor.
clazztype = cdef.sym.type;
Symbol sym = rs.resolveConstructor(
tree.pos(), localEnv, clazztype, argtypes,
List.<Type>nil(), true, false);
tree.constructor = sym;
}
// if (tree.constructor != null && tree.constructor.kind == MTH)
owntype = clazz.type; // this give declared type, where clazztype would give anon type
}
Scope partsScope = new Scope(clazztype.tsym);
for (JFXObjectLiteralPart localPt : tree.getParts()) {
// Protect against erroneous nodes
//
if (localPt == null) continue;
JFXObjectLiteralPart part = (JFXObjectLiteralPart)localPt;
boolean wasInBindContext = this.inBindContext;
this.inBindContext |= part.isBound();
Symbol memberSym = rs.findIdentInType(env, clazz.type, part.name, VAR);
memberSym = rs.access(memberSym, localPt.pos(), clazz.type, part.name, true);
memberSym.complete();
Scope.Entry oldEntry = partsScope.lookup(memberSym.name);
if (oldEntry.sym != null) {
log.error(localPt.pos(), MsgSym.MESSAGE_JAVAFX_ALREAD_DEFINED_OBJECT_LITERAL, memberSym);
}
partsScope.enter(memberSym);
Type memberType = memberSym.type;
if (!(memberSym instanceof VarSymbol) ) {
log.error(localPt.pos(), MsgSym.MESSAGE_JAVAFX_INVALID_ASSIGNMENT);
memberType = Type.noType;
}
Scope initScope = new Scope(new MethodSymbol(BLOCK, memberSym.name, null, env.enclClass.sym));
initScope.next = env.info.scope;
JavafxEnv<JavafxAttrContext> initEnv =
env.dup(localPt, env.info.dup(initScope));
initEnv.outer = localEnv;
// Protect against erroneous tress called for attribution from the IDE
//
if (part.getExpression() != null) {
attribExpr(part.getExpression(), initEnv, memberType);
}
if (memberSym instanceof VarSymbol) {
VarSymbol v = (VarSymbol) memberSym;
WriteKind kind = part.isBound() ? WriteKind.INIT_BIND : WriteKind.INIT_NON_BIND;
chk.checkAssignable(part.pos(), v, part, clazz.type, localEnv, kind);
chk.checkBidiBind(part.getExpression(), part.getBindStatus(), localEnv, v.type);
}
part.type = memberType;
part.sym = memberSym;
this.inBindContext = wasInBindContext;
}
result = check(tree, owntype, VAL, pkind, pt, pSequenceness);
localEnv.info.scope.leave();
}
/** Make an attributed null check tree.
*/
public JFXExpression makeNullCheck(JFXExpression arg) {
// optimization: X.this is never null; skip null check
Name name = JavafxTreeInfo.name(arg);
if (name == names._this || name == names._super) return arg;
JavafxTag optag = JavafxTag.NULLCHK;
JFXUnary tree = fxmake.at(arg.pos).Unary(optag, arg);
tree.operator = syms.nullcheck;
tree.type = arg.type;
return tree;
}
@Override
public void visitFunctionValue(JFXFunctionValue tree) {
JFXFunctionDefinition def = new JFXFunctionDefinition(fxmake.Modifiers(Flags.SYNTHETIC), defs.lambdaName, tree);
def.pos = tree.pos;
tree.definition = def;
MethodSymbol m = new MethodSymbol(SYNTHETIC, def.name, null, env.enclClass.sym);
// m.flags_field = chk.checkFlags(def.pos(), def.mods.flags, m, def);
def.sym = m;
finishFunctionDefinition(def, env);
result = tree.type = check(tree, syms.makeFunctionType((MethodType) def.type), VAL, pkind, pt, pSequenceness);
}
@Override
public void visitFunctionDefinition(JFXFunctionDefinition tree) {
// Tree may come in paritally complete or in error from IDE and so we protect
// against it. Do nothing if the tree isn't properly attributed.
//
if (tree.sym != null) {
MethodSymbol m = tree.sym;
m.complete();
warnOnStaticUse(tree.pos(), tree.getModifiers(), m);
}
}
/** Search super-clases for a parameter type in a matching method.
* The idea is that when a formal parameter isn't specified in a class
* function, see if there is a method with the same name in a superclass,
* and use that method's parameter type. If there are multiple methods
* in super-classes that all have the same name and argument count,
* the parameter types have to be the same in all of them.
* @param csym Class to search.
* @param name Name of matching methods.
* @param paramCount Number of parameters of matching methods.
* @param paramNum The parameter number we're concerned about,
* or -1 if we're searching for the return type.
* @return The found type. Null is we found no match.
* Notype if we found an ambiguity.
*/
private Type searchSupersForParamType (ClassSymbol c, Name name, int paramCount, int paramNum) {
Type found = null;
for (Scope.Entry e = c.members().lookup(name);
e.scope != null;
e = e.next()) {
if ((e.sym.kind & MTH) == 0 ||
(e.sym.flags_field & (STATIC|SYNTHETIC)) != 0)
continue;
Type mt = types.memberType(c.type, e.sym);
if (mt == null)
continue;
List<Type> formals = mt.getParameterTypes();
if (formals.size() != paramCount)
continue;
Type t = paramNum >= 0 ? formals.get(paramNum) : mt.getReturnType();
if (t == Type.noType)
return t;
if (found == null)
found = t;
else if (t != null && found != t)
return Type.noType;
}
Type st = types.supertype(c.type);
if (st.tag == CLASS) {
Type t = searchSupersForParamType((ClassSymbol)st.tsym, name, paramCount, paramNum);
if (t == Type.noType)
return t;
if (found == null)
found = t;
else if (t != null && found != t)
return Type.noType;
}
for (List<Type> l = types.interfaces(c.type);
l.nonEmpty();
l = l.tail) {
Type t = searchSupersForParamType((ClassSymbol)l.head.tsym, name, paramCount, paramNum);
if (t == Type.noType)
return t;
if (found == null)
found = t;
else if (t != null && found != t)
return Type.noType;
}
return found;
}
public void finishFunctionDefinition(JFXFunctionDefinition tree, JavafxEnv<JavafxAttrContext> env) {
MethodSymbol m = tree.sym;
JFXFunctionValue opVal = tree.operation;
JavafxEnv<JavafxAttrContext> localEnv = memberEnter.methodEnv(tree, env);
Type returnType;
// Create a new environment with local scope
// for attributing the method.
JavafxEnv<JavafxAttrContext> lintEnv = env;
while (lintEnv.info.lint == null)
lintEnv = lintEnv.next;
JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
Lint lint = lintEnv.info.lint.augment(m.attributes_field, m.flags());
Lint prevLint = chk.setLint(lint);
boolean wasInBindContext = this.inBindContext;
this.inBindContext = tree.isBound();
try {
localEnv.info.lint = lint;
ClassSymbol owner = env.enclClass.sym;
if ((owner.flags() & ANNOTATION) != 0 &&
tree.operation.funParams.nonEmpty())
log.error(tree.operation.funParams.head.pos(),
MsgSym.MESSAGE_INTF_ANNOTATION_MEMBERS_CANNOT_HAVE_PARAMS);
// Attribute all value parameters.
ListBuffer<Type> argbuf = new ListBuffer<Type>();
List<Type> pparam = null;
MethodType mtype = null;
if (pt.tag == TypeTags.METHOD || pt instanceof FunctionType) {
mtype = pt.asMethodType();
pparam = mtype.getParameterTypes();
}
int paramNum = 0;
List<JFXVar> params = tree.getParams();
int paramCount = params.size();
for (List<JFXVar> l = params; l.nonEmpty(); l = l.tail) {
JFXVar pvar = l.head;
// Don't try to deal with parameters that are Erroneous
// or missing, which can happen when the IDE is trying to
// make sense of a partially completed function definition
//
if ( pvar == null // Not even present
|| pvar.getJFXType() == null // There, but can't do anythign about typing it
|| pvar.getJFXType() instanceof JFXErroneousType // There, but flagged as an erroneous type for some syntactic reason
)
continue; // Hence, we can't do anythign with this parameter definitionm skip it
Type type;
if (pparam != null && pparam.nonEmpty()) {
type = pparam.head;
pparam = pparam.tail;
}
else {
type = syms.objectType;
if (pvar.getJFXType() instanceof JFXTypeUnknown) {
Type t = searchSupersForParamType (owner, m.name, paramCount, paramNum);
if (t == Type.noType)
log.warning(pvar.pos(), MsgSym.MESSAGE_JAVAFX_AMBIGUOUS_PARAM_TYPE_FROM_SUPER);
else if (t != null)
type = t;
}
}
pvar.type = type;
type = chk.checkNonVoid(pvar, attribVar(pvar, localEnv));
argbuf.append(type);
paramNum++;
}
returnType = syms.unknownType;
if (opVal.getJFXReturnType().getFXTag() != JavafxTag.TYPEUNKNOWN)
returnType = attribType(tree.getJFXReturnType(), localEnv);
else if (mtype != null) {
Type mrtype = mtype.getReturnType();
if (mrtype != null && mrtype.tag != TypeTags.NONE)
returnType = mrtype;
} else {
// If we made use of the parameter types to select a matching
// method, we could presumably get a non-ambiguoys return type.
// But this is pretty close, in practice.
Type t = searchSupersForParamType (owner, m.name, paramCount, -1);
if (t == Type.noType)
log.warning(tree.pos(), MsgSym.MESSAGE_JAVAFX_AMBIGUOUS_RETURN_TYPE_FROM_SUPER);
else if (t != null)
returnType = t;
}
if (returnType == syms.javafx_java_lang_VoidType)
returnType = syms.voidType;
mtype = new MethodType(argbuf.toList(),
returnType, // may be unknownType
List.<Type>nil(),
syms.methodClass);
m.type = mtype;
if (tree.getBodyExpression() == null) {
// Empty bodies are only allowed for
// abstract, native, or interface methods, or for methods
// in a retrofit signature class.
if ((owner.flags() & INTERFACE) == 0 &&
(tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
!relax)
log.error(tree.pos(), MsgSym.MESSAGE_MISSING_METH_BODY_OR_DECL_ABSTRACT);
else if (returnType == syms.unknownType)
// no body, can't infer, assume Any
// FIXME Should this be Void or an error?
returnType = syms.javafx_AnyType;
} else if ((owner.flags() & INTERFACE) != 0) {
log.error(tree.getBodyExpression().pos(), MsgSym.MESSAGE_INTF_METH_CANNOT_HAVE_BODY);
} else if ((tree.mods.flags & ABSTRACT) != 0) {
log.error(tree.pos(), MsgSym.MESSAGE_ABSTRACT_METH_CANNOT_HAVE_BODY);
} else if ((tree.mods.flags & NATIVE) != 0) {
log.error(tree.pos(), MsgSym.MESSAGE_NATIVE_METH_CANNOT_HAVE_BODY);
} else {
JFXBlock body = opVal.getBodyExpression();
if (body.value instanceof JFXReturn) {
body.value = ((JFXReturn) body.value).expr;
}
// Attribute method bodyExpression
Type typeToCheck = returnType;
if(tree.name == defs.internalRunFunctionName) {
typeToCheck = Type.noType;
}
else if (returnType == syms.voidType) {
typeToCheck = Type.noType;
}
Type bodyType = attribExpr(body, localEnv, typeToCheck); // Special handling for the run function. Its body is empty at this point.
if (body.value == null) {
if (returnType == syms.unknownType)
returnType = syms.javafx_VoidType; //TODO: this is wrong if there is a return statement
} else {
if (returnType == syms.unknownType)
returnType = bodyType == syms.unreachableType ? syms.javafx_VoidType : bodyType;
else if (returnType != syms.javafx_VoidType && tree.getName() != defs.internalRunFunctionName
// Temporary hack to suppress duplicate warning on Number->Integer.
// Hack can go away if/when we make it an error. FIXME.
&& ! (typeToCheck.tag <= LONG && bodyType.tag >= FLOAT && bodyType.tag <= DOUBLE))
chk.checkType(tree.pos(), bodyType, returnType, Sequenceness.DISALLOWED);
}
if (tree.isBound() && returnType == syms.javafx_VoidType) {
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_BOUND_FUNCTION_MUST_NOT_BE_VOID);
}
}
localEnv.info.scope.leave();
mtype.restype = returnType;
result = tree.type = mtype;
// If we override any other methods, check that we do so properly.
// JLS ???
if (m.owner instanceof ClassSymbol) {
// Fix primitive/number types so overridden Java methods will have the correct types.
fixOverride(tree, m);
chk.checkOverride(tree, m);
} else {
if ((m.flags() & JavafxFlags.OVERRIDE) != 0) {
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_DECLARED_OVERRIDE_DOES_NOT, m);
}
}
}
finally {
chk.setLint(prevLint);
log.useSource(prev);
this.inBindContext = wasInBindContext;
}
// mark the method varargs, if necessary
// if (isVarArgs) m.flags_field |= Flags.VARARGS;
// Set the inferred types in the MethodType.argtypes and in correct symbols in MethodSymbol
List<VarSymbol> paramSyms = List.<VarSymbol>nil();
List<Type> paramTypes = List.<Type>nil();
for (JFXVar var : tree.getParams()) {
// Skip erroneous parameters, which happens if the IDE is calling with a
// a paritally defined function.
//
if (var == null || var.type == null) continue;
paramSyms = paramSyms.append(var.sym);
paramTypes = paramTypes.append(var.type);
}
m.params = paramSyms;
if (m.type != null && m.type instanceof MethodType) {
((MethodType)m.type).argtypes = paramTypes;
}
}
@Override
public void visitTry(JFXTry tree) {
boolean canReturn = false;
// Attribute body
Type stype = attribExpr(tree.body, env.dup(tree, env.info.dup()));
if (stype != syms.unreachableType)
canReturn = true;
// Attribute catch clauses
for (List<JFXCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
JFXCatch c = l.head;
if (c == null) continue; // Don't try to handle erroneous catch blocks
JavafxEnv<JavafxAttrContext> catchEnv = newLocalEnv(c);
memberEnter.memberEnter(c.param, catchEnv);
if (c.param == null) continue; // Don't try to handle erroneous catch blocks
if (c.param.type == null)
c.param.sym.type = c.param.type = syms.throwableType;
Type ctype = attribDecl((JFXVar) c.param, catchEnv);
if (c.param.type.tsym.kind == Kinds.VAR) {
c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
}
//uses vartype
// chk.checkType(c.param.vartype.pos(),
// chk.checkClassType(c.param.vartype.pos(), ctype),
// syms.throwableType);
ctype = attribExpr(c.body, catchEnv);
if (ctype != syms.unreachableType)
canReturn = true;
}
// Attribute finalizer
if (tree.finalizer != null) attribExpr(tree.finalizer, env);
result = canReturn ? syms.voidType : syms.unreachableType;
tree.type = result;
}
@Override
public void visitIfExpression(JFXIfExpression tree) {
attribExpr(tree.cond, env, syms.booleanType);
attribTree(tree.truepart, env, VAL, pt, pSequenceness);
Type falsepartType;
if (tree.falsepart == null) {
falsepartType = syms.voidType;
} else {
falsepartType = attribTree(tree.falsepart, env, VAL, pt, pSequenceness);
{ //TODO: ...
// A kludge, which can go away if we change things so that
// the compiler and runtime accepts null and [] equivalently.
// Well, actually, look at JFXC-925.
// Also, in a bind context, we need to know th etype of null
if (tree.truepart instanceof JFXSequenceEmpty
|| tree.truepart.type.tag == BOT)
tree.truepart.type = falsepartType;
else if (tree.falsepart instanceof JFXSequenceEmpty
|| falsepartType.tag == BOT)
falsepartType = tree.falsepart.type = tree.truepart.type;
}
}
result = check(tree,
capture(condType(tree.pos(), tree.cond.type,
tree.truepart.type, falsepartType)),
VAL, pkind, pt, pSequenceness);
}
//where
/** Compute the type of a conditional expression, after
* checking that it exists. See Spec 15.25.
*
* @param pos The source position to be used for
* error diagnostics.
* @param condtype The type of the expression's condition.
* @param type1 The type of the expression's then-part.
* @param type2 The type of the expression's else-part.
*/
private Type condType(DiagnosticPosition pos,
Type condtype,
Type thentype,
Type elsetype) {
Type ctype = unionType(pos, thentype, elsetype);
// If condition and both arms are numeric constants,
// evaluate at compile-time.
return ((condtype.constValue() != null) &&
(thentype.constValue() != null) &&
(elsetype.constValue() != null))
? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
: ctype;
}
/** Compute the type of a conditional expression, after
* checking that it exists. Does not take into
* account the special case where condition and both arms
* are constants.
*
* @param pos The source position to be used for error
* diagnostics.
* @param condtype The type of the expression's condition.
* @param type1 The type of the expression's then-part.
* @param type2 The type of the expression's else-part.
*/
private Type unionType(DiagnosticPosition pos,
Type type1, Type type2) {
if (type1 == syms.unreachableType || type1 == syms.javafx_UnspecifiedType)
return type2;
if (type2 == syms.unreachableType || type2 == syms.javafx_UnspecifiedType)
return type1;
if (type1 == type2)
return type1;
// Ensure that we don't NPE if either of the inputs were from
// Erroneous nodes such as missing blocks on conditionals and so on.
//
if (type1 == null ) {
if (type2 == null) {
return syms.voidType;
} else {
return type2;
}
} else if (type2 == null) {
return type1;
}
if (type1.tag == VOID || type2.tag == VOID)
return syms.voidType;
boolean isSequence1 = types.isSequence(type1);
boolean isSequence2 = types.isSequence(type2);
if (isSequence1 || isSequence2) {
if (isSequence1)
type1 = types.elementType(type1);
if (isSequence2)
type2 = types.elementType(type2);
Type union = unionType(pos, type1, type2);
return union.tag == ERROR ? union : types.sequenceType(union);
}
// If same type, that is the result
if (types.isSameType(type1, type2))
return type1.baseType();
Type thenUnboxed = (!allowBoxing || type1.isPrimitive())
? type1 : types.unboxedType(type1);
Type elseUnboxed = (!allowBoxing || type2.isPrimitive())
? type2 : types.unboxedType(type2);
// Otherwise, if both arms can be converted to a numeric
// type, return the least numeric type that fits both arms
// (i.e. return larger of the two, or return int if one
// arm is short, the other is char).
if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
// If one arm has an integer subrange type (i.e., byte,
// short, or char), and the other is an integer constant
// that fits into the subrange, return the subrange type.
if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
types.isAssignable(elseUnboxed, thenUnboxed))
return thenUnboxed.baseType();
if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
types.isAssignable(thenUnboxed, elseUnboxed))
return elseUnboxed.baseType();
for (int i = BYTE; i < VOID; i++) {
Type candidate = syms.typeOfTag[i];
if (types.isSubtype(thenUnboxed, candidate) &&
types.isSubtype(elseUnboxed, candidate))
return candidate;
}
}
// Those were all the cases that could result in a primitive
if (allowBoxing) {
type1 = syms.boxIfNeeded(type1);
type2 = syms.boxIfNeeded(type2);
}
if (types.isSubtype(type1, type2))
return type2.baseType();
if (types.isSubtype(type2, type1))
return type1.baseType();
if (!allowBoxing) {
log.error(pos, MsgSym.MESSAGE_NEITHER_CONDITIONAL_SUBTYPE,
type1, type2);
return type1.baseType();
}
// both are known to be reference types. The result is
// lub(type1,type2). This cannot fail, as it will
// always be possible to infer "Object" if nothing better.
return types.lub(type1.baseType(), type2.baseType());
}
@Override
public void visitBreak(JFXBreak tree) {
tree.target = findJumpTarget(tree.pos(), tree.getFXTag(), tree.label, env);
result = tree.type = syms.unreachableType;
}
@Override
public void visitContinue(JFXContinue tree) {
tree.target = findJumpTarget(tree.pos(), tree.getFXTag(), tree.label, env);
result = tree.type = syms.unreachableType;
}
//where
/** Return the target of a break or continue statement, if it exists,
* report an error if not.
* Note: The target of a labelled break or continue is the
* (non-labelled) statement tree referred to by the label,
* not the tree representing the labelled statement itself.
*
* @param pos The position to be used for error diagnostics
* @param tag The tag of the jump statement. This is either
* Tree.BREAK or Tree.CONTINUE.
* @param label The label of the jump statement, or null if no
* label is given.
* @param env The environment current at the jump statement.
*/
private JFXTree findJumpTarget(DiagnosticPosition pos,
JavafxTag tag,
Name label,
JavafxEnv<JavafxAttrContext> env) {
// Search environments outwards from the point of jump.
JavafxEnv<JavafxAttrContext> env1 = env;
LOOP:
while (env1 != null) {
switch (env1.tree.getFXTag()) {
case WHILELOOP:
case FOR_EXPRESSION:
if (label == null) return env1.tree;
break;
default:
}
env1 = env1.next;
}
if (label != null)
log.error(pos, MsgSym.MESSAGE_UNDEF_LABEL, label);
else if (tag == JavafxTag.CONTINUE)
log.error(pos, MsgSym.MESSAGE_CONT_OUTSIDE_LOOP);
else
log.error(pos, MsgSym.MESSAGE_BREAK_OUTSIDE_SWITCH_LOOP);
return null;
}
@Override
public void visitReturn(JFXReturn tree) {
if (env.enclFunction == null) {
log.error(tree.pos(), MsgSym.MESSAGE_RETURN_OUTSIDE_METH);
} else {
// Attribute return expression, if it exists, and check that
// it conforms to result type of enclosing method.
Symbol m = env.enclFunction.sym;
tree.returnType = m.type.getReturnType();
JFXBlock enclBlock = env.enclFunction.operation.bodyExpression;
if (tree.returnType == null)
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_CANNOT_INFER_RETURN_TYPE);
else if (tree.returnType.tag == VOID) {
if (tree.expr != null) {
log.error(tree.expr.pos(),
MsgSym.MESSAGE_CANNOT_RET_VAL_FROM_METH_DECL_VOID);
}
} else if (tree.expr == null) {
if (enclBlock.type == syms.javafx_UnspecifiedType)
enclBlock.type = syms.javafx_VoidType;
else
log.error(tree.pos(), MsgSym.MESSAGE_MISSING_RET_VAL);
} else {
if (enclBlock.type.tag == VOID) {
log.error(tree.pos(), MsgSym.MESSAGE_CANNOT_RET_VAL_FROM_METH_DECL_VOID);
}
Type exprType = attribExpr(tree.expr, env);
enclBlock.type = unionType(tree.pos(), enclBlock.type, exprType);
}
}
result = tree.type = syms.unreachableType;
}
@Override
public void visitThrow(JFXThrow tree) {
if (tree.expr != null && !(tree.expr instanceof JFXErroneous)) {
attribExpr(tree.expr, env, syms.throwableType);
}
result = tree.type = syms.unreachableType;
}
private void searchParameterTypes (JFXExpression meth, Type[] paramTypes) {
// FUTURE: Search for matching overloaded methods/functions that
// would be a match for meth, and number of arguments==paramTypes.length.
// If all the candidates have the same type for parameter # i,
// set paramTypes[i] to that type.
// Otherwise, leave paramTypes[i]==null.
}
@Override
public void visitFunctionInvocation(JFXFunctionInvocation tree) {
// The local environment of a method application is
// a new environment nested in the current one.
JavafxEnv<JavafxAttrContext> localEnv = env.dup(tree, env.info.dup());
// The types of the actual method type arguments.
List<Type> typeargtypes;
Name methName = JavafxTreeInfo.name(tree.meth);
int argcount = tree.args.size();
Type[] paramTypes = new Type[argcount];
searchParameterTypes(tree.meth, paramTypes);
ListBuffer<Type> argtypebuffer = new ListBuffer<Type>();
int i = 0;
for (List<JFXExpression> l = tree.args; l.nonEmpty(); l = l.tail, i++) {
Type argtype = paramTypes[i];
if (argtype != null)
attribExpr(l.head, env, argtype);
else
argtype = chk.checkNonVoid(l.head.pos(),
types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly)));
argtypebuffer.append(argtype);
}
List<Type> argtypes = argtypebuffer.toList();
typeargtypes = attribTypes(tree.typeargs, localEnv);
// ... and attribute the method using as a prototype a methodtype
// whose formal argument types is exactly the list of actual
// arguments (this will also set the method symbol).
Type mpt = new MethodType(argtypes, pt, null, syms.methodClass);
if (typeargtypes.nonEmpty()) mpt = new ForAll(typeargtypes, mpt);
localEnv.info.varArgs = false;
Type mtype = attribExpr(tree.meth, localEnv, mpt);
if (localEnv.info.varArgs)
assert mtype.isErroneous() || tree.varargsElement != null;
// Compute the result type.
Type restype = mtype.getReturnType();
if (restype == syms.unknownType) {
log.error(tree.meth.pos(), MsgSym.MESSAGE_JAVAFX_FUNC_TYPE_INFER_CYCLE, methName);
restype = syms.objectType;
}
// as a special case, array.clone() has a result that is
// the same as static type of the array being cloned
if (tree.meth.getFXTag() == JavafxTag.SELECT &&
allowCovariantReturns &&
methName == names.clone &&
types.isArray(((JFXSelect) tree.meth).selected.type))
restype = ((JFXSelect) tree.meth).selected.type;
// as a special case, x.getClass() has type Class<? extends |X|>
if (allowGenerics &&
methName == names.getClass && tree.args.isEmpty()) {
Type qualifier = (tree.meth.getFXTag() == JavafxTag.SELECT)
? ((JFXSelect) tree.meth).selected.type
: env.enclClass.sym.type;
qualifier = syms.boxIfNeeded(qualifier);
restype = new
ClassType(restype.getEnclosingType(),
List.<Type>of(new WildcardType(types.erasure(qualifier),
BoundKind.EXTENDS,
syms.boundClass)),
restype.tsym);
}
if (mtype instanceof ErrorType) {
tree.type = mtype;
result = mtype;
}
else if (mtype instanceof MethodType || mtype instanceof FunctionType) {
// If the "method" has a symbol, we've already checked for
// formal/actual consistency. So doing it again would be
// wasteful - plus varargs hasn't been properly implemented.
if (tree.meth.getFXTag() != JavafxTag.SELECT &&
tree.meth.getFXTag() != JavafxTag.IDENT &&
! rs.argumentsAcceptable(argtypes, mtype.getParameterTypes(),
true, false, Warner.noWarnings))
log.error(tree,
MsgSym.MESSAGE_JAVAFX_CANNOT_APPLY_FUNCTION,
mtype.getParameterTypes(), argtypes);
// Check that value of resulting type is admissible in the
// current context. Also, capture the return type
result = check(tree, capture(restype), VAL, pkind, pt, pSequenceness);
}
else {
log.error(tree,
MsgSym.MESSAGE_JAVAFX_NOT_A_FUNC,
mtype, typeargtypes, Type.toString(argtypes));
tree.type = pt;
result = pt;
}
Symbol msym = JavafxTreeInfo.symbol(tree.meth);
// We can add more methods here that we want to warn about.
// If it becomes too hairy, it should be moved into a separate method,
// and perhaps be table-driven. FIXME.
if (msym != null && msym.owner instanceof ClassSymbol &&
((ClassSymbol) msym.owner).fullname == defs.javalangThreadName &&
msym.name == defs.startName) {
log.warning(tree.pos(), MsgSym.MESSAGE_JAVAFX_EXPLICIT_THREAD);
}
if (msym!=null && msym.owner!=null && msym.owner.type!=null &&
(msym.owner.type.tsym == syms.javafx_AutoImportRuntimeType.tsym ||
msym.owner.type.tsym == syms.javafx_FXRuntimeType.tsym) &&
methName == defs.isInitializedName) {
msym.flags_field |= JavafxFlags.FUNC_IS_INITIALIZED;
for (List<JFXExpression> l = tree.args; l.nonEmpty(); l = l.tail, i++) {
JFXExpression arg = l.head;
Symbol asym = JavafxTreeInfo.symbol(arg);
if (asym == null || !(asym.type instanceof ErrorType)) {
if (asym == null ||
!(asym instanceof VarSymbol) ||
(arg.getFXTag() != JavafxTag.IDENT && arg.getFXTag() != JavafxTag.SELECT) ||
(asym.flags() & JavafxFlags.IS_DEF) != 0 ||
asym.owner == null ||
asym.owner.kind != TYP) {
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_APPLIED_TO_INSTANCE_VAR, defs.isInitializedName);
} else {
// check that we have write access
// unless it is a public-init or public-read var, that was already handled
// the regular access check
if ((asym.flags() & (JavafxFlags.PUBLIC_INIT | JavafxFlags.PUBLIC_READ)) != 0) {
Type site;
JFXTree base;
switch (arg.getFXTag()) {
case IDENT:
base = null;
site = env.enclClass.sym.type;
break;
case SELECT:
base = ((JFXSelect)arg).selected;
site = base.type;
break;
default:
throw new AssertionError(); // see above, should not occur
}
chk.checkAssignable(tree.pos(), (VarSymbol) asym, base, site, env, WriteKind.VAR_QUERY);
}
}
}
}
}
chk.validate(tree.typeargs);
}
@Override
public void visitAssignop(JFXAssignOp tree) {
if (this.inBindContext) {
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_NOT_ALLOWED_IN_BIND_CONTEXT, "compound assignment");
}
// Attribute arguments.
Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
Type operand = attribExpr(tree.rhs, env);
// Fix types of numeric arguments with non -specified type.
Symbol lhsSym = JavafxTreeInfo.symbol(tree.lhs);
if (lhsSym != null &&
(lhsSym.type == null || lhsSym.type == Type.noType || lhsSym.type == syms.javafx_AnyType)) {
JFXVar lhsVarTree = varSymToTree.get(lhsSym);
owntype = setBinaryTypes(tree.getFXTag(), tree.lhs, lhsVarTree, lhsSym.type, lhsSym);
}
Symbol rhsSym = JavafxTreeInfo.symbol(tree.rhs);
if (rhsSym != null &&
(rhsSym.type == null || rhsSym.type == Type.noType || rhsSym.type == syms.javafx_AnyType)) {
JFXVar rhsVarTree = varSymToTree.get(rhsSym);
operand = setBinaryTypes(tree.getFXTag(), tree.rhs, rhsVarTree, rhsSym.type, rhsSym);
}
// Find operator.
Symbol operator = tree.operator = rs.resolveBinaryOperator(
tree.pos(), tree.getNormalOperatorFXTag(), env,
owntype, operand);
if (operator.kind == MTH) {
if (operator instanceof OperatorSymbol) {
chk.checkOperator(tree.pos(),
(OperatorSymbol)operator,
tree.getFXTag(),
owntype,
operand);
}
if (types.isSameType(operator.type.getReturnType(), syms.stringType)) {
// String assignment; make sure the lhs is a string
chk.checkType(tree.lhs.pos(),
owntype,
syms.stringType, Sequenceness.DISALLOWED);
} else {
chk.checkDivZero(tree.rhs.pos(), operator, operand);
chk.checkCastable(tree.rhs.pos(),
operator.type.getReturnType(),
owntype);
}
}
result = check(tree, owntype, VAL, pkind, pt, pSequenceness);
if (lhsSym != null && tree.rhs != null) {
JFXVar lhsVar = varSymToTree.get(lhsSym);
if (lhsVar != null && (lhsVar.getJFXType() instanceof JFXTypeUnknown)) {
if ((lhsVar.type == null || lhsVar.type == syms.javafx_AnyType)) {
if (tree.rhs.type != null && lhsVar.type != tree.rhs.type) {
lhsVar.type = lhsSym.type = tree.rhs.type;
JFXExpression jcExpr = fxmake.at(tree.pos()).Ident(lhsSym);
lhsVar.setJFXType(fxmake.at(tree.pos()).TypeClass(jcExpr, lhsVar.getJFXType().getCardinality()));
}
}
}
}
}
@Override
public void visitUnary(JFXUnary tree) {
switch (tree.getFXTag()) {
case SIZEOF: {
attribExpr(tree.arg, env);
result = check(tree, syms.javafx_IntegerType, VAL, pkind, pt, pSequenceness);
return;
}
case REVERSE: {
Type argtype = chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
result = check(tree, argtype, VAL, pkind, pt, pSequenceness);
return;
}
}
boolean isIncDec = tree.getFXTag().isIncDec();
Type argtype;
if (isIncDec) {
if (this.inBindContext) {
switch (tree.getFXTag()) {
case PREINC:
case POSTINC:
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_NOT_ALLOWED_IN_BIND_CONTEXT, "++");
break;
case PREDEC:
case POSTDEC:
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_NOT_ALLOWED_IN_BIND_CONTEXT, "--");
break;
}
}
// Attribute arguments.
argtype = attribTree(tree.arg, env, VAR, Type.noType);
} else {
argtype = chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
}
//TODO: redundant now, but if we want to deferentiate error for increment/decremenet
// from assignment, this code may be useful
/***
if (isIncDec) {
Symbol argSym = JavafxTreeInfo.symbol(tree.arg);
if (argSym == null) {
log.error(tree, MsgSym.MESSAGE_JAVAFX_INVALID_ASSIGNMENT);
return;
}
if ((argSym.flags() & JavafxFlags.IS_DEF) != 0L) {
log.error(tree, MsgSym.MESSAGE_JAVAFX_CANNOT_ASSIGN_TO_DEF, argSym);
return;
}
if ((argSym.flags() & Flags.PARAMETER) != 0L) {
log.error(tree, MsgSym.MESSAGE_JAVAFX_CANNOT_ASSIGN_TO_PARAMETER, argSym);
return;
}
}
***/
Symbol sym = rs.resolveUnaryOperator(tree.pos(), tree.getFXTag(), env, argtype);
Type owntype = syms.errType;
if (sym instanceof OperatorSymbol) {
// Find operator.
Symbol operator = tree.operator = sym;
if (operator.kind == MTH) {
owntype = isIncDec
? tree.arg.type
: operator.type.getReturnType();
}
} else {
owntype = sym.type.getReturnType();
}
result = check(tree, owntype, VAL, pkind, pt, pSequenceness);
}
private Type setBinaryTypes(JavafxTag opcode, JFXExpression tree, JFXVar var, Type type, Symbol treeSym) {
Type newType = type;
JFXExpression jcExpression = null;
// boolean type
if (opcode == JavafxTag.OR ||
opcode == JavafxTag.AND) {
newType = syms.javafx_BooleanType;
jcExpression = fxmake.at(tree.pos()).Ident(syms.javafx_BooleanType.tsym);
}
// Integer type
else if (opcode == JavafxTag.MOD) {
newType = syms.javafx_IntegerType;
jcExpression = fxmake.at(tree.pos()).Ident(syms.javafx_IntegerType.tsym);
}
// Number type
else if (opcode == JavafxTag.LT ||
opcode == JavafxTag.GT ||
opcode == JavafxTag.LE ||
opcode == JavafxTag.GE ||
opcode == JavafxTag.PLUS ||
opcode == JavafxTag.MINUS ||
opcode == JavafxTag.MUL ||
opcode == JavafxTag.DIV ||
opcode == JavafxTag.PLUS_ASG ||
opcode == JavafxTag.MINUS_ASG ||
opcode == JavafxTag.MUL_ASG ||
opcode == JavafxTag.DIV_ASG) {
newType = syms.javafx_DoubleType;
jcExpression = fxmake.at(tree.pos()).Ident(syms.javafx_DoubleType.tsym);
}
else
return newType;
// tree is not null here
tree.setType(newType);
treeSym.type = newType;
if (var != null) {
var.setType(newType);
JFXType jfxType = fxmake.at(tree.pos()).TypeClass(jcExpression, Cardinality.SINGLETON);
jfxType.type = newType;
var.setJFXType(jfxType);
var.sym.type = newType;
}
return newType;
}
@Override
public void visitBinary(JFXBinary tree) {
// Attribute arguments.
Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env));
if (left == syms.javafx_UnspecifiedType) {
left = setEffectiveExpressionType(tree.lhs, newTypeFromType(getEffectiveExpressionType(right)));
}
else if (right == syms.javafx_UnspecifiedType) {
right = setEffectiveExpressionType(tree.rhs, newTypeFromType(getEffectiveExpressionType(left)));
}
// Fix types of numeric arguments with non -specified type.
boolean lhsSet = false;
// If an operand is untyped AND it's a var or attribute, constrain the
// operand based on the operator. Rather a special-case kludge.
Symbol lhsSym = JavafxTreeInfo.symbol(tree.lhs);
if (lhsSym != null &&
(lhsSym.type == null || lhsSym.type == Type.noType || lhsSym.type == syms.javafx_AnyType)) {
JFXVar lhsVarTree = varSymToTree.get(lhsSym);
left = setBinaryTypes(tree.getFXTag(), tree.lhs, lhsVarTree, lhsSym.type, lhsSym);
lhsSet = true;
}
Symbol rhsSym = JavafxTreeInfo.symbol(tree.rhs);
if (rhsSym != null &&
(rhsSym.type == null || rhsSym.type == Type.noType || rhsSym.type == syms.javafx_AnyType) || (lhsSet && lhsSym == rhsSym)) {
JFXVar rhsVarTree = varSymToTree.get(rhsSym);
right = setBinaryTypes(tree.getFXTag(), tree.rhs, rhsVarTree, rhsSym.type, rhsSym);
}
boolean isEq = tree.getOperatorTag() == JFXTree.EQ || tree.getOperatorTag() == JFXTree.NE;
//comparson operators == and != should work in the sequence vs. non-sequence
//case - resolution of comparison operators works over non-sequence types
Symbol sym = rs.resolveBinaryOperator(tree.pos(), tree.getFXTag(), env,
(isEq && types.isSequence(left)) ? types.elementType(left) : left,
(isEq && types.isSequence(right)) ? types.elementType(right) : right);
Type owntype = syms.errType;
if (sym instanceof OperatorSymbol) {
// Find operator.
Symbol operator = tree.operator = sym;
if (operator.kind == MTH) {
owntype = operator.type.getReturnType();
int opc = chk.checkOperator(tree.lhs.pos(),
(OperatorSymbol)operator,
tree.getFXTag(),
left,
right);
// If both arguments are constants, fold them.
if (left.constValue() != null && right.constValue() != null) {
Type ctype = cfolder.fold2(opc, left, right);
if (ctype != null) {
owntype = cfolder.coerce(ctype, owntype);
// Remove constant types from arguments to
// conserve space. The parser will fold concatenations
// of string literals; the code here also
// gets rid of intermediate results when some of the
// operands are constant identifiers.
if (tree.lhs.type.tsym == syms.stringType.tsym) {
tree.lhs.type = syms.stringType;
}
if (tree.rhs.type.tsym == syms.stringType.tsym) {
tree.rhs.type = syms.stringType;
}
}
}
// Check that argument types of a reference ==, != are
// castable to each other, (JLS???).
if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
if (!types.isCastable(left, right, Warner.noWarnings)) {
log.error(tree.pos(), MsgSym.MESSAGE_INCOMPARABLE_TYPES,
types.toJavaFXString(left),
types.toJavaFXString(right));
}
}
chk.checkDivZero(tree.rhs.pos(), operator, right);
}
} else {
owntype = sym.type.getReturnType();
}
result = check(tree, owntype, VAL, pkind, pt, pSequenceness);
if (tree.getFXTag() == JavafxTag.PLUS && owntype == syms.stringType) {
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_STRING_CONCATENATION, expressionToString(tree));
}
}
//where
private String expressionToString(JFXExpression expr) {
if (expr.type == syms.stringType) {
if (expr.getFXTag() == JavafxTag.LITERAL) {
return (String) (((JFXLiteral) expr).getValue());
} else if (expr.getFXTag() == JavafxTag.PLUS) {
JFXBinary plus = (JFXBinary) expr;
return expressionToString(plus.lhs) + expressionToString(plus.rhs);
}
}
return "{" + expr.toString() + "}";
}
boolean isPrimitiveOrBoxed(Type pt, int tag) {
return pt.tag == tag ||
(pt.tsym instanceof ClassSymbol &&
((ClassSymbol) pt.tsym).fullname == syms.boxedName[tag]);
}
@Override
public void visitLiteral(JFXLiteral tree) {
if (tree.typetag == TypeTags.BOT && types.isSequence(pt))
result = tree.type = pt;
else {
Type expected = types.isSequence(pt)? types.elementType(pt) : pt;
if (tree.value instanceof Double) {
double dvalue = ((Double) tree.value).doubleValue();
double dabs = Math.abs(dvalue);
boolean fitsInFloat = Double.isInfinite(dvalue) || dvalue == 0.0 ||
(dabs <= Float.MAX_VALUE && dabs >= Float.MIN_VALUE);
if (isPrimitiveOrBoxed(expected, DOUBLE) || (expected.tag == UNKNOWN && !fitsInFloat)) {
tree.typetag = TypeTags.DOUBLE;
}
else {
if (isPrimitiveOrBoxed(expected, FLOAT) && !fitsInFloat) {
log.error(tree, MsgSym.MESSAGE_JAVAFX_LITERAL_OUT_OF_RANGE, "Number", tree.value.toString());
}
tree.typetag = TypeTags.FLOAT;
tree.value = Float.valueOf((float) dvalue);
}
}
else if ((tree.value instanceof Integer || tree.value instanceof Long) &&
tree.typetag != TypeTags.BOOLEAN) {
long lvalue = ((Number) tree.value).longValue();
if (isPrimitiveOrBoxed(expected, BYTE)) {
if (lvalue != (byte) lvalue) {
log.error(tree, MsgSym.MESSAGE_JAVAFX_LITERAL_OUT_OF_RANGE, "Byte", tree.value.toString());
}
tree.typetag = TypeTags.BYTE;
tree.value = Byte.valueOf((byte) lvalue);
}
else if (isPrimitiveOrBoxed(expected, SHORT)) {
if (lvalue != (short) lvalue) {
log.error(tree, MsgSym.MESSAGE_JAVAFX_LITERAL_OUT_OF_RANGE, "Short", tree.value.toString());
}
tree.typetag = TypeTags.SHORT;
tree.value = Short.valueOf((short) lvalue);
}
else if (isPrimitiveOrBoxed(expected, CHAR) && lvalue == (char) lvalue) {
tree.typetag = TypeTags.CHAR;
}
else if (isPrimitiveOrBoxed(expected, FLOAT)) {
tree.typetag = TypeTags.FLOAT;
tree.value = Float.valueOf(lvalue);
}
else if (isPrimitiveOrBoxed(expected, DOUBLE)) {
tree.typetag = TypeTags.DOUBLE;
tree.value = Double.valueOf(lvalue);
}
else if (isPrimitiveOrBoxed(expected, INT) || tree.typetag == TypeTags.INT) {
if (tree.typetag == TypeTags.LONG) {
log.error(tree, MsgSym.MESSAGE_JAVAFX_LITERAL_OUT_OF_RANGE, "Integer", tree.value.toString());
}
tree.typetag = TypeTags.INT;
if (! (tree.value instanceof Integer))
tree.value = Integer.valueOf((int) lvalue);
}
else {
tree.typetag = TypeTags.LONG;
if (! (tree.value instanceof Long))
tree.value = Long.valueOf(lvalue);
}
}
result = check(
tree, litType(tree.typetag, pt), VAL, pkind, pt, pSequenceness);
}
}
//where
/** Return the type of a literal with given type tag.
*/
private Type litType(int tag, Type pt) {
return (tag == TypeTags.CLASS) ? syms.stringType : // a class literal can only be a String
(tag == TypeTags.BOT && pt.tag == TypeTags.CLASS) ? pt : // for null, make the type the expected type
syms.typeOfTag[tag];
}
@Override
public void visitErroneous(JFXErroneous tree) {
// if (tree.getErrorTrees() != null)
// for (JFXTree err : tree.getErrorTrees())
// attribTree(err, env, ERR, pt);
result = tree.type = syms.errType;
}
/** Main method: attribute class definition associated with given class symbol.
* reporting completion failures at the given position.
* @param pos The source position at which completion errors are to be
* reported.
* @param c The class symbol whose definition will be attributed.
*/
public void attribClass(DiagnosticPosition pos, JFXClassDeclaration tree, ClassSymbol c) {
try {
annotate.flush();
attribClass(tree, c);
} catch (CompletionFailure ex) {
chk.completionError(pos, ex);
}
}
/** Attribute class definition associated with given class symbol.
* @param c The class symbol whose definition will be attributed.
*/
void attribClass(JFXClassDeclaration tree, ClassSymbol c) throws CompletionFailure {
if (c.type.tag == ERROR) return;
// Check for cycles in the inheritance graph, which can arise from
// ill-formed class files.
chk.checkNonCyclic(null, c.type);
if (tree != null) {
attribSupertypes(tree, c);
}
// The previous operations might have attributed the current class
// if there was a cycle. So we test first whether the class is still
// UNATTRIBUTED.
if ((c.flags_field & UNATTRIBUTED) != 0) {
c.flags_field &= ~UNATTRIBUTED;
// Get environment current at the point of class definition.
JavafxEnv<JavafxAttrContext> localEnv = enter.typeEnvs.get(c);
// The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
// because the annotations were not available at the time the env was created. Therefore,
// we look up the environment chain for the first enclosing environment for which the
// lint value is set. Typically, this is the parent env, but might be further if there
// are any envs created as a result of TypeParameter nodes.
JavafxEnv<JavafxAttrContext> lintEnv = localEnv;
while (lintEnv.info.lint == null)
lintEnv = lintEnv.next;
// Having found the enclosing lint value, we can initialize the lint value for this class
localEnv.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
Lint prevLint = chk.setLint(localEnv.info.lint);
JavaFileObject prev = log.useSource(c.sourcefile);
try {
attribClassBody(localEnv, c);
} finally {
log.useSource(prev);
chk.setLint(prevLint);
}
}
}
/** Clones a type without copiyng constant values
* @param t the type that needs to be cloned.
* @return the cloned type with no cloned constants.
*/
public Type newTypeFromType(Type t) {
if (t == null) return null;
switch (t.tag) {
case BYTE:
return syms.byteType;
case CHAR:
return syms.charType;
case SHORT:
return syms.shortType;
case INT:
return syms.intType;
case LONG:
return syms.longType;
case FLOAT:
return syms.floatType;
case DOUBLE:
return syms.doubleType;
case BOOLEAN:
return syms.booleanType;
case VOID:
return syms.voidType;
default:
return t;
}
}
/**
* Gets the effective type of a type. If MethodType - the return type,
* otherwise the passed in type.
*/
private Type getEffectiveExpressionType(Type type) {
if (type.tag == TypeTags.METHOD) {
return type.getReturnType();
}
return type;
}
/**
* Sets the effective type of an expression. If MethodType - the return type,
* otherwise the whole type of the expression is set.
*/
private Type setEffectiveExpressionType(JFXExpression expression, Type type) {
if (expression.type.tag == TypeTags.METHOD) {
((MethodType)expression.type).restype = type;
}
else {
expression.type = type;
}
return expression.type;
}
// Begin JavaFX trees
@Override
public void visitClassDeclaration(JFXClassDeclaration tree) {
boolean wasInBindContext = this.inBindContext;
this.inBindContext = false;
// Local classes have not been entered yet, so we need to do it now:
if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
enter.classEnter(tree, env);
ClassSymbol c = tree.sym;
if (c == null) {
// exit in case something drastic went wrong during enter.
result = null;
} else {
// make sure class has been completed:
c.complete();
attribSupertypes(tree, c);
attribClass(tree.pos(), tree, c);
result = tree.type = c.type;
types.addFxClass(c, tree);
}
result = syms.voidType;
this.inBindContext = wasInBindContext;
}
private void attribSupertypes(JFXClassDeclaration tree, ClassSymbol c) {
JavafxClassSymbol javafxClassSymbol = null;
if (c instanceof JavafxClassSymbol) {
javafxClassSymbol = (JavafxClassSymbol)c;
}
Symbol javaSupertypeSymbol = null;
boolean addToSuperTypes = true;
for (JFXExpression superClass : tree.getSupertypes()) {
Type supType = superClass.type == null ? attribType(superClass, env)
: superClass.type;
// java.lang.Enum may not be subclassed by a non-enum
if (supType.tsym == syms.enumSym &&
((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
log.error(superClass.pos(), MsgSym.MESSAGE_ENUM_NO_SUBCLASSING);
// Enums may not be extended by source-level classes
if (supType.tsym != null &&
((supType.tsym.flags_field & Flags.ENUM) != 0) &&
((c.flags_field & Flags.ENUM) == 0) &&
!target.compilerBootstrap(c)) {
log.error(superClass.pos(), MsgSym.MESSAGE_ENUM_TYPES_NOT_EXTENSIBLE);
}
if (!supType.isInterface() &&
!types.isJFXClass(supType.tsym) &&
!supType.isPrimitive() &&
javafxClassSymbol.type instanceof ClassType) {
if (javaSupertypeSymbol == null) {
javaSupertypeSymbol = supType.tsym;
// Verify there is a non-parametric constructor.
boolean hasNonParamCtor = true; // If there is no non-param constr we will create one later.
for (Scope.Entry e1 = javaSupertypeSymbol.members().elems;
e1 != null;
e1 = e1.sibling) {
Symbol s1 = e1.sym;
if (s1 != null &&
s1.name == names.init &&
s1.kind == Kinds.MTH) {
MethodType mtype = ((MethodSymbol)s1).type.asMethodType();
if (mtype != null && mtype.getParameterTypes().isEmpty()) {
hasNonParamCtor = true;
break;
}
else {
hasNonParamCtor = false;
}
}
}
if (hasNonParamCtor) {
((ClassType)javafxClassSymbol.type).supertype_field = supType;
addToSuperTypes = false;
}
else {
log.error(superClass.pos(), MsgSym.MESSAGE_JAVAFX_BASE_JAVA_CLASS_NON_PAPAR_CTOR, supType.tsym.name);
}
}
else {
// We are already extending one Java class. No more than one is allowed. Report an error.
log.error(superClass.pos(), MsgSym.MESSAGE_JAVAFX_ONLY_ONE_BASE_JAVA_CLASS_ALLOWED, supType.tsym.name);
}
}
if (addToSuperTypes && javafxClassSymbol != null) {
javafxClassSymbol.addSuperType(supType);
}
addToSuperTypes = true;
}
}
@Override
public void visitInitDefinition(JFXInitDefinition that) {
Symbol symOwner = env.info.scope.owner;
try {
MethodType mt = new MethodType(List.<Type>nil(), syms.voidType, List.<Type>nil(), (TypeSymbol)symOwner);
that.sym = new MethodSymbol(0L, defs.initDefName, mt, symOwner);
env.info.scope.owner = that.sym;
JavafxEnv<JavafxAttrContext> localEnv = env.dup(that);
localEnv.outer = env;
attribExpr(that.getBody(), localEnv);
}
finally {
env.info.scope.owner = symOwner;
}
}
public void visitPostInitDefinition(JFXPostInitDefinition that) {
Symbol symOwner = env.info.scope.owner;
try {
MethodType mt = new MethodType(List.<Type>nil(), syms.voidType, List.<Type>nil(), (TypeSymbol)symOwner);
that.sym = new MethodSymbol(0L, defs.postInitDefName, mt, symOwner);
env.info.scope.owner = that.sym;
JavafxEnv<JavafxAttrContext> localEnv = env.dup(that);
localEnv.outer = env;
attribExpr(that.getBody(), localEnv);
}
finally {
env.info.scope.owner = symOwner;
}
}
@Override
public void visitSequenceEmpty(JFXSequenceEmpty tree) {
boolean isSeq = false;
if (pt.tag != NONE && pt != syms.javafx_UnspecifiedType && !(isSeq = types.isSequence(pt)) && pSequenceness == Sequenceness.DISALLOWED) {
// Cannot use an empty sequence here
//
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_BAD_EMPTY_SEQUENCE, types.toJavaFXString(pt));
result = syms.errType;
} else {
Type owntype = pt.tag == NONE || pt.tag == UNKNOWN ? syms.javafx_EmptySequenceType :
isSeq ? pt : types.sequenceType(pt);
result = check(tree, owntype, VAL, pkind, Type.noType, pSequenceness);
}
}
@Override
public void visitSequenceRange(JFXSequenceRange tree) {
Type lowerType = attribExpr(tree.getLower(), env);
Type upperType = attribExpr(tree.getUpper(), env);
Type stepType = tree.getStepOrNull() == null? syms.javafx_IntegerType : attribExpr(tree.getStepOrNull(), env);
boolean allInt = true;
if (lowerType != syms.javafx_IntegerType) {
allInt = false;
if (lowerType != syms.javafx_FloatType && lowerType != syms.javafx_DoubleType) {
log.error(tree.getLower().pos(), MsgSym.MESSAGE_JAVAFX_RANGE_START_INT_OR_NUMBER);
}
}
if (upperType != syms.javafx_IntegerType) {
allInt = false;
if (upperType != syms.javafx_FloatType && upperType != syms.javafx_DoubleType) {
log.error(tree.getLower().pos(), MsgSym.MESSAGE_JAVAFX_RANGE_END_INT_OR_NUMBER);
}
}
if (stepType != syms.javafx_IntegerType) {
allInt = false;
if (stepType != syms.javafx_FloatType && stepType != syms.javafx_DoubleType) {
log.error(tree.getStepOrNull().pos(), MsgSym.MESSAGE_JAVAFX_RANGE_STEP_INT_OR_NUMBER);
}
}
if (tree.getLower().getFXTag() == JavafxTag.LITERAL && tree.getUpper().getFXTag() == JavafxTag.LITERAL
&& (tree.getStepOrNull() == null || tree.getStepOrNull().getFXTag() == JavafxTag.LITERAL)) {
chk.warnEmptyRangeLiteral(tree.pos(), (JFXLiteral)tree.getLower(), (JFXLiteral)tree.getUpper(), (JFXLiteral)tree.getStepOrNull(), tree.isExclusive());
}
Type owntype = types.sequenceType(allInt? syms.javafx_IntegerType : syms.javafx_FloatType);
result = check(tree, owntype, VAL, pkind, pt, pSequenceness);
}
@Override
public void visitSequenceExplicit(JFXSequenceExplicit tree) {
Type elemType = null;
Type expected = pt;
if (types.isSequence(expected))
expected = types.elementType(expected);
for (JFXExpression expr : tree.getItems()) {
Type itemType = attribTree(expr, env, VAL,
expected, Sequenceness.PERMITTED);
if (types.isSequence(itemType) || types.isArray(itemType)) {
itemType = types.isSequence(itemType) ? types.elementType(itemType) : types.elemtype(itemType);
}
itemType = chk.checkNonVoid(expr, itemType);
if (elemType == null || itemType.tag == NONE || itemType.tag == ERROR)
elemType = itemType;
else
elemType = unionType(tree, itemType, elemType);
}
Type owntype = elemType.tag == ERROR ? elemType : types.sequenceType(elemType);
result = check(tree, owntype, VAL, pkind, pt, pSequenceness);
if (owntype == result && pt.tag != NONE && pt != syms.javafx_UnspecifiedType) {
if (pSequenceness != Sequenceness.DISALLOWED)
expected = types.sequenceType(expected);
result = tree.type = expected;
}
}
@Override
public void visitSequenceSlice(JFXSequenceSlice tree) {
JFXExpression seq = tree.getSequence();
Type seqType = attribExpr(seq, env);
attribExpr(tree.getFirstIndex(), env, syms.javafx_IntegerType);
if (tree.getLastIndex() != null) {
attribExpr(tree.getLastIndex(), env, syms.javafx_IntegerType);
}
result = check(tree, seqType, VAR, pkind, pt, pSequenceness);
}
@Override
public void visitSequenceIndexed(JFXSequenceIndexed tree) {
JFXExpression seq = tree.getSequence();
// Attribute as a tree so we can check that target is assignable
// when pkind is VAR
//
Type seqType = attribTree(seq, env, pkind, Type.noType, Sequenceness.PERMITTED);
attribExpr(tree.getIndex(), env, syms.javafx_IntegerType);
Type owntype;
if (seqType.tag == TypeTags.ARRAY) {
owntype = ((ArrayType)seqType).elemtype;
}
else {
owntype = chk.checkSequenceElementType(seq, seqType);
}
result = check(tree, owntype, VAR, pkind, pt, pSequenceness);
}
@Override
public void visitSequenceInsert(JFXSequenceInsert tree) {
JFXExpression seq = tree.getSequence();
Type seqType = attribTree(seq, env, VAR, Type.noType, Sequenceness.REQUIRED);
attribExpr(tree.getElement(), env, seqType);
if (tree.getPosition() != null) {
attribExpr(tree.getPosition(), env, syms.javafx_IntegerType);
}
result = syms.voidType;
tree.type = result;
}
@Override
public void visitSequenceDelete(JFXSequenceDelete tree) {
JFXExpression seq = tree.getSequence();
if (tree.getElement() == null) {
if (seq instanceof JFXSequenceIndexed) {
// delete seq[index];
JFXSequenceIndexed si = (JFXSequenceIndexed)seq;
JFXExpression seqseq = si.getSequence();
JFXExpression index = si.getIndex();
attribTree(seqseq, env, VAR, Type.noType, Sequenceness.REQUIRED);
attribExpr(index, env, syms.javafx_IntegerType);
} else if (seq instanceof JFXSequenceSlice) {
// delete seq[first..last];
JFXSequenceSlice slice = (JFXSequenceSlice)seq;
JFXExpression seqseq = slice.getSequence();
JFXExpression first = slice.getFirstIndex();
JFXExpression last = slice.getLastIndex();
attribTree(seqseq, env, VAR, Type.noType, Sequenceness.REQUIRED);
attribExpr(first, env, syms.javafx_IntegerType);
if (last != null) {
attribExpr(last, env, syms.javafx_IntegerType);
}
} else {
// delete seq; // that is, all the elements
attribTree(seq, env, VAR, Type.noType, Sequenceness.REQUIRED);
}
} else {
Type seqType = attribTree(seq, env, VAR, Type.noType, Sequenceness.REQUIRED);
attribExpr(tree.getElement(), env,
chk.checkSequenceElementType(seq.pos(), seqType));
}
result = syms.voidType;
tree.type = result;
}
@Override
public void visitStringExpression(JFXStringExpression tree) {
List<JFXExpression> parts = tree.getParts();
attribExpr(parts.head, env, syms.javafx_StringType);
parts = parts.tail;
while (parts.nonEmpty()) {
// First the format specifier:
attribExpr(parts.head, env, syms.javafx_StringType);
parts = parts.tail;
// Next the enclosed expression:
chk.checkNonVoid(parts.head.pos(), attribExpr(parts.head, env, Type.noType));
parts = parts.tail;
// Next the following string literal part:
attribExpr(parts.head, env, syms.javafx_StringType);
parts = parts.tail;
}
result = check(tree, syms.javafx_StringType, VAL, pkind, pt, pSequenceness);
}
@Override
public void visitObjectLiteralPart(JFXObjectLiteralPart that) {
// Note that this method can be reached legitimately if visitErroneous is
// called and the error nodes contain an objectLiteralPart. Hence this
// just sets the result to errType.
//
result = syms.errType;
}
@Override
public void visitTypeAny(JFXTypeAny tree) {
assert false : "MUST IMPLEMENT";
}
@Override
public void visitTypeClass(JFXTypeClass tree) {
JFXExpression classNameExpr = ((JFXTypeClass) tree).getClassName();
Type type = attribType(classNameExpr, env);
Cardinality cardinality = tree.getCardinality();
if (cardinality != Cardinality.SINGLETON &&
type == syms.voidType) {
log.error(tree, MsgSym.MESSAGE_JAVAFX_VOID_SEQUENCE_NOT_ALLOWED);
cardinality = Cardinality.SINGLETON;
}
type = sequenceType(type, cardinality);
tree.type = type;
result = type;
}
@Override
public void visitTypeFunctional(JFXTypeFunctional tree) {
Type restype = attribType(tree.restype, env);
if (restype == syms.unknownType)
restype = syms.voidType;
Type rtype = restype == syms.voidType ? syms.javafx_java_lang_VoidType
: new WildcardType(syms.boxIfNeeded(restype), BoundKind.EXTENDS, syms.boundClass);
ListBuffer<Type> typarams = new ListBuffer<Type>();
ListBuffer<Type> argtypes = new ListBuffer<Type>();
typarams.append(rtype);
int nargs = 0;
for (JFXType param : (List<JFXType>)tree.params) {
Type argtype = attribType(param, env);
if (argtype == syms.javafx_UnspecifiedType)
argtype = syms.objectType;
argtypes.append(argtype);
Type ptype = syms.boxIfNeeded(argtype);
ptype = new WildcardType(ptype, BoundKind.SUPER, syms.boundClass);
typarams.append(ptype);
nargs++;
}
MethodType mtype = new MethodType(argtypes.toList(), restype, null, syms.methodClass);
if (nargs > JavafxSymtab.MAX_FIXED_PARAM_LENGTH) {
log.error(tree, MsgSym.MESSAGE_TOO_MANY_PARAMETERS);
tree.type = result = syms.objectType;
return;
}
FunctionType ftype = syms.makeFunctionType(typarams.toList(), mtype);
Type type = sequenceType(ftype, tree.getCardinality());
tree.type = type;
result = type;
}
@Override
public void visitTypeUnknown(JFXTypeUnknown tree) {
result = tree.type = syms.javafx_UnspecifiedType;
}
Type sequenceType(Type elemType, Cardinality cardinality) {
return cardinality == cardinality.ANY
? types.sequenceType(elemType)
: elemType;
}
/** Determine type of identifier or select expression and check that
* (1) the referenced symbol is not deprecated
* (2) the symbol's type is safe (@see checkSafe)
* (3) if symbol is a variable, check that its type and kind are
* compatible with the prototype and protokind.
* (4) if symbol is an instance field of a raw type,
* which is being assigned to, issue an unchecked warning if its
* type changes under erasure.
* (5) if symbol is an instance method of a raw type, issue an
* unchecked warning if its argument types change under erasure.
* If checks succeed:
* If symbol is a constant, return its constant type
* else if symbol is a method, return its result type
* otherwise return its type.
* Otherwise return errType.
*
* @param tree The syntax tree representing the identifier
* @param site If this is a select, the type of the selected
* expression, otherwise the type of the current class.
* @param sym The symbol representing the identifier.
* @param env The current environment.
* @param pkind The set of expected kinds.
* @param pt The expected type.
*/
Type checkId(JFXTree tree,
Type site,
Symbol sym,
JavafxEnv<JavafxAttrContext> env,
int pkind,
Type pt,
Sequenceness pSequenceness,
boolean useVarargs) {
if (pt.isErroneous()) return syms.errType;
Type owntype; // The computed type of this identifier occurrence.
switch (sym.kind) {
case TYP:
// For types, the computed type equals the symbol's type,
// except for two situations:
owntype = sym.type;
if (owntype.tag == CLASS) {
Type ownOuter = owntype.getEnclosingType();
// (a) If the symbol's type is parameterized, erase it
// because no type parameters were given.
// We recover generic outer type later in visitTypeApply.
if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
owntype = types.erasure(owntype);
}
// (b) If the symbol's type is an inner class, then
// we have to interpret its outer type as a superclass
// of the site type. Example:
//
// class Tree<A> { class Visitor { ... } }
// class PointTree extends Tree<Point> { ... }
// ...PointTree.Visitor...
//
// Then the type of the last expression above is
// Tree<Point>.Visitor.
else if (ownOuter.tag == CLASS && site != ownOuter) {
Type normOuter = site;
if (normOuter.tag == CLASS)
normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
if (normOuter == null) // perhaps from an import
normOuter = types.erasure(ownOuter);
if (normOuter != ownOuter)
owntype = new ClassType(
normOuter, List.<Type>nil(), owntype.tsym);
}
}
break;
case VAR:
VarSymbol v = (VarSymbol)sym;
// Test (4): if symbol is an instance field of a raw type,
// which is being assigned to, issue an unchecked warning if
// its type changes under erasure.
if (allowGenerics &&
pkind == VAR &&
v.owner.kind == TYP &&
(v.flags() & STATIC) == 0 &&
(site.tag == CLASS || site.tag == TYPEVAR)) {
Type s = types.asOuterSuper(site, v.owner);
if (s != null &&
s.isRaw() &&
!types.isSameType(v.type, v.erasure(types))) {
chk.warnUnchecked(tree.pos(),
MsgSym.MESSAGE_UNCHECKED_ASSIGN_TO_VAR,
v, s);
}
}
// The computed type of a variable is the type of the
// variable symbol, taken as a member of the site type.
owntype = (sym.owner.kind == TYP &&
sym.name != names._this && sym.name != names._super)
? types.memberType(site, sym)
: sym.type;
if (env.info.tvars.nonEmpty()) {
Type owntype1 = new ForAll(env.info.tvars, owntype);
for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
if (!owntype.contains(l.head)) {
log.error(tree.pos(), MsgSym.MESSAGE_UNDETERMINDED_TYPE, owntype1);
owntype1 = syms.errType;
}
owntype = owntype1;
}
// If the variable is a constant, record constant value in
// computed type.
//if (v.getConstValue() != null && isStaticReference(tree))
// owntype = owntype.constType(v.getConstValue());
if (pkind == VAL) {
owntype = capture(owntype); // capture "names as expressions"
}
break;
case MTH: {
owntype = sym.type;
// This is probably wrong now that we have function expressions.
// Instead, we should checkMethod in visitFunctionInvocation.
// In that case we should also handle FunctionType. FIXME.
if (pt instanceof MethodType || pt instanceof ForAll) {
JFXFunctionInvocation app = (JFXFunctionInvocation)env.tree;
owntype = checkMethod(site, sym, env, app.args,
pt.getParameterTypes(), pt.getTypeArguments(),
env.info.varArgs);
}
break;
}
case PCK: case ERR:
owntype = sym.type;
break;
default:
throw new AssertionError("unexpected kind: " + sym.kind +
" in tree " + tree);
}
// Test (1): emit a `deprecation' warning if symbol is deprecated.
// (for constructors, the error was given when the constructor was
// resolved)
if (sym.name != names.init &&
(sym.flags() & DEPRECATED) != 0 &&
(env.info.scope.owner.flags() & DEPRECATED) == 0 &&
sym.outermostClass() != env.info.scope.owner.outermostClass())
chk.warnDeprecated(tree.pos(), sym);
if ((sym.flags() & PROPRIETARY) != 0)
log.strictWarning(tree.pos(), MsgSym.MESSAGE_SUN_PROPRIETARY, sym);
// Test (3): if symbol is a variable, check that its type and
// kind are compatible with the prototype and protokind.
return check(tree, owntype, sym.kind, pkind, pt, pSequenceness);
}
/** Check that variable is initialized and evaluate the variable's
* initializer, if not yet done. Also check that variable is not
* referenced before it is defined.
* @param tree The tree making up the variable reference.
* @param env The current environment.
* @param v The variable's symbol.
*/
private void checkInit(JFXTree tree,
JavafxEnv<JavafxAttrContext> env,
VarSymbol v) {
v.getConstValue(); // ensure initializer is evaluated
checkEnumInitializer(tree, env, v);
}
private void checkForward(JFXTree tree,
JavafxEnv<JavafxAttrContext> env,
VarSymbol v
) {
// A forward reference is diagnosed if the declaration position
// of the variable is greater than the current tree position
// and the tree and variable definition share the same enclosing
// scope. A forward reference to a def variable whose initializer is
// an object literal is always allowed. Selection on such variables
// is only allowed when it occurs within bound/function/class context.
if (v.pos > tree.pos && (env.info.inSelect ?
true : !isObjLiteralDef(v)) &&
inSameEnclosingScope(v, env))
log.warning(tree.pos(), MsgSym.MESSAGE_ILLEGAL_FORWARD_REF, Resolve.kindName(v.kind), v);
}
//where
private boolean isObjLiteralDef(VarSymbol v) {
return (v.flags() & JavafxFlags.OBJ_LIT_INIT) != 0;
}
//where
public boolean inSameEnclosingScope(VarSymbol v, JavafxEnv<JavafxAttrContext> env) {
while (env != null) {
Symbol s = env.info.scope.owner;
if (v.owner == s) return true;
if (isBound(env) || isClassOrFuncDef(env))
return false;
env = env.outer;
}
return false;
}
//where
private boolean isClassOrFuncDef(JavafxEnv<JavafxAttrContext> env) {
return isFunctionDef(env) ||
env.tree.getFXTag() == JavafxTag.FUNCTIONEXPRESSION ||
env.tree.getFXTag() == JavafxTag.CLASS_DEF ||
env.tree.getFXTag() == JavafxTag.ON_REPLACE ||
env.tree.getFXTag() == JavafxTag.KEYFRAME_LITERAL ||
env.tree.getFXTag() == JavafxTag.INIT_DEF ||
env.tree.getFXTag() == JavafxTag.POSTINIT_DEF;
}
//where
private boolean isFunctionDef(JavafxEnv<JavafxAttrContext> env) {
return env.tree.getFXTag() == JavafxTag.FUNCTION_DEF &&
((((JFXFunctionDefinition)env.tree).sym.flags() & SYNTHETIC) == 0 ||
(((JFXFunctionDefinition)env.tree).name.equals(names.fromString("lambda"))));
}
//where
private boolean isBound(JavafxEnv<JavafxAttrContext> env) {
return (env.tree.getFXTag() == JavafxTag.VAR_DEF &&
((JFXVar)env.tree).isBound()) ||
(env.tree.getFXTag() == JavafxTag.OBJECT_LITERAL_PART &&
((JFXObjectLiteralPart)env.tree).isBound()) ||
(env.tree.getFXTag() == JavafxTag.OVERRIDE_ATTRIBUTE_DEF &&
((JFXOverrideClassVar)env.tree).isBound());
}
/**
* Check for illegal references to static members of enum. In
* an enum type, constructors and initializers may not
* reference its static members unless they are constant.
*
* @param tree The tree making up the variable reference.
* @param env The current environment.
* @param v The variable's symbol.
* @see JLS 3rd Ed. (8.9 Enums)
*/
private void checkEnumInitializer(JFXTree tree, JavafxEnv<JavafxAttrContext> env, VarSymbol v) {
// JLS 3rd Ed.:
//
// "It is a compile-time error to reference a static field
// of an enum type that is not a compile-time constant
// (15.28) from constructors, instance initializer blocks,
// or instance variable initializer expressions of that
// type. It is a compile-time error for the constructors,
// instance initializer blocks, or instance variable
// initializer expressions of an enum constant e to refer
// to itself or to an enum constant of the same type that
// is declared to the right of e."
if (isNonStaticEnumField(v)) {
ClassSymbol enclClass = env.info.scope.owner.enclClass();
if (enclClass == null || enclClass.owner == null)
return;
// See if the enclosing class is the enum (or a
// subclass thereof) declaring v. If not, this
// reference is OK.
if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
return;
// If the reference isn't from an initializer, then
// the reference is OK.
if (!JavafxResolve.isInitializer(env))
return;
log.error(tree.pos(), MsgSym.MESSAGE_ILLEGAL_ENUM_STATIC_REF);
}
}
private boolean isNonStaticEnumField(VarSymbol v) {
return Flags.isEnum(v.owner) && Flags.isStatic(v) && !Flags.isConstant(v);
}
/** Can the given symbol be the owner of code which forms part
* if class initialization? This is the case if the symbol is
* a type or field, or if the symbol is the synthetic method.
* owning a block.
*/
private boolean canOwnInitializer(Symbol sym) {
return
(sym.kind & (VAR | TYP)) != 0 ||
(sym.kind == MTH && (sym.flags() & BLOCK) != 0);
}
Warner noteWarner = new Warner();
/**
* Check that method arguments conform to its instantation.
**/
public Type checkMethod(Type site,
Symbol sym,
JavafxEnv<JavafxAttrContext> env,
final List<JFXExpression> argtrees,
List<Type> argtypes,
List<Type> typeargtypes,
boolean useVarargs) {
// Test (5): if symbol is an instance method of a raw type, issue
// an unchecked warning if its argument types change under erasure.
if (allowGenerics &&
(sym.flags() & STATIC) == 0 &&
(site.tag == CLASS || site.tag == TYPEVAR)) {
Type s = types.asOuterSuper(site, sym.owner);
if (s != null && s.isRaw() &&
!types.isSameTypes(sym.type.getParameterTypes(),
sym.erasure(types).getParameterTypes())) {
chk.warnUnchecked(env.tree.pos(),
MsgSym.MESSAGE_UNCHECKED_CALL_MBR_OF_RAW_TYPE,
sym, s);
}
}
// Compute the identifier's instantiated type.
// For methods, we need to compute the instance type by
// Resolve.instantiate from the symbol's type as well as
// any type arguments and value arguments.
noteWarner.warned = false;
Type owntype = rs.instantiate(env,
site,
sym,
argtypes,
typeargtypes,
true,
useVarargs,
noteWarner);
boolean warned = noteWarner.warned;
// If this fails, something went wrong; we should not have
// found the identifier in the first place.
if (owntype == null) {
if (!pt.isErroneous())
log.error(env.tree.pos(),
MsgSym.MESSAGE_INTERNAL_ERROR_CANNOT_INSTANTIATE,
sym, site,
Type.toString(pt.getParameterTypes()));
owntype = syms.errType;
} else {
// System.out.println("call : " + env.tree);
// System.out.println("method : " + owntype);
// System.out.println("actuals: " + argtypes);
List<Type> formals = owntype.getParameterTypes();
Type last = useVarargs ? formals.last() : null;
if (sym.name==names.init &&
sym.owner == syms.enumSym)
formals = formals.tail.tail;
List<JFXExpression> args = argtrees;
while (formals.head != last) {
JFXTree arg = args.head;
Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
assertConvertible(arg, arg.type, formals.head, warn);
warned |= warn.warned;
args = args.tail;
formals = formals.tail;
}
if (useVarargs) {
Type varArg = types.elemtype(last);
while (args.tail != null) {
JFXTree arg = args.head;
Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
assertConvertible(arg, arg.type, varArg, warn);
warned |= warn.warned;
args = args.tail;
}
} else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
// non-varargs call to varargs method
Type varParam = owntype.getParameterTypes().last();
Type lastArg = argtypes.last();
if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
!types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
log.warning(argtrees.last().pos(), MsgSym.MESSAGE_INEXACT_NON_VARARGS_CALL,
types.elemtype(varParam),
varParam);
}
if (warned && sym.type.tag == FORALL) {
String typeargs = "";
if (typeargtypes != null && typeargtypes.nonEmpty()) {
typeargs = "<" + Type.toString(typeargtypes) + ">";
}
chk.warnUnchecked(env.tree.pos(),
MsgSym.MESSAGE_UNCHECKED_METH_INVOCATION_APPLIED,
sym,
sym.location(),
typeargs,
Type.toString(argtypes));
owntype = new MethodType(owntype.getParameterTypes(),
types.erasure(owntype.getReturnType()),
owntype.getThrownTypes(),
syms.methodClass);
}
if (useVarargs) {
JFXTree tree = env.tree;
Type argtype = owntype.getParameterTypes().last();
if (!types.isReifiable(argtype))
chk.warnUnchecked(env.tree.pos(),
MsgSym.MESSAGE_UNCHECKED_GENERIC_ARRAY_CREATION,
argtype);
Type elemtype = types.elemtype(argtype);
switch (tree.getFXTag()) {
case APPLY:
((JFXFunctionInvocation) tree).varargsElement = elemtype;
break;
default:
throw new AssertionError(""+tree);
}
}
}
return owntype;
}
private void assertConvertible(JFXTree tree, Type actual, Type formal, Warner warn) {
if (types.isConvertible(actual, formal, warn))
return;
if (formal.isCompound()
&& types.isSubtype(actual, types.supertype(formal))
&& types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
return;
if (false) {
// TODO: make assertConvertible work
chk.typeError(tree.pos(), JCDiagnostic.fragment(MsgSym.MESSAGE_INCOMPATIBLE_TYPES), actual, formal);
throw new AssertionError("Tree: " + tree
+ " actual:" + actual
+ " formal: " + formal);
}
}
@Override
public void visitImport(JFXImport tree) {
// nothing to do
}
/** Finish the attribution of a class. */
public void attribClassBody(JavafxEnv<JavafxAttrContext> env, ClassSymbol c) {
JFXClassDeclaration tree = (JFXClassDeclaration)env.tree;
assert c == tree.sym;
// Validate annotations
//chk.validateAnnotations(tree.mods.annotations, c);
// Validate type parameters, supertype and interfaces.
//attribBounds(tree.getEmptyTypeParameters());
//chk.validateTypeParams(tree.getEmptyTypeParameters());
chk.validate(tree.getSupertypes());
// Check that class does not import the same parameterized interface
// with two different argument lists.
chk.checkClassBounds(tree.pos(), c.type);
tree.type = c.type;
// Check that a generic class doesn't extend Throwable
if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
log.error(tree.getExtending().head.pos(), MsgSym.MESSAGE_GENERIC_THROWABLE);
for (List<JFXTree> l = tree.getMembers(); l.nonEmpty(); l = l.tail) {
// Attribute declaration
attribDecl(l.head, env);
// Check that declarations in inner classes are not static (JLS 8.1.2)
// Make an exception for static constants.
// Javafx allows that.
// if (c.owner.kind != PCK &&
// ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
// (JavafxTreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
// Symbol sym = null;
// if (l.head.getFXTag() == JavafxTag.VARDEF) sym = ((JCVariableDecl) l.head).sym;
// if (sym == null ||
// sym.kind != VAR ||
// ((VarSymbol) sym).getConstValue() == null)
// log.error(l.head.pos(), "icls.cant.have.static.decl");
// }
}
// If this is a non-abstract class, check that it has no abstract
// methods or unimplemented methods of an implemented interface.
if ((c.flags() & (ABSTRACT | INTERFACE | JavafxFlags.MIXIN)) == 0) {
if (!relax)
chk.checkAllDefined(tree.pos(), c);
}
// Check that all extended classes and interfaces
// are compatible (i.e. no two define methods with same arguments
// yet different return types). (JLS 8.4.6.3)
chk.checkCompatibleSupertypes(tree.pos(), c.type);
// Check that all methods which implement some
// method conform to the method they implement.
chk.checkImplementations(tree);
Scope enclScope = JavafxEnter.enterScope(env);
for (List<JFXTree> l = tree.getMembers(); l.nonEmpty(); l = l.tail) {
if (l.head instanceof JFXFunctionDefinition)
chk.checkUnique(l.head.pos(), ((JFXFunctionDefinition) l.head).sym, enclScope);
}
// Check for proper use of serialVersionUID
if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
isSerializable(c) &&
(c.flags() & Flags.ENUM) == 0 &&
(c.flags() & ABSTRACT | JavafxFlags.MIXIN) == 0) {
checkSerialVersionUID(tree, c);
}
}
// where
/** check if a class is a subtype of Serializable, if that is available. */
private boolean isSerializable(ClassSymbol c) {
try {
syms.serializableType.complete();
}
catch (CompletionFailure e) {
return false;
}
return types.isSubtype(c.type, syms.serializableType);
}
/** Check that an appropriate serialVersionUID member is defined. */
private void checkSerialVersionUID(JFXClassDeclaration tree, ClassSymbol c) {
// check for presence of serialVersionUID
Scope.Entry e = c.members().lookup(names.serialVersionUID);
while (e.scope != null && e.sym.kind != VAR) e = e.next();
if (e.scope == null) {
log.warning(tree.pos(), MsgSym.MESSAGE_MISSING_SVUID, c);
return;
}
// check that it is static final
VarSymbol svuid = (VarSymbol)e.sym;
if ((svuid.flags() & (STATIC | FINAL)) !=
(STATIC | FINAL))
log.warning(JavafxTreeInfo.diagnosticPositionFor(svuid, tree), MsgSym.MESSAGE_IMPROPER_SVUID, c);
// check that it is long
else if (svuid.type.tag != TypeTags.LONG)
log.warning(JavafxTreeInfo.diagnosticPositionFor(svuid, tree), MsgSym.MESSAGE_LONG_SVUID, c);
// check constant
else if (svuid.getConstValue() == null)
log.warning(JavafxTreeInfo.diagnosticPositionFor(svuid, tree), MsgSym.MESSAGE_CONSTANT_SVUID, c);
}
private Type capture(Type type) {
Type ctype = types.capture(type);
if (type instanceof FunctionType)
ctype = new FunctionType((FunctionType) type);
return ctype;
}
public void clearCaches() {
varSymToTree = null;
methodSymToTree = null;
}
private void fixOverride(JFXFunctionDefinition tree, MethodSymbol m) {
ClassSymbol origin = (ClassSymbol) m.owner;
if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) {
if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
log.error(tree.pos(), MsgSym.MESSAGE_ENUM_NO_FINALIZE);
return;
}
}
for (Type t : types.supertypes(origin)) {
if (t.tag == CLASS) {
TypeSymbol c = t.tsym;
Scope.Entry e = c.members().lookup(m.name);
while (e.scope != null) {
e.sym.complete();
if (m.overrides(e.sym, origin, types, false)) {
if (fixOverride(tree, m, (MethodSymbol) e.sym, origin)) {
break;
}
}
e = e.next();
}
}
}
}
public boolean fixOverride(JFXFunctionDefinition tree,
MethodSymbol m,
MethodSymbol other,
ClassSymbol origin) {
Type mt = types.memberType(origin.type, m);
Type ot = types.memberType(origin.type, other);
// Error if overriding result type is different
// (or, in the case of generics mode, not a subtype) of
// overridden result type. We have to rename any type parameters
// before comparing types.
List<Type> mtvars = mt.getTypeArguments();
List<Type> otvars = ot.getTypeArguments();
Type mtres = mt.getReturnType();
Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
boolean resultTypesOK =
types.returnTypeSubstitutable(mt, ot, otres, noteWarner);
if (!resultTypesOK) {
if (!source.allowCovariantReturns() &&
m.owner != origin &&
m.owner.isSubClass(other.owner, types)) {
// allow limited interoperability with covariant returns
}
else {
Type setReturnType = null;
if (mtres == syms.javafx_DoubleType && otres == syms.floatType) {
setReturnType = syms.floatType;
}
else if ((mtres == syms.javafx_IntegerType || mtres == syms.javafx_DoubleType) && otres == syms.byteType) {
setReturnType = syms.byteType;
}
else if ((mtres == syms.javafx_IntegerType || mtres == syms.javafx_DoubleType) && otres == syms.charType) {
setReturnType = syms.charType;
}
else if ((mtres == syms.javafx_IntegerType || mtres == syms.javafx_DoubleType) && otres == syms.shortType) {
setReturnType = syms.shortType;
}
else if ((mtres == syms.javafx_IntegerType || mtres == syms.javafx_DoubleType) && otres == syms.longType) {
setReturnType = syms.longType;
}
if (setReturnType != null) {
JFXType oldType = tree.operation.getJFXReturnType();
tree.operation.rettype = fxmake.TypeClass(fxmake.Type(setReturnType), oldType.getCardinality());
if (mt instanceof MethodType) {
((MethodType)mt).restype = setReturnType;
}
if (tree.type != null && tree.type instanceof MethodType) {
((MethodType)tree.type).restype = setReturnType;
}
}
}
}
// now fix up the access modifiers
long origFlags = m.flags();
long flags = origFlags;
if ((flags & JavafxFlags.JavafxExplicitAccessFlags) == 0) {
flags |= other.flags() & (JavafxFlags.JavafxExplicitAccessFlags | JavafxFlags.JavafxAccessFlags);
}
if (flags != origFlags) {
m.flags_field = flags;
tree.getModifiers().flags = flags;
}
return true;
}
public void visitTimeLiteral(JFXTimeLiteral tree) {
result = check(tree, syms.javafx_DurationType, VAL, pkind, pt, pSequenceness);
}
public void visitInterpolateValue(JFXInterpolateValue tree) {
boolean wasInBindContext = this.inBindContext;
this.inBindContext = true;
JavafxEnv<JavafxAttrContext> dupEnv = env.dup(tree);
dupEnv.outer = env;
Type instType = attribTree(tree.attribute, dupEnv, VAR, Type.noType);
if (instType == null || instType == syms.javafx_UnspecifiedType) {
instType = Type.noType;
}
attribExpr(tree.value, dupEnv, instType);
if (tree.interpolation != null)
attribExpr(tree.interpolation, dupEnv);
tree.sym = JavafxTreeInfo.symbol(tree.attribute);
//TODO: this is evil
// wrap it in a function
tree.value = fxmake.at(tree.pos()).FunctionValue(fxmake.at(tree.pos()).TypeUnknown(),
List.<JFXVar>nil(),
fxmake.at(tree.pos()).Block(0L,
List.<JFXExpression>nil(),
tree.value));
attribExpr(tree.value, env);
result = check(tree, syms.javafx_KeyValueType, VAL, pkind, pt, pSequenceness);
this.inBindContext = wasInBindContext;
}
/*
private void checkInterpolationValue(JFXInterpolateValue tree, JFXExpression var) {
final Type targetType;
if (tree.getAttribute() != null) {
JFXExpression t = tree.getAttribute();
JavafxEnv<JavafxAttrContext> localEnv = newLocalEnv(tree);
Name attribute = names.fromString(t.toString());
Symbol memberSym = rs.findIdentInType(env, var.type, attribute, VAR);
memberSym = rs.access(memberSym, t.pos(), var.type, attribute, true);
memberSym.complete();
t.type = memberSym.type;
t.sym = memberSym;
targetType = t.type;
} else
targetType = var.type;
Type valueType = attribExpr(tree.getValue(), env, Infer.anyPoly);
Type interpolateType = syms.errType;
if (types.isAssignable(valueType, syms.javafx_ColorType)) {
interpolateType = syms.javafx_ColorInterpolatorType;
} else if (types.isAssignable(valueType, syms.javafx_DoubleType) ||
types.isAssignable(valueType, syms.javafx_IntegerType)) {
interpolateType = syms.javafx_NumberInterpolatorType;
} else {
log.error(tree.pos(), "unexpected.type", Resolve.kindNames(pkind), Resolve.kindName(pkind));
interpolateType = syms.errType;
}
tree.type = interpolateType;
result = tree.type;
}
*/
public void visitKeyFrameLiteral(JFXKeyFrameLiteral tree) {
JavafxEnv<JavafxAttrContext> localEnv = env.dup(tree);
localEnv.outer = env;
attribExpr(tree.start, localEnv);
for (JFXExpression e:tree.values) {
attribExpr(e, localEnv);
}
result = check(tree, syms.javafx_KeyFrameType, VAL, pkind, pt, pSequenceness);
}
private JFXTree breakTree = null;
public JavafxEnv<JavafxAttrContext> attribExprToTree(JFXTree expr, JavafxEnv<JavafxAttrContext> env, JFXTree tree) {
breakTree = tree;
JavaFileObject prev = log.useSource(null);
try {
attribExpr(expr, env);
} catch (BreakAttr b) {
return b.env;
} finally {
breakTree = null;
log.useSource(prev);
}
return env;
}
public JavafxEnv<JavafxAttrContext> attribStatToTree(JFXTree stmt, JavafxEnv<JavafxAttrContext> env, JFXTree tree) {
breakTree = tree;
JavaFileObject prev = log.useSource(null);
try {
attribDecl(stmt, env);
} catch (BreakAttr b) {
return b.env;
} finally {
breakTree = null;
log.useSource(prev);
}
return env;
}
private static class BreakAttr extends RuntimeException {
static final long serialVersionUID = -6924771130405446405L;
private JavafxEnv<JavafxAttrContext> env;
private BreakAttr(JavafxEnv<JavafxAttrContext> env) {
this.env = env;
}
}
public void visitScript(JFXScript tree) {
// Do not assert that we cannot reach here as this unit can
// be visited by virtue of visiting JFXErronous which
// will attempt to visit each Erroneous node that it has
// encapsualted.
//
this.inBindContext = false;
}
public void visitCatch(JFXCatch tree) {
// Do not assert that we cannot reach here as this unit can
// be visited by virtue of visiting JFXErronous which
// will attempt to visit each Erroneous node that it has
// encapsualted.
//
}
public void visitModifiers(JFXModifiers tree) {
// Do not assert that we cannot reach here as this unit can
// be visited by virtue of visiting JFXErronous which
// will attempt to visit each Erroneous node that it has
// encapsualted.
//
}
}
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxToBound.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxToBound.java
index 716fdc37d..e92f7e7af 100755
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxToBound.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxToBound.java
@@ -1,1882 +1,1885 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import com.sun.javafx.api.JavafxBindStatus;
import com.sun.javafx.api.tree.SequenceSliceTree;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javafx.code.FunctionType;
import com.sun.tools.javafx.comp.JavafxToJava.DurationOperationTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.UseSequenceBuilder;
import com.sun.tools.javafx.comp.JavafxToJava.Translator;
import com.sun.tools.javafx.comp.JavafxToJava.FunctionCallTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.InstanciateTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.InterpolateValueTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.StringExpressionTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.Locationness;
import static com.sun.tools.javafx.code.JavafxVarSymbol.*;
import static com.sun.tools.javafx.comp.JavafxDefs.*;
import com.sun.tools.javafx.comp.JavafxTypeMorpher.TypeMorphInfo;
import com.sun.tools.javafx.comp.JavafxTypeMorpher.VarMorphInfo;
import com.sun.tools.javafx.tree.*;
import com.sun.tools.javafx.util.MsgSym;
import static com.sun.tools.javac.code.TypeTags.*;
public class JavafxToBound extends JavafxTranslationSupport implements JavafxVisitor {
protected static final Context.Key<JavafxToBound> jfxToBoundKey =
new Context.Key<JavafxToBound>();
enum ArgKind { BOUND, DEPENDENT, FREE };
/*
* modules imported by context
*/
private final JavafxToJava toJava;
private final JavafxOptimizationStatistics optStat;
/*
* other instance information
*/
private final Name computeElementsName;
/*
* State
*/
private ListBuffer<BindingExpressionClosureTranslator> bects;
private TypeMorphInfo tmiTarget = null;
private JavafxBindStatus bindStatus = null; // should never be accessed before set
/*
* static information
*/
private static final String cBoundSequences = sequencePackageNameString + ".BoundSequences";
private static final String cBoundOperators = locationPackageNameString + ".BoundOperators";
private static final String cLocations = locationPackageNameString + ".Locations";
private static final String cFunction0 = functionsPackageNameString + ".Function0";
private static final String cFunction1 = functionsPackageNameString + ".Function1";
private static final String cOperator = cBoundOperators + ".Operator";
private static final String opPLUS = cOperator + ".PLUS";
private static final String opMINUS = cOperator + ".MINUS";
private static final String opTIMES = cOperator + ".TIMES";
private static final String opDIVIDE = cOperator + ".DIVIDE";
private static final String opMODULO = cOperator + ".MODULO";
private static final String opLT = cOperator + ".CMP_LT";
private static final String opLE = cOperator + ".CMP_LE";
private static final String opGT = cOperator + ".CMP_GT";
private static final String opGE = cOperator + ".CMP_GE";
private static final String opEQ = cOperator + ".CMP_EQ";
private static final String opNE = cOperator + ".CMP_NE";
private static final String opNEGATE = cOperator + ".NEGATE";
private static final String opNOT = cOperator + ".NOT";
public static JavafxToBound instance(Context context) {
JavafxToBound instance = context.get(jfxToBoundKey);
if (instance == null)
instance = new JavafxToBound(context);
return instance;
}
protected JavafxToBound(Context context) {
super(context);
context.put(jfxToBoundKey, this);
toJava = JavafxToJava.instance(context);
optStat = JavafxOptimizationStatistics.instance(context);
computeElementsName = names.fromString("computeElements$");
}
/*** External entry points ***/
JCExpression translate(JFXExpression tree, JavafxBindStatus bindStatus, TypeMorphInfo tmi) {
JavafxBindStatus prevBindStatus = this.bindStatus;
this.bindStatus = bindStatus;
JCExpression res = translateGeneric(tree, tmi);
this.bindStatus = prevBindStatus;
return res;
}
JCExpression translate(JFXExpression tree, JavafxBindStatus bindStatus, Type type) {
JavafxBindStatus prevBindStatus = this.bindStatus;
this.bindStatus = bindStatus;
JCExpression res = translateGeneric(tree, type);
this.bindStatus = prevBindStatus;
return res;
}
// only for re-entry use by SequenceBuilder
JCExpression translate(JFXExpression tree) {
return translateGeneric(tree);
}
private JCExpression translate(JFXExpression tree, TypeMorphInfo tmi) {
return translateGeneric(tree, tmi);
}
JCExpression translate(JFXExpression tree, Type type) {
return translateGeneric(tree, type);
}
/** Visitor method: Translate a single node.
*/
@SuppressWarnings("unchecked")
private <TFX extends JFXExpression, TC extends JCTree> TC translateGeneric(TFX tree, TypeMorphInfo tmi) {
TypeMorphInfo tmiPrevTarget = tmiTarget;
this.tmiTarget = tmi;
TC ret;
if (tree == null) {
ret = null;
} else {
JFXTree prevWhere = toJava.attrEnv.where;
toJava.attrEnv.where = tree;
tree.accept(this);
toJava.attrEnv.where = prevWhere;
ret = (TC) this.result;
this.result = null;
}
this.tmiTarget = tmiPrevTarget;
return ret;
}
private <TFX extends JFXExpression, TC extends JCTree> TC translateGeneric(TFX tree, Type type) {
return translateGeneric(tree, typeMorpher.typeMorphInfo(type));
}
private <TFX extends JFXExpression, TC extends JCTree> TC translateGeneric(TFX tree) {
return translateGeneric(tree, (TypeMorphInfo) null);
}
private List<JCExpression> translate(List<JFXExpression> trees, Type methType, boolean usesVarArgs) {
return translateGeneric(trees, methType, usesVarArgs);
}
private <TFX extends JFXExpression, TC extends JCExpression> List<TC> translateGeneric(List<TFX> trees, Type methType, boolean usesVarArgs) {
ListBuffer<TC> translated = ListBuffer.lb();
boolean handlingVarargs = false;
Type formal = null;
List<Type> t = methType.getParameterTypes();
for (List<TFX> l = trees; l.nonEmpty(); l = l.tail) {
if (!handlingVarargs) {
formal = t.head;
t = t.tail;
if (usesVarArgs && t.isEmpty()) {
formal = types.elemtype(formal);
handlingVarargs = true;
}
}
TC tree = translateGeneric(l.head, formal);
if (tree != null) {
if (tree.type == null) { // if not set by convert()
tree.type = formal; // mark the type to declare the holder of this arg
}
translated.append(tree);
}
}
List<TC> args = translated.toList();
return args;
}
private JCExpression convert(Type inType, JCExpression tree) {
if (tmiTarget == null) {
tree.type = inType;
return tree;
}
Type targetType = tmiTarget.getRealType();
return convert(inType, tree, targetType);
}
private JCExpression convert(Type inType, JCExpression tree, Type targetType) {
DiagnosticPosition diagPos = tree.pos();
if (!types.isSameType(inType, targetType)) {
if (types.isSequence(targetType)) {
Type targetElementType = types.elementType(targetType);
if (targetElementType == null) { // runtime classes written in Java do this
tree.type = inType;
return tree;
}
if (!types.isSequence(inType)) {
JCExpression targetTypeInfo = makeTypeInfo(diagPos, targetElementType);
tree = runtime(diagPos,
cBoundSequences,
"singleton",
List.of(targetTypeInfo, convert(inType, tree, targetElementType)));
} else {
// this additional test is needed because wildcards compare as different
Type sourceElementType = types.elementType(inType);
if (!types.isSameType(sourceElementType, targetElementType)) {
if (types.isNumeric(sourceElementType) && types.isNumeric(targetElementType)) {
tree = convertNumericSequence(diagPos,
cBoundSequences,
tree,
sourceElementType,
targetElementType);
} else {
JCExpression targetTypeInfo = makeTypeInfo(diagPos, targetElementType);
tree = runtime(diagPos, cBoundSequences, "upcast", List.of(targetTypeInfo, tree));
}
}
}
} else if (targetType.isPrimitive()) {
if (inType.isPrimitive()) {
JCExpression classTypeExpr = makeIdentifier(diagPos, cLocations + "." + "NumericTo" + primitiveTypePrefix(targetType) + "LocationConversionWrapper");
JavafxTypeMorpher.TypeMorphInfo tmi = typeMorpher.typeMorphInfo(inType);
JCExpression locationType = makeTypeTree(diagPos, tmi.getLocationType());
JCExpression boxType = makeTypeTree(diagPos, syms.boxIfNeeded(inType));
tree = make.NewClass(null, List.of(locationType, boxType), classTypeExpr,
List.of(tree, makeTypeInfo(diagPos, inType)),
null);
}
//TODO: boxed inType
} else {
List<JCExpression> typeArgs = List.of(makeTypeTree(diagPos, targetType, true),
makeTypeTree(diagPos, syms.boxIfNeeded(inType), true));
Type inRealType = typeMorpher.typeMorphInfo(inType).getRealType();
JCExpression inClass = makeTypeInfo(diagPos, inRealType);
tree = runtime(diagPos, cLocations, "upcast", typeArgs, List.of(inClass, tree));
}
}
tree.type = targetType; // as a way of passing it to methods which needs to know the target type
return tree;
}
//where
private String primitiveTypePrefix(Type type) {
switch (type.tag) {
case BYTE:
return "Byte";
case SHORT:
return "Short";
case INT:
return "Int";
case LONG:
return "Long";
case FLOAT:
return "Float";
case DOUBLE:
return "Double";
}
assert false : "Should not reach here";
return "Unknown";
}
/**
*
* @param diagPos
* @return a boolean expression indicating if the bind is lazy
*/
private JCExpression makeLaziness(DiagnosticPosition diagPos) {
return makeLaziness(diagPos, bindStatus);
}
private Type targetType(Type type) {
return tmiTarget!=null? tmiTarget.getRealType() : type;
}
private JCVariableDecl translateVar(JFXVar tree) {
DiagnosticPosition diagPos = tree.pos();
JFXModifiers mods = tree.getModifiers();
long modFlags = mods == null ? 0L : mods.flags;
modFlags |= Flags.FINAL; // Locations are never overwritten
JCModifiers tmods = make.at(diagPos).Modifiers(modFlags);
VarMorphInfo vmi = typeMorpher.varMorphInfo(tree.sym);
JCExpression typeExpression = makeTypeTree( diagPos,vmi.getLocationType(), true);
//TODO: handle array initializers (but, really, shouldn't that be somewhere else?)
JCExpression init;
if (tree.init == null) {
init = makeLocationAttributeVariable(vmi, diagPos);
} else {
init = translate(tree.init, vmi.getRealFXType());
}
return make.at(diagPos).VarDef(tmods, tree.name, typeExpression, init);
}
private abstract class ClosureTranslator extends Translator {
protected final TypeMorphInfo tmiResult;
protected final int typeKindResult;
protected final Type elementTypeResult;
// these only used when fields are built
ListBuffer<JCTree> members = ListBuffer.lb();
ListBuffer<JCStatement> fieldInits = ListBuffer.lb();
int dependents = 0;
ListBuffer<JCExpression> callArgs = ListBuffer.lb();
int argNum = 0;
ClosureTranslator(DiagnosticPosition diagPos, Type resultType) {
this(diagPos, JavafxToBound.this.toJava, (tmiTarget != null) ? tmiTarget : typeMorpher.typeMorphInfo(resultType));
}
private ClosureTranslator(DiagnosticPosition diagPos, JavafxToJava toJava, TypeMorphInfo tmiResult) {
super(diagPos, toJava);
this.tmiResult = tmiResult;
typeKindResult = tmiResult.getTypeKind();
elementTypeResult = boxedElementType(tmiResult.getLocationType()); // want boxed, JavafxTypes version won't work
}
/**
* Make a method paramter
*/
protected JCVariableDecl makeParam(Type type, Name name) {
return make.at(diagPos).VarDef(
m().Modifiers(Flags.PARAMETER | Flags.FINAL),
name,
makeExpression(type),
null);
}
protected JCTree makeClosureMethod(Name methName, JCExpression expr, List<JCVariableDecl> params, Type returnType, long flags) {
return toJava.makeMethod(diagPos, methName, List.<JCStatement>of((returnType == syms.voidType) ? m().Exec(expr) : m().Return(expr)), params, returnType, flags);
}
protected abstract List<JCTree> makeBody();
protected abstract JCExpression makeBaseClass();
protected JCExpression makeBaseClass(Type clazzType, Type additionTypeParamOrNull) {
JCExpression clazz = makeExpression(types.erasure(clazzType)); // type params added below, so erase formals
ListBuffer<JCExpression> typeParams = ListBuffer.lb();
if (typeKindResult == TYPE_KIND_OBJECT || typeKindResult == TYPE_KIND_SEQUENCE) {
typeParams.append(makeExpression(elementTypeResult));
}
if (additionTypeParamOrNull != null) {
typeParams.append(makeExpression(additionTypeParamOrNull));
}
return typeParams.isEmpty()? clazz : m().TypeApply(clazz, typeParams.toList());
}
protected abstract List<JCExpression> makeConstructorArgs();
protected JCExpression buildClosure() {
List<JCTree> body = makeBody();
JCClassDecl classDecl = body==null? null : m().AnonymousClassDef(m().Modifiers(0L), body);
List<JCExpression> typeArgs = List.nil();
return m().NewClass(null/*encl*/, typeArgs, makeBaseClass(), makeConstructorArgs(), classDecl);
}
protected JCExpression doit() {
return buildClosure();
}
// field building support
protected List<JCTree> completeMembers() {
members.append(m().Block(0L, fieldInits.toList()));
return members.toList();
}
protected JCExpression makeLocationGet(JCExpression locExpr, int typeKind) {
Name getMethodName = defs.locationGetMethodName[typeKind];
JCFieldAccess select = m().Select(locExpr, getMethodName);
return m().Apply(null, select, List.<JCExpression>nil());
}
class FieldInfo {
final String desc;
final int num;
final TypeMorphInfo tmi;
final boolean isLocation;
FieldInfo(Type type) {
this((String)null, type);
}
FieldInfo(Name descName, Type type) {
this(descName.toString(), type);
}
FieldInfo(Name descName, TypeMorphInfo tmi) {
this(descName.toString(), tmi);
}
FieldInfo(String desc, Type type) {
this(desc, typeMorpher.typeMorphInfo(type));
}
FieldInfo(TypeMorphInfo tmi) {
this((String)null, tmi);
}
FieldInfo(String desc, TypeMorphInfo tmi) {
this(desc, tmi, true);
}
FieldInfo(String desc, TypeMorphInfo tmi, boolean isLocation) {
this.desc = desc;
this.num = argNum++;
this.tmi = tmi;
this.isLocation = isLocation;
}
JCExpression makeGetField() {
return makeGetField(tmi.getTypeKind());
}
JCExpression makeGetField(int typeKind) {
return isLocation ? makeLocationGet(makeAccess(this), typeKind) : makeAccess(this);
}
Type type() {
return isLocation ? tmi.getLocationType() : tmi.getRealBoxedType();
}
}
private Name argAccessName(FieldInfo fieldInfo) {
return names.fromString("arg$" + fieldInfo.num);
}
JCExpression makeAccess(FieldInfo fieldInfo) {
return m().Ident(argAccessName(fieldInfo));
}
protected void makeLocationField(JCExpression targ, FieldInfo fieldInfo) {
fieldInits.append( m().Exec( m().Assign(makeAccess(fieldInfo), targ)) );
members.append(m().VarDef(
m().Modifiers(Flags.PRIVATE),
argAccessName(fieldInfo),
makeExpression(fieldInfo.type()),
null));
}
protected JCExpression buildArgField(JCExpression arg, Type type) {
return buildArgField(arg, type, ArgKind.DEPENDENT);
}
protected JCExpression buildArgField(JCExpression arg, Type type, ArgKind kind) {
return buildArgField(arg, new FieldInfo(type), kind);
}
protected JCExpression buildArgField(JCExpression arg, FieldInfo fieldInfo) {
return buildArgField(arg, fieldInfo, ArgKind.DEPENDENT);
}
protected JCExpression buildArgField(JCExpression arg, FieldInfo fieldInfo, ArgKind kind) {
// translate the method arg into a Location field of the BindingExpression
// XxxLocation arg$0 = ...;
makeLocationField(arg, fieldInfo);
// build a list of these args, for use as dependents -- arg$0, arg$1, ...
if (kind == ArgKind.BOUND) {
return makeAccess(fieldInfo);
} else {
if (fieldInfo.num > 32) {
log.error(diagPos, MsgSym.MESSAGE_BIND_TOO_COMPLEX);
}
if (kind == ArgKind.DEPENDENT) {
dependents |= 1 << fieldInfo.num;
}
// set up these arg for the call -- arg$0.getXxx()
return fieldInfo.makeGetField();
}
}
protected void buildArgFields(List<JCExpression> targs, ArgKind kind) {
for (JCExpression targ : targs) {
assert targ.type != null : "caller is supposed to decorate the translated arg with its type";
callArgs.append( buildArgField(targ, targ.type, kind) );
}
}
}
void scriptBegin() {
bects = ListBuffer.lb();
}
List<JCTree> scriptComplete(DiagnosticPosition diagPos) {
ListBuffer<JCTree> trees = ListBuffer.lb();
// Add _Bindings class
if (!bects.isEmpty()) {
ListBuffer<JCCase> cases = ListBuffer.lb();
for (BindingExpressionClosureTranslator b : bects) {
cases.append(b.makeBindingCase());
}
JCStatement swit = make.at(diagPos).Switch(make.at(diagPos).Ident(defs.bindingIdName), cases.toList());
JCTree computeMethod = makeMethod(diagPos, defs.computeMethodName, List.of(swit), null, syms.voidType, Flags.PUBLIC);
Type objectArrayType = new Type.ArrayType(syms.objectType, syms.arrayClass);
ListBuffer<JCVariableDecl> params = ListBuffer.lb();
params.append(makeParam(diagPos, defs.idName, syms.intType));
params.append(makeParam(diagPos, defs.arg0Name, syms.objectType));
params.append(makeParam(diagPos, defs.arg1Name, syms.objectType));
params.append(makeParam(diagPos, defs.moreArgsName, objectArrayType));
params.append(makeParam(diagPos, defs.dependentsName, syms.intType));
JCStatement cbody = make.Exec(make.Apply(null, make.Ident(names._super), List.<JCExpression>of(
make.Ident(defs.idName),
make.Ident(defs.arg0Name),
make.Ident(defs.arg1Name),
make.Ident(defs.moreArgsName),
make.Ident(defs.dependentsName)
)));
JCTree constr = makeMethod(diagPos, names.init, List.of(cbody), params.toList(), syms.voidType, Flags.PRIVATE);
JCClassDecl bindingClass = make.at(diagPos).ClassDef(
make.at(diagPos).Modifiers(Flags.PRIVATE | Flags.STATIC),
defs.scriptBindingClassName,
List.<JCTypeParameter>nil(),
makeQualifiedTree(diagPos, JavafxDefs.scriptBindingExpressionsString),
List.<JCExpression>nil(),
List.of(computeMethod, constr));
trees.append(bindingClass);
}
return trees.toList();
}
@Override
public void visitInstanciate(final JFXInstanciate tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
return new InstanciateTranslator(tree, toJava) {
protected void processLocalVar(JFXVar var) {
preDecls.append(translateVar(var));
}
@Override
protected List<JCExpression> translatedConstructorArgs() {
List<JFXExpression> args = tree.getArgs();
if (args != null && args.size() > 0) {
assert tree.constructor != null : "args passed on instanciation of class without constructor";
boolean usesVarArgs = (tree.constructor.flags() & Flags.VARARGS) != 0L;
buildArgFields(translate(args, tree.constructor.type, usesVarArgs), ArgKind.DEPENDENT);
return callArgs.toList();
} else {
return List.<JCExpression>nil();
}
}
@Override
void setInstanceVariable(Name instName, JavafxBindStatus bindStatus, VarSymbol vsym, JFXExpression init) {
// bind staus to use for translation needs to propagate laziness if this isn't a bound init
JavafxBindStatus translationBindStatus = bindStatus.isBound()?
bindStatus :
JavafxToBound.this.bindStatus.isLazy()?
JavafxBindStatus.LAZY_UNBOUND :
JavafxBindStatus.UNBOUND;
JCExpression initRef = buildArgField(
translate(init, translationBindStatus, vsym.type),
new FieldInfo(vsym.type),
bindStatus.isBound()? ArgKind.BOUND : ArgKind.DEPENDENT);
setInstanceVariable(init.pos(), instName, bindStatus, vsym, initRef);
}
}.doit();
}
}.doit();
}
@Override
public void visitStringExpression(final JFXStringExpression tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), syms.stringType) {
protected JCExpression makePushExpression() {
return new StringExpressionTranslator(tree, toJava) {
protected JCExpression translateArg(JFXExpression arg) {
return buildArgField(translate(arg), arg.type);
}
}.doit();
}
}.doit();
}
@Override
public void visitFunctionValue(JFXFunctionValue tree) {
JFXFunctionDefinition def = tree.definition;
result = makeConstantLocation(tree.pos(), targetType(tree.type), toJava.makeFunctionValue(make.Ident(defs.lambdaName), def, tree.pos(), (MethodType) def.type) );
}
public void visitBlockExpression(JFXBlock tree) { //done
assert (tree.type != syms.voidType) : "void block expressions should be not exist in bind expressions";
DiagnosticPosition diagPos = tree.pos();
JFXExpression value = tree.value;
ListBuffer<JCStatement> translatedVars = ListBuffer.lb();
for (JFXExpression stmt : tree.getStmts()) {
if (stmt.getFXTag() == JavafxTag.VAR_DEF) {
JFXVar var = (JFXVar) stmt;
translatedVars.append(translateVar(var));
optStat.recordLocalVar(var.sym, true, true);
} else {
assert false : "non VAR_DEF in block expression in bind context";
}
}
while (value.getFXTag() == JavafxTag.VAR_DEF) {
// for now, at least, ignore the declaration part of a terminal var decl.
//TODO: when vars can be referenced before decl (say in "var: self" replacement)
// this will need to be changed.
value = ((JFXVar)value).getInitializer();
}
assert value.getFXTag() != JavafxTag.RETURN;
result = makeBlockExpression(diagPos, //TODO tree.flags lost
translatedVars.toList(),
translate(value, tmiTarget) );
}
@Override
public void visitAssign(JFXAssign tree) {
//TODO: this should probably not be allowed
// log.error(tree.pos(), "javafx.not.allowed.in.bind.context", "=");
DiagnosticPosition diagPos = tree.pos();
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(tree.type);
int typeKind = tmi.getTypeKind();
// create a temp var to hold the RHS
JCVariableDecl varDecl = makeTmpVar(diagPos, tmi.getLocationType(), translate(tree.rhs));
// call the set method
JCStatement setStmt = callStatement(diagPos,
translate(tree.lhs),
defs.locationSetMethodName[typeKind],
callExpression(diagPos,
make.at(diagPos).Ident(varDecl.name),
defs.locationGetMethodName[typeKind]));
// bundle it all into a block-expression that looks like --
// { ObjectLocation tmp = rhs; lhs.set(tmp.get()); tmp }
result = makeBlockExpression(diagPos,
List.of(varDecl, setStmt),
make.at(diagPos).Ident(varDecl.name));
}
@Override
public void visitAssignop(JFXAssignOp tree) {
// should have caught this in attribution
assert false : "Assignment operator in bind context";
}
private JCExpression makeBoundSelect(final DiagnosticPosition diagPos,
final Type resultType,
final BindingExpressionClosureTranslator translator) {
TypeMorphInfo tmi = (tmiTarget != null) ? tmiTarget : typeMorpher.typeMorphInfo(resultType);
JCExpression bindingExpression = translator.buildClosure();
List<JCExpression> args = List.of(
makeTypeInfo(diagPos, tmi.isSequence()? tmi.getElementType() : tmi.getRealType()),
makeLaziness(diagPos),
bindingExpression);
return runtime(diagPos, cBoundOperators, tmi.isSequence()? "makeBoundSequenceSelect" : "makeBoundSelect", args);
}
@Override
public void visitSelect(final JFXSelect tree) {
if (tree.type instanceof FunctionType && tree.sym.type instanceof MethodType) {
result = convert(tree.type, toJava.translateAsLocation(tree)); //TODO -- for now punt, translate like normal case
return;
}
DiagnosticPosition diagPos = tree.pos();
Symbol owner = tree.sym.owner;
if (types.isJFXClass(owner) && typeMorpher.requiresLocation(tree.sym)) {
if (tree.sym.isStatic()) {
// if this is a static reference to an attribute, eg. MyClass.myAttribute
JCExpression classRef = makeTypeTree( diagPos,types.erasure(tree.sym.owner.type), false);
result = convert(tree.type, make.at(diagPos).Select(classRef, attributeFieldName(tree.sym)));
} else {
// this is a dynamic reference to an attribute
final JFXExpression expr = tree.getExpression();
result = makeBoundSelect(diagPos,
tree.type,
new BindingExpressionClosureTranslator(tree.pos(), typeMorpher.baseLocation.type) {
protected JCExpression makePushExpression() {
return convert(tree.type, toJava.convertVariableReference(diagPos,
m().Select(
buildArgField(
translate(expr),
new FieldInfo("selector", expr.type)),
tree.getIdentifier()),
tree.sym,
Locationness.AsLocation));
}
});
}
} else {
if (tree.sym.isStatic()) {
// This is a static reference to a Java member or elided member e.g. System.out -- do unbound translation, then wrap
result = this.makeUnboundLocation(diagPos, targetType(tree.type), toJava.translateAsUnconvertedValue(tree));
} else {
// This is a dynamic reference to a Java member or elided member
result = (new BindingExpressionClosureTranslator(diagPos, tree.type) {
private JFXExpression selector = tree.getExpression();
private TypeMorphInfo tmiSelector = typeMorpher.typeMorphInfo(selector.type);
private Name selectorName = getSyntheticName("selector");
private FieldInfo selectorField = new FieldInfo(selectorName, tmiSelector);
protected JCExpression makePushExpression() {
// create two accesses to the value of to selector field -- selector$.blip
// one for the method call and one for the nul test
JCExpression transSelector = selectorField.makeGetField();
JCExpression toTest = selectorField.makeGetField();
// construct the actual select
JCExpression selectExpr = toJava.convertVariableReference(diagPos,
m().Select(transSelector, tree.getIdentifier()),
tree.sym,
Locationness.AsValue);
// test the selector for null before attempting to select the field
// if it would dereference null, then instead give the default value
JCExpression cond = m().Binary(JCTree.NE, toTest, make.Literal(TypeTags.BOT, null));
JCExpression defaultExpr = makeDefaultValue(diagPos, actualTranslatedType);
return m().Conditional(cond, selectExpr, defaultExpr);
}
@Override
protected void buildFields() {
// translate the selector into a Location field of the BindingExpression
// XxxLocation selector$ = ...;
buildArgField(translate(selector), selectorField);
}
}).doit();
}
}
}
@Override
public void visitIdent(JFXIdent tree) { //TODO: don't use toJava
// assert (tree.sym.flags() & Flags.PARAMETER) != 0 || tree.name == names._this || tree.sym.isStatic() || toJava.requiresLocation(typeMorpher.varMorphInfo(tree.sym)) : "we are bound, so should have been marked to morph: " + tree;
JCExpression transId = toJava.translateAsLocation(tree);
result = convert(tree.type, transId );
}
@Override
public void visitSequenceExplicit(JFXSequenceExplicit tree) { //done
ListBuffer<JCStatement> stmts = ListBuffer.lb();
Type elemType = boxedElementType(targetType(tree.type));
UseSequenceBuilder builder = toJava.useBoundSequenceBuilder(tree.pos(), elemType, tree.getItems().length());
stmts.append(builder.makeBuilderVar());
for (JFXExpression item : tree.getItems()) {
stmts.append(builder.addElement( item ) );
}
result = makeBlockExpression(tree.pos(), stmts, builder.makeToSequence());
}
@Override
public void visitSequenceRange(JFXSequenceRange tree) { //done: except for step and exclusive
DiagnosticPosition diagPos = tree.pos();
Type elemType = syms.javafx_IntegerType;
int ltag = tree.getLower().type.tag;
int utag = tree.getUpper().type.tag;
int stag = tree.getStepOrNull() == null? TypeTags.INT : tree.getStepOrNull().type.tag;
if (ltag == TypeTags.FLOAT || ltag == TypeTags.DOUBLE ||
utag == TypeTags.FLOAT || utag == TypeTags.DOUBLE ||
stag == TypeTags.FLOAT || stag == TypeTags.DOUBLE) {
elemType = syms.javafx_NumberType;
}
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(elemType);
ListBuffer<JCExpression> args = ListBuffer.lb();
args.append( translate( tree.getLower(), tmi ));
args.append( translate( tree.getUpper(), tmi ));
if (tree.getStepOrNull() != null) {
args.append( translate( tree.getStepOrNull(), tmi ));
}
if (tree.isExclusive()) {
args.append( make.at(diagPos).Literal(TypeTags.BOOLEAN, 1) );
}
result = convert(types.sequenceType(elemType), runtime(diagPos, cBoundSequences, "range", args));
}
@Override
public void visitSequenceEmpty(JFXSequenceEmpty tree) { //done
DiagnosticPosition diagPos = tree.pos();
if (types.isSequence(tree.type)) {
Type elemType = types.elementType(targetType(tree.type));
result = runtime(diagPos, cBoundSequences, "empty", List.of(makeTypeInfo(diagPos, elemType)));
} else {
result = makeConstantLocation(diagPos, targetType(tree.type), makeNull(diagPos));
}
}
@Override
public void visitSequenceIndexed(JFXSequenceIndexed tree) { //done
DiagnosticPosition diagPos = tree.pos();
result = convert(tree.type, runtime(diagPos, cBoundSequences, "element",
List.of(translate(tree.getSequence()),
translate(tree.getIndex(), syms.intType))));
}
@Override
public void visitSequenceSlice(JFXSequenceSlice tree) { //done
DiagnosticPosition diagPos = tree.pos();
result = runtime(diagPos, cBoundSequences,
tree.getEndKind()==SequenceSliceTree.END_EXCLUSIVE? "sliceExclusive" : "slice",
List.of(
makeTypeInfo(diagPos, types.elementType(targetType(tree.type))),
translate(tree.getSequence()),
translate(tree.getFirstIndex()),
tree.getLastIndex()==null? makeNull(diagPos) : translate(tree.getLastIndex())
));
}
/**
* Generate this template, expanding to handle multiple in-clauses
*
* SequenceLocation<V> derived = new BoundComprehension<T,V>(..., IN_SEQUENCE, USE_INDEX) {
protected SequenceLocation<V> getMappedElement$(final ObjectLocation<T> IVAR_NAME, final IntLocation INDEXOF_IVAR_NAME) {
return SequenceVariable.make(...,
new SequenceBindingExpression<V>() {
public Sequence<V> computeValue() {
if (WHERE)
return BODY with s/indexof IVAR_NAME/INDEXOF_IVAR_NAME/;
else
return ....emptySequence;
}
}, maybe IVAR_NAME, maybe INDEXOF_IVAR_NAME);
}
};
*
* **/
@Override
public void visitForExpression(final JFXForExpression tree) {
result = (new Translator( tree.pos(), toJava ) {
private final TypeMorphInfo tmiResult = typeMorpher.typeMorphInfo(targetType(tree.type));
/**
* V
*/
private final Type resultElementType = tmiResult.getElementType();
/**
* SequenceLocation<V>
*/
private final Type resultSequenceLocationType = typeMorpher.generifyIfNeeded(typeMorpher.locationType(TYPE_KIND_SEQUENCE), tmiResult);
/**
* isSimple -- true if the for-loop is simple enough that it can use SimpleBoundComprehension
*/
private final boolean isSimple = false; //TODO
/**
* Make: V.class
*/
private JCExpression makeResultClass() {
return makeTypeInfo(diagPos, resultElementType);
}
/**
* Make a method parameter
*/
private JCVariableDecl makeParam(Type type, Name name) {
return make.at(diagPos).VarDef(
make.Modifiers(Flags.PARAMETER | Flags.FINAL),
name,
makeExpression(type),
null);
}
/**
* Starting with the body of the comprehension...
* Wrap in a singleton sequence, if not a sequence.
* Wrap in a conditional if there are where-clauses: whereClause? body : []
*/
private JCExpression makeCore() {
JCExpression body;
if (types.isSequence(tree.getBodyExpression().type)) {
// the body is a sequence, desired type is the same as for the for-loop
body = translate(tree.getBodyExpression(), tmiTarget);
} else {
// the body is not a sequence, desired type is the element tpe need for for-loop
JCExpression single = translate(tree.getBodyExpression(), types.unboxedTypeOrType(tmiTarget.getElementType()));
List<JCExpression> args = List.of(makeResultClass(), single);
body = runtime(diagPos, cBoundSequences, "singleton", args);
}
JCExpression whereTest = null;
for (JFXForExpressionInClause clause : tree.getForExpressionInClauses()) {
JCExpression where = translate(clause.getWhereExpression());
if (where != null) {
if (whereTest == null) {
whereTest = where;
} else {
whereTest = runtime(diagPos, cBoundOperators, "and_bb", List.of(whereTest, where));
}
}
}
if (whereTest != null) {
body = makeBoundConditional(diagPos,
tree.type,
body,
runtime(diagPos, cBoundSequences, "empty", List.of(makeTypeInfo(diagPos, resultElementType))),
whereTest);
}
return body;
}
/**
* protected SequenceLocation<V> computeElements$(final ObjectLocation<T> IVAR_NAME, final IntLocation INDEXOF_IVAR_NAME) {
* return ...
* }
*/
private JCTree makeComputeElementsMethod(JFXForExpressionInClause clause, JCExpression inner, TypeMorphInfo tmiInduction) {
Type iVarType;
Type idxVarType;
Name computeName;
if (isSimple) {
iVarType = tmiInduction.getRealFXType();
idxVarType = syms.intType;
computeName = computeElementsName;
} else {
iVarType = tmiInduction.getLocationType();
idxVarType = typeMorpher.locationType(TYPE_KIND_INT);
computeName = computeElementsName;
}
ListBuffer<JCStatement> stmts = ListBuffer.lb();
Name ivarName = clause.getVar().name;
stmts.append(m().Return( inner ));
List<JCVariableDecl> params = List.of(
makeParam(iVarType, ivarName),
makeParam(idxVarType, indexVarName(clause) )
);
return m().MethodDef(
m().Modifiers(Flags.PROTECTED),
computeName,
makeExpression( resultSequenceLocationType ),
List.<JCTypeParameter>nil(),
params,
List.<JCExpression>nil(),
m().Block(0L, stmts.toList()),
null);
}
/**
* new BoundComprehension<T,V>(V.class, IN_SEQUENCE, USE_INDEX) { ... }
*/
private JCExpression makeBoundComprehension(JFXForExpressionInClause clause, JCExpression inner) {
JFXExpression seq = clause.getSequenceExpression();
TypeMorphInfo tmiSeq = typeMorpher.typeMorphInfo(seq.type);
TypeMorphInfo tmiInduction = typeMorpher.typeMorphInfo(clause.getVar().type);
JCClassDecl classDecl = m().AnonymousClassDef(
m().Modifiers(0L),
List.<JCTree>of(makeComputeElementsMethod(clause, inner, tmiInduction)));
List<JCExpression> typeArgs = List.nil();
boolean useIndex = clause.getIndexUsed();
JCExpression transSeq = translate( seq );
if (!tmiSeq.isSequence()) {
transSeq = runtime(diagPos, cBoundSequences, "singleton", List.of(makeResultClass(), transSeq));
}
List<JCExpression> constructorArgs = List.of(
makeResultClass(),
makeTypeInfo(diagPos, tmiInduction.getRealBoxedType()),
transSeq,
m().Literal(TypeTags.BOOLEAN, useIndex? 1 : 0) );
Type bcType = typeMorpher.abstractBoundComprehension.type;
JCExpression clazz = makeExpression(types.erasure(bcType)); // type params added below, so erase formals
ListBuffer<JCExpression> typeParams = ListBuffer.lb();
typeParams.append( makeExpression(tmiInduction.getRealBoxedType()) );
typeParams.append( makeExpression(tmiInduction.getLocationType()) );
typeParams.append( makeExpression(resultElementType) );
clazz = m().TypeApply(clazz, typeParams.toList());
return m().NewClass(null,
typeArgs,
clazz,
constructorArgs,
classDecl);
}
/**
* Put everything together, handle multiple in clauses -- wrap from the inner-most first
*/
public JCExpression doit() {
List<JFXForExpressionInClause> clauses = tree.getForExpressionInClauses();
// make the body of loop
JCExpression expr = makeCore();
// then wrap it in the looping constructs
for (int inx = clauses.size() - 1; inx >= 0; --inx) {
JFXForExpressionInClause clause = clauses.get(inx);
expr = makeBoundComprehension(clause, expr);
}
return expr;
}
}).doit();
}
public void visitIndexof(JFXIndexof tree) {
assert tree.clause.getIndexUsed() : "assert that index used is set correctly";
JCExpression transIndex = make.at(tree.pos()).Ident(indexVarName(tree.fname));
VarSymbol vsym = (VarSymbol)tree.clause.getVar().sym;
if (toJava.requiresLocation(vsym)) {
// from inside the bind, already a Location
result = convert(tree.type, transIndex);
} else {
// it came from outside of the bind, make it into a Location
result = makeConstantLocation(tree.pos(), targetType(tree.type), transIndex);
}
}
/**
* Build a tree for a conditional.
* @param diagPos
* @param resultType
* @param trueExpr then branch, already translated
* @param falseExpr else branch, already translated
* @param condExpr conditional expression branch, already translated
* @return
*/
private JCExpression makeBoundConditional(final DiagnosticPosition diagPos,
final Type resultType,
final JCExpression trueExpr,
final JCExpression falseExpr,
final JCExpression condExpr) {
TypeMorphInfo tmi = (tmiTarget != null) ? tmiTarget : typeMorpher.typeMorphInfo(resultType);
List<JCExpression> args = List.of(
makeLaziness(diagPos),
condExpr,
makeFunction0(resultType, trueExpr),
makeFunction0(resultType, falseExpr));
if (tmi.isSequence()) {
// prepend "Foo.class, "
args = args.prepend(makeTypeInfo(diagPos, tmi.getElementType()));
}
return runtime(diagPos, cBoundOperators, "makeBoundIf", args);
}
private JCExpression makeFunction0(
final Type resultType,
final JCExpression bodyExpr) {
return (new ClosureTranslator(bodyExpr.pos(), resultType) {
protected List<JCTree> makeBody() {
return List.<JCTree>of(
makeClosureMethod(defs.invokeName, bodyExpr, null, tmiResult.getLocationType(), Flags.PUBLIC));
}
protected JCExpression makeBaseClass() {
JCExpression objFactory = makeQualifiedTree(diagPos, cFunction0);
Type clazzType = tmiResult.getLocationType();
JCExpression clazz = makeExpression(clazzType);
return m().TypeApply(objFactory, List.of(clazz));
}
protected List<JCExpression> makeConstructorArgs() {
return List.<JCExpression>nil();
}
}).doit();
}
/*** New Version -- in process
*
private JCExpression makeBoundConditional(final DiagnosticPosition diagPos,
final Type resultType,
final JCExpression trueExpr,
final JCExpression falseExpr,
final JCExpression condExpr) {
return new BindingExpressionClosureTranslator(diagPos, resultType) {
final FieldInfo condField = new FieldInfo("condition", syms.booleanType);
final FieldInfo thenField = new FieldInfo("trueBranch", resultType);
final FieldInfo elseField = new FieldInfo("elseBranch", resultType);
JCStatement makeBranch(FieldInfo takenBranch, FieldInfo abandonedBranch) {
ListBuffer<JCStatement> stmts = ListBuffer.lb();
// stmts.append(callStatement(diagPos, makeAccess(abandonedBranch), "unbind"));
// stmts.append(callStatement(diagPos, makeAccess(takenBranch), "resetState", makeLaziness(diagPos)));
stmts.append(callStatement(diagPos, null, "pushValue", takenBranch.makeGetField()));
return m().Block(0L, stmts.toList());
}
protected JCExpression makePushExpression() {
throw new AssertionError("Should not reach here");
}
@Override
protected List<JCTree> makeBody() {
buildArgField(condExpr, condField);
buildArgField(trueExpr, thenField);
buildArgField(falseExpr, elseField);
pushStatement = m().If(
condField.makeGetField(),
makeBranch(thenField, elseField),
makeBranch(elseField, thenField));
return null;
}
}.doit();
}
private JCExpression makeBoundConditionalTT(final DiagnosticPosition diagPos,
final Type resultType,
final JCExpression trueExpr,
final JCExpression falseExpr,
final JCExpression condExpr) {
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(resultType);
List<JCExpression> args = List.of(
makeTypeInfo(diagPos, tmi.isSequence()? tmi.getElementType() : resultType),
makeLaziness(diagPos),
condExpr,
makeClosure0(diagPos, trueExpr, resultType),
makeClosure0(diagPos, falseExpr, resultType));
String makeBoundIf = tmi.isSequence()? "makeBoundSequenceIf" : "makeBoundIf";
return runtime(diagPos, cBoundOperators, makeBoundIf, args);
}
private JCExpression makeClosure0(final DiagnosticPosition diagPos, final JCExpression expr, final Type resultType) {
final TypeMorphInfo tmiPrevTarget = tmiTarget;
tmiTarget = null;
try {
return new BindingExpressionClosureTranslator(diagPos, typeMorpher.baseLocation.type) {
protected JCExpression makePushExpression() {
return buildArgField(expr, resultType, ArgKind.FREE);
}
}.buildClosure();
} finally {
tmiTarget = tmiPrevTarget;
}
}
/***/
@Override
public void visitIfExpression(final JFXIfExpression tree) {
Type targetType = targetType(tree.type);
result = makeBoundConditional(tree.pos(),
targetType,
translate(tree.getTrueExpression(), targetType),
translate(tree.getFalseExpression(), targetType),
translate(tree.getCondition()) );
}
@Override
public void visitParens(JFXParens tree) { //done
JCExpression expr = translate(tree.expr);
result = make.at(tree.pos).Parens(expr);
}
@Override
public void visitInstanceOf(final JFXInstanceOf tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
+ Type type = tree.clazz.type;
+ if (type.isPrimitive())
+ type = types.boxedClass(type).type;
return m().TypeTest(
buildArgField(translate(tree.expr),
new FieldInfo(defs.toTestName, tree.expr.type)),
- makeExpression(tree.clazz.type) );
+ makeExpression(type) );
}
}.doit();
}
@Override
public void visitTypeCast(final JFXTypeCast tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
return makeTypeCast(tree.pos(), tree.clazz.type, tree.expr.type,
buildArgField(translate(tree.expr), new FieldInfo(defs.toBeCastName, tree.expr.type)));
}
}.doit();
}
@Override
public void visitLiteral(JFXLiteral tree) {
final DiagnosticPosition diagPos = tree.pos();
if (tree.typetag == TypeTags.BOT && types.isSequence(tree.type)) {
Type elemType = types.elementType(targetType(tree.type));
result = runtime(diagPos, cBoundSequences, "empty", List.of(makeTypeInfo(diagPos, elemType)));
} else {
Type targetType = targetType(tree.type);
JCExpression unbound = toJava.convertTranslated(make.at(diagPos).Literal(tree.typetag, tree.value), diagPos, tree.type, targetType);
result = makeConstantLocation(diagPos, targetType, unbound);
}
}
/**
* Translator for Java method and non-bound JavaFX functions.
*/
private abstract class BindingExpressionClosureTranslator extends ClosureTranslator {
final Type actualTranslatedType;
final int id;
JCStatement pushStatement;
final ListBuffer<JCExpression> argInits = ListBuffer.lb();
final ListBuffer<JCStatement> preDecls = ListBuffer.lb();
BindingExpressionClosureTranslator(DiagnosticPosition diagPos, Type resultType) {
super(diagPos, resultType);
this.id = bects.size();
this.actualTranslatedType = resultType;
bects.append(this);
}
protected abstract JCExpression makePushExpression();
protected void buildFields() {
// by default do this dynamically
}
JCCase makeBindingCase() {
return m().Case(m().Literal(id), List.<JCStatement>of(
pushStatement,
m().Break(null)));
}
@Override
JCExpression makeAccess(FieldInfo fieldInfo) {
JCExpression uncast;
if (fieldInfo.num < 2) {
// arg$0 and arg$1, use Ident
uncast = super.makeAccess(fieldInfo);
} else {
// moreArgs
uncast = m().Indexed(m().Ident(defs.moreArgsName), m().Literal(fieldInfo.num - 2));
}
// These are just "Location" -- cast to their XxxLocation type
return m().TypeCast(makeExpression(fieldInfo.type()), uncast);
}
protected List<JCTree> makeBody() {
buildFields();
// build first since this may add dependencies
JCExpression resultVal = makePushExpression();
if (tmiTarget != null && actualTranslatedType != typeMorpher.baseLocation.type) {
// If we have a target type and this isn't a Location yielding translation (which handles it's own), do any needed type conversion
resultVal = toJava.convertTranslated(resultVal, diagPos, actualTranslatedType, tmiTarget.getRealType());
}
pushStatement = callStatement(diagPos, null, "pushValue", resultVal);
return null;
}
protected JCExpression makeBaseClass() {
return m().Ident(defs.scriptBindingClassName);
}
@Override
protected void makeLocationField(JCExpression targ, FieldInfo fieldInfo) {
// We use the fields in the base class, just store to Location constructions for use in the constructor args
argInits.append(targ);
}
protected List<JCExpression> makeConstructorArgs() {
ListBuffer<JCExpression> args = ListBuffer.lb();
// arg: id
args.append(m().Literal(id));
List<JCExpression> inits = argInits.toList();
assert inits.length() == argNum : "Mismatch Args: " + argNum + ", Inits: " + inits.length();
// arg: arg$0
if (argNum > 0) {
args.append(inits.head);
inits = inits.tail;
} else {
args.append(m().Literal(TypeTags.BOT, null));
}
// arg: arg$1
if (argNum > 1) {
args.append(inits.head);
inits = inits.tail;
} else {
args.append(m().Literal(TypeTags.BOT, null));
}
// arg: moreArgs
if (argNum > 2) {
args.append(m().NewArray(makeExpression(syms.objectType), List.<JCExpression>nil(), inits));
} else {
args.append(m().Literal(TypeTags.BOT, null));
}
// arg: dependents
args.append(m().Literal(TypeTags.INT, dependents));
return args.toList();
}
@Override
protected JCExpression doit() {
ListBuffer<JCExpression> args = ListBuffer.lb();
if (tmiResult.getTypeKind() == TYPE_KIND_OBJECT) {
args.append(makeDefaultValue(diagPos, tmiResult));
}
args.append(makeLaziness(diagPos));
args.append(buildClosure());
JCExpression varResult = makeLocationLocalVariable(tmiResult, diagPos, args.toList());
if (preDecls.nonEmpty()) {
return toJava.makeBlockExpression(diagPos, preDecls, varResult);
} else {
return varResult;
}
}
}
@Override
public void visitFunctionInvocation(final JFXFunctionInvocation tree) {
//TODO: painfully in need of refactoring
result = (new FunctionCallTranslator(tree, toJava) {
final List<JCExpression> typeArgs = toJava.translateExpressions(tree.typeargs); //TODO: should, I think, be nil list
final List<JCExpression> targs = translate(tree.args, meth.type, usesVarArgs);
public JCExpression doit() {
if (callBound) {
if (selectorMutable) {
return makeBoundSelect(diagPos,
tree.type,
new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
JCExpression transSelect = buildArgField(translate(selector), new FieldInfo("selector", selector.type));
// create a field in the closure for each argument
buildArgFields(targs, ArgKind.BOUND);
// translate the method name -- e.g., foo to foo$bound
Name name = functionName(msym, false, callBound);
// selectors are always Objects
JCExpression expr = m().Apply(typeArgs,
m().Select(transSelect, name),
callArgs.toList());
return convert(tree.type, expr); // convert type, if needed
}
});
} else {
List<JCExpression> callArgs = targs;
if (superToStatic) { //TODO: should this be higher?
// This is a super call, add the receiver so that the impl is called directly
callArgs = callArgs.prepend(make.Ident(defs.receiverName));
}
return convert(tree.type, m().Apply(typeArgs, transMeth(), callArgs));
}
} else {
// call to Java method or unbound JavaFX function
//TODO: varargs
if (selectorMutable || useInvoke) {
return (new BindingExpressionClosureTranslator(diagPos, tree.type) {
private JFXExpression check = useInvoke? meth : selector;
private TypeMorphInfo tmiSelector = typeMorpher.typeMorphInfo(check.type);
private Name selectorName = getSyntheticName("selector");
private FieldInfo selectorField = new FieldInfo(selectorName, tmiSelector);
protected JCExpression makePushExpression() {
// access the selector field for the method call-- selector$.get()
// selectors are always Objects
JCExpression transSelector = selectorField.makeGetField(TYPE_KIND_OBJECT);
// construct the actual method invocation
Name methName = useInvoke? defs.invokeName : ((JFXSelect) tree.meth).name;
JCExpression callMeth = m().Select(transSelector, methName);
JCExpression call = m().Apply(typeArgs, callMeth, callArgs.toList());
if (tmiSelector.getTypeKind() == TYPE_KIND_OBJECT) {
// create another access to the selector field for the null test (below)
JCExpression toTest = selectorField.makeGetField(TYPE_KIND_OBJECT);
// test the selector for null before attempting to invoke the method
// if it would dereference null, then instead give the default value
JCExpression cond = m().Binary(JCTree.NE, toTest, make.Literal(TypeTags.BOT, null));
JCExpression defaultExpr = makeDefaultValue(diagPos, actualTranslatedType);
return m().Conditional(cond, call, defaultExpr);
} else {
return call;
}
}
@Override
protected void buildFields() {
// translate the method selector into a Location field of the BindingExpression
// XxxLocation selector$ = ...;
// Must be first, because of pre-definition of selectorField
buildArgField(translate(check), selectorField);
// create a field in the BindingExpression for each argument
buildArgFields(targs, ArgKind.DEPENDENT);
}
}).doit();
} else {
return (new BindingExpressionClosureTranslator(diagPos, tree.type) {
FieldInfo rcvrField = null;
// construct the actual value computing method (with the method call)
protected JCExpression makePushExpression() {
if (superToStatic) { //TODO: should this be higher?
// This is a super call, add the receiver so that the impl is called directly
callArgs.prepend( receiver() );
}
// result is a block expression that has the definition of receiver$ at the beginning
return m().Apply(null, translatedImmutableMethodReference(), callArgs.toList());
}
@Override
protected void buildFields() {
// create a field in the BindingExpression for each argument
buildArgFields(targs, ArgKind.DEPENDENT);
}
JCExpression receiver() {
if (rcvrField == null) {
Type rcvrType = msym.owner.type;
rcvrField = new FieldInfo(JavafxDefs.receiverNameString, typeMorpher.typeMorphInfo(rcvrType), false);
return buildArgField(toJava.makeReceiver(diagPos, msym, toJava.attrEnv.enclClass.sym), rcvrField, ArgKind.BOUND);
} else {
return rcvrField.makeGetField();
}
}
JCExpression translatedImmutableMethodReference() {
Name name = functionName(msym, superToStatic, callBound);
JCExpression stor;
if (renameToSuper) {
stor = m().Select(makeTypeTree(diagPos, toJava.attrEnv.enclClass.sym.type, false), names._super);
} else if (superCall) {
stor = m().Ident(names._super);
} else if (superToStatic || msym.isStatic()) {
stor = makeTypeTree(diagPos, types.erasure(msym.owner.type), false);
} else if (selector == null || thisCall) {
stor = receiver();
} else {
stor = makeTypeTree(diagPos, types.erasure(msym.owner.type), false);
}
return m().Select(stor, name);
}
}).doit();
}
}
}
public JCExpression transMeth() {
assert !useInvoke;
JCExpression transMeth = toJava.translateAsUnconvertedValue(meth);
if (superToStatic || callBound) {
// translate the method name -- e.g., foo to foo$bound or foo$impl
Name name = functionName(msym, superToStatic, callBound);
JCExpression expr = superToStatic ? makeTypeTree(diagPos, msym.owner.type, false) : ((JCFieldAccess) transMeth).getExpression();
transMeth = m().Select(expr, name);
}
return transMeth;
}
}).doit();
}
private class BinaryTranslator {
final JFXBinary tree;
final DiagnosticPosition diagPos;
final JFXExpression l;
final JFXExpression r;
final boolean lBoxed;
final boolean rBoxed;
final Type lType;
final Type rType;
BinaryTranslator(final JFXBinary tree) {
this.tree = tree;
this.diagPos = tree.pos();
this.l = tree.lhs;
this.r = tree.rhs;
Type tubl = types.unboxedType(tree.lhs.type);
lBoxed = tubl.tag != TypeTags.NONE;
lType = lBoxed? tubl : tree.lhs.type;
Type tubr = types.unboxedType(tree.rhs.type);
rBoxed = tubr.tag != TypeTags.NONE;
rType = rBoxed? tubr : tree.rhs.type;
}
String typeString() {
if (types.isSameType(rType, syms.doubleType) || types.isSameType(lType, syms.doubleType)) {
return "double";
}
if (types.isSameType(rType, syms.floatType) || types.isSameType(lType, syms.floatType)) {
return "float";
}
if (types.isSameType(rType, syms.longType) || types.isSameType(lType, syms.longType)) {
return "long";
}
return "int";
}
JCExpression makeBinaryOperator(String op, String prefix) {
final JCExpression lhs = translate(l);
final JCExpression rhs = translate(r);
return runtime(diagPos, cBoundOperators, prefix + typeString(), List.of(makeLaziness(diagPos), lhs, rhs, makeQualifiedTree(diagPos, op)));
}
JCExpression makeBinaryArithmeticOperator(String op) {
return makeBinaryOperator(op, "op_");
}
JCExpression makeBinaryComparisonOperator(String op) {
return makeBinaryOperator(op, "cmp_");
}
boolean isNumeric(Type opType) {
switch (opType.tag) {
case BYTE:
case CHAR:
case SHORT:
case INT:
case LONG:
case FLOAT:
case DOUBLE:
return true;
}
return false;
}
JCExpression makeBinaryEqualityOperator(String op) {
if (isNumeric(lType) && isNumeric(rType)) {
return makeBinaryComparisonOperator(op);
} else {
final JCExpression lhs = translate(l);
final JCExpression rhs = translate(r);
String methodName = (lType.tag == BOOLEAN && rType.tag == BOOLEAN) ? "op_boolean" : "cmp_other";
return runtime(diagPos, cBoundOperators, methodName, List.of(makeLaziness(diagPos), lhs, rhs, makeQualifiedTree(diagPos, op)));
}
}
JCExpression doit() {
if ((types.isSameType(lType, syms.javafx_DurationType) ||
types.isSameType(rType, syms.javafx_DurationType)) &&
(tree.getFXTag() != JavafxTag.EQ && tree.getFXTag() != JavafxTag.NE)) {
// This is a Duration operation (other than equality). Use the Duration translator
return new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
return new DurationOperationTranslator(diagPos, tree.getFXTag(),
buildArgField(translate(l), lType), buildArgField(translate(r), rType),
lType, rType, toJava).doit();
}
}.doit();
}
switch (tree.getFXTag()) {
case PLUS:
return makeBinaryArithmeticOperator(opPLUS);
case MINUS:
return makeBinaryArithmeticOperator(opMINUS);
case DIV:
return makeBinaryArithmeticOperator(opDIVIDE);
case MUL:
return makeBinaryArithmeticOperator(opTIMES);
case MOD:
return makeBinaryArithmeticOperator(opMODULO);
case LT:
return makeBinaryComparisonOperator(opLT);
case LE:
return makeBinaryComparisonOperator(opLE);
case GT:
return makeBinaryComparisonOperator(opGT);
case GE:
return makeBinaryComparisonOperator(opGE);
case EQ:
return makeBinaryEqualityOperator(opEQ);
case NE:
return makeBinaryEqualityOperator(opNE);
case AND:
return makeBoundConditional(diagPos,
syms.booleanType,
translate(r, syms.booleanType),
makeConstantLocation(diagPos, syms.booleanType, makeLit(diagPos, syms.booleanType, 0)),
translate(l, syms.booleanType));
case OR:
return makeBoundConditional(diagPos,
syms.booleanType,
makeConstantLocation(diagPos, syms.booleanType, makeLit(diagPos, syms.booleanType, 1)),
translate(r, syms.booleanType),
translate(l, syms.booleanType));
default:
assert false : "unhandled binary operator";
return translate(l);
}
}
}
@Override
public void visitBinary(final JFXBinary tree) {
result = convert(tree.type, new BinaryTranslator(tree).doit());
}
@Override
public void visitUnary(final JFXUnary tree) {
DiagnosticPosition diagPos = tree.pos();
JFXExpression expr = tree.getExpression();
JCExpression transExpr = translate(expr);
JCExpression res;
switch (tree.getFXTag()) {
case SIZEOF:
res = runtime(diagPos, cBoundSequences, "sizeof", List.of(transExpr) );
break;
case REVERSE:
res = runtime(diagPos, cBoundSequences, "reverse", List.of(transExpr) );
break;
case NOT:
res = runtime(diagPos, cBoundOperators, "op_boolean", List.of(makeLaziness(diagPos), transExpr, make.Literal(TypeTags.BOT, null), makeQualifiedTree(diagPos, opNOT)));
break;
case NEG:
if (types.isSameType(tree.type, syms.javafx_DurationType)) {
//TODO: totally wrong
res = make.at(diagPos).Apply(null,
make.at(diagPos).Select(translate(tree.arg), names.fromString("negate")), List.<JCExpression>nil());
} else {
Type t = expr.type;
Type tub = types.unboxedType(t);
if (tub.tag != TypeTags.NONE) {
t = tub;
}
String typeString = (types.isSameType(t, syms.doubleType)) ? "double" : (types.isSameType(t, syms.floatType)) ? "float" : (types.isSameType(t, syms.longType)) ? "long" : "int";
res = runtime(diagPos, cBoundOperators, "op_" + typeString, List.of(makeLaziness(diagPos), transExpr, make.Literal(TypeTags.BOT, null), makeQualifiedTree(diagPos, opNEGATE)));
}
break;
case PREINC:
case PREDEC:
case POSTINC:
case POSTDEC:
// should have caught this in attribution
assert false : "++/-- in bind context f";
res = transExpr;
break;
default:
assert false : "unhandled unary operator";
res = transExpr;
break;
}
result = convert(tree.type, res);
}
@Override
public void visitTimeLiteral(JFXTimeLiteral tree) {
//TODO: code should be something like the below, but this requires a similar change to visitInterpolateValue
/***
DiagnosticPosition diagPos = tree.pos();
JCExpression unbound = toJava.translate(tree, Wrapped.InNothing);
result = makeConstantLocation(diagPos, targetType(tree.type), unbound);
*/
// convert this time literal to a javafx.lang.Duration.valueOf() invocation
JFXFunctionInvocation duration = timeLiteralToDuration(tree);
// now convert that FX invocation to Java
visitFunctionInvocation(duration); // sets result
}
public void visitInterpolateValue(final JFXInterpolateValue tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
return new InterpolateValueTranslator(tree, toJava) {
@Override
void setInstanceVariable(DiagnosticPosition diagPos, Name instName, JavafxBindStatus bindStatus, VarSymbol vsym, JCExpression transInit) {
JCExpression initRef = buildArgField(
transInit,
new FieldInfo(vsym.name, vsym.type),
bindStatus.isBound()? ArgKind.BOUND : ArgKind.DEPENDENT);
super.setInstanceVariable(diagPos, instName, bindStatus, vsym, initRef);
}
@Override
protected JCExpression translateInstanceVariableInit(JFXExpression init, JavafxBindStatus bindStatus, VarSymbol vsym) {
return translate(init, bindStatus, vsym.type);
}
protected JCExpression translateTarget() {
JCExpression target = translate(tree.attribute);
JCExpression val = toJava.callExpression(diagPos, makeExpression(syms.javafx_PointerType), "make", target);
return makeConstantLocation(diagPos, syms.javafx_KeyValueTargetType, val);
}
}.doit();
}
}.doit();
}
/***********************************************************************
*
* Utilities
*s
*/
protected String getSyntheticPrefix() {
return "bfx$";
}
/***********************************************************************
*
* Moot visitors
*
*/
@Override
public void visitForExpressionInClause(JFXForExpressionInClause that) {
assert false : "should be processed by parent tree";
}
@Override
public void visitModifiers(JFXModifiers tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitSkip(JFXSkip tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitThrow(JFXThrow tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTry(JFXTry tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitWhileLoop(JFXWhileLoop tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitOnReplace(JFXOnReplace tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitScript(JFXScript tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitClassDeclaration(JFXClassDeclaration tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitInitDefinition(JFXInitDefinition tree) {
assert false : "should not be processed as part of a binding";
}
public void visitPostInitDefinition(JFXPostInitDefinition tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitFunctionDefinition(JFXFunctionDefinition tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitSequenceInsert(JFXSequenceInsert tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitSequenceDelete(JFXSequenceDelete tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitContinue(JFXContinue tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitReturn(JFXReturn tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitImport(JFXImport tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitBreak(JFXBreak tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitCatch(JFXCatch tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTypeAny(JFXTypeAny that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTypeClass(JFXTypeClass that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTypeFunctional(JFXTypeFunctional that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTypeUnknown(JFXTypeUnknown that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitObjectLiteralPart(JFXObjectLiteralPart that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitVarScriptInit(JFXVarScriptInit tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitVar(JFXVar tree) {
// this is handled in translarVar
assert false : "should not be processed as part of a binding";
}
@Override
public void visitKeyFrameLiteral(JFXKeyFrameLiteral tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitErroneous(JFXErroneous tree) {
assert false : "erroneous nodes shouldn't have gotten this far";
}
}
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxToJava.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxToJava.java
index 08e02f6e7..fa3f993f6 100755
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxToJava.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxToJava.java
@@ -1,3690 +1,3693 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.lang.model.type.TypeKind;
import com.sun.javafx.api.JavafxBindStatus;
import com.sun.javafx.api.tree.SequenceSliceTree;
import com.sun.javafx.api.tree.Tree.JavaFXKind;
import com.sun.tools.javac.code.*;
import static com.sun.tools.javac.code.Flags.*;
import com.sun.tools.javac.code.Type.MethodType;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.tree.TreeTranslator;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javafx.code.*;
import static com.sun.tools.javafx.code.JavafxVarSymbol.*;
import com.sun.tools.javafx.comp.JavafxAnalyzeClass.TranslatedOverrideClassVarInfo;
import com.sun.tools.javafx.comp.JavafxAnalyzeClass.TranslatedVarInfo;
import static com.sun.tools.javafx.comp.JavafxDefs.*;
import com.sun.tools.javafx.comp.JavafxInitializationBuilder.JavafxClassModel;
import com.sun.tools.javafx.comp.JavafxTypeMorpher.TypeMorphInfo;
import com.sun.tools.javafx.comp.JavafxTypeMorpher.VarMorphInfo;
import com.sun.tools.javafx.tree.*;
import static com.sun.tools.javafx.comp.JavafxToJava.Yield.*;
import static com.sun.tools.javafx.comp.JavafxToJava.Locationness.*;
/**
* Translate JavaFX ASTs into Java ASTs
*
* @author Robert Field
* @author Per Bothner
* @author Lubo Litchev
*/
public class JavafxToJava extends JavafxTranslationSupport implements JavafxVisitor {
protected static final Context.Key<JavafxToJava> jfxToJavaKey =
new Context.Key<JavafxToJava>();
/*
* modules imported by context
*/
private final JavafxToBound toBound;
private final JavafxInitializationBuilder initBuilder;
private final JavafxOptimizationStatistics optStat;
/*
* Buffers holding definitions waiting to be prepended to the current list of definitions.
* At class or top-level these are the same.
* Within a method (or block) prependToStatements is split off.
* They need to be different because anonymous classes need to be declared in the scope of the method,
* but interfaces can't be declared here.
*/
private ListBuffer<JCStatement> prependToDefinitions = null;
private ListBuffer<JCStatement> prependToStatements = null;
private ListBuffer<JCExpression> additionalImports = null;
private Map<Symbol, Name> substitutionMap = new HashMap<Symbol, Name>();
public enum Locationness {
// We need a Location
AsLocation,
// We need a sequence element or size.
// Normally, when we access (read) a sequence variable, we need to call
// Sequences.noteShared, which sets the shared bit on the sequence.
// But for seq[index] or sizeof seq we don't need to do that.
// The AsShareSafeValue enum is used to supress the noteShared call.
AsShareSafeValue,
// We need a value
AsValue
}
enum Yield {
ToExpression,
ToStatement
}
private static class TranslationState {
final Yield yield;
final Locationness wrapper;
final Type targetType;
TranslationState(Yield yield, Locationness wrapper, Type targetType) {
this.yield = yield;
this.wrapper = wrapper;
this.targetType = targetType;
}
}
private TranslationState translationState = null; // should be set before use
protected JavafxEnv<JavafxAttrContext> attrEnv;
private Target target;
abstract static class Translator {
protected DiagnosticPosition diagPos;
protected final JavafxToJava toJava;
protected final JavafxDefs defs;
protected final JavafxTypes types;
protected final JavafxSymtab syms;
protected final Name.Table names;;
Translator(DiagnosticPosition diagPos, JavafxToJava toJava) {
this.diagPos = diagPos;
this.toJava = toJava;
this.defs = toJava.defs;
this.types = toJava.types;
this.syms = toJava.syms;
this.names = toJava.names;
}
protected abstract JCTree doit();
protected TreeMaker m() {
return toJava.make.at(diagPos);
}
protected JavafxTreeMaker fxm() {
return toJava.fxmake.at(diagPos);
}
/**
* Convert type to JCExpression
*/
protected JCExpression makeExpression(Type type) {
return toJava.makeTypeTree(diagPos, type, true);
}
}
/*
* static information
*/
private static final String sequencesRangeString = "com.sun.javafx.runtime.sequence.Sequences.range";
private static final String sequencesRangeExclusiveString = "com.sun.javafx.runtime.sequence.Sequences.rangeExclusive";
private static final String sequenceBuilderString = "com.sun.javafx.runtime.sequence.ArraySequence";
private static final String boundSequenceBuilderString = "com.sun.javafx.runtime.sequence.BoundSequenceBuilder";
private static final String noMainExceptionString = "com.sun.javafx.runtime.NoMainException";
private static final String toSequenceString = "toSequence";
private static final String methodThrowsString = "java.lang.Throwable";
private JFXClassDeclaration currentClass; //TODO: this is redundant with attrEnv.enclClass
/** Class symbols for classes that need a reference to the outer class. */
Set<ClassSymbol> hasOuters = new HashSet<ClassSymbol>();
private static final Pattern EXTENDED_FORMAT_PATTERN = Pattern.compile("%[<$0-9]*[tT][guwxGUVWXE]");
abstract class NullCheckTranslator extends Translator {
protected final JFXExpression toCheck;
protected final Type resultType;
private final boolean needNullCheck;
private boolean hasSideEffects;
private boolean hse;
private ListBuffer<JCStatement> tmpVarList;
protected final Locationness wrapper;
NullCheckTranslator(DiagnosticPosition diagPos, JFXExpression toCheck, Type resultType, boolean knownNonNull, Locationness wrapper) {
super(diagPos, JavafxToJava.this);
this.toCheck = toCheck;
this.resultType = resultType;
this.needNullCheck = !knownNonNull && !toCheck.type.isPrimitive() && possiblyNull(toCheck);
this.hasSideEffects = needNullCheck && computeHasSideEffects(toCheck);
this.tmpVarList = ListBuffer.<JCStatement>lb();
this.wrapper = wrapper;
}
abstract JCExpression fullExpression(JCExpression mungedToCheckTranslated);
abstract JCExpression translateToCheck(JFXExpression expr);
protected JCExpression preserveSideEffects(Type type, JFXExpression expr, JCExpression trans) {
if (needNullCheck && expr!=null && computeHasSideEffects(expr)) {
// if there is going to be a null check (which thus could keep expr
// from being evaluated), and expr has side-effects, then eval
// it first and put it in a temp var.
return addTempVar(type, trans);
} else {
// no side-effects, just pass-through
return trans;
}
}
protected JCExpression addTempVar(Type varType, JCExpression trans) {
JCVariableDecl tmpVar = makeTmpVar(diagPos, "pse", varType, trans);
tmpVarList.append(tmpVar);
return m().Ident(tmpVar.name);
}
private boolean possiblyNull(JFXExpression expr) {
if (expr == null) {
return true;
}
switch (expr.getFXTag()) {
case ASSIGN:
return possiblyNull(((JFXAssign)expr).getExpression());
case APPLY:
return true;
case BLOCK_EXPRESSION:
return possiblyNull(((JFXBlock)expr).getValue());
case IDENT:
return ((JFXIdent)expr).sym instanceof VarSymbol;
case CONDEXPR:
return possiblyNull(((JFXIfExpression)expr).getTrueExpression()) || possiblyNull(((JFXIfExpression)expr).getFalseExpression());
case LITERAL:
return expr.getJavaFXKind() == JavaFXKind.NULL_LITERAL;
case PARENS:
return possiblyNull(((JFXParens)expr).getExpression());
case SELECT:
return ((JFXSelect)expr).sym instanceof VarSymbol;
case SEQUENCE_INDEXED:
return true;
case TYPECAST:
return possiblyNull(((JFXTypeCast)expr).getExpression());
case VAR_DEF:
return possiblyNull(((JFXVar)expr).getInitializer());
default:
return false;
}
}
private boolean computeHasSideEffects(JFXExpression expr) {
hse = false;
new JavafxTreeScanner() {
private void markSideEffects() {
hse = true;
}
@Override
public void visitBlockExpression(JFXBlock tree) {
markSideEffects(); // maybe doesn't but covers all statements
}
@Override
public void visitUnary(JFXUnary tree) {
markSideEffects();
}
@Override
public void visitAssign(JFXAssign tree) {
markSideEffects();
}
@Override
public void visitAssignop(JFXAssignOp tree) {
markSideEffects();
}
@Override
public void visitInstanciate(JFXInstanciate tree) {
markSideEffects();
}
@Override
public void visitFunctionInvocation(JFXFunctionInvocation tree) {
markSideEffects();
}
@Override
public void visitSelect(JFXSelect tree) {
// Doesn't really have side-effects but the dupllicate null checking is aweful
//TODO: do this in a cleaner way
markSideEffects();
}
}.scan(expr);
return hse;
}
protected JCTree doit() {
JCExpression mungedToCheckTranslated = translateToCheck(toCheck);
JCVariableDecl tmpVar = null;
if (hasSideEffects) {
// if the toCheck sub-expression has side-effects, compute it and stash in a
// temp var so we don't invoke it twice.
tmpVar = makeTmpVar(diagPos, "toCheck", toCheck.type, mungedToCheckTranslated);
tmpVarList.append(tmpVar);
mungedToCheckTranslated = m().Ident(tmpVar.name);
}
JCExpression full = fullExpression(mungedToCheckTranslated);
if (!needNullCheck && tmpVarList.isEmpty()) {
return full;
}
// Do a null check
JCExpression toTest = hasSideEffects ? m().Ident(tmpVar.name) : translateToCheck(toCheck);
// we have a testable guard for null, test before the invoke (boxed conversions don't need a test)
JCExpression cond = m().Binary(JCTree.NE, toTest, make.Literal(TypeTags.BOT, null));
if (resultType == syms.voidType) {
// if this is a void expression, check it with an If-statement
JCStatement stmt = m().Exec(full);
if (needNullCheck) {
stmt = m().If(cond, stmt, null);
}
// a statement is the desired result of the translation, return the If-statement
if (tmpVarList.nonEmpty()) {
// if the selector has side-effects, we created a temp var to hold it
// so we need to make a block to include the temp var
return m().Block(0L, tmpVarList.toList().append(stmt));
} else {
return stmt;
}
} else {
if (needNullCheck) {
// it has a non-void return type, convert it to a conditional expression
// if it would dereference null, then the full expression instead yields the default value
TypeMorphInfo returnTypeInfo = typeMorpher.typeMorphInfo(resultType);
JCExpression defaultExpr = makeDefaultValue(diagPos, returnTypeInfo);
if (wrapper == AsLocation) {
defaultExpr = makeUnboundLocation(diagPos, returnTypeInfo, defaultExpr);
}
full = m().Conditional(cond, full, defaultExpr);
}
if (tmpVarList.nonEmpty()) {
// if the selector has side-effects, we created a temp var to hold it
// so we need to make a block-expression to include the temp var
full = makeBlockExpression(diagPos, tmpVarList.toList(), full);
}
return full;
}
}
}
public static JavafxToJava instance(Context context) {
JavafxToJava instance = context.get(jfxToJavaKey);
if (instance == null)
instance = new JavafxToJava(context);
return instance;
}
protected JavafxToJava(Context context) {
super(context);
context.put(jfxToJavaKey, this);
toBound = JavafxToBound.instance(context);
initBuilder = JavafxInitializationBuilder.instance(context);
optStat = JavafxOptimizationStatistics.instance(context);
target = Target.instance(context);
}
JCExpression convertTranslated(JCExpression translated, DiagnosticPosition diagPos,
Type sourceType, Type targetType) {
assert sourceType != null;
assert targetType != null;
if (targetType.tag == TypeTags.UNKNOWN) {
//TODO: this is bad attribution
return translated;
}
if (types.isSameType(targetType, sourceType)) {
return translated;
}
boolean sourceIsSequence = types.isSequence(sourceType);
boolean targetIsSequence = types.isSequence(targetType);
boolean sourceIsArray = types.isArray(sourceType);
boolean targetIsArray = types.isArray(targetType);
if (targetIsArray) {
Type elemType = types.elemtype(targetType);
if (sourceIsSequence) {
if (elemType.isPrimitive()) {
String mname = "toArray";
if (elemType == syms.floatType) {
mname = "toFloatArray";
} else if (elemType == syms.doubleType) {
mname = "toDoubleArray";
}
return callExpression(diagPos, makeTypeTree(diagPos, syms.javafx_SequencesType, false),
mname, translated);
}
ListBuffer<JCStatement> stats = ListBuffer.lb();
JCVariableDecl tmpVar = makeTmpVar(diagPos, sourceType, translated);
stats.append(tmpVar);
JCVariableDecl sizeVar = makeTmpVar(diagPos, syms.intType, callExpression(diagPos, make.at(diagPos).Ident(tmpVar.name), "size"));
stats.append(sizeVar);
JCVariableDecl arrVar = makeTmpVar(diagPos, "arr", targetType, make.at(diagPos).NewArray(
makeTypeTree(diagPos, elemType, true),
List.<JCExpression>of(make.at(diagPos).Ident(sizeVar.name)),
null));
stats.append(arrVar);
stats.append(callStatement(diagPos, make.at(diagPos).Ident(tmpVar.name), "toArray", List.of(
make.Literal(TypeTags.INT, 0),
make.at(diagPos).Ident(sizeVar.name),
make.at(diagPos).Ident(arrVar.name),
make.at(diagPos).Literal(TypeTags.INT, 0))));
JCIdent ident2 = make.at(diagPos).Ident(arrVar.name);
return makeBlockExpression(diagPos, stats, ident2);
} else {
//TODO: conversion may be needed here, but this is better than what we had
return translated;
}
}
if (sourceIsArray && targetIsSequence) {
Type sourceElemType = types.elemtype(sourceType);
List<JCExpression> args;
if (sourceElemType.isPrimitive()) {
args = List.of(translated);
} else {
args = List.of(makeTypeInfo(diagPos, sourceElemType), translated);
}
JCExpression cSequences = makeTypeTree(diagPos, syms.javafx_SequencesType, false);
return callExpression(diagPos, cSequences, "fromArray", args);
}
if (targetIsSequence && ! sourceIsSequence) {
//if (sourceType.tag == TypeTags.BOT) {
// // it is a null, convert to empty sequence
// //TODO: should we leave this null?
// Type elemType = types.elemtype(type);
// return makeEmptySequenceCreator(diagPos, elemType);
//}
Type targetElemType = types.elementType(targetType);
JCExpression cSequences = makeTypeTree(diagPos, syms.javafx_SequencesType, false);
if (sourceType.isPrimitive())
translated = convertTranslated(translated, diagPos, sourceType, targetElemType);
return callExpression(diagPos,
cSequences,
"singleton",
List.of(makeTypeInfo(diagPos, targetElemType), translated));
}
if (targetIsSequence && sourceIsSequence) {
Type sourceElementType = types.elementType(sourceType);
Type targetElementType = types.elementType(targetType);
if (!types.isSameType(sourceElementType, targetElementType) &&
types.isNumeric(sourceElementType) && types.isNumeric(targetElementType)) {
return convertNumericSequence(diagPos,
cSequences,
translated,
sourceElementType,
targetElementType);
}
}
// Convert primitive types
Type unboxedTargetType = targetType.isPrimitive() ? targetType : types.unboxedType(targetType);
Type unboxedSourceType = sourceType.isPrimitive() ? sourceType : types.unboxedType(sourceType);
if (unboxedTargetType != Type.noType && unboxedSourceType != Type.noType) {
if (!sourceType.isPrimitive()) {
// unboxed source if sourceboxed
translated = make.at(diagPos).TypeCast(unboxedSourceType, translated);
}
if (unboxedSourceType != unboxedTargetType) {
// convert as primitive types
translated = make.at(diagPos).TypeCast(unboxedTargetType, translated);
}
if (!targetType.isPrimitive()) {
// box target if target boxed
translated = make.at(diagPos).TypeCast(makeTypeTree(diagPos, targetType, false), translated);
}
}
if (sourceType.isCompound()) {
translated = make.at(diagPos).TypeCast(makeTypeTree(diagPos, types.erasure(targetType), true), translated);
}
return translated;
}
/** Visitor method: Translate a single node.
*/
@SuppressWarnings("unchecked")
private <TFX extends JFXTree, TC extends JCTree> TC translateGeneric(TFX tree) {
if (tree == null) {
return null;
} else {
TC ret;
JFXTree prevWhere = attrEnv.where;
attrEnv.where = tree;
tree.accept(this);
attrEnv.where = prevWhere;
ret = (TC) this.result;
this.result = null;
return ret;
}
}
private JCMethodDecl translate(JFXFunctionDefinition tree) {
return translateGeneric(tree);
}
private JCVariableDecl translate(JFXVar tree) {
return translateGeneric(tree);
}
private JCCompilationUnit translate(JFXScript tree) {
return translateGeneric(tree);
}
private JCTree translate(JFXTree tree) {
return translateGeneric(tree);
}
private JCStatement translateClassDef(JFXClassDeclaration tree) {
return translateGeneric(tree);
}
/** Visitor method: translate a list of nodes.
*/
private <TFX extends JFXTree, TC extends JCTree> List<TC> translateGeneric(List<TFX> trees) {
ListBuffer<TC> translated = ListBuffer.lb();
if (trees == null) {
return null;
}
for (List<TFX> l = trees; l.nonEmpty(); l = l.tail) {
TC tree = translateGeneric(l.head);
if (tree != null) {
translated.append(tree);
}
}
return translated.toList();
}
public List<JCExpression> translateExpressions(List<JFXExpression> trees) {
return translateGeneric(trees);
}
private List<JCCatch> translateCatchers(List<JFXCatch> trees) {
return translateGeneric(trees);
}
private JCBlock translateBlockExpressionToBlock(JFXBlock bexpr) {
JCStatement stmt = translateToStatement(bexpr);
return stmt==null? null : asBlock(stmt);
}
JCExpression translateToExpression(JFXExpression expr, Locationness wrapper, Type targetType) {
if (expr == null) {
return null;
} else {
JFXTree prevWhere = attrEnv.where;
attrEnv.where = expr;
TranslationState prevZ = translationState;
translationState = new TranslationState(ToExpression, wrapper, targetType);
expr.accept(this);
translationState = prevZ;
attrEnv.where = prevWhere;
JCExpression ret = (JCExpression)this.result;
this.result = null;
return (targetType==null)? ret : convertTranslated(ret, expr.pos(), expr.type, targetType);
}
}
JCExpression translateAsValue(JFXExpression expr, Type targetType) {
return translateToExpression(expr, AsValue, targetType);
}
JCExpression translateAsUnconvertedValue(JFXExpression expr) {
return translateToExpression(expr, AsValue, null);
}
JCExpression translateAsLocation(JFXExpression expr) {
return translateToExpression(expr, AsLocation, null);
}
private JCStatement translateToStatement(JFXExpression expr, Type targetType) {
if (expr == null) {
return null;
} else {
JFXTree prevWhere = attrEnv.where;
attrEnv.where = expr;
TranslationState prevZ = translationState;
translationState = new TranslationState(ToStatement, AsValue, targetType);
expr.accept(this);
translationState = prevZ;
attrEnv.where = prevWhere;
JCTree ret = this.result;
this.result = null;
if (ret instanceof JCStatement) {
return (JCStatement) ret; // already converted
}
JCExpression translated = (JCExpression) ret;
DiagnosticPosition diagPos = expr.pos();
if (targetType == syms.voidType) {
return make.at(diagPos).Exec(translated);
} else {
return make.at(diagPos).Return(convertTranslated(translated, diagPos, expr.type, targetType));
}
}
}
private JCStatement translateToStatement(JFXExpression expr) {
return translateToStatement(expr, syms.voidType);
}
/**
* For special cases where the expression may not be fully attributed.
* Specifically: package and import names.
* Do a dumb simple conversion.
*
* @param tree
* @return
*/
private JCExpression straightConvert(JFXExpression tree) {
if (tree == null) {
return null;
}
DiagnosticPosition diagPos = tree.pos();
switch (tree.getFXTag()) {
case IDENT: {
JFXIdent id = (JFXIdent) tree;
return make.at(diagPos).Ident(id.name);
}
case SELECT: {
JFXSelect sel = (JFXSelect) tree;
return make.at(diagPos).Select(
straightConvert(sel.getExpression()),
sel.getIdentifier());
}
default:
throw new RuntimeException("bad conversion");
}
}
JCBlock asBlock(JCStatement stmt) {
if (stmt.getTag() == JCTree.BLOCK) {
return (JCBlock)stmt;
} else {
return make.at(stmt).Block(0L, List.of(stmt));
}
}
private boolean substitute(Symbol sym, Locationness wrapper) {
if (wrapper == AsLocation) {
return false;
}
Name name = substitutionMap.get(sym);
if (name == null) {
return false;
} else {
result = make.Ident(name);
return true;
}
}
private void setSubstitution(JFXTree target, Symbol sym) {
if (target instanceof JFXInstanciate) {
// Set up to substitute a reference to the this var within its definition
((JFXInstanciate) target).varDefinedByThis = sym;
}
}
public void toJava(JavafxEnv<JavafxAttrContext> attrEnv) {
this.attrEnv = attrEnv;
attrEnv.translatedToplevel = translate(attrEnv.toplevel);
attrEnv.translatedToplevel.endPositions = attrEnv.toplevel.endPositions;
}
@Override
public void visitScript(JFXScript tree) {
// add to the hasOuters set the clas symbols for classes that need a reference to the outer class
fillClassesWithOuters(tree);
ListBuffer<JCTree> translatedDefinitions = ListBuffer.lb();
ListBuffer<JCTree> imports = ListBuffer.lb();
additionalImports = ListBuffer.lb();
prependToStatements = prependToDefinitions = ListBuffer.lb();
for (JFXTree def : tree.defs) {
if (def.getFXTag() != JavafxTag.IMPORT) {
// anything but an import
translatedDefinitions.append(translate(def));
}
}
// order is imports, any prepends, then the translated non-imports
for (JCTree prepend : prependToDefinitions) {
translatedDefinitions.prepend(prepend);
}
for (JCTree prepend : imports) {
translatedDefinitions.prepend(prepend);
}
for (JCExpression prepend : additionalImports) {
translatedDefinitions.append(make.Import(prepend, false));
}
prependToStatements = prependToDefinitions = null; // shouldn't be used again until the next top level
JCExpression pid = straightConvert(tree.pid);
JCCompilationUnit translated = make.at(tree.pos).TopLevel(List.<JCAnnotation>nil(), pid, translatedDefinitions.toList());
translated.sourcefile = tree.sourcefile;
translated.docComments = null;
translated.lineMap = tree.lineMap;
translated.flags = tree.flags;
result = translated;
}
@Override
public void visitClassDeclaration(JFXClassDeclaration tree) {
JFXClassDeclaration prevClass = currentClass;
JFXClassDeclaration prevEnclClass = attrEnv.enclClass;
currentClass = tree;
if (tree.isScriptClass) {
toBound.scriptBegin();
}
try {
DiagnosticPosition diagPos = tree.pos();
attrEnv.enclClass = tree;
ListBuffer<JCStatement> translatedInitBlocks = ListBuffer.lb();
ListBuffer<JCStatement> translatedPostInitBlocks = ListBuffer.lb();
ListBuffer<JCTree> translatedDefs = ListBuffer.lb();
ListBuffer<TranslatedVarInfo> attrInfo = ListBuffer.lb();
ListBuffer<TranslatedOverrideClassVarInfo> overrideInfo = ListBuffer.lb();
// translate all the definitions that make up the class.
// collect any prepended definitions, and prepend then to the tranlations
ListBuffer<JCStatement> prevPrependToDefinitions = prependToDefinitions;
ListBuffer<JCStatement> prevPrependToStatements = prependToStatements;
prependToStatements = prependToDefinitions = ListBuffer.lb();
{
for (JFXTree def : tree.getMembers()) {
switch(def.getFXTag()) {
case INIT_DEF: {
translateAndAppendStaticBlock(((JFXInitDefinition) def).getBody(), translatedInitBlocks);
break;
}
case POSTINIT_DEF: {
translateAndAppendStaticBlock(((JFXPostInitDefinition) def).getBody(), translatedPostInitBlocks);
break;
}
case VAR_DEF: {
JFXVar attrDef = (JFXVar) def;
boolean isStatic = (attrDef.getModifiers().flags & STATIC) != 0;
JCStatement init = (!isStatic || attrEnv.toplevel.isLibrary)?
translateDefinitionalAssignmentToSet(attrDef.pos(),
attrDef.getInitializer(), attrDef.getBindStatus(), attrDef.sym,
isStatic? null : defs.receiverName, FROM_DEFAULT_MILIEU)
: null;
attrInfo.append(new TranslatedVarInfo(
attrDef,
typeMorpher.varMorphInfo(attrDef.sym),
init,
attrDef.getOnReplace(),
translatedOnReplaceBody(attrDef.getOnReplace())));
//translatedDefs.append(trans);
break;
}
case OVERRIDE_ATTRIBUTE_DEF: {
JFXOverrideClassVar override = (JFXOverrideClassVar) def;
boolean isStatic = (override.sym.flags() & STATIC) != 0;
JCStatement init;
if (override.getInitializer() == null) {
init = null;
} else {
init = translateDefinitionalAssignmentToSet(override.pos(),
override.getInitializer(), override.getBindStatus(), override.sym,
isStatic? null : defs.receiverName,
FROM_DEFAULT_MILIEU);
}
overrideInfo.append(new TranslatedOverrideClassVarInfo(
override,
typeMorpher.varMorphInfo(override.sym),
init,
override.getOnReplace(),
translatedOnReplaceBody(override.getOnReplace())));
break;
}
case FUNCTION_DEF : {
JFXFunctionDefinition funcDef = (JFXFunctionDefinition) def;
translatedDefs.append(translate(funcDef));
break;
}
default: {
JCTree tdef = translate(def);
if ( tdef != null ) {
translatedDefs.append( tdef );
}
break;
}
}
}
}
// the translated defs have prepends in front
for (JCTree prepend : prependToDefinitions) {
translatedDefs.prepend(prepend);
}
prependToDefinitions = prevPrependToDefinitions ;
prependToStatements = prevPrependToStatements;
// WARNING: translate can't be called directly or indirectly after this point in the method, or the prepends won't be included
boolean classOnly = tree.generateClassOnly();
JavafxClassModel model = initBuilder.createJFXClassModel(tree, attrInfo.toList(), overrideInfo.toList());
additionalImports.appendList(model.additionalImports);
boolean classIsFinal = (tree.getModifiers().flags & Flags.FINAL) != 0;
// include the interface only once
if (!tree.hasBeenTranslated) {
if (! classOnly) {
JCModifiers mods = make.Modifiers(Flags.PUBLIC | Flags.INTERFACE);
mods = addAccessAnnotationModifiers(diagPos, tree.mods.flags, mods);
JCClassDecl cInterface = make.ClassDef(mods,
model.interfaceName, List.<JCTypeParameter>nil(), null,
model.interfaces, model.iDefinitions);
prependToDefinitions.append(cInterface); // prepend to the enclosing class or top-level
}
tree.hasBeenTranslated = true;
}
translatedDefs.appendList(model.additionalClassMembers);
{
// Add the userInit$ method
List<JCVariableDecl> receiverVarDeclList = List.of(makeReceiverParam(tree));
ListBuffer<JCStatement> initStats = ListBuffer.lb();
// call the superclasses userInit$
Set<String> dupSet = new HashSet<String>();
for (JFXExpression parent : tree.getExtending()) {
if (! (parent instanceof JFXIdent))
continue;
Symbol symbol = expressionSymbol(parent);
if (types.isJFXClass(symbol)) {
ClassSymbol cSym = (ClassSymbol) symbol;
String className = cSym.fullname.toString();
if (className.endsWith(interfaceSuffix)) {
className = className.substring(0, className.length() - interfaceSuffix.length());
}
if (!dupSet.contains(className)) {
dupSet.add(className);
List<JCExpression> args1 = List.nil();
args1 = args1.append(make.TypeCast(makeTypeTree( diagPos,cSym.type, true), make.Ident(defs.receiverName)));
initStats = initStats.append(callStatement(tree.pos(), makeIdentifier(diagPos, className), defs.userInitName, args1));
}
}
}
initStats.appendList(translatedInitBlocks);
JCBlock userInitBlock = make.Block(0L, initStats.toList());
translatedDefs.append(make.MethodDef(
make.Modifiers(classIsFinal? Flags.PUBLIC : Flags.PUBLIC | Flags.STATIC),
defs.userInitName,
makeTypeTree( null,syms.voidType),
List.<JCTypeParameter>nil(),
receiverVarDeclList,
List.<JCExpression>nil(),
userInitBlock,
null));
}
{
// Add the userPostInit$ method
List<JCVariableDecl> receiverVarDeclList = List.of(makeReceiverParam(tree));
ListBuffer<JCStatement> initStats = ListBuffer.lb();
// call the superclasses postInit$
Set<String> dupSet = new HashSet<String>();
for (JFXExpression parent : tree.getExtending()) {
if (! (parent instanceof JFXIdent))
continue;
Symbol symbol = expressionSymbol(parent);
if (types.isJFXClass(symbol)) {
ClassSymbol cSym = (ClassSymbol) symbol;
String className = cSym.fullname.toString();
if (className.endsWith(interfaceSuffix)) {
className = className.substring(0, className.length() - interfaceSuffix.length());
}
if (!dupSet.contains(className)) {
dupSet.add(className);
List<JCExpression> args1 = List.nil();
args1 = args1.append(make.TypeCast(makeTypeTree( diagPos,cSym.type, true), make.Ident(defs.receiverName)));
initStats = initStats.append(callStatement(tree.pos(), makeIdentifier(diagPos, className), defs.postInitName, args1));
}
}
}
initStats.appendList(translatedPostInitBlocks);
JCBlock postInitBlock = make.Block(0L, initStats.toList());
translatedDefs.append(make.MethodDef(
make.Modifiers(classIsFinal? Flags.PUBLIC : Flags.PUBLIC | Flags.STATIC),
defs.postInitName,
makeTypeTree( null,syms.voidType),
List.<JCTypeParameter>nil(),
receiverVarDeclList,
List.<JCExpression>nil(),
postInitBlock,
null));
}
if (tree.isScriptClass) {
// Add main method...
translatedDefs.append(makeMainMethod(diagPos, tree.getName()));
// Add binding support
translatedDefs.appendList(toBound.scriptComplete(tree.pos()));
}
// build the list of implemented interfaces
List<JCExpression> implementing;
if (classOnly) {
implementing = model.interfaces;
}
else {
implementing = List.of(make.Ident(model.interfaceName), makeIdentifier(diagPos, fxObjectString));
}
long flags = tree.mods.flags & (Flags.PUBLIC | Flags.PRIVATE | Flags.PROTECTED | Flags.FINAL | Flags.ABSTRACT);
if (tree.sym.owner.kind == Kinds.TYP) {
flags |= Flags.STATIC;
}
JCModifiers classMods = make.at(diagPos).Modifiers(flags);
classMods = addAccessAnnotationModifiers(diagPos, tree.mods.flags, classMods);
// make the Java class corresponding to this FX class, and return it
JCClassDecl res = make.at(diagPos).ClassDef(
classMods,
tree.getName(),
List.<JCTypeParameter>nil(), // type parameters
model.superType==null? null : makeTypeTree( null,model.superType, false),
implementing,
translatedDefs.toList());
res.sym = tree.sym;
res.type = tree.type;
result = res;
}
finally {
attrEnv.enclClass = prevEnclClass;
currentClass = prevClass;
}
}
//where
private void translateAndAppendStaticBlock(JFXBlock block, ListBuffer<JCStatement> translatedBlocks) {
JCStatement stmt = translateToStatement(block);
if (stmt != null) {
translatedBlocks.append(stmt);
}
}
@Override
public void visitInitDefinition(JFXInitDefinition tree) {
assert false : "should be processed by class tree";
}
public void visitPostInitDefinition(JFXPostInitDefinition tree) {
assert false : "should be processed by class tree";
}
abstract static class NewInstanceTranslator extends Translator {
protected ListBuffer<JCStatement> stats = ListBuffer.lb();
NewInstanceTranslator(DiagnosticPosition diagPos, JavafxToJava toJava) {
super(diagPos, toJava);
}
/**
* Initialize the instance variables of the instance
* @param instName
*/
protected abstract void initInstanceVariables(Name instName);
/**
* @return the constructor args -- translating any supplied args
*/
protected abstract List<JCExpression> completeTranslatedConstructorArgs();
protected JCExpression translateInstanceVariableInit(JFXExpression init, JavafxBindStatus bindStatus, VarSymbol vsym) {
VarMorphInfo vmi = toJava.typeMorpher.varMorphInfo(vsym);
return toJava.translateDefinitionalAssignmentToValueArg(init.pos(), init, bindStatus, vmi);
}
void setInstanceVariable(DiagnosticPosition diagPos, Name instName, JavafxBindStatus bindStatus, VarSymbol vsym, JCExpression transInit) {
stats.append(toJava.definitionalAssignmentToSet(diagPos, transInit, bindStatus, vsym, instName,
FROM_LITERAL_MILIEU));
}
void setInstanceVariable(DiagnosticPosition diagPos, Name instName, VarSymbol vsym, JCExpression transInit) {
setInstanceVariable(diagPos, instName, JavafxBindStatus.UNBOUND, vsym, transInit);
}
void setInstanceVariable(Name instName, JavafxBindStatus bindStatus, VarSymbol vsym, JFXExpression init) {
DiagnosticPosition initPos = init.pos();
JCExpression transInit = translateInstanceVariableInit(init, bindStatus, vsym);
setInstanceVariable(initPos, instName, bindStatus, vsym, transInit);
}
void setInstanceVariable(Name instName, VarSymbol vsym, JFXExpression init) {
setInstanceVariable(instName, JavafxBindStatus.UNBOUND, vsym, init);
}
/**
* Return the instance building expression
* @param declaredType
* @param cdef
* @param isFX
* @return
*/
protected JCExpression buildInstance(Type declaredType, JFXClassDeclaration cdef, boolean isFX) {
Type type;
if (cdef == null) {
type = declaredType;
} else {
stats.append(toJava.translateClassDef(cdef));
type = cdef.type;
}
JCExpression classTypeExpr = toJava.makeTypeTree(diagPos, type, false);
List<JCExpression> newClassArgs = completeTranslatedConstructorArgs();
JCNewClass newClass =
m().NewClass(null, null, classTypeExpr,
newClassArgs,
null);
JCExpression instExpression;
{
if (isFX || cdef != null) {
// it is a JavaFX class, initializa it properly
JCVariableDecl tmpVar = toJava.makeTmpVar(diagPos, "objlit", type, newClass);
stats.append(tmpVar);
initInstanceVariables(tmpVar.name);
JCIdent ident3 = m().Ident(tmpVar.name);
JCStatement applyExec = toJava.callStatement(diagPos, ident3, defs.initializeName);
stats.append(applyExec);
JCIdent ident2 = m().Ident(tmpVar.name);
instExpression = toJava.makeBlockExpression(diagPos, stats, ident2);
} else {
// this is a Java class, just instanciate it
instExpression = newClass;
}
}
return instExpression;
}
}
/**
* Translate to a built-in type
*/
abstract static class NewBuiltInInstanceTranslator extends NewInstanceTranslator {
protected final Type builtIn;
NewBuiltInInstanceTranslator(DiagnosticPosition diagPos, Type builtIn, JavafxToJava toJava) {
super(diagPos, toJava);
this.builtIn = builtIn;
}
/**
* Arguments for the constructor.
* There are no user arguments to built-in class constructors.
* Just generate the default init 'true' flag for JavaFX generated constructors.
*/
protected List<JCExpression> completeTranslatedConstructorArgs() {
return List.<JCExpression>of(m().Literal(TypeTags.BOOLEAN, 1));
}
VarSymbol varSym(Name varName) {
return (VarSymbol) builtIn.tsym.members().lookup(varName).sym;
}
void setInstanceVariable(Name instName, Name varName, JFXExpression init) {
VarSymbol vsym = varSym(varName);
setInstanceVariable(instName, vsym, init);
}
@Override
protected JCExpression doit() {
return buildInstance(builtIn, null, true);
}
}
/**
* Translator for object literals
*/
abstract static class InstanciateTranslator extends NewInstanceTranslator {
protected final JFXInstanciate tree;
private final Symbol idSym;
InstanciateTranslator(final JFXInstanciate tree, JavafxToJava toJava) {
super(tree.pos(), toJava);
this.tree = tree;
this.idSym = JavafxTreeInfo.symbol(tree.getIdentifier());
}
abstract protected void processLocalVar(JFXVar var);
protected void initInstanceVariables(Name instName) {
if (tree.varDefinedByThis != null) {
toJava.substitutionMap.put(tree.varDefinedByThis, instName);
}
for (JFXObjectLiteralPart olpart : tree.getParts()) {
diagPos = olpart.pos(); // overwrite diagPos (must restore)
JavafxBindStatus bindStatus = olpart.getBindStatus();
JFXExpression init = olpart.getExpression();
VarSymbol vsym = (VarSymbol) olpart.sym;
setInstanceVariable(instName, bindStatus, vsym, init);
}
if (tree.varDefinedByThis != null) {
toJava.substitutionMap.remove(tree.varDefinedByThis);
}
diagPos = tree.pos();
}
protected List<JCExpression> translatedConstructorArgs() {
List<JFXExpression> args = tree.getArgs();
Symbol sym = tree.constructor;
if (sym != null && sym.type != null) {
ListBuffer<JCExpression> translated = ListBuffer.lb();
List<Type> formals = sym.type.asMethodType().getParameterTypes();
boolean usesVarArgs = (sym.flags() & VARARGS) != 0L &&
(formals.size() != args.size() ||
types.isConvertible(args.last().type, types.elemtype(formals.last())));
boolean handlingVarargs = false;
Type formal = null;
List<Type> t = formals;
for (List<JFXExpression> l = args; l.nonEmpty(); l = l.tail) {
if (!handlingVarargs) {
formal = t.head;
t = t.tail;
if (usesVarArgs && t.isEmpty()) {
formal = types.elemtype(formal);
handlingVarargs = true;
}
}
JCExpression targ = toJava.translateAsValue(l.head, formal);
if (targ != null) {
translated.append(targ);
}
}
return translated.toList();
} else {
return toJava.translateExpressions(args);
}
}
@Override
protected List<JCExpression> completeTranslatedConstructorArgs() {
List<JCExpression> translated = translatedConstructorArgs();
if (tree.getClassBody() != null || types.isJFXClass(idSym)) {
assert translated.size() == 0 : "should not be args for JavaFX class constructors";
translated = translated.append(m().Literal(TypeTags.BOOLEAN, 1));
}
if (tree.getClassBody() != null &&
tree.getClassBody().sym != null && toJava.hasOuters.contains(tree.getClassBody().sym) ||
idSym != null && toJava.hasOuters.contains(idSym)) {
JCIdent thisIdent = m().Ident(defs.receiverName);
translated = translated.prepend(thisIdent);
}
return translated;
}
protected JCExpression doit() {
for (JFXVar var : tree.getLocalvars()) {
// add the variable before the class definition or object litersl assignment
processLocalVar(var);
}
return buildInstance(tree.type, tree.getClassBody(), types.isJFXClass(idSym));
}
}
@Override
public void visitInstanciate(JFXInstanciate tree) {
ListBuffer<JCStatement> prevPrependToStatements = prependToStatements;
prependToStatements = ListBuffer.lb();
result = new InstanciateTranslator(tree, this) {
protected void processLocalVar(JFXVar var) {
stats.append(translateToStatement(var));
}
}.doit();
if (result instanceof BlockExprJCBlockExpression) {
BlockExprJCBlockExpression blockExpr = (BlockExprJCBlockExpression) result;
blockExpr.stats = blockExpr.getStatements().prependList(prependToStatements.toList());
}
prependToStatements = prevPrependToStatements;
}
abstract static class StringExpressionTranslator extends Translator {
private final JFXStringExpression tree;
StringExpressionTranslator(JFXStringExpression tree, JavafxToJava toJava) {
super(tree.pos(), toJava);
this.tree = tree;
}
protected JCExpression doit() {
StringBuffer sb = new StringBuffer();
List<JFXExpression> parts = tree.getParts();
ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
JFXLiteral lit = (JFXLiteral) (parts.head); // "...{
sb.append((String) lit.value);
parts = parts.tail;
boolean containsExtendedFormat = false;
while (parts.nonEmpty()) {
lit = (JFXLiteral) (parts.head); // optional format (or null)
String format = (String) lit.value;
if ((!containsExtendedFormat) && format.length() > 0
&& EXTENDED_FORMAT_PATTERN.matcher(format).find()) {
containsExtendedFormat = true;
}
parts = parts.tail;
JFXExpression exp = parts.head;
JCExpression texp;
if (exp != null &&
types.isSameType(exp.type, syms.javafx_DurationType)) {
texp = m().Apply(null,
m().Select(translateArg(exp),
toJava.names.fromString("toDate")),
List.<JCExpression>nil());
sb.append(format.length() == 0 ? "%tQms" : format);
} else {
texp = translateArg(exp);
sb.append(format.length() == 0 ? "%s" : format);
}
values.append(texp);
parts = parts.tail;
lit = (JFXLiteral) (parts.head); // }...{ or }..."
String part = (String)lit.value;
sb.append(part.replace("%", "%%")); // escape percent signs
parts = parts.tail;
}
JCLiteral formatLiteral = m().Literal(TypeTags.CLASS, sb.toString());
values.prepend(formatLiteral);
String formatMethod;
if (tree.translationKey != null) {
formatMethod = "com.sun.javafx.runtime.util.StringLocalization.getLocalizedString";
if (tree.translationKey.length() == 0) {
values.prepend(m().Literal(TypeTags.BOT, null));
} else {
values.prepend(m().Literal(TypeTags.CLASS, tree.translationKey));
}
String resourceName =
toJava.attrEnv.enclClass.sym.flatname.toString().replace('.', '/').replaceAll("\\$.*", "");
values.prepend(m().Literal(TypeTags.CLASS, resourceName));
} else if (containsExtendedFormat) {
formatMethod = "com.sun.javafx.runtime.util.FXFormatter.sprintf";
} else {
formatMethod = "java.lang.String.format";
}
JCExpression formatter = toJava.makeQualifiedTree(diagPos, formatMethod);
return m().Apply(null, formatter, values.toList());
}
abstract protected JCExpression translateArg(JFXExpression arg);
}
@Override
public void visitStringExpression(JFXStringExpression tree) {
result = new StringExpressionTranslator(tree, this) {
protected JCExpression translateArg(JFXExpression arg) {
return translateAsUnconvertedValue(arg);
}
}.doit();
}
private JCExpression translateDefinitionalAssignmentToValueArg(DiagnosticPosition diagPos,
JFXExpression init, JavafxBindStatus bindStatus, VarMorphInfo vmi) {
if (bindStatus.isUnidiBind()) {
return toBound.translate(init, bindStatus, vmi.getRealType());
} else if (bindStatus.isBidiBind()) {
assert requiresLocation(vmi);
// Bi-directional bind translate so it stays in a Location
return translateAsLocation(init);
} else {
// normal init -- unbound
if (init == null) {
// no initializing expression determine a default value from the type
return makeDefaultValue(diagPos, vmi);
} else {
// do a vanilla translation of the expression
Type resultType = vmi.getSymbol().type;
JCExpression trans = translateAsValue(init, resultType);
return convertNullability(diagPos, trans, init, resultType);
}
}
}
private JCExpression translateDefinitionalAssignmentToValue(DiagnosticPosition diagPos,
JFXExpression init, JavafxBindStatus bindStatus, VarSymbol vsym) {
VarMorphInfo vmi = typeMorpher.varMorphInfo(vsym);
JCExpression valueArg = translateDefinitionalAssignmentToValueArg(diagPos, init, bindStatus, vmi);
if (bindStatus.isUnidiBind()) {
return valueArg;
} else if (requiresLocation(vmi)) {
Name makeName = defs.makeMethodName;
if (bindStatus.isBidiBind()) {
makeName = defs.makeBijectiveMethodName;
}
return makeLocationVariable(vmi, diagPos, List.of(valueArg), makeName);
} else {
return valueArg;
}
}
private JCStatement translateDefinitionalAssignmentToSet(DiagnosticPosition diagPos,
JFXExpression init, JavafxBindStatus bindStatus, VarSymbol vsym,
Name instanceName, int milieu) {
if (init == null && vsym.owner.kind == Kinds.TYP && requiresLocation(vsym)) {
// this is a class variable with no explicit initializer,
// use setDefault() so that it is flagged as a default
assert !bindStatus.isBound() : "cannot be bound and have no init expression";
JCExpression localAttr = makeAttributeAccess(diagPos, vsym, instanceName);
Name methName = defs.setDefaultMethodName;
return callStatement(diagPos, localAttr, methName);
}
return make.at(diagPos).Exec( translateDefinitionalAssignmentToSetExpression(diagPos,
init, bindStatus, vsym,
instanceName, milieu) );
}
private JCExpression translateDefinitionalAssignmentToSetExpression(DiagnosticPosition diagPos,
JFXExpression init, JavafxBindStatus bindStatus, VarSymbol vsym,
Name instanceName, int milieu) {
assert( (vsym.flags() & Flags.PARAMETER) == 0L): "Parameters are not initialized";
setSubstitution(init, vsym);
VarMorphInfo vmi = typeMorpher.varMorphInfo(vsym);
JCExpression valueArg = translateDefinitionalAssignmentToValueArg(diagPos, init, bindStatus, vmi);
return definitionalAssignmentToSetExpression(diagPos, valueArg, bindStatus, vsym, instanceName,
vmi.getTypeKind(), milieu);
}
JCExpression definitionalAssignmentToSetExpression(DiagnosticPosition diagPos,
JCExpression valueArg, JavafxBindStatus bindStatus, VarSymbol vsym,
Name instanceName, int typeKind, int milieu) {
JCExpression varRef;
if (!requiresLocation(vsym)) {
if (vsym.owner.kind == Kinds.TYP) {
// It is a member variable
if (instanceName == null) {
varRef = make.at(diagPos).Ident(attributeFieldName(vsym));
} else {
JCExpression tc = make.at(diagPos).Ident(instanceName);
final Name setter = attributeSetterName(vsym);
JCExpression toApply = make.at(diagPos).Select(tc, setter);
return make.at(diagPos).Apply(null, toApply, List.of(valueArg));
}
} else {
// It is a local variable
assert instanceName == null;
varRef = make.at(diagPos).Ident(vsym);
}
return make.at(diagPos).Assign(varRef, valueArg);
}
if (vsym.owner.kind == Kinds.TYP) {
// It is a member variable
varRef = makeAttributeAccess(diagPos, vsym, instanceName);
} else {
// It is a local variable
varRef = make.at(diagPos).Ident(vsym);
}
Name methName;
ListBuffer<JCExpression> args = new ListBuffer<JCExpression>();
if (bindStatus.isUnidiBind()) {
methName = defs.locationBindMilieuMethodName[milieu];
args.append(makeLaziness(diagPos, bindStatus));
} else if (bindStatus.isBidiBind()) {
methName = defs.locationBijectiveBindMilieuMethodName[milieu];
} else {
methName = defs.locationSetMilieuMethodName[typeKind][milieu];
}
args.append(valueArg);
return callExpression(diagPos, varRef, methName, args);
}
JCStatement definitionalAssignmentToSet(DiagnosticPosition diagPos,
JCExpression init, JavafxBindStatus bindStatus, VarSymbol vsym,
Name instanceName, int milieu) {
VarMorphInfo vmi = typeMorpher.varMorphInfo(vsym);
JCExpression nonNullInit = (init == null)? makeDefaultValue(diagPos, vmi) : init; //TODO: is this needed?
JCExpression setExpr = definitionalAssignmentToSetExpression(diagPos, nonNullInit, bindStatus, vsym, instanceName,
vmi.getTypeKind(), milieu);
return make.at(diagPos).Exec( setExpr );
}
@Override
public void visitVarScriptInit(JFXVarScriptInit tree) {
DiagnosticPosition diagPos = tree.pos();
JFXModifiers mods = tree.getModifiers();
long modFlags = mods.flags | Flags.FINAL;
VarSymbol vsym = tree.getSymbol();
JFXVar var = tree.getVar();
assert vsym.owner.kind == Kinds.TYP : "this should just be for script-level variables";
assert (modFlags & Flags.STATIC) != 0;
assert (modFlags & JavafxFlags.SCRIPT_LEVEL_SYNTH_STATIC) != 0;
assert !attrEnv.toplevel.isLibrary;
result = translateDefinitionalAssignmentToSetExpression(diagPos, var.init, var.getBindStatus(), vsym, null, 0);
}
@Override
public void visitVar(JFXVar tree) {
DiagnosticPosition diagPos = tree.pos();
JFXModifiers mods = tree.getModifiers();
final VarSymbol vsym = tree.getSymbol();
final VarMorphInfo vmi = typeMorpher.varMorphInfo(vsym);
assert vsym.owner.kind != Kinds.TYP : "attributes are processed in the class and should never come here";
final long flags = vsym.flags();
final boolean requiresLocation = requiresLocation(vsym);
final boolean isParameter = (flags & Flags.PARAMETER) != 0;
final boolean hasInnerAccess = (flags & JavafxFlags.VARUSE_INNER_ACCESS) != 0;
final long modFlags = (mods.flags & ~Flags.FINAL) | ((hasInnerAccess | requiresLocation)? Flags.FINAL : 0L);
final JCModifiers tmods = make.at(diagPos).Modifiers(modFlags);
final Type type =
requiresLocation?
(isParameter?
vmi.getLocationType() :
vmi.getVariableType()) :
tree.type;
final JCExpression typeExpression = makeTypeTree(diagPos, type, true);
// for class vars, initialization happens during class init, so set to
// default Location. For local vars translate as definitional
JCExpression init;
if (isParameter) {
// parameters aren't initialized
init = null;
result = make.at(diagPos).VarDef(tmods, tree.name, typeExpression, init);
} else {
// create a blank variable declaration and move the declaration to the beginning of the block
if (requiresLocation) {
// location types: XXXVariable.make()
optStat.recordLocalVar(vsym, tree.getBindStatus().isBound(), true);
init = makeLocationAttributeVariable(vmi, diagPos);
} else {
optStat.recordLocalVar(vsym, tree.getBindStatus().isBound(), false);
if ((modFlags & Flags.FINAL) != 0) {
init = translateDefinitionalAssignmentToValue(tree.pos(), tree.init,
tree.getBindStatus(), vsym);
result = make.at(diagPos).VarDef(tmods, tree.name, typeExpression, init);
return;
}
// non location types:
init = makeDefaultValue(diagPos, vmi);
}
prependToStatements.append(make.at(Position.NOPOS).VarDef(tmods, tree.name, typeExpression, init));
// create change Listener and append it to the beginning of the block after the blank variable declaration
JFXOnReplace onReplace = tree.getOnReplace();
if ( onReplace != null ) {
TranslatedVarInfo varInfo = new TranslatedVarInfo(
tree,
vmi,
null,
tree.getOnReplace(),
translatedOnReplaceBody(tree.getOnReplace()));
JCStatement changeListener = initBuilder.makeChangeListenerCall(varInfo);
prependToStatements.append(changeListener);
}
result = translateDefinitionalAssignmentToSetExpression(diagPos, tree.init, tree.getBindStatus(), tree.sym, null, 0);
}
}
@Override
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
assert false : "should be processed by parent tree";
}
@Override
public void visitOnReplace(JFXOnReplace tree) {
assert false : "should be processed by parent tree";
}
@Override
public void visitFunctionValue(JFXFunctionValue tree) {
JFXFunctionDefinition def = tree.definition;
result = makeFunctionValue(make.Ident(defs.lambdaName), def, tree.pos(), (MethodType) def.type);
}
JCExpression makeFunctionValue (JCExpression meth, JFXFunctionDefinition def, DiagnosticPosition diagPos, MethodType mtype) {
ListBuffer<JCTree> members = new ListBuffer<JCTree>();
if (def != null)
members.append(translate(def));
JCExpression encl = null;
int nargs = mtype.argtypes.size();
Type ftype = syms.javafx_FunctionTypes[nargs];
JCExpression t = makeQualifiedTree(null, ftype.tsym.getQualifiedName().toString());
ListBuffer<JCExpression> typeargs = new ListBuffer<JCExpression>();
Type rtype = syms.boxIfNeeded(mtype.restype);
typeargs.append(makeTypeTree(diagPos, rtype));
ListBuffer<JCVariableDecl> params = new ListBuffer<JCVariableDecl>();
ListBuffer<JCExpression> margs = new ListBuffer<JCExpression>();
int i = 0;
for (List<Type> l = mtype.argtypes; l.nonEmpty(); l = l.tail) {
Name pname = make.paramName(i++);
Type ptype = syms.boxIfNeeded(l.head);
JCVariableDecl param = make.VarDef(make.Modifiers(0), pname,
makeTypeTree(diagPos, ptype), null);
params.append(param);
JCExpression marg = make.Ident(pname);
margs.append(marg);
typeargs.append(makeTypeTree(diagPos, ptype));
}
// The backend's Attr skips SYNTHETIC methods when looking for a matching method.
long flags = PUBLIC | BRIDGE; // | SYNTHETIC;
JCExpression call = make.Apply(null, meth, margs.toList());
List<JCStatement> stats;
if (mtype.restype == syms.voidType)
stats = List.of(make.Exec(call), make.Return(make.Literal(TypeTags.BOT, null)));
else {
if (mtype.restype.isPrimitive())
call = makeBox(diagPos, call, mtype.restype);
stats = List.<JCStatement>of(make.Return(call));
}
JCMethodDecl bridgeDef = make.at(diagPos).MethodDef(
make.Modifiers(flags),
defs.invokeName,
makeTypeTree(diagPos, rtype),
List.<JCTypeParameter>nil(),
params.toList(),
make.at(diagPos).Types(mtype.getThrownTypes()),
make.Block(0, stats),
null);
members.append(bridgeDef);
JCClassDecl cl = make.AnonymousClassDef(make.Modifiers(0), members.toList());
List<JCExpression> nilArgs = List.nil();
return make.NewClass(encl, nilArgs, make.TypeApply(t, typeargs.toList()), nilArgs, cl);
}
boolean isInnerFunction (MethodSymbol sym) {
return sym.owner != null && sym.owner.kind != Kinds.TYP
&& (sym.flags() & Flags.SYNTHETIC) == 0;
}
/**
* Translate JavaFX a class definition into a Java static implementation method.
*/
@Override
public void visitFunctionDefinition(JFXFunctionDefinition tree) {
if (isInnerFunction(tree.sym)) {
// If tree's context is not a class, then translate:
// function foo(args) { body }
// to: final var foo = function(args) { body };
// A probably cleaner and possibly more efficient solution would
// be to create an anonymous class containing the function as
// a method; closed-over local variables become fields.
// That would have the advantage that calling the function directly
// translates into a direct method call, rather than going via
// Function's invoke method, which implies extra casts, possibly
// boxing, etc. FIXME
DiagnosticPosition diagPos = tree.pos();
MethodType mtype = (MethodType) tree.type;
JCExpression typeExpression = makeTypeTree( diagPos,syms.makeFunctionType(mtype), true);
JFXFunctionDefinition def = new JFXFunctionDefinition(fxmake.Modifiers(Flags.SYNTHETIC), tree.name, tree.operation);
def.type = mtype;
def.sym = new MethodSymbol(0, def.name, mtype, tree.sym.owner.owner);
JCExpression init =
makeFunctionValue(make.Ident(tree.name), def, tree.pos(), mtype);
JCModifiers mods = make.at(diagPos).Modifiers(Flags.FINAL);
result = make.at(diagPos).VarDef(mods, tree.name, typeExpression, init);
return;
}
boolean isBound = (tree.sym.flags() & JavafxFlags.BOUND) != 0;
TranslationState prevZ = translationState;
translationState = null; //should be explicitly set
try {
boolean classOnly = currentClass.generateClassOnly();
// Made all the operations public. Per Brian's spec.
// If they are left package level it interfere with Multiple Inheritance
// The interface methods cannot be package level and an error is reported.
long flags = tree.mods.flags;
long originalFlags = flags;
flags &= ~Flags.PROTECTED;
if ((tree.mods.flags & Flags.PRIVATE) == 0)
flags |= Flags.PUBLIC;
if (((flags & (Flags.ABSTRACT | Flags.SYNTHETIC)) == 0) && !classOnly) {
flags |= Flags.STATIC;
}
flags &= ~Flags.SYNTHETIC;
JCModifiers mods = make.Modifiers(flags);
final boolean isRunMethod = syms.isRunMethod(tree.sym);
final boolean isImplMethod = (originalFlags & (Flags.STATIC | Flags.ABSTRACT | Flags.SYNTHETIC)) == 0L && !isRunMethod && !classOnly;
DiagnosticPosition diagPos = tree.pos();
MethodType mtype = (MethodType)tree.type;
// construct the body of the translated function
JFXBlock bexpr = tree.getBodyExpression();
JCBlock body;
if (bexpr == null) {
body = null; // null if no block expression
} else if (isBound) {
// Build the body of a bound function by treating it as a bound expression
// TODO: Remove entry in findbugs-exclude.xml if permeateBind is implemented -- it is, so it should be
JCExpression expr = toBound.translate(bexpr, JavafxBindStatus.UNIDIBIND, typeMorpher.varMorphInfo(tree.sym));
body = asBlock(make.at(diagPos).Return(expr));
} else if (isRunMethod) {
// it is a module level run method, do special translation
body = makeRunMethodBody(bexpr);
} else {
// the "normal" case
body = asBlock(translateToStatement(bexpr, mtype.getReturnType()));
}
ListBuffer<JCVariableDecl> params = ListBuffer.lb();
if ((originalFlags & (Flags.STATIC | Flags.ABSTRACT | Flags.SYNTHETIC)) == 0) {
if (classOnly) {
// all implementation code is generated assuming a receiver parameter.
// in the final class case, there is no receiver param, so allow generated code
// to function by adding: var receiver = this;
body.stats = body.stats.prepend(
make.at(diagPos).VarDef(
make.at(diagPos).Modifiers(Flags.FINAL),
defs.receiverName,
make.Ident(initBuilder.interfaceName(currentClass)),
make.at(diagPos).Ident(names._this))
);
} else {
// if we are converting a standard instance function (to a static method), the first parameter becomes a reference to the receiver
params.prepend(makeReceiverParam(currentClass));
}
}
for (JFXVar fxVar : tree.getParams()) {
JCVariableDecl var = (JCVariableDecl)translate(fxVar);
params.append(var);
}
mods = addAccessAnnotationModifiers(diagPos, tree.mods.flags, mods);
result = make.at(diagPos).MethodDef(
mods,
functionName(tree.sym, isImplMethod, isBound),
makeReturnTypeTree(diagPos, tree.sym, isBound),
make.at(diagPos).TypeParams(mtype.getTypeArguments()),
params.toList(),
make.at(diagPos).Types(mtype.getThrownTypes()), // makeThrows(diagPos), //
body,
null);
((JCMethodDecl)result).sym = tree.sym;
result.type = tree.type;
}
finally {
translationState = prevZ;
}
}
public void visitBlockExpression(JFXBlock tree) {
Type targetType = translationState.targetType;
Yield yield = translationState.yield;
DiagnosticPosition diagPos = tree.pos();
ListBuffer<JCStatement> prevPrependToStatements = prependToStatements;
prependToStatements = ListBuffer.lb();
JFXExpression value = tree.value;
ListBuffer<JCStatement> translatedStmts = ListBuffer.lb();
for(JFXExpression expr : tree.getStmts()) {
JCStatement stmt = translateToStatement(expr);
if (stmt != null) {
translatedStmts.append(stmt);
}
}
List<JCStatement> localDefs = translatedStmts.toList();
if (yield == ToExpression) {
// make into block expression
assert (tree.type != syms.voidType) : "void block expressions should be handled below";
//TODO: this may be unneeded, or even wrong
if (value.getFXTag() == JavafxTag.RETURN) {
value = ((JFXReturn) value).getExpression();
}
JCExpression tvalue = translateToExpression(value, translationState.wrapper, null); // must be before prepend
localDefs = prependToStatements.appendList(localDefs).toList();
result = makeBlockExpression(tree.pos(), localDefs, tvalue); //TODO: tree.flags lost
} else {
// make into block
prependToStatements.appendList(localDefs);
if (value != null) {
JCStatement stmt = translateToStatement(value, targetType);
if (stmt != null) {
prependToStatements.append(stmt);
}
}
localDefs = prependToStatements.toList();
result = localDefs.size() == 1? localDefs.head : make.at(diagPos).Block(0L, localDefs);
}
prependToStatements = prevPrependToStatements;
}
abstract class AssignTranslator extends Translator {
protected final JFXExpression lhs;
protected final JFXExpression rhs;
protected final Symbol sym;
protected final JCExpression rhsTranslated;
AssignTranslator(final DiagnosticPosition diagPos, final JFXExpression lhs, final JFXExpression rhs) {
super(diagPos, JavafxToJava.this);
this.lhs = lhs;
this.rhs = rhs;
this.rhsTranslated = convertNullability(diagPos, translateAsValue(rhs, rhsType()), rhs, rhsType());
this.sym = expressionSymbol(lhs);
}
abstract JCExpression defaultFullExpression(JCExpression lhsTranslated, JCExpression rhsTranslated);
abstract JCExpression buildRHS(JCExpression rhsTranslated);
/**
* Override to change the translation type of the right-hand side
*/
protected Type rhsType() {
return lhs.type;
}
/**
* Override to change result in the non-default case.
*/
protected JCExpression postProcess(JCExpression built) {
return built;
}
private JCExpression buildSetter(JCExpression tc, JCExpression rhsComplete) {
final Name setter = attributeSetterName(sym);
JCExpression toApply = tc==null? m().Ident(setter) : m().Select(tc, setter);
return m().Apply(null, toApply, List.of(rhsComplete));
}
protected JCTree doit() {
if (lhs.getFXTag() == JavafxTag.SEQUENCE_INDEXED) {
// set of a sequence element -- s[i]=8, call the sequence set method
JFXSequenceIndexed si = (JFXSequenceIndexed) lhs;
JCExpression seq = translateAsLocation(si.getSequence());
JCExpression index = translateAsValue(si.getIndex(), syms.intType);
JCFieldAccess select = m().Select(seq, defs.setMethodName);
List<JCExpression> args = List.of(index, buildRHS(rhsTranslated));
return postProcess(m().Apply(null, select, args));
} else if (requiresLocation(sym)) {
// we are setting a var Location, call the set method
JCExpression lhsTranslated = translateAsLocation(lhs);
JCFieldAccess setSelect = m().Select(lhsTranslated, defs.locationSetMethodName[typeMorpher.typeMorphInfo(lhs.type).getTypeKind()]);
List<JCExpression> setArgs = List.of(buildRHS(rhsTranslated));
return postProcess(m().Apply(null, setSelect, setArgs));
} else {
final boolean useSetters = sym.owner.kind == Kinds.TYP && !sym.isStatic() && types.isJFXClass(sym.owner);
if (lhs.getFXTag() == JavafxTag.SELECT) {
final JFXSelect select = (JFXSelect) lhs;
return new NullCheckTranslator(diagPos, select.getExpression(), lhs.type, false, AsValue) { //assume assignment doesn't yield Location
private final JCExpression rhsTranslatedPreserved = preserveSideEffects(lhs.type, rhs, rhsTranslated);
@Override
JCExpression translateToCheck( JFXExpression expr) {
return translateAsUnconvertedValue(expr);
}
@Override
JCExpression fullExpression( JCExpression mungedToCheckTranslated) {
if (useSetters) {
return postProcess(buildSetter(mungedToCheckTranslated, buildRHS(rhsTranslatedPreserved)));
} else {
//TODO: possibly should use, or be unified with convertVariableReference
JCFieldAccess fa = m().Select(mungedToCheckTranslated, attributeFieldName(select.sym));
return defaultFullExpression(fa, rhsTranslatedPreserved);
}
}
}.doit();
} else {
// not SELECT
if (useSetters) {
JCExpression recv = makeReceiver(diagPos, sym, attrEnv.enclClass.sym);
return postProcess(buildSetter(recv, buildRHS(rhsTranslated)));
} else {
return defaultFullExpression(translateToExpression(lhs, Locationness.AsShareSafeValue, null), rhsTranslated);
}
}
}
}
}
@Override
public void visitAssign(final JFXAssign tree) {
DiagnosticPosition diagPos = tree.pos();
if (tree.lhs.getFXTag() == JavafxTag.SEQUENCE_SLICE) {
// assignment of a sequence slice -- s[i..j]=8, call the sequence set method
JFXSequenceSlice si = (JFXSequenceSlice)tree.lhs;
JCExpression rhs = translateAsValue(tree.rhs, si.getSequence().type);
JCExpression seq = translateToExpression(si.getSequence(), AsLocation, null);
JCExpression firstIndex = translateAsValue(si.getFirstIndex(), syms.intType);
JCExpression lastIndex = makeSliceLastIndex(si);
JCFieldAccess select = make.Select(seq, defs.replaceSliceMethodName);
List<JCExpression> args = List.of(firstIndex, lastIndex, rhs);
result = make.at(diagPos).Apply(null, select, args);
} else {
result = new AssignTranslator(diagPos, tree.lhs, tree.rhs) {
JCExpression buildRHS(JCExpression rhsTranslated) {
return rhsTranslated;
}
JCExpression defaultFullExpression(JCExpression lhsTranslated, JCExpression rhsTranslated) {
return m().Assign(lhsTranslated, rhsTranslated);
}
}.doit();
}
}
@Override
public void visitAssignop(final JFXAssignOp tree) {
result = new AssignTranslator(tree.pos(), tree.lhs, tree.rhs) {
private boolean useDurationOperations() {
return types.isSameType(lhs.type, syms.javafx_DurationType);
}
@Override
JCExpression buildRHS(JCExpression rhsTranslated) {
final JCExpression lhsTranslated = translateAsUnconvertedValue(lhs);
if (useDurationOperations()) {
JCExpression method = m().Select(lhsTranslated, tree.operator);
return m().Apply(null, method, List.<JCExpression>of(rhsTranslated));
} else {
JCExpression ret = m().Binary(getBinaryOp(), lhsTranslated, rhsTranslated);
if (!types.isSameType(rhsType(), lhs.type)) {
// Because the RHS is a different type than the LHS, a cast may be needed
ret = m().TypeCast(lhs.type, ret);
}
return ret;
}
}
@Override
protected Type rhsType() {
switch (tree.getFXTag()) {
case MUL_ASG:
case DIV_ASG:
// Allow for cases like 'k *= 0.5' where k is an Integer or Duration
return operationalType(useDurationOperations()? syms.javafx_NumberType : rhs.type);
default:
return operationalType(lhs.type);
}
}
@Override
JCExpression defaultFullExpression( JCExpression lhsTranslated, JCExpression rhsTranslated) {
return useDurationOperations()?
m().Assign(lhsTranslated, buildRHS(rhsTranslated)) :
m().Assignop(tree.getOperatorTag(), lhsTranslated, rhsTranslated);
}
private int getBinaryOp() {
switch (tree.getFXTag()) {
case PLUS_ASG:
return JCTree.PLUS;
case MINUS_ASG:
return JCTree.MINUS;
case MUL_ASG:
return JCTree.MUL;
case DIV_ASG:
return JCTree.DIV;
default:
assert false : "unexpected assign op kind";
return JCTree.PLUS;
}
}
}.doit();
}
class SelectTranslator extends NullCheckTranslator {
protected final Symbol sym;
protected final boolean isFunctionReference;
protected final boolean staticReference;
protected final Name name;
protected SelectTranslator(JFXSelect tree, Locationness wrapper) {
super(tree.pos(), tree.getExpression(), tree.type, tree.sym.isStatic(), wrapper);
sym = tree.sym;
isFunctionReference = tree.type instanceof FunctionType && tree.sym.type instanceof MethodType;
staticReference = tree.sym.isStatic();
name = tree.getIdentifier();
}
@Override
protected JCExpression translateToCheck(JFXExpression expr) {
// this may or may not be in a LHS but in either
// event the selector is a value expression
JCExpression translatedSelected = translateAsUnconvertedValue(expr);
if (staticReference) {
translatedSelected = makeTypeTree(diagPos, types.erasure(sym.owner.type), false);
}
return translatedSelected;
}
@Override
protected JCExpression fullExpression(JCExpression mungedToCheckTranslated) {
if (isFunctionReference) {
MethodType mtype = (MethodType) sym.type;
JCExpression tc = staticReference?
mungedToCheckTranslated :
addTempVar(toCheck.type, mungedToCheckTranslated);
JCExpression translated = m().Select(tc, name);
return makeFunctionValue(translated, null, diagPos, mtype);
} else {
JCExpression tc = mungedToCheckTranslated;
if (toCheck.type != null && toCheck.type.isPrimitive()) { // expr.type is null for package symbols.
tc = makeBox(diagPos, tc, toCheck.type);
}
JCFieldAccess translated = make.at(diagPos).Select(tc, name);
return convertVariableReference(
diagPos,
translated,
sym,
wrapper);
}
}
}
public void visitSelect(JFXSelect tree) {
Locationness wrapper = translationState.wrapper;
if (substitute(tree.sym, wrapper)) {
return;
}
result = new SelectTranslator(tree, wrapper).doit();
}
@Override
public void visitIdent(JFXIdent tree) {
Locationness wrapper = translationState.wrapper;
DiagnosticPosition diagPos = tree.pos();
if (substitute(tree.sym, wrapper)) {
return;
}
if (tree.name == names._this) {
// in the static implementation method, "this" becomes "receiver$"
JCExpression rcvr = make.at(diagPos).Ident(defs.receiverName);
if (wrapper == AsLocation) {
rcvr = makeConstantLocation(diagPos, tree.type, rcvr);
}
result = rcvr;
return;
} else if (tree.name == names._super) {
if (types.isCompoundClass(tree.type.tsym)) {
// "super" become just the class where the static implementation method is defined
// the rest of the implementation is in visitFunctionInvocation
result = make.at(diagPos).Ident(tree.type.tsym.name);
}
else {
JCFieldAccess superSelect = make.at(diagPos).Select(make.at(diagPos).Ident(defs.receiverName), tree.name);
result = superSelect;
}
return;
}
int kind = tree.sym.kind;
if (kind == Kinds.TYP) {
// This is a class name, replace it with the full name (no generics)
result = makeTypeTree(diagPos, types.erasure(tree.sym.type), false);
return;
}
// if this is an instance reference to an attribute or function, it needs to go the the "receiver$" arg,
// and possible outer access methods
JCExpression convert;
boolean isStatic = tree.sym.isStatic();
if (isStatic) {
// make class-based direct static reference: Foo.x
convert = make.at(diagPos).Select(makeTypeTree(diagPos, tree.sym.owner.type, false), tree.name);
} else {
if ((kind == Kinds.VAR || kind == Kinds.MTH) && tree.sym.owner.kind == Kinds.TYP) {
// it is a non-static attribute or function class member
// reference it through the receiver
JCExpression mRec = makeReceiver(diagPos, tree.sym, attrEnv.enclClass.sym);
convert = make.at(diagPos).Select(mRec, tree.name);
} else {
convert = make.at(diagPos).Ident(tree.name);
}
}
if (tree.type instanceof FunctionType && tree.sym.type instanceof MethodType) {
MethodType mtype = (MethodType) tree.sym.type;
JFXFunctionDefinition def = null; // FIXME
result = makeFunctionValue(convert, def, tree.pos(), mtype);
return;
}
result = convertVariableReference(diagPos,
convert,
tree.sym,
wrapper);
}
static class ExplicitSequenceTranslator extends Translator {
final List<JFXExpression> items;
final Type elemType;
ExplicitSequenceTranslator(DiagnosticPosition diagPos, JavafxToJava toJava, List<JFXExpression> items, Type elemType) {
super(diagPos, toJava);
this.items = items;
this.elemType = elemType; // boxed
}
/***
* In cases where the components of an explicitly constructed
* sequence are all singletons, we can revert to this (more
* optimal) implementation.
DiagnosticPosition diagPos = tree.pos();
JCExpression meth = ((JavafxTreeMaker)make).at(diagPos).Identifier(sequencesMakeString);
Type elemType = tree.type.getTypeArguments().get(0);
ListBuffer<JCExpression> args = ListBuffer.<JCExpression>lb();
List<JCExpression> typeArgs = List.<JCExpression>of(makeTypeTree(elemType, diagPos));
// type name .class
args.append(makeTypeInfo(diagPos, elemType));
args.appendList( translate( tree.getItems() ) );
result = make.at(diagPos).Apply(typeArgs, meth, args.toList());
*/
protected JCExpression doit() {
ListBuffer<JCStatement> stmts = ListBuffer.lb();
UseSequenceBuilder builder = toJava.useSequenceBuilder(diagPos, elemType, items.length());
stmts.append(builder.makeBuilderVar());
for (JFXExpression item : items) {
if (item.getJavaFXKind() != JavaFXKind.NULL_LITERAL) {
// Insert all non-null elements
stmts.append(builder.addElement(item));
}
}
return toJava.makeBlockExpression(diagPos, stmts, builder.makeToSequence());
}
}
@Override
public void visitSequenceExplicit(JFXSequenceExplicit tree) {
result = new ExplicitSequenceTranslator(
tree.pos(),
this,
tree.getItems(),
boxedElementType(tree.type)
).doit();
}
@Override
public void visitSequenceRange(JFXSequenceRange tree) {
DiagnosticPosition diagPos = tree.pos();
JCExpression meth = makeQualifiedTree(
diagPos, tree.isExclusive()?
sequencesRangeExclusiveString :
sequencesRangeString);
Type elemType = syms.javafx_IntegerType;
int ltag = tree.getLower().type.tag;
int utag = tree.getUpper().type.tag;
int stag = tree.getStepOrNull() == null? TypeTags.INT : tree.getStepOrNull().type.tag;
if (ltag == TypeTags.FLOAT || ltag == TypeTags.DOUBLE ||
utag == TypeTags.FLOAT || utag == TypeTags.DOUBLE ||
stag == TypeTags.FLOAT || stag == TypeTags.DOUBLE) {
elemType = syms.javafx_NumberType;
}
ListBuffer<JCExpression> args = ListBuffer.lb();
List<JCExpression> typeArgs = List.nil();
args.append( translateAsValue( tree.getLower(), elemType ));
args.append( translateAsValue( tree.getUpper(), elemType ));
if (tree.getStepOrNull() != null) {
args.append( translateAsValue( tree.getStepOrNull(), elemType ));
}
result = convertTranslated(make.at(diagPos).Apply(typeArgs, meth, args.toList()), diagPos, types.sequenceType(elemType), tree.type);
}
@Override
public void visitSequenceEmpty(JFXSequenceEmpty tree) {
if (types.isSequence(tree.type)) {
Type elemType = boxedElementType(tree.type);
JCExpression expr = accessEmptySequence(tree.pos(), elemType);
result = castFromObject(expr, syms.javafx_SequenceTypeErasure);
}
else
result = make.at(tree.pos).Literal(TypeTags.BOT, null);
}
public JCExpression translateSequenceExpression (JFXExpression seq) {
Locationness w;
if (types.isSequence(seq.type) &&
(seq instanceof JFXIdent || seq instanceof JFXSelect)) {
w = AsShareSafeValue;
} else
w = AsValue;
return translateToExpression(seq, w, null);
}
@Override
public void visitSequenceIndexed(final JFXSequenceIndexed tree) {
DiagnosticPosition diagPos = tree.pos();
JFXExpression seq = tree.getSequence();
JCExpression index = translateAsValue(tree.getIndex(), syms.intType);
Locationness w;
if (types.isSequence(seq.type) &&
(seq instanceof JFXIdent || seq instanceof JFXSelect)) {
Symbol sym = JavafxTreeInfo.symbol(seq);
// An optimization of translateSequenceExpression - instead of:
// v.getAsSequenceRaw().get(index) we should generate v.get(index)
if (sym instanceof VarSymbol && requiresLocation(sym))
w = AsLocation;
else
w = AsShareSafeValue;
} else
w = AsValue;
JCExpression tseq = translateToExpression(seq, w, null);
if (seq.type.tag == TypeTags.ARRAY) {
result = make.at(diagPos).Indexed(tseq, index);
}
else {
JCExpression trans = callExpression(diagPos, tseq, defs.getMethodName, index);
result = tree.type.isPrimitive()? convertTranslated(trans, diagPos, types.boxedClass(tree.type).type, tree.type) : trans;
}
}
@Override
public void visitSequenceSlice(JFXSequenceSlice tree) {
DiagnosticPosition diagPos = tree.pos();
JCExpression seq = translateAsLocation(tree.getSequence());
JCExpression firstIndex = translateAsValue(tree.getFirstIndex(), syms.intType);
JCExpression lastIndex = makeSliceLastIndex(tree);
JCFieldAccess select = make.at(diagPos).Select(seq, defs.getSliceMethodName);
List<JCExpression> args = List.of(firstIndex, lastIndex);
result = make.at(diagPos).Apply(null, select, args);
}
@Override
public void visitSequenceInsert(JFXSequenceInsert tree) {
DiagnosticPosition diagPos = tree.pos();
JCExpression seqLoc = translateAsLocation(tree.getSequence());
JCExpression elem = translateAsUnconvertedValue( tree.getElement() );
Type elemType = tree.getElement().type;
if (types.isArray(elemType) || types.isSequence(elemType))
elem = convertTranslated(elem, diagPos, elemType, tree.getSequence().type);
else
elem = convertTranslated(elem, diagPos, elemType, boxedElementType(tree.getSequence().type));
if (tree.getPosition() == null) {
result = callStatement(diagPos, seqLoc, "insert", elem);
} else {
String meth = tree.shouldInsertAfter()? "insertAfter" : "insertBefore";
result = callStatement(diagPos, seqLoc, meth,
List.of(elem, translateAsValue(tree.getPosition(), syms.intType)));
}
}
@Override
public void visitSequenceDelete(JFXSequenceDelete tree) {
JFXExpression seq = tree.getSequence();
if (tree.getElement() != null) {
JCExpression seqLoc = translateAsLocation(seq);
result = callStatement(tree.pos(), seqLoc, "deleteValue", translateAsUnconvertedValue(tree.getElement())); //TODO: convert to seqence type
} else {
if (seq.getFXTag() == JavafxTag.SEQUENCE_INDEXED) {
// deletion of a sequence element -- delete s[i]
JFXSequenceIndexed si = (JFXSequenceIndexed) seq;
JFXExpression seqseq = si.getSequence();
JCExpression seqLoc = translateAsLocation(seqseq);
JCExpression index = translateAsValue(si.getIndex(), syms.intType);
result = callStatement(tree.pos(), seqLoc, "delete", index);
} else if (seq.getFXTag() == JavafxTag.SEQUENCE_SLICE) {
// deletion of a sequence slice -- delete s[i..j]=8
JFXSequenceSlice slice = (JFXSequenceSlice) seq;
JFXExpression seqseq = slice.getSequence();
JCExpression seqLoc = translateAsLocation(seqseq);
JCExpression first = translateAsValue(slice.getFirstIndex(), syms.intType);
JCExpression last = makeSliceLastIndex(slice);
result = callStatement(tree.pos(), seqLoc, "deleteSlice", List.of(first, last));
} else if (types.isSequence(seq.type)) {
JCExpression seqLoc = translateAsLocation(seq);
result = callStatement(tree.pos(), seqLoc, "deleteAll");
} else {
result = make.at(tree.pos()).Exec(
make.Assign(
translateAsUnconvertedValue(seq), //TODO: does this work?
make.Literal(TypeTags.BOT, null)));
}
}
}
/**** utility methods ******/
JCExpression makeSliceLastIndex(JFXSequenceSlice tree) {
JCExpression lastIndex = tree.getLastIndex() == null ?
callExpression(tree,
translateAsUnconvertedValue(tree.getSequence()),
defs.sizeMethodName) :
translateAsValue(tree.getLastIndex(), syms.intType);
int decr =
(tree.getEndKind() == SequenceSliceTree.END_EXCLUSIVE ? 1 : 0) +
(tree.getLastIndex() == null ? 1 : 0);
if (decr > 0) {
lastIndex = make.at(tree).Binary(JCTree.MINUS,
lastIndex, make.Literal(TypeTags.INT, decr));
}
return lastIndex;
}
JCMethodDecl makeMainMethod(DiagnosticPosition diagPos, Name className) {
List<JCStatement> mainStats;
if (!attrEnv.toplevel.isRunnable) {
List<JCExpression> newClassArgs = List.<JCExpression>of(make.at(diagPos).Literal(TypeTags.CLASS, className.toString()));
mainStats = List.<JCStatement>of(make.at(diagPos).Throw(make.at(diagPos).NewClass(null, null, makeIdentifier(diagPos, noMainExceptionString), newClassArgs, null)));
} else {
List<JCExpression> emptyExpressionList = List.nil();
JCExpression classIdent = make.at(diagPos).Ident(className);
JCExpression classConstant = make.at(diagPos).Select(classIdent, names._class);
JCExpression commandLineArgs = makeIdentifier(diagPos, "args");
JCExpression startIdent = makeQualifiedTree(diagPos, JavafxDefs.startMethodString);
ListBuffer<JCExpression>args = new ListBuffer<JCExpression>();
args.append(classConstant);
args.append(commandLineArgs);
JCMethodInvocation runCall = make.at(diagPos).Apply(emptyExpressionList, startIdent, args.toList());
mainStats = List.<JCStatement>of(make.at(diagPos).Exec(runCall));
}
List<JCVariableDecl> paramList = List.nil();
paramList = paramList.append(make.at(diagPos).VarDef(make.Modifiers(0),
names.fromString("args"),
make.at(diagPos).TypeArray(make.Ident(names.fromString("String"))),
null));
JCBlock body = make.Block(0, mainStats);
return make.at(diagPos).MethodDef(make.Modifiers(Flags.PUBLIC | Flags.STATIC),
defs.mainName,
make.at(diagPos).TypeIdent(TypeTags.VOID),
List.<JCTypeParameter>nil(),
paramList,
makeThrows(diagPos),
body,
null);
}
/** Equivalent to make.at(pos.getStartPosition()) with side effect of caching
* pos as make_pos, for use in diagnostics.
**/
TreeMaker make_at(DiagnosticPosition pos) {
return make.at(pos);
}
/** Look up a method in a given scope.
*/
private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, null);
}
/** Look up a constructor.
*/
private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
return rs.resolveInternalConstructor(pos, attrEnv, qual, args, null);
}
/** Box up a single primitive expression. */
JCExpression makeBox(DiagnosticPosition diagPos, JCExpression translatedExpr, Type primitiveType) {
make_at(translatedExpr.pos());
Type boxedType = types.boxedClass(primitiveType).type;
JCExpression box;
if (target.boxWithConstructors()) {
Symbol ctor = lookupConstructor(translatedExpr.pos(),
boxedType,
List.<Type>nil()
.prepend(primitiveType));
box = make.Create(ctor, List.of(translatedExpr));
} else {
Symbol valueOfSym = lookupMethod(translatedExpr.pos(),
names.valueOf,
boxedType,
List.<Type>nil()
.prepend(primitiveType));
// JCExpression meth =makeIdentifier(valueOfSym.owner.type.toString() + "." + valueOfSym.name.toString());
JCExpression meth = make.Select(makeTypeTree( diagPos,valueOfSym.owner.type), valueOfSym.name);
TreeInfo.setSymbol(meth, valueOfSym);
meth.type = valueOfSym.type;
box = make.App(meth, List.of(translatedExpr));
}
return box;
}
public List<JCExpression> makeThrows(DiagnosticPosition diagPos) {
return List.of(makeQualifiedTree(diagPos, methodThrowsString));
}
UseSequenceBuilder useSequenceBuilder(DiagnosticPosition diagPos, Type elemType, final int initLength) {
return new UseSequenceBuilder(diagPos, elemType, sequenceBuilderString) {
JCStatement addElement(JFXExpression exprToAdd) {
JCExpression expr = translateAsValue(exprToAdd, targetType(exprToAdd));
return makeAdd(expr);
}
JCExpression makeConstructorArg() {
return makeTypeInfo(diagPos, elemType);
}
@Override
JCExpression makeInitialLengthArg() {
return (initLength != -1)? make.at(diagPos).Literal(Integer.valueOf(initLength)) : null;
}
@Override
JCExpression makeToSequence() {
return makeBuilderVarAccess();
}
};
}
UseSequenceBuilder useSequenceBuilder(DiagnosticPosition diagPos, Type elemType) {
return useSequenceBuilder(diagPos, elemType, -1);
}
UseSequenceBuilder useBoundSequenceBuilder(DiagnosticPosition diagPos, Type elemType, final int initLength) {
return new UseSequenceBuilder(diagPos, elemType, boundSequenceBuilderString) {
JCStatement addElement(JFXExpression exprToAdd) {
JCExpression expr = toBound.translate(exprToAdd, targetType(exprToAdd));
return makeAdd(expr);
}
JCExpression makeConstructorArg() {
return makeTypeInfo(diagPos, elemType);
}
@Override
JCExpression makeInitialLengthArg() {
return (initLength != -1)? make.at(diagPos).Literal(Integer.valueOf(initLength)) : null;
}
};
}
abstract class UseSequenceBuilder {
final DiagnosticPosition diagPos;
final Type elemType;
final String seqBuilder;
Name sbName;
private UseSequenceBuilder(DiagnosticPosition diagPos, Type elemType, String seqBuilder) {
this.diagPos = diagPos;
this.elemType = elemType;
this.seqBuilder = seqBuilder;
}
Type targetType(JFXExpression exprToAdd) {
Type exprType = exprToAdd.type;
if (types.isArray(exprType) || types.isSequence(exprType)) {
return types.sequenceType(elemType);
} else {
Type unboxed = types.unboxedType(elemType);
return (unboxed.tag != TypeTags.NONE) ? unboxed : elemType;
}
}
JCStatement makeBuilderVar() {
JCExpression builderTypeExpr = makeQualifiedTree(diagPos, seqBuilder);
List<JCExpression> btargs = List.of(makeTypeTree(diagPos, elemType));
builderTypeExpr = make.at(diagPos).TypeApply(builderTypeExpr, btargs);
// Sequence builder temp var name "sb"
sbName = getSyntheticName("sb");
JCExpression initialLengthArg = makeInitialLengthArg();
// Build "sb" initializing expression -- new SequenceBuilder<T>(clazz)
JCExpression newExpr = make.at(diagPos).NewClass(
null, // enclosing
List.<JCExpression>nil(), // type args
make.at(diagPos).TypeApply( // class name -- SequenceBuilder<elemType>
makeQualifiedTree(diagPos, seqBuilder),
List.<JCExpression>of(makeTypeTree(diagPos, elemType))),
initialLengthArg == null?
List.<JCExpression>of(makeConstructorArg()) :
List.<JCExpression>of(initialLengthArg, makeConstructorArg()), // args
null // empty body
);
// Build the sequence builder variable
return make.at(diagPos).VarDef(
make.at(diagPos).Modifiers(0L),
sbName, builderTypeExpr, newExpr);
}
JCIdent makeBuilderVarAccess() {
return make.Ident(sbName);
}
abstract JCStatement addElement(JFXExpression expr);
abstract JCExpression makeConstructorArg();
JCExpression makeInitialLengthArg() {
return null;
}
JCStatement makeAdd(JCExpression expr) {
JCMethodInvocation addCall = make.Apply(
List.<JCExpression>nil(),
make.at(diagPos).Select(
makeBuilderVarAccess(),
names.fromString("add")),
List.<JCExpression>of(expr));
return make.at(diagPos).Exec(addCall);
}
JCExpression makeToSequence() {
return make.Apply(
List.<JCExpression>nil(), // type arguments
make.at(diagPos).Select(
makeBuilderVarAccess(),
names.fromString(toSequenceString)),
List.<JCExpression>nil() // arguments
);
}
}
JCExpression castFromObject (JCExpression arg, Type castType) {
if (castType.isPrimitive())
castType = types.boxedClass(castType).type;
return make.TypeCast(makeTypeTree( arg.pos(),castType), arg);
}
static class DurationOperationTranslator extends Translator {
private final JavafxTag tag;
private final JCExpression lhsExpr;
private final JCExpression rhsExpr;
private final Type rhsType;
private final Type lhsType;
DurationOperationTranslator(DiagnosticPosition diagPos, JavafxTag tag,
JCExpression lhsExpr, JCExpression rhsExpr,
Type lhsType, Type rhsType,
JavafxToJava toJava) {
super(diagPos, toJava);
this.tag = tag;
this.lhsExpr = lhsExpr;
this.rhsExpr = rhsExpr;
this.lhsType = lhsType;
this.rhsType = rhsType;
}
protected JCExpression doit() {
switch (tag) {
case PLUS:
return m().Apply(null,
m().Select(lhsExpr, names.fromString("add")), List.<JCExpression>of(rhsExpr));
// lhs.add(rhs);
case MINUS:
// lhs.sub(rhs);
return m().Apply(null,
m().Select(lhsExpr, names.fromString("sub")), List.<JCExpression>of(rhsExpr));
case DIV:
// lhs.div(rhs);
return m().Apply(null,
m().Select(lhsExpr, names.fromString("div")),
List.<JCExpression>of(toJava.convertTranslated(rhsExpr, diagPos, rhsType, syms.javafx_NumberType)));
case MUL: {
// lhs.mul(rhs);
JCExpression rcvr;
JCExpression arg;
Type argType;
if (!types.isSameType(lhsType, syms.javafx_DurationType)) {
// FIXME This may get side-effects out-of-order.
// A simple fix is to use a static Duration.mul(double,Duration).
// Another is to use a Block and a temporary.
rcvr = rhsExpr;
arg = lhsExpr;
argType = lhsType;
} else {
rcvr = lhsExpr;
arg = rhsExpr;
argType = rhsType;
}
return m().Apply(null,
m().Select(rcvr, names.fromString("mul")),
List.<JCExpression>of(toJava.convertTranslated(arg, diagPos, argType, syms.javafx_NumberType)));
}
case LT:
return m().Apply(null,
m().Select(lhsExpr, names.fromString("lt")), List.<JCExpression>of(rhsExpr));
case LE:
return m().Apply(null,
m().Select(lhsExpr, names.fromString("le")), List.<JCExpression>of(rhsExpr));
case GT:
return m().Apply(null,
m().Select(lhsExpr, names.fromString("gt")), List.<JCExpression>of(rhsExpr));
case GE:
return m().Apply(null,
m().Select(lhsExpr, names.fromString("ge")), List.<JCExpression>of(rhsExpr));
}
throw new RuntimeException("Internal Error: bad Duration operation");
}
}
@Override
public void visitBinary(final JFXBinary tree) {
result = (new Translator( tree.pos(), this ) {
/**
* Compare against null
*/
private JCExpression makeNullCheck(JCExpression targ) {
return makeEqEq(targ, makeNull());
}
//TODO: after type system is figured out, this needs to be revisited
/**
* Check if a primitive has the default value for its type.
*/
private JCExpression makePrimitiveNullCheck(Type argType, JCExpression arg) {
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(argType);
JCExpression defaultValue = makeLit(diagPos, tmi.getRealType(), tmi.getDefaultValue());
return makeEqEq( arg, defaultValue);
}
/**
* Check if a non-primitive has the default value for its type.
*/
private JCExpression makeObjectNullCheck(Type argType, JCExpression arg) {
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(argType);
if (tmi.getTypeKind() == TYPE_KIND_SEQUENCE || tmi.getRealType() == syms.javafx_StringType) {
return callRuntime(JavafxDefs.isNullMethodString, List.of(arg));
} else {
return makeNullCheck(arg);
}
}
/*
* Do a == compare
*/
private JCExpression makeEqEq(JCExpression arg1, JCExpression arg2) {
return makeBinary(JCTree.EQ, arg1, arg2);
}
private JCExpression makeBinary(int tag, JCExpression arg1, JCExpression arg2) {
return make.at(diagPos).Binary(tag, arg1, arg2);
}
private JCExpression makeNull() {
return make.at(diagPos).Literal(TypeTags.BOT, null);
}
private JCExpression callRuntime(String methNameString, List<JCExpression> args) {
JCExpression meth = makeQualifiedTree(diagPos, methNameString);
List<JCExpression> typeArgs = List.nil();
return m().Apply(typeArgs, meth, args);
}
/**
* Make a .equals() comparison with a null check on the receiver
*/
private JCExpression makeFullCheck(JCExpression lhs, JCExpression rhs) {
return callRuntime(JavafxDefs.equalsMethodString, List.of(lhs, rhs));
}
/**
* Return the translation for a == comparision
*/
private JCExpression translateEqualsEquals() {
final Type lhsType = tree.lhs.type;
final Type rhsType = tree.rhs.type;
final boolean reqSeq = types.isSequence(lhsType) ||
types.isSequence(rhsType);
Type expected = tree.operator.type.getParameterTypes().head;
if (reqSeq) {
Type left = types.isSequence(lhsType) ? types.elementType(lhsType) : lhsType;
Type right = types.isSequence(rhsType) ? types.elementType(rhsType) : rhsType;
if (left.isPrimitive() && right.isPrimitive() && left == right)
expected = left;
}
final JCExpression lhs = translateAsValue(tree.lhs, reqSeq ?
types.sequenceType(expected) : null);
final JCExpression rhs = translateAsValue(tree.rhs, reqSeq ?
types.sequenceType(expected) : null);
// this is an x == y
if (lhsType.getKind() == TypeKind.NULL) {
if (rhsType.getKind() == TypeKind.NULL) {
// both are known to be null
return make.at(diagPos).Literal(TypeTags.BOOLEAN, 1);
} else if (rhsType.isPrimitive()) {
// lhs is null, rhs is primitive, do default check
return makePrimitiveNullCheck(rhsType, rhs);
} else {
// lhs is null, rhs is non-primitive, figure out what check to do
return makeObjectNullCheck(rhsType, rhs);
}
} else if (lhsType.isPrimitive()) {
if (rhsType.getKind() == TypeKind.NULL) {
// lhs is primitive, rhs is null, do default check on lhs
return makePrimitiveNullCheck(lhsType, lhs);
} else if (rhsType.isPrimitive()) {
// both are primitive, use ==
return makeEqEq(lhs, rhs);
} else {
// lhs is primitive, rhs is non-primitive, use equals(), but switch them
return makeFullCheck(rhs, lhs);
}
} else {
if (rhsType.getKind() == TypeKind.NULL) {
// lhs is non-primitive, rhs is null, figure out what check to do
return makeObjectNullCheck(lhsType, lhs);
} else {
// lhs is non-primitive, use equals()
return makeFullCheck(lhs, rhs);
}
}
}
/**
* Translate a binary expressions
*/
public JCTree doit() {
//TODO: handle <>
if (tree.getFXTag() == JavafxTag.EQ) {
return translateEqualsEquals();
} else if (tree.getFXTag() == JavafxTag.NE) {
return make.at(diagPos).Unary(JCTree.NOT, translateEqualsEquals());
} else {
// anything other than == or <>
// Duration type operator overloading
final JCExpression lhs = translateAsUnconvertedValue(tree.lhs);
final JCExpression rhs = translateAsUnconvertedValue(tree.rhs);
if ((types.isSameType(tree.lhs.type, syms.javafx_DurationType) ||
types.isSameType(tree.rhs.type, syms.javafx_DurationType)) &&
tree.operator == null) { // operator check is to try to get a decent error message by falling through if the Duration method isn't matched
return new DurationOperationTranslator(diagPos, tree.getFXTag(), lhs, rhs, tree.lhs.type, tree.rhs.type, JavafxToJava.this).doit();
}
return makeBinary(tree.getOperatorTag(), lhs, rhs);
}
}
}).doit();
}
public void visitBreak(JFXBreak tree) {
result = make.at(tree.pos).Break(tree.label);
}
public void visitCatch(JFXCatch tree) {
JCVariableDecl param = translate(tree.param);
JCBlock body = translateBlockExpressionToBlock(tree.body);
result = make.at(tree.pos).Catch(param, body);
}
/**
* assume seq is a sequence of element type U
* convert for (x in seq where cond) { body }
* into the following block expression
*
* {
* SequenceBuilder<T> sb = new SequenceBuilder<T>(clazz);
* for (U x : seq) {
* if (!cond)
* continue;
* sb.add( { body } );
* }
* sb.toSequence()
* }
*
* **/
@Override
public void visitForExpression(JFXForExpression tree) {
Type targetType = translationState.targetType;
Yield yield = translationState.yield;
// sub-translation in done inline -- no super.visitForExpression(tree);
if (yield == ToStatement && targetType == syms.voidType) {
result = wrapWithInClause(tree, translateToStatement(tree.getBodyExpression()));
} else {
// body has value (non-void)
assert tree.type != syms.voidType : "should be handled above";
DiagnosticPosition diagPos = tree.pos();
ListBuffer<JCStatement> stmts = ListBuffer.lb();
JCStatement stmt;
JCExpression value;
// Compute the element type from the sequence type
assert tree.type.getTypeArguments().size() == 1;
Type elemType = boxedElementType(tree.type);
UseSequenceBuilder builder = useSequenceBuilder(diagPos, elemType);
stmts.append(builder.makeBuilderVar());
// Build innermost loop body
stmt = builder.addElement( tree.getBodyExpression() );
// Build the result value
value = builder.makeToSequence();
stmt = wrapWithInClause(tree, stmt);
stmts.append(stmt);
if (yield == ToStatement) {
stmts.append(make.at(tree).Return(value));
result = make.at(diagPos).Block(0L, stmts.toList());
} else {
// Build the block expression -- which is what we translate to
result = makeBlockExpression(diagPos, stmts, value);
}
}
}
//where
private JCStatement wrapWithInClause(JFXForExpression tree, JCStatement coreStmt) {
JCStatement stmt = coreStmt;
for (int inx = tree.getInClauses().size() - 1; inx >= 0; --inx) {
JFXForExpressionInClause clause = (JFXForExpressionInClause)tree.getInClauses().get(inx);
if (clause.getWhereExpression() != null) {
stmt = make.at(clause).If( translateAsUnconvertedValue( clause.getWhereExpression() ), stmt, null);
}
// Build the loop
//TODO: below is the simpler version of the loop. Ideally, this should be used in
// cases where the loop variable does not need to be final.
/*
stmt = make.at(clause).ForeachLoop(
// loop variable is synthetic should not be bound
// even if we are in a bind context
boundTranslate(clause.getVar(), JavafxBindStatus.UNBOUND),
translate(clause.getSequenceExpression()),
stmt);
*/
JFXVar var = clause.getVar();
Name tmpVarName = getSyntheticName(var.getName().toString());
JCVariableDecl finalVar = make.VarDef(
make.Modifiers(Flags.FINAL),
var.getName(),
makeTypeTree( var,var.type),
make.Ident(tmpVarName));
Name tmpIndexVarName;
if (clause.getIndexUsed()) {
Name indexVarName = indexVarName(clause);
tmpIndexVarName = getSyntheticName(indexVarName.toString());
JCVariableDecl finalIndexVar = make.VarDef(
make.Modifiers(Flags.FINAL),
indexVarName,
makeTypeTree( var,syms.javafx_IntegerType),
make.Unary(JCTree.POSTINC, make.Ident(tmpIndexVarName)));
stmt = make.Block(0L, List.of(finalIndexVar, finalVar, stmt));
}
else {
tmpIndexVarName = null;
stmt = make.Block(0L, List.of(finalVar, stmt));
}
DiagnosticPosition diagPos = clause.seqExpr;
if (types.isSequence(clause.seqExpr.type)) {
// It would be more efficient to move the Iterable.iterator call
// to a static method, which can also check for null.
// But that requires expanding the ForeachLoop by hand. Later.
JCExpression seq = callExpression(diagPos,
makeQualifiedTree(diagPos, "com.sun.javafx.runtime.sequence.Sequences"),
"forceNonNull",
List.of(makeTypeInfo(diagPos, var.type),
translateAsUnconvertedValue(clause.seqExpr)));
stmt = make.at(clause).ForeachLoop(
// loop variable is synthetic should not be bound
// even if we are in a bind context
make.VarDef(
make.Modifiers(0L),
tmpVarName,
makeTypeTree( var,var.type, true),
null),
seq,
stmt);
} else if (types.asSuper(clause.seqExpr.type, syms.iterableType.tsym) != null) {
stmt = make.at(clause).ForeachLoop(
// loop variable is synthetic should not be bound
// even if we are in a bind context
make.VarDef(
make.Modifiers(0L),
tmpVarName,
makeTypeTree(var,var.type, true),
null),
translateAsUnconvertedValue(clause.seqExpr),
stmt);
} else {
// The "sequence" isn't a Sequence.
// Compile: { var tmp = seq; if (tmp!=null) stmt; }
if (! var.type.isPrimitive())
stmt = make.If(make.Binary(JCTree.NE, make.Ident(tmpVarName),
make.Literal(TypeTags.BOT, null)),
stmt, null);
stmt = make.at(diagPos).Block(0,
List.of(make.at(diagPos).VarDef(
make.Modifiers(0L),
tmpVarName,
makeTypeTree( var,var.type, true),
translateAsUnconvertedValue(clause.seqExpr)),
stmt));
}
if (clause.getIndexUsed()) {
JCVariableDecl tmpIndexVar =
make.VarDef(
make.Modifiers(0L),
tmpIndexVarName,
makeTypeTree( var,syms.javafx_IntegerType),
make.Literal(Integer.valueOf(0)));
stmt = make.Block(0L, List.of(tmpIndexVar, stmt));
}
}
return stmt;
}
public void visitIndexof(JFXIndexof tree) {
final DiagnosticPosition diagPos = tree.pos();
assert tree.clause.getIndexUsed() : "assert that index used is set correctly";
JCExpression transIndex = make.at(diagPos).Ident(indexVarName(tree.fname));
VarSymbol vsym = (VarSymbol)tree.clause.getVar().sym;
if (requiresLocation(vsym)) {
// from inside the bind, its a Location, convert to value
result = getLocationValue(diagPos, transIndex, TYPE_KIND_INT);
} else {
// it came from outside of the bind, not a Location
result = transIndex;
}
}
@Override
public void visitIfExpression(JFXIfExpression tree) {
Yield yield = translationState.yield;
final DiagnosticPosition diagPos = tree.pos();
JCExpression cond = translateAsUnconvertedValue(tree.getCondition());
JFXExpression trueSide = tree.getTrueExpression();
JFXExpression falseSide = tree.getFalseExpression();
if (yield == ToExpression) {
Type targetType = tree.type;
result = make.at(diagPos).Conditional(
cond,
translateAsValue(trueSide, targetType),
translateAsValue(falseSide, targetType));
} else {
Type targetType = translationState.targetType;
result = make.at(diagPos).If(
cond,
translateToStatement(trueSide, targetType),
falseSide == null ? null : translateToStatement(falseSide, targetType));
}
}
@Override
public void visitContinue(JFXContinue tree) {
result = make.at(tree.pos).Continue(tree.label);
}
@Override
public void visitErroneous(JFXErroneous tree) {
List<? extends JCTree> errs = translateGeneric(tree.getErrorTrees());
result = make.at(tree.pos).Erroneous(errs);
}
@Override
public void visitReturn(JFXReturn tree) {
JFXExpression exp = tree.getExpression();
if (exp == null) {
result = make.at(tree).Return(null);
} else {
result = translateToStatement(exp, tree.returnType);
}
}
@Override
public void visitParens(JFXParens tree) {
Type targetType = translationState.targetType;
Yield yield = translationState.yield;
if (yield == ToExpression) {
JCExpression expr = translateAsUnconvertedValue(tree.expr);
result = make.at(tree.pos).Parens(expr);
} else {
result = translateToStatement(tree.expr, targetType);
}
}
@Override
public void visitImport(JFXImport tree) {
//JCTree qualid = straightConvert(tree.qualid);
//result = make.at(tree.pos).Import(qualid, tree.staticImport);
assert false : "should be processed by parent tree";
}
@Override
public void visitInstanceOf(JFXInstanceOf tree) {
- JCTree clazz = this.makeTypeTree( tree,tree.clazz.type);
+ Type type = tree.clazz.type;
+ if (type.isPrimitive())
+ type = types.boxedClass(type).type;
+ JCTree clazz = this.makeTypeTree( tree, type);
JCExpression expr = translateAsUnconvertedValue(tree.expr);
if (tree.expr.type.isPrimitive()) {
expr = this.makeBox(tree.expr.pos(), expr, tree.expr.type);
}
- if (types.isSequence(tree.expr.type) && ! types.isSequence(tree.clazz.type))
+ if (types.isSequence(tree.expr.type) && ! types.isSequence(type))
expr = callExpression(tree.expr,
makeQualifiedTree(tree.expr, "com.sun.javafx.runtime.sequence.Sequences"),
"getSingleValue", expr);
result = make.at(tree.pos).TypeTest(expr, clazz);
}
@Override
public void visitTypeCast(final JFXTypeCast tree) {
final DiagnosticPosition diagPos = tree.pos();
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(tree.expr.type);
if (tmi.getTypeKind() == TYPE_KIND_OBJECT) {
// We can't just cast the Object to Float (for example)
// because if the Object is not Float, we will get a ClassCastException at runtime.
// And we can't just call java.lang.Number.floatValue() because java.lang.Number
// doesn't exist on mobile, at least not as of Jan 2009.
String method = null;
switch (tree.clazz.type.tag) {
case TypeTags.CHAR:
method="objectToCharacter";
break;
case TypeTags.BYTE:
method="objectToByte";
break;
case TypeTags.SHORT:
method="objectToShort";
break;
case TypeTags.INT:
method="objectToInt";
break;
case TypeTags.LONG:
method="objectToLong";
break;
case TypeTags.FLOAT:
method="objectToFloat";
break;
case TypeTags.DOUBLE:
method="objectToDouble";
break;
}
if (method != null) {
result = callExpression(diagPos,
makeQualifiedTree(diagPos, "com.sun.javafx.runtime.Util"),
method,
translate(tree.expr));
return;
}
}
JCExpression ret = makeTypeCast(diagPos, tree.clazz.type, tree.expr.type, translateAsUnconvertedValue(tree.expr));
result = convertNullability(diagPos, ret, tree.expr, tree.clazz.type);
}
@Override
public void visitLiteral(JFXLiteral tree) {
if (tree.typetag == TypeTags.BOT && types.isSequence(tree.type)) {
Type elemType = boxedElementType(tree.type);
JCExpression expr = accessEmptySequence(tree.pos(), elemType);
result = castFromObject(expr, syms.javafx_SequenceTypeErasure);
} else {
result = make.at(tree.pos).Literal(tree.typetag, tree.value);
}
}
abstract static class FunctionCallTranslator extends Translator {
protected final JFXExpression meth;
protected final JFXExpression selector;
private final Name selectorIdName;
protected final boolean thisCall;
protected final boolean superCall;
protected final MethodSymbol msym;
protected final boolean renameToSuper;
protected final boolean superToStatic;
protected final List<Type> formals;
protected final boolean usesVarArgs;
protected final boolean useInvoke;
protected final boolean selectorMutable;
protected final boolean callBound;
protected final boolean magicIsInitializedFunction;
protected final Type returnType;
FunctionCallTranslator(final JFXFunctionInvocation tree, JavafxToJava toJava) {
super(tree.pos(), toJava);
meth = tree.meth;
returnType = tree.type;
JFXSelect fieldAccess = meth.getFXTag() == JavafxTag.SELECT ? (JFXSelect) meth : null;
selector = fieldAccess != null ? fieldAccess.getExpression() : null;
Symbol sym = toJava.expressionSymbol(meth);
msym = (sym instanceof MethodSymbol) ? (MethodSymbol) sym : null;
selectorIdName = (selector != null && selector.getFXTag() == JavafxTag.IDENT) ? ((JFXIdent) selector).getName() : null;
thisCall = selectorIdName == toJava.names._this;
superCall = selectorIdName == toJava.names._super;
ClassSymbol csym = toJava.attrEnv.enclClass.sym;
useInvoke = meth.type instanceof FunctionType;
Symbol selectorSym = selector != null? toJava.expressionSymbol(selector) : null;
boolean namedSuperCall =
msym != null && !msym.isStatic() &&
selectorSym instanceof ClassSymbol &&
// FIXME should also allow other enclosing classes:
types.isSuperType(selectorSym.type, csym);
renameToSuper = namedSuperCall && !types.isCompoundClass(csym);
superToStatic = (superCall || namedSuperCall) && !renameToSuper;
formals = meth.type.getParameterTypes();
//TODO: probably move this local to the arg processing
usesVarArgs = tree.args != null && msym != null &&
(msym.flags() & VARARGS) != 0 &&
(formals.size() != tree.args.size() ||
types.isConvertible(tree.args.last().type,
types.elemtype(formals.last())));
selectorMutable = msym != null &&
!sym.isStatic() && selector != null && !superCall && !namedSuperCall &&
!thisCall && !renameToSuper;
callBound = msym != null && !useInvoke &&
((msym.flags() & JavafxFlags.BOUND) != 0);
magicIsInitializedFunction = (msym != null) &&
(msym.flags_field & JavafxFlags.FUNC_IS_INITIALIZED) != 0;
}
}
@Override
public void visitFunctionInvocation(final JFXFunctionInvocation tree) {
final Locationness wrapper = translationState.wrapper;
result = (new FunctionCallTranslator( tree, this ) {
private Name funcName = null;
protected JCTree doit() {
JFXExpression toCheckOrNull;
boolean knownNonNull;
if (useInvoke) {
// this is a function var call, check the whole expression for null
toCheckOrNull = meth;
funcName = defs.invokeName;
knownNonNull = false;
} else if (selector == null) {
// This is not an function var call and not a selector, so we assume it is a simple foo()
if (meth.getFXTag() == JavafxTag.IDENT) {
JFXIdent fr = fxm().Ident(functionName(msym, superToStatic, callBound));
fr.type = meth.type;
fr.sym = msym;
toCheckOrNull = fr;
funcName = null;
knownNonNull = true;
} else {
// Should never get here
assert false : meth;
toCheckOrNull = meth;
funcName = null;
knownNonNull = true;
}
} else {
// Regular selector call foo.bar() -- so, check the selector not the whole meth
toCheckOrNull = selector;
funcName = functionName(msym, superToStatic, callBound);
knownNonNull = selector.type.isPrimitive() || !selectorMutable;
}
return new NullCheckTranslator(diagPos, toCheckOrNull, returnType, knownNonNull, wrapper) {
List<JCExpression> args = determineArgs();
JCExpression translateToCheck(JFXExpression expr) {
JCExpression trans;
if (renameToSuper) {
trans = m().Select(makeTypeTree(diagPos, currentClass.sym.type, false), names._super);
} else if (superToStatic) {
trans = makeTypeTree(diagPos, types.erasure(msym.owner.type), false);
} else if (selector != null && !useInvoke && msym != null && msym.isStatic()) {
//TODO: clean this up -- handles referencing a static function via an instance
trans = makeTypeTree(diagPos, types.erasure(msym.owner.type), false);
} else {
trans = translateAsUnconvertedValue(expr);
if (expr.type.isPrimitive()) {
// Java doesn't allow calls directly on a primitive, wrap it
trans = makeBox(diagPos, trans, expr.type);
}
}
return trans;
}
@Override
JCExpression fullExpression( JCExpression mungedToCheckTranslated) {
JCExpression tc = mungedToCheckTranslated;
if (funcName != null) {
// add the selector name back
tc = m().Select(tc, funcName);
}
JCMethodInvocation app = m().Apply(translateExpressions(tree.typeargs), tc, args);
JCExpression full = callBound ? makeBoundCall(app) : app;
if (useInvoke) {
if (tree.type.tag != TypeTags.VOID) {
full = castFromObject(full, tree.type);
}
}
return full;
}
/**
* Compute the translated arguments.
*/
List<JCExpression> determineArgs() {
ListBuffer<JCExpression> targs = ListBuffer.lb();
// if this is a super.foo(x) call, "super" will be translated to referenced class,
// so we add a receiver arg to make a direct call to the implementing method MyClass.foo(receiver$, x)
if (superToStatic) {
targs.append(make.Ident(defs.receiverName));
}
if (callBound) {
//TODO: this code looks completely messed-up
/**
* If this is a bound call, use left-hand side references for arguments consisting
* solely of a var or attribute reference, or function call, otherwise, wrap it
* in an expression location
*/
List<Type> formal = formals;
for (JFXExpression arg : tree.args) {
switch (arg.getFXTag()) {
case IDENT:
case SELECT:
case APPLY:
// This arg expression is one that will translate into a Location;
// since that is needed for a this into Location, do so.
// However, if the types need to by changed (subclass), this won't
// directly work.
// Also, if this is a mismatched sequence type, we will need
// to do some different
//TODO: never actually gets here
if (arg.type.equals(formal.head) ||
types.isSequence(formal.head) ||
formal.head == syms.objectType // don't add conversion for parameter type of java.lang.Object: doing so breaks the Pointer trick to obtain the original location (JFC-826)
) {
targs.append(translateAsLocation(arg));
break;
}
//TODO: handle sequence subclasses
//TODO: use more efficient mechanism (use currently apears rare)
//System.err.println("Not match: " + arg.type + " vs " + formal.head);
// Otherwise, fall-through, presumably a conversion will work.
default: {
targs.append(makeUnboundLocation(
arg.pos(),
typeMorpher.typeMorphInfo(formal.head),
translateAsValue(arg, arg.type)));
}
}
formal = formal.tail;
}
} else {
boolean handlingVarargs = false;
Type formal = null;
List<Type> t = formals;
for (List<JFXExpression> l = tree.args; l.nonEmpty(); l = l.tail) {
if (!handlingVarargs) {
formal = t.head;
t = t.tail;
if (usesVarArgs && t.isEmpty()) {
formal = types.elemtype(formal);
handlingVarargs = true;
}
}
JCExpression targ;
if (magicIsInitializedFunction) {
//TODO: in theory, this could have side-effects (but only in theory)
targ = translateAsLocation(l.head);
} else {
targ = preserveSideEffects(formal, l.head, translateAsValue(l.head, formal));
}
targs.append(targ);
}
}
return targs.toList();
}
}.doit();
}
// This is for calls from non-bound contexts (code for true bound calls is in JavafxToBound)
JCExpression makeBoundCall(JCExpression applyExpression) {
JavafxTypeMorpher.TypeMorphInfo tmi = typeMorpher.typeMorphInfo(msym.getReturnType());
if (wrapper == AsLocation) {
return applyExpression;
} else {
return callExpression(diagPos,
m().Parens(applyExpression),
defs.locationGetMethodName[tmi.getTypeKind()]);
}
}
}).doit();
}
@Override
public void visitModifiers(JFXModifiers tree) {
result = make.at(tree.pos).Modifiers(tree.flags, List.<JCAnnotation>nil());
}
@Override
public void visitSkip(JFXSkip tree) {
result = make.at(tree.pos).Skip();
}
@Override
public void visitThrow(JFXThrow tree) {
JCTree expr = translateAsUnconvertedValue(tree.expr);
result = make.at(tree.pos).Throw(expr);
}
@Override
public void visitTry(JFXTry tree) {
JCBlock body = translateBlockExpressionToBlock(tree.body);
List<JCCatch> catchers = translateCatchers(tree.catchers);
JCBlock finalizer = translateBlockExpressionToBlock(tree.finalizer);
result = make.at(tree.pos).Try(body, catchers, finalizer);
}
@Override
public void visitUnary(final JFXUnary tree) {
final Locationness wrapper = translationState.wrapper;
result = (new Translator( tree.pos(), this ) {
private final JFXExpression expr = tree.getExpression();
private JCExpression translateForSizeof(JFXExpression expr) {
return translateSequenceExpression(expr);
}
private final JCExpression transExpr =
tree.getFXTag() == JavafxTag.SIZEOF && wrapper == AsValue &&
(expr instanceof JFXIdent || expr instanceof JFXSelect) ? translateForSizeof(expr)
: translateAsUnconvertedValue(expr);
private JCExpression doIncDec(final int binaryOp, final boolean postfix) {
return (JCExpression) new AssignTranslator(diagPos, expr, fxm().Literal(1)) {
private JCExpression castIfNeeded(JCExpression transExpr) {
int ttag = expr.type.tag;
if (ttag == TypeTags.BYTE || ttag == TypeTags.SHORT) {
return m().TypeCast(expr.type, transExpr);
}
return transExpr;
}
@Override
JCExpression buildRHS(JCExpression rhsTranslated) {
return castIfNeeded(m().Binary(binaryOp, transExpr, rhsTranslated));
}
@Override
JCExpression defaultFullExpression( JCExpression lhsTranslated, JCExpression rhsTranslated) {
return m().Unary(tree.getOperatorTag(), lhsTranslated);
}
@Override
protected JCExpression postProcess(JCExpression built) {
if (postfix) {
// this is a postfix operation, undo the value (not the variable) change
return castIfNeeded(m().Binary(binaryOp, (JCExpression) built, m().Literal(-1)));
} else {
// prefix operation
return built;
}
}
}.doit();
}
public JCTree doit() {
switch (tree.getFXTag()) {
case SIZEOF:
return callExpression(diagPos,
makeQualifiedTree(diagPos, "com.sun.javafx.runtime.sequence.Sequences"),
defs.sizeMethodName, transExpr);
case REVERSE:
return callExpression(diagPos,
makeQualifiedTree(diagPos, "com.sun.javafx.runtime.sequence.Sequences"),
"reverse", transExpr);
case PREINC:
return doIncDec(JCTree.PLUS, false);
case PREDEC:
return doIncDec(JCTree.MINUS, false);
case POSTINC:
return doIncDec(JCTree.PLUS, true);
case POSTDEC:
return doIncDec(JCTree.MINUS, true);
case NEG:
if (types.isSameType(tree.type, syms.javafx_DurationType)) {
return m().Apply(null, m().Select(translateAsUnconvertedValue(tree.arg), names.fromString("negate")), List.<JCExpression>nil());
}
default:
return m().Unary(tree.getOperatorTag(), transExpr);
}
}
}).doit();
}
@Override
public void visitWhileLoop(JFXWhileLoop tree) {
JCStatement body = translateToStatement(tree.body);
JCExpression cond = translateAsUnconvertedValue(tree.cond);
result = make.at(tree.pos).WhileLoop(cond, body);
}
/******** goofy visitors, most of which should go away ******/
public void visitObjectLiteralPart(JFXObjectLiteralPart that) {
assert false : "should be processed by parent tree";
}
public void visitTypeAny(JFXTypeAny that) {
assert false : "should be processed by parent tree";
}
public void visitTypeClass(JFXTypeClass that) {
assert false : "should be processed by parent tree";
}
public void visitTypeFunctional(JFXTypeFunctional that) {
assert false : "should be processed by parent tree";
}
public void visitTypeUnknown(JFXTypeUnknown that) {
assert false : "should be processed by parent tree";
}
public void visitForExpressionInClause(JFXForExpressionInClause that) {
assert false : "should be processed by parent tree";
}
/***********************************************************************
*
* Utilities
*
*/
private JCBlock makeRunMethodBody(JFXBlock bexpr) {
DiagnosticPosition diagPos = bexpr.pos();
final JFXExpression value = bexpr.value;
JCBlock block;
if (value == null || value.type == syms.voidType) {
// the block has no value: translate as simple statement and add a null return
block = asBlock(translateToStatement(bexpr));
block.stats = block.stats.append(make.Return(make.at(diagPos).Literal(TypeTags.BOT, null)));
} else {
// block has a value, return it
block = asBlock(translateToStatement(bexpr, value.type));
final Type valueType = value.type;
if (valueType != null && valueType.isPrimitive()) {
// box up any primitives returns so they return Object -- the return type of the run method
new TreeTranslator() {
@Override
public void visitReturn(JCReturn tree) {
tree.expr = makeBox(tree.expr.pos(), tree.expr, valueType);
result = tree;
}
// do not descend into inner classes
@Override
public void visitClassDef(JCClassDecl tree) {
result = tree;
}
}.translate(block);
}
}
return block;
}
protected String getSyntheticPrefix() {
return "jfx$";
}
boolean requiresLocation(Symbol sym) {
if (sym == null) {
return false;
}
return typeMorpher.requiresLocation(sym);
}
boolean requiresLocation(VarMorphInfo vmi) {
return requiresLocation(vmi.getSymbol());
}
JCBlock translatedOnReplaceBody(JFXOnReplace onr) {
return (onr == null)? null : translateBlockExpressionToBlock(onr.getBody());
}
JCExpression convertVariableReference(DiagnosticPosition diagPos,
JCExpression varRef, Symbol sym,
Locationness wrapper) {
JCExpression expr = varRef;
boolean staticReference = sym.isStatic();
if (sym instanceof VarSymbol) {
final VarSymbol vsym = (VarSymbol) sym;
boolean doNoteShared = false;
if (wrapper == AsValue) {
Type type = vsym.type;
if (types.isSequence(type))
doNoteShared = true;
}
if (sym.owner.kind == Kinds.TYP && types.isJFXClass(sym.owner)) {
// this is a reference to a JavaFX class variable
if (staticReference) {
// a script-level (static) variable, direct access with prefix
expr = switchName(diagPos, varRef, attributeFieldName(vsym));
} else {
// an instance variable, use get$
JCExpression accessFunc = switchName(diagPos, varRef, attributeGetterName(vsym));
List<JCExpression> emptyArgs = List.nil();
expr = make.at(diagPos).Apply(null, accessFunc, emptyArgs);
}
}
VarMorphInfo vmi = typeMorpher.varMorphInfo(vsym);
if (requiresLocation(vsym)) {
if (wrapper == AsLocation) {
// already in correct form-- leave it
} else {
// non-bind context -- want v1.get()
int typeKind = vmi.getTypeKind();
Name getMethodName = defs.locationGetMethodName[typeKind];
if (typeKind == JavafxVarSymbol.TYPE_KIND_SEQUENCE) {
if (doNoteShared)
doNoteShared = false;
else
getMethodName = defs.getAsSequenceRawMethodName;
}
expr = getLocationValue(diagPos, expr, getMethodName);
}
} else {
// not morphed
if (wrapper == AsLocation) {
expr = makeUnboundLocation(diagPos, vmi, expr);
}
}
if (doNoteShared) {
// typeArgs = List.of(makeTypeTree(diagPos, tmi.getRealType(), true));
JCExpression st = makeQualifiedTree(diagPos, "com.sun.javafx.runtime.sequence.Sequences");
JCExpression fn = make.at(diagPos).Select(st, defs.noteSharedMethodName);
expr = make.at(diagPos).Apply(null/*typeArgs*/, fn, List.of(expr));
}
}
return expr;
}
//where
private JCExpression switchName(DiagnosticPosition diagPos, JCExpression identOrSelect, Name name) {
switch (identOrSelect.getTag()) {
case JCTree.IDENT:
return make.at(diagPos).Ident(name);
case JCTree.SELECT:
return make.at(diagPos).Select(((JCFieldAccess)identOrSelect).getExpression(), name);
default:
throw new AssertionError();
}
}
/**
* Build the AST for accessing the outer member.
* The accessors might be chained if the member accessed is more than one level up in the outer chain.
* */
JCExpression makeReceiver(DiagnosticPosition pos, Symbol treeSym, Symbol siteOwner) {
JCExpression ret = null;
if (treeSym != null && siteOwner != null) {
ret = make.Ident(defs.receiverName);
ret.type = siteOwner.type;
// check if it is in the chain
if (siteOwner != treeSym.owner) {
Symbol siteCursor = siteOwner;
boolean foundOwner = false;
int numOfOuters = 0;
ownerSearch:
while (siteCursor.kind != Kinds.PCK) {
ListBuffer<Type> supertypes = ListBuffer.lb();
Set<Type> superSet = new HashSet<Type>();
if (siteCursor.type != null) {
supertypes.append(siteCursor.type);
superSet.add(siteCursor.type);
}
if (siteCursor.kind == Kinds.TYP) {
types.getSupertypes(siteCursor, supertypes, superSet);
}
for (Type supType : supertypes) {
if (types.isSameType(supType, treeSym.owner.type)) {
foundOwner = true;
break ownerSearch;
}
}
if (siteCursor.kind == Kinds.TYP) {
numOfOuters++;
}
siteCursor = siteCursor.owner;
}
if (foundOwner) {
// site was found up the outer class chain, add the chaining accessors
siteCursor = siteOwner;
while (numOfOuters > 0) {
if (siteCursor.kind == Kinds.TYP) {
ret = callExpression(pos, ret, initBuilder.outerAccessorName);
ret.type = siteCursor.type;
}
if (siteCursor.kind == Kinds.TYP) {
numOfOuters--;
}
siteCursor = siteCursor.owner;
}
}
}
}
return ret;
}
private void fillClassesWithOuters(JFXScript tree) {
class FillClassesWithOuters extends JavafxTreeScanner {
JFXClassDeclaration currentClass;
@Override
public void visitClassDeclaration(JFXClassDeclaration tree) {
JFXClassDeclaration prevClass = currentClass;
try {
currentClass = tree;
super.visitClassDeclaration(tree);
}
finally {
currentClass = prevClass;
}
}
@Override
public void visitIdent(JFXIdent tree) {
super.visitIdent(tree);
if (currentClass != null && tree.sym.kind != Kinds.TYP) {
addOutersForOuterAccess(tree.sym, currentClass.sym);
}
}
@Override // Need this because JavafxTreeScanner is not visiting the args of the JFXInstanciate tree. Starting to visit them generate tons of errors.
public void visitInstanciate(JFXInstanciate tree) {
super.visitInstanciate(tree);
super.scan(tree.getArgs());
}
private void addOutersForOuterAccess(Symbol sym, Symbol currentClass) {
if (sym != null && sym.owner != null && sym.owner.type != null
&& !sym.isStatic() && currentClass != null) {
Symbol outerSym = currentClass;
ListBuffer<ClassSymbol> potentialOuters = new ListBuffer<ClassSymbol>();
boolean foundOuterOwner = false;
while (outerSym != null) {
if (outerSym.kind == Kinds.TYP) {
ClassSymbol outerCSym = (ClassSymbol) outerSym;
if (types.isSuperType(sym.owner.type, outerCSym)) {
foundOuterOwner = true;
break;
}
potentialOuters.append(outerCSym);
}
else if (sym.owner == outerSym)
break;
outerSym = outerSym.owner;
}
if (foundOuterOwner) {
for (ClassSymbol cs : potentialOuters) {
hasOuters.add(cs);
}
}
}
}
}
new FillClassesWithOuters().scan(tree);
}
@Override
public void visitTimeLiteral(JFXTimeLiteral tree) {
//TODO: code should be something like the below, but this requires a similar change to visitInterpolateValue
/***
result = makeDurationLiteral(tree.pos(), translate(tree.value));
*/
// convert this time literal to a javafx.lang.Duration.valueOf() invocation
JFXFunctionInvocation duration = timeLiteralToDuration(tree); // sets result
// now convert that FX invocation to Java
visitFunctionInvocation(duration); // sets result
}
abstract static class InterpolateValueTranslator extends NewBuiltInInstanceTranslator {
final JFXInterpolateValue tree;
InterpolateValueTranslator(JFXInterpolateValue tree, JavafxToJava toJava) {
super(tree.pos(), toJava.syms.javafx_KeyValueType, toJava);
this.tree = tree;
}
protected abstract JCExpression translateTarget();
protected void initInstanceVariables(Name instName) {
// value
setInstanceVariable(instName, defs.valueName, tree.value);
// interpolator kind
if (tree.interpolation != null) {
VarSymbol vsym = varSym(defs.interpolateName);
setInstanceVariable(instName, JavafxBindStatus.UNBOUND, vsym, tree.interpolation);
}
// target -- convert to Pointer
setInstanceVariable(tree.attribute.pos(), instName, JavafxBindStatus.UNBOUND, varSym(defs.targetName), translateTarget());
}
}
public void visitInterpolateValue(final JFXInterpolateValue tree) {
result = new InterpolateValueTranslator(tree, JavafxToJava.this) {
protected JCExpression translateTarget() {
JCExpression target = toJava.translateAsLocation(tree.attribute);
return toJava.callExpression(diagPos, makeExpression(syms.javafx_PointerType), "make", target);
}
}.doit();
}
public void visitKeyFrameLiteral(final JFXKeyFrameLiteral tree) {
result = new NewBuiltInInstanceTranslator(tree.pos(), syms.javafx_KeyFrameType, JavafxToJava.this) {
protected void initInstanceVariables(Name instName) {
// start time
setInstanceVariable(instName, defs.timeName, tree.start);
// key values -- as sequence
JCExpression values = new ExplicitSequenceTranslator(
tree.pos(),
JavafxToJava.this,
tree.getInterpolationValues(),
syms.javafx_KeyValueType
).doit();
setInstanceVariable(tree.pos(), instName, varSym(defs.valuesName), values);
}
}.doit();
}
}
| false | false | null | null |
diff --git a/org.caltoopia.frontend/src/org/caltoopia/codegen/transformer/analysis/IrVariableAnnotation.java b/org.caltoopia.frontend/src/org/caltoopia/codegen/transformer/analysis/IrVariableAnnotation.java
index 112d4f2..bccae52 100644
--- a/org.caltoopia.frontend/src/org/caltoopia/codegen/transformer/analysis/IrVariableAnnotation.java
+++ b/org.caltoopia.frontend/src/org/caltoopia/codegen/transformer/analysis/IrVariableAnnotation.java
@@ -1,1077 +1,1089 @@
/*
* Copyright (c) Ericsson AB, 2013
* All rights reserved.
*
* License terms:
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names
* of its contributors may be used to endorse or promote
* products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.caltoopia.codegen.transformer.analysis;
import java.io.File;
import java.io.PrintStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.caltoopia.ir.AbstractActor;
import org.caltoopia.ir.Action;
import org.caltoopia.ir.Actor;
import org.caltoopia.ir.ActorInstance;
import org.caltoopia.ir.Annotation;
import org.caltoopia.ir.AnnotationArgument;
import org.caltoopia.ir.Assign;
import org.caltoopia.ir.Block;
import org.caltoopia.ir.Declaration;
import org.caltoopia.ir.Expression;
import org.caltoopia.ir.ExternalActor;
import org.caltoopia.ir.ForwardDeclaration;
import org.caltoopia.ir.Generator;
import org.caltoopia.ir.Guard;
import org.caltoopia.ir.IrFactory;
import org.caltoopia.ir.LambdaExpression;
import org.caltoopia.ir.Member;
import org.caltoopia.ir.Namespace;
import org.caltoopia.ir.Network;
import org.caltoopia.ir.Node;
import org.caltoopia.ir.PortPeek;
import org.caltoopia.ir.PortRead;
import org.caltoopia.ir.PortWrite;
import org.caltoopia.ir.ProcCall;
import org.caltoopia.ir.ProcExpression;
import org.caltoopia.ir.Statement;
import org.caltoopia.ir.Type;
import org.caltoopia.ir.TypeActor;
import org.caltoopia.ir.TypeBool;
import org.caltoopia.ir.TypeConstructor;
import org.caltoopia.ir.TypeDeclaration;
import org.caltoopia.ir.TypeFloat;
import org.caltoopia.ir.TypeInt;
import org.caltoopia.ir.TypeLambda;
import org.caltoopia.ir.TypeList;
import org.caltoopia.ir.TypeProc;
import org.caltoopia.ir.TypeRecord;
import org.caltoopia.ir.TypeUint;
import org.caltoopia.ir.TypeUser;
import org.caltoopia.ir.Variable;
import org.caltoopia.ir.VariableExpression;
import org.caltoopia.ir.VariableExternal;
import org.caltoopia.ir.VariableImport;
import org.caltoopia.ir.VariableReference;
import org.caltoopia.ir.util.IrReplaceSwitch;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.caltoopia.cli.ActorDirectory;
import org.caltoopia.cli.CompilationSession;
import org.caltoopia.cli.DirectoryException;
import org.caltoopia.codegen.IrXmlPrinter;
import org.caltoopia.codegen.UtilIR;
import org.caltoopia.codegen.transformer.IrTransformer;
import org.caltoopia.codegen.transformer.IrTransformer.IrPassTypes;
import org.caltoopia.codegen.transformer.TransUtil.HowLiteral;
import org.caltoopia.codegen.transformer.TransUtil;
public class IrVariableAnnotation extends IrReplaceSwitch {
private class UsedInBody extends IrReplaceSwitch {
private String searchID=null;
private boolean found=false;
public void setId(String id) {
this.searchID=id;
}
public boolean getFound() {
return found;
}
@Override
public Expression caseVariableExpression(VariableExpression var) {
if(var.getVariable().getId().equals(searchID))
found=true;
return super.caseVariableExpression(var);
}
}
private Map<String,Boolean> foundMap = new HashMap<String,Boolean>();
private boolean isUsedInBody(String id, Action a) {
if(foundMap.containsKey(id))
return foundMap.get(id);
UsedInBody u = new UsedInBody();
u.setId(id);
//Used in body of action or ...
for(Statement s : a.getStatements())
u.doSwitch(s);
//directly in port write expressions or ..
for(PortWrite p : a.getOutputs())
u.doSwitch(p);
//part of initValue in declarations
for(Declaration d : a.getDeclarations())
u.doSwitch(d);
foundMap.put(id, u.getFound());
return u.getFound();
}
private Actor currentActor;
private Network currentNetwork;
private Action currentAction;
private Namespace currentNamespace;
private PortRead currentRead;
private PortWrite currentWrite;
private Map<String,String> idInVarAccessMap = new HashMap<String,String>();
private Map<String,String> idOutVarAccessMap = new HashMap<String,String>();
private PrintStream serr = null;
private CompilationSession session;
public IrVariableAnnotation(Node node, CompilationSession session, boolean errPrint) {
if(!errPrint) {
serr = new PrintStream(new OutputStream(){
public void write(int b) {
//NO-OP
}
});
} else {
serr = System.err;
}
this.session = session;
this.doSwitch(node);
}
public enum VarType {
unknown,
//Functions and procedures of different flavors
func,
proc,
actorFunc,
externFunc,
externProc,
importFunc,
importProc,
//Normal variables of different flavors
externBuiltInTypeVar,
externBuiltInListTypeVar,
externOtherTypeVar, //TODO frontend won't allow user types in external declarations
externOtherListTypeVar, //TODO frontend won't allow user types in external declarations
importConstVar,
constVar,
generatorVar,
blockVar,
blockConstVar,
funcVar,
funcInParamVar,
procVar,
procInParamVar,
procOutParamVar,
actorVar,
actorParamVar,
actorConstParamVar,
actionVar,
actionInitInDepVar,
syncVar, //The value of this input token is never used in the action
peekVar,
inPortPeekVar, //Both read and peek
inPortVar,
inOutPortVar, //input var used on output directly
inOutPortPeekVar, //input var used on output directly and in guard
outPortVar, //Only when directly used as variable on port, not if part of some expression giving the output port expression
//Declarations
declarationType,
memberDeclType
};
public enum VarAccess {
unknown,
//Port accesses
scalarSingle,
scalarInterleaved,
listSingle,
listInterleaved, //Is this possible in the syntax???
scalarUserTypeSingle,
scalarUserTypeInterleaved,
listUserTypeSingle,
listUserTypeInterleaved, //Is this possible in the syntax???
//Member accesses
inlinedMember,
refMember
};
public enum VarLocalAccess {
unknown,
scalar, //scalar builtin type
list, //list of builtin type
listMultiList, //list multi-dim (only single list after index) of builtin type
listMulti, //list multi-dim (still multi-dim after index) of builtin type
scalarUserType, //scalar user type
listUserType, //list of user type
listMultiUserTypeList, //list multi-dim (only single list after index) of user type
listMultiUserType, //list multi-dim (still multi-dim after index) of user type
listSingle, //list of builtin type (indexed to scalar)
listMultiSingle, //list multi-dim (indexed to scalar) of builtin type
listUserTypeSingle, //list of user type (indexed to scalar)
listMultiUserTypeSingle, //list multi-dim (indexed to scalar) of user type
//when a scalar user type's member
memberScalar,
memberList,
memberListMultiList,
memberListMulti,
memberScalarUserType,
memberListUserType,
memberListMultiUserTypeList,
memberListMultiUserType,
memberListSingle,
memberListMultiSingle,
memberListUserTypeSingle,
memberListMultiUserTypeSingle,
//when a list user type's member
listMemberScalar,
listMemberList,
listMemberListMultiList,
listMemberListMulti,
listMemberScalarUserType,
listMemberListUserType,
listMemberListMultiUserTypeList,
listMemberListMultiUserType,
listMemberListSingle,
listMemberListMultiSingle,
listMemberListUserTypeSingle,
listMemberListMultiUserTypeSingle,
//assignment ref and expr same variable
self,
//assignment of temp (codegenerator only) variable
temp,
//Member accesses
inlinedMember,
refMember
};
public enum VarAssign {
unknown,
assigned,
movedInitAssigned,
movedRetAssigned
//TODO add more types of assignment when needed, e.g. if member is assigned, assigned due to procedure output, etc
};
public enum VarLiteral {
unknown,
assignedLit,
assignedListLit,
assignedListLitwLVEoFC,
assignedListLitwTC,
assignedTypeConstructLit,
assignedTypeConstruct,
assignedInitLit,
assignedInitListLit,
assignedInitListLitwLVEoFC,
assignedInitListLitwTC,
assignedInitTypeConstructLit,
assignedInitTypeConstruct,
initializedLit,
initializedListLit,
initializedListLitwLVEoFC,
initializedListLitwTC,
initializedTypeConstructLit,
initializedTypeConstruct
};
private VarType annotatePortVar(Declaration variable, Action a) {
VarType t = VarType.unknown;
if(!a.getOutputs().isEmpty()) {
//See if declaration is used as output variable expression
for(PortWrite p : a.getOutputs()) {
if(!p.getExpressions().isEmpty()) {
for(Expression e : p.getExpressions()) {
if(e instanceof VariableExpression && UtilIR.getDeclaration(((VariableExpression)e).getVariable()).getId().equals(variable.getId())) {
t = VarType.outPortVar;
break;
}
}
if(t != VarType.unknown) {
break;
}
}
}
}
if(!a.getInputs().isEmpty()) {
//See if the declaration is used as input port variable (this does not actually guarantee any statements using it)
for(PortRead p : a.getInputs()) {
if(!p.getVariables().isEmpty()) {
for(VariableReference v : p.getVariables()) {
if(UtilIR.getDeclaration(v.getDeclaration()).getId().equals(variable.getId())) {
if(t == VarType.outPortVar)
t = VarType.inOutPortVar;
else
t = VarType.inPortVar;
break;
}
}
if(t == VarType.inPortVar || t == VarType.inOutPortVar) {
break;
}
}
}
//Now we need to verify if it is used in any statements
boolean found = false;
if(t==VarType.inPortVar) {
found = isUsedInBody(variable.getId(),a);
if(!found) {
//Not found then used as sync token (or we will discover below if used in guard)
t=VarType.syncVar;
}
}
//Check if is used as a guard
if(!a.getGuards().isEmpty()) {
for(Guard g : a.getGuards()) {
if(!g.getPeeks().isEmpty()) {
for(PortPeek p : g.getPeeks()) {
Declaration d = p.getVariable().getDeclaration();
if(UtilIR.getDeclaration(d).getId().equals(variable.getId())) {
if(t==VarType.inPortVar) {
t = VarType.inPortPeekVar;
} else if(t==VarType.inOutPortVar) {
t = VarType.inOutPortPeekVar;
} else {
t = VarType.peekVar;
}
break;
}
}
if(t == VarType.peekVar || t == VarType.inPortPeekVar || t == VarType.inOutPortPeekVar) {
break;
}
}
}
}
}
return t;
}
private boolean foundInSwitch;
private List<PortRead> LookForReadSwitch;
private VarType findVariableType(Declaration inDecl) {
Declaration decl = UtilIR.getDeclaration(inDecl); //Any of: (import, forward,) external, variable
VarType t = VarType.unknown;
if(decl instanceof Variable) {
Variable variable = (Variable) decl;
if(variable.getInitValue() instanceof LambdaExpression) {
if(inDecl instanceof VariableImport) {
t = VarType.importFunc;
} else {
if(currentActor==null) {
t = VarType.func;
} else {
t = VarType.actorFunc;
}
}
} else if(variable.getInitValue() instanceof ProcExpression) {
if(inDecl instanceof VariableImport) {
t = VarType.importProc;
} else {
t = VarType.proc;
}
} else {
if(inDecl instanceof VariableImport) {
t = VarType.importConstVar;
TransUtil.setNamespaceAnnotation(inDecl, variable.getScope());
} else if(variable.getScope() instanceof Actor) {
if(variable.isConstant() && variable.getInitValue()!=null) {
if(variable.isParameter())
t = VarType.actorConstParamVar;
else {
t = VarType.constVar;
TransUtil.setNamespaceAnnotation(inDecl, variable.getScope());
}
} else {
if(variable.isParameter())
t = VarType.actorParamVar;
else
t = VarType.actorVar;
}
} else if(variable.getScope() instanceof Namespace) {
if(variable.isConstant() && variable.getInitValue()!=null) {
t = VarType.constVar;
TransUtil.setNamespaceAnnotation(inDecl, variable.getScope());
} else {
System.err.println("[IrAnnotate] Did not expect a non-const var in namespace "+ ((Namespace)variable.getScope()).getName() + " and of class " + variable.getClass());
}
} else if(variable.getScope() instanceof Network) {
if(variable.isConstant() && variable.getInitValue()!=null) {
t = VarType.constVar;
TransUtil.setNamespaceAnnotation(inDecl, variable.getScope());
} else {
System.err.println("[IrAnnotate] Did not expect a non-const var in network of class " + variable.getClass());
}
} else if(variable.getScope() instanceof Variable && ((Variable)variable.getScope()).getInitValue() instanceof LambdaExpression) {
if(variable.isParameter()) {
t = VarType.funcInParamVar;
} else {
t = VarType.funcVar;
}
} else if(variable.getScope() instanceof LambdaExpression) {
if(variable.isParameter()) {
t = VarType.funcInParamVar;
} else {
t = VarType.funcVar;
}
} else if(variable.getScope() instanceof Variable && ((Variable)variable.getScope()).getInitValue() instanceof ProcExpression) {
//FIXME should check for in/out
t = VarType.procInParamVar;
} else if(variable.getScope() instanceof ProcExpression) {
//FIXME should check for in/out
t = VarType.procInParamVar;
} else if(variable.getScope() instanceof Block && variable.getScope().getOuter() instanceof ProcExpression) {
t = VarType.procVar;
} else if(variable.getScope() instanceof Action) {
Action a = (Action) variable.getScope();
t = annotatePortVar(variable, a);
if(t == VarType.unknown) {
//Check if the initValue contains ref to any in-port variable
if(variable.getInitValue()==null) {
t = VarType.actionVar;
} else {
foundInSwitch=false;
LookForReadSwitch = a.getInputs();
new IrReplaceSwitch() {
@Override
public Expression caseVariableExpression(VariableExpression var) {
for(PortRead r : LookForReadSwitch) {
for(VariableReference vr : r.getVariables()) {
if(vr.getDeclaration().getId().equals(var.getVariable().getId())) {
foundInSwitch=true;
}
}
}
return super.caseVariableExpression(var);
}
}.doSwitch(variable.getInitValue());
if(foundInSwitch) {
t = VarType.actionInitInDepVar;
} else {
t = VarType.actionVar;
}
}
}
} else if(variable.getScope() instanceof PortWrite) {
t = annotatePortVar(variable, currentAction);
if(t == VarType.unknown) {
t = VarType.actionVar;
}
} else if(variable.getScope() instanceof Generator) {
t = VarType.generatorVar;
} else if(variable.getScope() instanceof Block) {
if(variable.isConstant() && variable.getInitValue()!=null) {
t = VarType.blockConstVar;
} else {
t = VarType.blockVar;
}
} else {
serr.println("[IrAnnotate] Did not expect a normal var in scope "+variable.getScope().getClass()+ " and of name " + variable.getName());
}
}
} else if(decl instanceof VariableExternal){
VariableExternal variable = (VariableExternal) decl;
Type type = variable.getType();
if(type instanceof TypeLambda) {
t = VarType.externFunc;
} else if(type instanceof TypeProc) {
t = VarType.externProc;
//TODO any more types that should be classified as built in, how about lists?
} else if(type instanceof TypeBool || type instanceof TypeInt || type instanceof TypeUint || type instanceof TypeFloat) {
t = VarType.externBuiltInTypeVar;
} else if(type instanceof TypeList) {
Type list = type;
while(list instanceof TypeList) {
list = ((TypeList)list).getType();
}
if(list instanceof TypeBool || list instanceof TypeInt || list instanceof TypeUint || list instanceof TypeFloat) {
t = VarType.externBuiltInListTypeVar;
} else if(list instanceof TypeUser) {
t = VarType.externOtherListTypeVar;
} else {
serr.println("[IrAnnotate] Did not expect an external list variable of type "+list.getClass());
}
} else if(type instanceof TypeUser) {
t = VarType.externOtherTypeVar;
} else {
serr.println("[IrAnnotate] Did not expect an external variable of type "+type.getClass());
}
} else {
if(decl == null && inDecl!=null && inDecl.getName().startsWith("dprint")) {
t = VarType.externProc; //FIXME special case until we have dropped legacy CPrinter and can change getDeclaration()
} else {
serr.println("[IrAnnotate] Did not expect a variable of class "+ (inDecl==null?"none":inDecl.getClass()));
}
}
return t;
}
private VarAccess findPortAccess(Type type, boolean isRepeat, int size) {
VarAccess va = VarAccess.unknown;
if(UtilIR.isList(type)) {
if(UtilIR.isRecord(((TypeList)UtilIR.getType(type)).getType())) {
va = VarAccess.listUserTypeSingle;
} else {
va = VarAccess.listSingle;
}
} else {
if(UtilIR.isRecord(type)) {
if(isRepeat) {
va = VarAccess.listUserTypeSingle;
} else {
va = VarAccess.scalarUserTypeSingle;
}
} else {
if(isRepeat) {
va = VarAccess.listSingle;
} else {
va = VarAccess.scalarSingle;
}
}
}
if(size>1) {
switch(va) {
case listUserTypeSingle:
va = VarAccess.listUserTypeInterleaved;
break;
case listSingle:
va = VarAccess.listInterleaved;
break;
case scalarUserTypeSingle:
va = VarAccess.scalarUserTypeInterleaved;
break;
case scalarSingle:
va = VarAccess.scalarInterleaved;
break;
}
}
return va;
}
private VarLocalAccess findLocalAccess(Declaration decl, List<Expression> index, List<Member> member) {
VarLocalAccess vla = VarLocalAccess.unknown;
int dim = (index != null)?index.size():0;
if(decl instanceof Variable) {
Type type = UtilIR.getType(((Variable)decl).getType());
if(member !=null && member.size()>0){
Declaration mv = null;
List<Expression> mi = null;
for(Member mm:member) {
if(UtilIR.isList(type)) {
while(type instanceof TypeList) {
dim--;
type = ((TypeList)type).getType();
}
type = UtilIR.getType(type);
}
if(type instanceof TypeRecord) {
for(Variable m:((TypeRecord)type).getMembers()) {
if(m.getName().equals(mm.getName())) {
mv = m;
mi = mm.getIndex();
type = m.getType();
break;
}
}
}
}
if(mv != null) {
boolean varIsList = (index != null)?index.size()>0:false;
vla = findLocalAccess(mv,mi,null);
switch (vla) {
case unknown:
case inlinedMember:
case refMember:
case self:
+ break;
case scalarUserType:
+ if(varIsList) {
+ vla = VarLocalAccess.listMemberScalarUserType;
+ } else {
+ vla = VarLocalAccess.memberScalarUserType;
+ }
+ break;
case scalar:
+ if(varIsList) {
+ vla = VarLocalAccess.listMemberScalar;
+ } else {
+ vla = VarLocalAccess.memberScalar;
+ }
break;
case list:
if(varIsList) {
vla = VarLocalAccess.listMemberList;
} else {
vla = VarLocalAccess.memberList;
}
break;
case listMulti:
if(varIsList) {
vla = VarLocalAccess.listMemberListMulti;
} else {
vla = VarLocalAccess.memberListMulti;
}
break;
case listMultiList:
if(varIsList) {
vla = VarLocalAccess.listMemberListMultiList;
} else {
vla = VarLocalAccess.memberListMultiList;
}
break;
case listMultiSingle:
if(varIsList) {
vla = VarLocalAccess.listMemberListMultiSingle;
} else {
vla = VarLocalAccess.memberListMultiSingle;
}
break;
case listMultiUserType:
if(varIsList) {
vla = VarLocalAccess.listMemberListMultiUserType;
} else {
vla = VarLocalAccess.memberListMultiUserType;
}
break;
case listMultiUserTypeList:
if(varIsList) {
vla = VarLocalAccess.listMemberListMultiUserTypeList;
} else {
vla = VarLocalAccess.memberListMultiUserTypeList;
}
break;
case listMultiUserTypeSingle:
if(varIsList) {
vla = VarLocalAccess.listMemberListMultiUserTypeSingle;
} else {
vla = VarLocalAccess.memberListMultiUserTypeSingle;
}
break;
case listSingle:
if(varIsList) {
vla = VarLocalAccess.listMemberListSingle;
} else {
vla = VarLocalAccess.memberListSingle;
}
break;
case listUserType:
if(varIsList) {
vla = VarLocalAccess.listMemberListUserType;
} else {
vla = VarLocalAccess.memberListUserType;
}
break;
case listUserTypeSingle:
if(varIsList) {
vla = VarLocalAccess.listMemberListUserTypeSingle;
} else {
vla = VarLocalAccess.memberListUserTypeSingle;
}
break;
default:
}
return vla;
}
} else {
if(UtilIR.isList(type)) {
int tDim = 0;
while(type instanceof TypeList) {
tDim++;
type = ((TypeList)type).getType();
}
if(UtilIR.isRecord(type)) {
if(tDim>1) {
if(dim<(tDim-1)) {
vla = VarLocalAccess.listMultiUserType;
} else if(dim<tDim) {
vla = VarLocalAccess.listMultiUserTypeList;
} else {
vla = VarLocalAccess.listMultiUserTypeSingle;
}
} else {
if(dim<tDim) {
vla = VarLocalAccess.listUserType;
} else {
vla = VarLocalAccess.listUserTypeSingle;
}
}
} else {
if(tDim>1) {
if(dim<(tDim-1)) {
vla = VarLocalAccess.listMulti;
} else if(dim<tDim) {
vla = VarLocalAccess.listMultiList;
} else {
vla = VarLocalAccess.listMultiSingle;
}
} else {
if(dim<tDim) {
vla = VarLocalAccess.list;
} else {
vla = VarLocalAccess.listSingle;
}
}
}
} else {
if(UtilIR.isRecord(type)) {
vla = VarLocalAccess.scalarUserType;
} else {
vla = VarLocalAccess.scalar;
}
}
}
}
return vla;
}
@Override
public Expression caseVariableExpression(VariableExpression var) {
VarType t = findVariableType(var.getVariable());
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,"VarType",t.name());
TransUtil.copyNamespaceAnnotation(var, var.getVariable());
VarAccess va = VarAccess.unknown;
//Put the access annotation in the map, will be replicated in caseAction to all variables, var ref and exp refering to the same id
if(currentWrite!=null) {
switch(t) {
case inOutPortVar:
case inOutPortPeekVar:
case outPortVar:
va = findPortAccess(var.getType(),currentWrite.getRepeat()!=null,currentWrite.getExpressions().size());
idOutVarAccessMap.put(var.getVariable().getId(), va.name());
}
}
Declaration decl = UtilIR.getDeclaration(var.getVariable());
VarLocalAccess vla = findLocalAccess(decl,var.getIndex(),var.getMember());
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,"VarLocalAccess",vla.name());
return super.caseVariableExpression(var);
}
@Override
public VariableReference caseVariableReference(VariableReference var) {
VarType t = findVariableType(var.getDeclaration());
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,"VarType",t.name());
TransUtil.copyNamespaceAnnotation(var, var.getDeclaration());
VarAccess va = VarAccess.unknown;
//Put the access annotation in the map, will be replicated in caseAction to all variables, var ref and exp refering to the same id
if(currentRead!=null) {
va = findPortAccess(var.getType(),currentRead.getRepeat()!=null,currentRead.getVariables().size());
idInVarAccessMap.put(var.getDeclaration().getId(), va.name());
}
Declaration decl = UtilIR.getDeclaration(var.getDeclaration());
VarLocalAccess vla = findLocalAccess(decl,var.getIndex(),var.getMember());
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,"VarLocalAccess",vla.name());
return super.caseVariableReference(var);
}
@Override
public Statement caseProcCall(ProcCall call) {
Declaration p = call.getProcedure() instanceof ForwardDeclaration?((ForwardDeclaration)call.getProcedure()).getDeclaration():call.getProcedure();
VarType t = findVariableType(p);
TransUtil.setAnnotation(p,IrTransformer.VARIABLE_ANNOTATION,"VarType",t.name());
TransUtil.copyNamespaceAnnotation(call, p);
return super.caseProcCall(call);
}
@Override
public Declaration caseVariable(Variable var) {
VarType t = findVariableType(var);
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,"VarType",t.name());
VarLiteral l = null;
if(var.getInitValue() != null) {
HowLiteral h = TransUtil.isLiteralExpression(var.getInitValue());
if(h.total) {
if(h.list) {
if(h.typeConstruct) {
l = VarLiteral.initializedListLitwTC;
} else {
if(h.containsListType) {
l = VarLiteral.initializedListLitwLVEoFC;
} else {
l = VarLiteral.initializedListLit;
}
}
} else if(h.typeConstruct) {
l = VarLiteral.initializedTypeConstructLit;
} else if(h.builtin) {
l = VarLiteral.initializedLit;
}
} else {
if(h.typeConstruct) {
l = VarLiteral.initializedTypeConstruct;
}
}
if(l != null) {
TransUtil.setAnnotation(var.getInitValue(),IrTransformer.VARIABLE_ANNOTATION,
"VarLiteral",l.name());
VarLiteral current = VarLiteral.valueOf(TransUtil.getAnnotationArg(var, IrTransformer.VARIABLE_ANNOTATION, "VarLiteral"));
switch(current) {
case assignedLit:
l = VarLiteral.assignedInitLit;
break;
case assignedListLit:
l = VarLiteral.assignedInitListLit;
break;
case assignedListLitwTC:
l = VarLiteral.assignedInitListLitwTC;
break;
case assignedListLitwLVEoFC:
l = VarLiteral.assignedInitListLitwLVEoFC;
break;
case assignedTypeConstructLit:
l = VarLiteral.assignedInitTypeConstructLit;
break;
case assignedTypeConstruct:
l = VarLiteral.assignedInitTypeConstruct;
break;
case unknown:
break;
default:
//>>>>> NB! leaving current function <<<<<<
return super.caseVariable(var);
}
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,
"VarLiteral",l.name());
}
}
return super.caseVariable(var);
}
@Override
public EObject caseVariableImport(VariableImport var) {
VarType t = findVariableType(var);
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,"VarType",t.name());
return super.caseVariableImport(var);
}
@Override
public Declaration caseVariableExternal(VariableExternal var) {
VarType t = findVariableType(var);
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,"VarType",t.name());
return super.caseVariableExternal(var);
}
@Override
public TypeDeclaration caseTypeDeclaration(TypeDeclaration decl) {
TransUtil.setAnnotation(decl,IrTransformer.VARIABLE_ANNOTATION,"VarType",VarType.declarationType.name());
super.caseTypeDeclaration(decl);
return decl;
}
@Override
public Type caseTypeRecord(TypeRecord decl) {
for(Declaration m : decl.getMembers()) {
TransUtil.setAnnotation(m,IrTransformer.VARIABLE_ANNOTATION,"VarType",VarType.memberDeclType.name());
}
return decl;
}
@Override
public AbstractActor caseActor(Actor obj) {
currentActor = obj;
AbstractActor ret = super.caseActor(obj);
currentActor = null;
return ret;
}
@Override
public Action caseAction(Action obj) {
currentAction = obj;
Action ret = super.caseAction(obj);
//Need to run over second time to copy VarAccess from definitions to variable, variable ref and expr
new IrReplaceSwitch(){
@Override
public VariableReference caseVariableReference(VariableReference var) {
if(idInVarAccessMap.containsKey(var.getDeclaration().getId()))
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,
"VarAccessIn",idInVarAccessMap.get(var.getDeclaration().getId()));
if(idOutVarAccessMap.containsKey(var.getDeclaration().getId()))
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,
"VarAccessOut",idOutVarAccessMap.get(var.getDeclaration().getId()));
return var;
}
@Override
public VariableExpression caseVariableExpression(VariableExpression var) {
if(idInVarAccessMap.containsKey(var.getVariable().getId()))
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,
"VarAccessIn",idInVarAccessMap.get(var.getVariable().getId()));
if(idOutVarAccessMap.containsKey(var.getVariable().getId()))
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,
"VarAccessOut",idOutVarAccessMap.get(var.getVariable().getId()));
return var;
}
@Override
public Variable caseVariable(Variable var) {
if(idInVarAccessMap.containsKey(var.getId()))
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,
"VarAccessIn",idInVarAccessMap.get(var.getId()));
if(idOutVarAccessMap.containsKey(var.getId()))
TransUtil.setAnnotation(var,IrTransformer.VARIABLE_ANNOTATION,
"VarAccessOut",idOutVarAccessMap.get(var.getId()));
return var;
}
}.doSwitch(obj);
currentAction = null;
return ret;
}
@Override
public PortRead casePortRead(PortRead obj) {
currentRead = obj;
PortRead ret = super.casePortRead(obj);
currentRead = null;
return ret;
}
@Override
public PortWrite casePortWrite(PortWrite obj) {
currentWrite = obj;
PortWrite ret = super.casePortWrite(obj);
currentWrite = null;
return ret;
}
@Override
public Statement caseAssign(Assign assign) {
boolean retValue = TransUtil.getAnnotationArg(assign.getTarget().getDeclaration(), IrTransformer.VARIABLE_ANNOTATION, "VarAssign").equals(IrVariableAnnotation.VarAssign.movedRetAssigned.name());
if(!retValue) {
TransUtil.setAnnotation(assign.getTarget().getDeclaration(),IrTransformer.VARIABLE_ANNOTATION,
"VarAssign",VarAssign.assigned.name());
}
TransUtil.setAnnotation(assign.getTarget(),IrTransformer.VARIABLE_ANNOTATION,
"VarAssign",VarAssign.assigned.name());
foundInSwitch=false;
final String target = assign.getTarget().getDeclaration().getId();
if(target != null) {
new IrReplaceSwitch() {
@Override
public Declaration caseVariable(Variable var) {
if(target.equals(var.getId())) {
foundInSwitch = true;
}
return super.caseVariable(var);
}
@Override
public Declaration caseForwardDeclaration(ForwardDeclaration decl) {
doSwitch(decl.getDeclaration());
return decl;
}
}.doSwitch(assign.getExpression());
if(foundInSwitch) {
TransUtil.setAnnotation(assign,IrTransformer.VARIABLE_ANNOTATION,
"VarLocalAccess",VarLocalAccess.self.name());
}
}
VarLiteral l = null;
HowLiteral h = TransUtil.isLiteralExpression(assign.getExpression());
if(h.total) {
if(h.list) {
if(h.typeConstruct) {
l = VarLiteral.initializedListLitwTC;
} else {
if(h.containsListType) {
l = VarLiteral.initializedListLitwLVEoFC;
} else {
l = VarLiteral.initializedListLit;
}
}
} else if(h.literalTypeConstruct) {
l = VarLiteral.assignedTypeConstructLit;
} else if(h.builtin) {
l = VarLiteral.assignedLit;
}
} else {
if(h.typeConstruct) {
l = VarLiteral.assignedTypeConstruct;
}
}
if(l != null) {
TransUtil.setAnnotation(assign.getTarget(),IrTransformer.VARIABLE_ANNOTATION,
"VarLiteral",l.name());
TransUtil.setAnnotation(assign.getExpression(),IrTransformer.VARIABLE_ANNOTATION,
"VarLiteral",l.name());
VarLiteral current = VarLiteral.valueOf(TransUtil.getAnnotationArg(assign.getTarget().getDeclaration(), IrTransformer.VARIABLE_ANNOTATION, "VarLiteral"));
switch(current) {
case initializedLit:
l = VarLiteral.assignedInitLit;
break;
case initializedListLit:
l = VarLiteral.assignedInitListLit;
break;
case initializedListLitwTC:
l = VarLiteral.assignedInitListLitwTC;
break;
case initializedListLitwLVEoFC:
l = VarLiteral.assignedInitListLitwLVEoFC;
break;
case initializedTypeConstructLit:
l = VarLiteral.assignedInitTypeConstructLit;
break;
case initializedTypeConstruct:
l = VarLiteral.assignedInitTypeConstruct;
break;
case unknown:
break;
default:
//>>>>> NB! leaving current function <<<<<<
return super.caseAssign(assign);
}
TransUtil.setAnnotation(assign.getTarget().getDeclaration(),IrTransformer.VARIABLE_ANNOTATION,
"VarLiteral",l.name());
}
return super.caseAssign(assign);
}
@Override
public AbstractActor caseNetwork(Network obj) {
currentNetwork = obj;
for(ActorInstance a : obj.getActors()) {
AbstractActor actor=null;
try {
System.out.println("[IrAnnotateVariable] Read in actor instance '" + a.getName() + "' of class " + ((TypeActor) a.getType()).getName());
actor = (AbstractActor) ActorDirectory.findTransformedActor(a);
} catch (DirectoryException x) {
//serr.println("[IrAnnotateVariable] Internal error could not get actor of type " + a.getType().toString());
}
if(actor!=null && !(actor instanceof ExternalActor)) {
actor = (AbstractActor) doSwitch(actor);
String path = TransUtil.getPath(actor);
TransUtil.AnnotatePass(actor, IrPassTypes.Variable, "0");
ActorDirectory.addTransformedActor(actor, a, path);
}
}
AbstractActor ret = super.caseNetwork(obj);
String path = TransUtil.getPath(ret);
TransUtil.AnnotatePass(ret, IrPassTypes.Variable, "0");
ActorDirectory.addTransformedActor(ret, null, path);
currentNetwork = null;
return ret;
}
@Override
public Namespace caseNamespace(Namespace obj) {
currentNamespace = obj;
Namespace ret = super.caseNamespace(obj);
currentNamespace = null;
return ret;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/org/bruno/frontend/ProjectExplorer.java b/src/org/bruno/frontend/ProjectExplorer.java
index eb65065..fdd655f 100644
--- a/src/org/bruno/frontend/ProjectExplorer.java
+++ b/src/org/bruno/frontend/ProjectExplorer.java
@@ -1,237 +1,242 @@
package org.bruno.frontend;
import java.awt.CardLayout;
import java.awt.Font;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.TreePath;
import org.bruno.foobar.FileFooable;
import org.bruno.frontend.FileSystemTreeModel.TreeFileObject;
public class ProjectExplorer extends JPanel implements DropTargetListener {
/**
*
*/
private static final long serialVersionUID = -6000650682129841885L;
private static final File configLoadingFile = new File(Bruno.SUPPORT_DIR
+ "/plugins/config/load folder.js");
private final Bruno parentApp;
private final CardLayout layout;
// private final DropTarget dropTarget;
private final JTree fileTree;
private File currentFolder;
public ProjectExplorer(final Bruno parentApp) {
this.parentApp = parentApp;
layout = new CardLayout();
setLayout(layout);
// Empty label
JLabel emptyLabel = new JLabel(
"<html><div style=\"text-align: center; color: #888888;\">Drag and drop folders<br /> here to get started</div></html>");
emptyLabel.setFont(new Font("Arial", Font.BOLD, 14));
emptyLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(emptyLabel, "empty");
// File tree
fileTree = new JTree();
fileTree.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int selectedRow = fileTree.getRowForLocation(e.getX(), e.getY());
TreePath selectedPath = fileTree.getPathForLocation(e.getX(),
e.getY());
if (selectedRow != -1 && e.getClickCount() == 2) {
File file = ((TreeFileObject) selectedPath
.getLastPathComponent()).getFile();
if (file.isFile()) {
parentApp.openFile(file);
}
}
}
});
fileTree.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
TreePath selectedPath = fileTree.getSelectionPath();
if (e.getKeyCode() == KeyEvent.VK_ENTER && selectedPath != null) {
TreeFileObject selected = (TreeFileObject) selectedPath
.getLastPathComponent();
File file = selected.getFile();
if (file.isFile()) {
parentApp.openFile(file);
}
}
}
});
add(fileTree, "tree");
// Set up drag n drop
new DropTarget(this, this);
}
public void showFolder(File folder) {
if (currentFolder != null) {
removeFooables(currentFolder);
}
if (folder == null) {
layout.show(this, "empty");
} else {
fileTree.setModel(new FileSystemTreeModel(folder));
layout.show(this, "tree");
addFooables(folder);
}
currentFolder = folder;
printLoadFolder(folder);
}
public void printLoadFolder(File folder) {
PrintWriter pw = null;
try {
if (!configLoadingFile.exists()) {
configLoadingFile.getParentFile().mkdirs();
configLoadingFile.createNewFile();
}
pw = new PrintWriter(new BufferedWriter(new FileWriter(
configLoadingFile)));
} catch (IOException ex) {
ex.printStackTrace();
}
if (folder == null) {
pw.println("");
pw.flush();
pw.close();
} else {
pw.println("importPackage(Packages.java.io);");
- pw.println("bruno.getProjectExplorer().showFolder(new java.io.File("
- + "\"" + folder.getAbsolutePath() + "\"" + "));");
+ pw.println("var file = new java.io.File("+ "\"" + folder.getAbsolutePath() + "\"" + ");");
+ pw.println("if (file.exists()){");
+ pw.println("bruno.getProjectExplorer().showFolder(file);");
+ pw.println("}");
+ pw.println("else{");
+ pw.println("bruno.getProjectExplorer().showFolder(null);");
+ pw.println("}");
pw.flush();
pw.close();
}
}
private Set<FileFooable> getAllFileFooables(File f) {
Set<FileFooable> r = new HashSet<>();
FileFilter bff = new BrunoFileFilter();
if (bff.accept(f)) {
if (f.isFile()) {
r.add(new FileFooable(parentApp, this, f));
} else {
for (File file : f.listFiles()) {
r.addAll(getAllFileFooables(file));
}
}
}
return r;
}
private void addFooables(File f) {
if (parentApp != null) {
for (FileFooable foo : getAllFileFooables(f)) {
parentApp.getFoobar().addFooable(foo);
}
}
}
private void removeFooables(File f) {
if (parentApp != null) {
for (FileFooable foo : getAllFileFooables(f)) {
parentApp.getFoobar().removeFooable(foo);
}
}
}
@Override
public void dragEnter(DropTargetDragEvent dtde) {
}
@Override
public void dragOver(DropTargetDragEvent dtde) {
}
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
@Override
public void dragExit(DropTargetEvent dte) {
}
@SuppressWarnings("unchecked")
@Override
public void drop(DropTargetDropEvent dtde) {
int dropAction = dtde.getDropAction();
dtde.acceptDrop(dropAction);
try {
Transferable data = dtde.getTransferable();
if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> files = (List<File>) data
.getTransferData(DataFlavor.javaFileListFlavor);
showFolder(files.get(0));
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
dtde.dropComplete(true);
repaint();
}
}
public File getCurrentFolder() {
return currentFolder;
}
}
| true | false | null | null |
diff --git a/javafx.platform/src/org/netbeans/modules/javafx/platform/wizard/DetectPanel.java b/javafx.platform/src/org/netbeans/modules/javafx/platform/wizard/DetectPanel.java
index 3f4a0f4e..d0df8912 100644
--- a/javafx.platform/src/org/netbeans/modules/javafx/platform/wizard/DetectPanel.java
+++ b/javafx.platform/src/org/netbeans/modules/javafx/platform/wizard/DetectPanel.java
@@ -1,415 +1,416 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.javafx.platform.wizard;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.filechooser.FileView;
import org.netbeans.api.java.platform.JavaPlatform;
import org.netbeans.api.java.platform.JavaPlatformManager;
import org.netbeans.modules.javafx.platform.PlatformUiSupport;
import org.openide.modules.InstalledFileLocator;
import org.openide.util.NbBundle;
import org.openide.util.HelpCtx;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileUtil;
import org.openide.util.ChangeSupport;
import org.openide.util.Utilities;
/**
* This Panel launches autoconfiguration during the New JavaFX Platform sequence.
* The UI views properties of the platform, reacts to the end of detection by
* updating itself. It triggers the detection task when the button is pressed.
* The inner class WizardPanel acts as a controller, reacts to the UI completness
* (jdk name filled in) and autoconfig result (passed successfully) - and manages
* Next/Finish button (valid state) according to those.
*
* @author Svata Dedic
*/
public class DetectPanel extends javax.swing.JPanel {
private static final Icon BADGE = new ImageIcon(Utilities.loadImage("org/netbeans/modules/javafx/platform/resources/platformBadge.gif")); // NOI18N
private static final Icon EMPTY = new ImageIcon(Utilities.loadImage("org/netbeans/modules/javafx/platform/resources/empty.gif")); // NOI18N
private final ChangeSupport cs = new ChangeSupport(this);
/**
* Creates a detect panel
* start the task and update on its completion
* @param primaryPlatform the platform being customized.
*/
public DetectPanel() {
initComponents();
postInitComponents ();
putClientProperty("WizardPanel_contentData",
new String[] {
NbBundle.getMessage(DetectPanel.class,"TITLE_PlatformName"),
});
this.setName (NbBundle.getMessage(DetectPanel.class,"TITLE_PlatformName"));
}
public void addNotify() {
super.addNotify();
}
private void postInitComponents () {
DocumentListener lsn = new DocumentListener () {
public void insertUpdate(DocumentEvent e) {
cs.fireChange();
}
public void removeUpdate(DocumentEvent e) {
cs.fireChange();
}
public void changedUpdate(DocumentEvent e) {
cs.fireChange();
}
};
jdkName.getDocument().addDocumentListener(lsn);
fxFolder.getDocument().addDocumentListener(lsn);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel3 = new javax.swing.JLabel();
jdkName = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
fxFolder = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jLabel3.setLabelFor(jdkName);
org.openide.awt.Mnemonics.setLocalizedText(jLabel3, NbBundle.getBundle(DetectPanel.class).getString("LBL_DetailsPanel_Name")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel3, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jdkName, gridBagConstraints);
jdkName.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_PlatformName")); // NOI18N
+ jLabel5.setLabelFor(fxFolder);
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(DetectPanel.class, "TXT_FX")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel5, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(fxFolder, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(jButton4, org.openide.util.NbBundle.getMessage(DetectPanel.class, "LBL_BrowseFX")); // NOI18N
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jButton4, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_DetectPanel")); // NOI18N
}// </editor-fold>//GEN-END:initComponents
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
JFileChooser chooser = new JFileChooser ();
final FileSystemView fsv = chooser.getFileSystemView();
chooser.setFileView(new FileView() {
private Icon lastOriginal;
private Icon lastMerged;
public Icon getIcon(File _f) {
File f = FileUtil.normalizeFile(_f);
Icon original = fsv.getSystemIcon(f);
if (original == null) {
// L&F (e.g. GTK) did not specify any icon.
original = EMPTY;
}
if ((new File(f, "bin/javafxpackager.exe").isFile() || new File(f, "bin/javafxpackager").isFile()) && new File(f, "lib/shared/javafxc.jar").isFile() && new File(f, "lib/shared/javafxrt.jar").isFile()) {
if ( original.equals( lastOriginal ) ) {
return lastMerged;
}
lastOriginal = original;
lastMerged = new MergedIcon(original, BADGE, -1, -1);
return lastMerged;
} else {
return original;
}
}
});
FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File f = new File (fxFolder.getText());
chooser.setSelectedFile(f);
chooser.setDialogTitle (NbBundle.getMessage(DetectPanel.class, "TITLE_SelectFX"));
if (chooser.showOpenDialog (this) == JFileChooser.APPROVE_OPTION) {
fxFolder.setText(chooser.getSelectedFile().getAbsolutePath());
}
}//GEN-LAST:event_jButton4ActionPerformed
public final synchronized void addChangeListener (ChangeListener listener) {
cs.addChangeListener(listener);
}
public final synchronized void removeChangeListener (ChangeListener listener) {
cs.removeChangeListener(listener);
}
public String getPlatformName() {
return jdkName.getText();
}
public File getPlatformFolder() {
return FileUtil.toFile(JavaPlatformManager.getDefault().getDefaultPlatform().getInstallFolders().iterator().next());
}
public File getFxFolder() {
return FileUtil.normalizeFile(new File(fxFolder.getText()));
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JTextField fxFolder;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jdkName;
// End of variables declaration//GEN-END:variables
/**
* Controller for the outer class: manages wizard panel's valid state
* according to the user's input and detection state.
*/
static class WizardPanel implements WizardDescriptor.Panel<WizardDescriptor>,ChangeListener {
private DetectPanel component;
private final JavaFXWizardIterator iterator;
private final ChangeSupport cs = new ChangeSupport(this);
private boolean valid;
private WizardDescriptor wiz;
WizardPanel(JavaFXWizardIterator iterator) {
this.iterator = iterator;
}
public void addChangeListener(ChangeListener l) {
cs.addChangeListener(l);
}
public java.awt.Component getComponent() {
if (component == null) {
component = new DetectPanel();
component.addChangeListener (this);
}
return component;
}
void setValid(boolean v) {
if (v == valid) return;
valid = v;
cs.fireChange();
}
public HelpCtx getHelp() {
return new HelpCtx (DetectPanel.class);
}
public boolean isValid() {
return valid;
}
public void readSettings(WizardDescriptor settings) {
this.wiz = settings;
String name;
int i = 1;
while (!checkName(name = NbBundle.getMessage(DetectPanel.class, "TXT_DefaultPlaformName", String.valueOf(i)))) i++;
component.jdkName.setText(name);
File fxPath = InstalledFileLocator.getDefault().locate("javafx-sdk1.0/lib/shared/javafxc.jar", "org.netbeans.modules.javafx", false);
if (fxPath == null) //try to find runtime in the root javafx folder as for public compiler
fxPath = InstalledFileLocator.getDefault().locate("lib/shared/javafxc.jar", "org.netbeans.modules.javafx", false);
if (fxPath != null && fxPath.isFile()) component.fxFolder.setText(fxPath.getParentFile().getParentFile().getParent());
File f = component.getPlatformFolder();
checkValid();
}
public void removeChangeListener(ChangeListener l) {
cs.removeChangeListener(l);
}
/**
Updates the Platform's display name with the one the user
has entered. Stores user-customized display name into the Platform.
*/
public void storeSettings(WizardDescriptor settings) {
if (isValid()) {
iterator.platformName = component.getPlatformName();
iterator.installFolder = component.getPlatformFolder();
iterator.fxFolder = component.getFxFolder();
}
}
public void stateChanged(ChangeEvent e) {
this.checkValid();
}
private void setErrorMessage(String key) {
this.wiz.putProperty("WizardPanel_errorMessage", NbBundle.getMessage(DetectPanel.class, key)); //NOI18N
setValid(false);
}
private boolean checkName(String name) {
JavaPlatform[] platforms = JavaPlatformManager.getDefault().getInstalledPlatforms();
for (int i=0; i<platforms.length; i++) {
if (name.equals (platforms[i].getDisplayName())) {
setErrorMessage("ERROR_UsedDisplayName"); //NOI18N
return false;
}
}
return true;
}
private void checkValid () {
String name = this.component.getPlatformName ();
if (name.length() == 0) {
setErrorMessage("ERROR_InvalidDisplayName"); //NOI18N
return;
}
if (!checkName(name)) {
setErrorMessage("ERROR_UsedDisplayName"); //NOI18N
return;
}
// File f = component.getPlatformFolder();
// if (!new File(f, "bin/java").isFile() && !new File(f, "bin/java.exe").isFile()) {
// setErrorMessage("ERROR_WrongJavaPlatformLocation"); //NOI18N
// return;
// }
File f = component.getFxFolder();
if (!(new File(f, "bin/javafxpackager.exe").isFile() || new File(f, "bin/javafxpackager").isFile()) || !new File(f, "lib/shared/javafxc.jar").isFile() || !new File(f, "lib/shared/javafxrt.jar").isFile()) {
setErrorMessage("ERROR_WrongFxLocation"); //NOI18N
return;
}
this.wiz.putProperty("WizardPanel_errorMessage", ""); //NOI18N
setValid(true);
}
}
private static class MergedIcon implements Icon {
private Icon icon1;
private Icon icon2;
private int xMerge;
private int yMerge;
MergedIcon( Icon icon1, Icon icon2, int xMerge, int yMerge ) {
this.icon1 = icon1;
this.icon2 = icon2;
if ( xMerge == -1 ) {
xMerge = icon1.getIconWidth() - icon2.getIconWidth();
}
if ( yMerge == -1 ) {
yMerge = icon1.getIconHeight() - icon2.getIconHeight();
}
this.xMerge = xMerge;
this.yMerge = yMerge;
}
public int getIconHeight() {
return Math.max( icon1.getIconHeight(), yMerge + icon2.getIconHeight() );
}
public int getIconWidth() {
return Math.max( icon1.getIconWidth(), yMerge + icon2.getIconWidth() );
}
public void paintIcon(java.awt.Component c, java.awt.Graphics g, int x, int y) {
icon1.paintIcon( c, g, x, y );
icon2.paintIcon( c, g, x + xMerge, y + yMerge );
}
}
}
| true | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel3 = new javax.swing.JLabel();
jdkName = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
fxFolder = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jLabel3.setLabelFor(jdkName);
org.openide.awt.Mnemonics.setLocalizedText(jLabel3, NbBundle.getBundle(DetectPanel.class).getString("LBL_DetailsPanel_Name")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel3, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jdkName, gridBagConstraints);
jdkName.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_PlatformName")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(DetectPanel.class, "TXT_FX")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel5, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(fxFolder, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(jButton4, org.openide.util.NbBundle.getMessage(DetectPanel.class, "LBL_BrowseFX")); // NOI18N
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jButton4, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_DetectPanel")); // NOI18N
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel3 = new javax.swing.JLabel();
jdkName = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
fxFolder = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jLabel3.setLabelFor(jdkName);
org.openide.awt.Mnemonics.setLocalizedText(jLabel3, NbBundle.getBundle(DetectPanel.class).getString("LBL_DetailsPanel_Name")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel3, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jdkName, gridBagConstraints);
jdkName.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_PlatformName")); // NOI18N
jLabel5.setLabelFor(fxFolder);
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(DetectPanel.class, "TXT_FX")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
add(jLabel5, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(fxFolder, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(jButton4, org.openide.util.NbBundle.getMessage(DetectPanel.class, "LBL_BrowseFX")); // NOI18N
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(11, 5, 0, 0);
add(jButton4, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(DetectPanel.class).getString("AD_DetectPanel")); // NOI18N
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/eclipse/plugins/net.sf.orcc.xdf.ui/src/net/sf/orcc/xdf/ui/patterns/ConnectionPattern.java b/eclipse/plugins/net.sf.orcc.xdf.ui/src/net/sf/orcc/xdf/ui/patterns/ConnectionPattern.java
index 7d2f77cdf..740402afa 100644
--- a/eclipse/plugins/net.sf.orcc.xdf.ui/src/net/sf/orcc/xdf/ui/patterns/ConnectionPattern.java
+++ b/eclipse/plugins/net.sf.orcc.xdf.ui/src/net/sf/orcc/xdf/ui/patterns/ConnectionPattern.java
@@ -1,297 +1,298 @@
/*
* Copyright (c) 2013, IETR/INSA of Rennes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the IETR/INSA of Rennes nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.orcc.xdf.ui.patterns;
import net.sf.orcc.df.DfFactory;
import net.sf.orcc.df.Instance;
import net.sf.orcc.df.Network;
import net.sf.orcc.df.Port;
import net.sf.orcc.graph.Vertex;
import net.sf.orcc.xdf.ui.styles.StyleUtil;
import org.eclipse.graphiti.features.context.IAddConnectionContext;
import org.eclipse.graphiti.features.context.IAddContext;
import org.eclipse.graphiti.features.context.ICreateConnectionContext;
import org.eclipse.graphiti.features.context.impl.AddConnectionContext;
import org.eclipse.graphiti.mm.GraphicsAlgorithmContainer;
import org.eclipse.graphiti.mm.algorithms.Polyline;
import org.eclipse.graphiti.mm.pictograms.Anchor;
import org.eclipse.graphiti.mm.pictograms.Connection;
import org.eclipse.graphiti.mm.pictograms.ConnectionDecorator;
import org.eclipse.graphiti.mm.pictograms.FixPointAnchor;
import org.eclipse.graphiti.mm.pictograms.FreeFormConnection;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
import org.eclipse.graphiti.pattern.AbstractConnectionPattern;
import org.eclipse.graphiti.pattern.IFeatureProviderWithPatterns;
import org.eclipse.graphiti.pattern.IPattern;
import org.eclipse.graphiti.services.Graphiti;
import org.eclipse.graphiti.services.IGaService;
import org.eclipse.graphiti.services.ILinkService;
import org.eclipse.graphiti.services.IPeCreateService;
/**
* Implements a visible connection between 2 ports.
*
* Each connection link an input and an output port. A port can be represented
* by an Input or an Output port directly contained in the network, or a port in
* an Instance. In the second case, the real port is a port contained in an
* Actor or in a Network, depending on how the instance has been refined.
*
* @author Antoine Lorence
*
*/
public class ConnectionPattern extends AbstractConnectionPattern {
private enum PortDirection {
INPUT, OUTPUT
}
private enum PortType {
NETWORK_PORT, INSTANCE_PORT
}
private class PortInformation {
private final Vertex vertex;
private final Port port;
private final PortDirection direction;
private final PortType type;
public PortInformation(Vertex vertex, Port port, PortDirection direction, PortType type) {
this.vertex = vertex;
this.port = port;
this.direction = direction;
this.type = type;
}
public Vertex getVertex() {
return vertex;
}
public Port getPort() {
return port;
}
public PortDirection getDirection() {
return direction;
}
public PortType getType() {
return type;
}
}
@Override
public String getCreateName() {
return "Connection";
}
@Override
public String getCreateDescription() {
return "Add a connection between 2 ports";
}
@Override
public boolean canStartConnection(ICreateConnectionContext context) {
final PortInformation src = getPortInformations(context.getSourceAnchor());
if (src == null) {
return false;
}
return true;
}
@Override
public boolean canCreate(ICreateConnectionContext context) {
// The current diagram has a Network attached
if (!(getBusinessObjectForPictogramElement(getDiagram()) instanceof Network)) {
return false;
}
final PortInformation src = getPortInformations(context.getSourceAnchor());
final PortInformation trgt = getPortInformations(context.getTargetAnchor());
if (src == null || trgt == null) {
return false;
}
// Disallow connection between 2 network ports
if (src.getType() == PortType.NETWORK_PORT && trgt.getType() == PortType.NETWORK_PORT) {
return false;
}
// Connection between instance ports are checked specifically
if (src.getType() == PortType.INSTANCE_PORT && trgt.getType() == PortType.INSTANCE_PORT) {
// User tries to connect 2 ports from the same instance
if (context.getSourcePictogramElement().eContainer() == context.getTargetPictogramElement().eContainer()) {
return false;
}
// User tries to connect incompatible ports directions
if (src.getDirection() == trgt.getDirection()) {
return false;
}
}
// net IN -> inst IN = OK
// net IN -> inst OUT = NOK
// net OUT -> inst OUT = OK
// net OUT -> inst IN = NOK
// etc.
if (src.getType() != trgt.getType()) {
if (src.getDirection() != trgt.getDirection()) {
return false;
}
}
// TODO: Check in an input port has not already a connection connected
// to it.
return true;
}
@Override
public Connection create(ICreateConnectionContext context) {
// In some case, connection source and target need to be exchanged, to
// avoid arrow on the wrong side of the connection shape
- final PortInformation src = getPortInformations(context.getSourceAnchor());
+ PortInformation src = getPortInformations(context.getSourceAnchor());
boolean needInverseSourceTarget = false;
if (src.getType() == PortType.NETWORK_PORT && src.getDirection() == PortDirection.OUTPUT) {
needInverseSourceTarget = true;
} else if (src.getType() == PortType.INSTANCE_PORT && src.getDirection() == PortDirection.INPUT) {
needInverseSourceTarget = true;
}
// Create connection context
final AddConnectionContext addContext;
if (needInverseSourceTarget) {
addContext = new AddConnectionContext(context.getTargetAnchor(), context.getSourceAnchor());
} else {
addContext = new AddConnectionContext(context.getSourceAnchor(), context.getTargetAnchor());
}
- final PortInformation tgt = getPortInformations(context.getTargetAnchor());
+ src = getPortInformations(addContext.getSourceAnchor());
+ final PortInformation tgt = getPortInformations(addContext.getTargetAnchor());
// Create new business object
final net.sf.orcc.df.Connection dfConnection = DfFactory.eINSTANCE.createConnection(src.getVertex(),
src.getPort(), tgt.getVertex(), tgt.getPort());
final Network network = (Network) getBusinessObjectForPictogramElement(getDiagram());
network.getConnections().add(dfConnection);
addContext.setNewObject(dfConnection);
Connection newConnection = (Connection) getFeatureProvider().addIfPossible(addContext);
return newConnection;
}
@Override
public boolean canAdd(IAddContext context) {
if (context instanceof IAddConnectionContext) {
if (context.getNewObject() instanceof net.sf.orcc.df.Connection) {
return true;
}
}
return super.canAdd(context);
}
@Override
public PictogramElement add(IAddContext context) {
final IAddConnectionContext addConContext = (IAddConnectionContext) context;
final net.sf.orcc.df.Connection addedConnection = (net.sf.orcc.df.Connection) context.getNewObject();
final IPeCreateService peCreateService = Graphiti.getPeCreateService();
final IGaService gaService = Graphiti.getGaService();
// CONNECTION WITH POLYLINE
final FreeFormConnection connection = peCreateService.createFreeFormConnection(getDiagram());
connection.setStart(addConContext.getSourceAnchor());
connection.setEnd(addConContext.getTargetAnchor());
ConnectionDecorator cd;
cd = peCreateService.createConnectionDecorator(connection, false, 1.0, true);
createArrow(cd);
/* Polyline polyline = */gaService.createPolyline(connection);
StyleUtil.getStyleForConnection(getDiagram());
// create link and wire it
link(connection, addedConnection);
return super.add(context);
}
/**
* Retrieve all information related to a port in a network/diagram. Build
* corresponding PortInformation structure.
*
* @param anchor
* The anchor corresponding to a port in a Network or an Instance
* @return
*/
private PortInformation getPortInformations(Anchor anchor) {
ILinkService linkService = Graphiti.getLinkService();
if (anchor == null) {
return null;
}
// Instance port are linked directly to the anchor
Object obj = getBusinessObjectForPictogramElement(anchor);
if (obj instanceof Port) {
FixPointAnchor fpAnchor = (FixPointAnchor) anchor;
// FIXME: a better detection of in/out port ?
PortDirection dir = fpAnchor.getLocation().getX() == 0 ? PortDirection.INPUT : PortDirection.OUTPUT;
Instance parentInstance = (Instance) linkService
.getBusinessObjectForLinkedPictogramElement(anchor
.getParent());
PortInformation info = new PortInformation(parentInstance, (Port) obj, dir, PortType.INSTANCE_PORT);
return info;
}
// Network ports are linked to the top level shape (anchor container)
obj = getBusinessObjectForPictogramElement(anchor.getParent());
if (obj instanceof Port) {
// Retrieve the pattern corresponding to the current port
IPattern ipattern = ((IFeatureProviderWithPatterns) getFeatureProvider())
.getPatternForPictogramElement(anchor.getParent());
// Check the type of this pattern to know the direction of the port
PortDirection dir = ipattern instanceof InputNetworkPortPattern ? PortDirection.INPUT
: PortDirection.OUTPUT;
Network network = (Network) linkService
.getBusinessObjectForLinkedPictogramElement((PictogramElement) anchor
.getParent().eContainer());
PortInformation info = new PortInformation(network, (Port) obj, dir, PortType.NETWORK_PORT);
return info;
}
// Anchor without port ? Maybe an error here...
return null;
}
private Polyline createArrow(GraphicsAlgorithmContainer gaContainer) {
IGaService gaService = Graphiti.getGaService();
Polyline polyline = gaService.createPolyline(gaContainer, new int[] { -15, 10, 0, 0, -15, -10 });
polyline.setStyle(StyleUtil.getStyleForConnection(getDiagram()));
return polyline;
}
}
| false | false | null | null |
diff --git a/gnu/testlet/org/omg/PortableInterceptor/Interceptor/testInterceptors.java b/gnu/testlet/org/omg/PortableInterceptor/Interceptor/testInterceptors.java
index bb818887..7e58f9c7 100644
--- a/gnu/testlet/org/omg/PortableInterceptor/Interceptor/testInterceptors.java
+++ b/gnu/testlet/org/omg/PortableInterceptor/Interceptor/testInterceptors.java
@@ -1,318 +1,314 @@
// Tags: JDK1.4
// Uses: ../../CORBA/Asserter ../../PortableServer/POAOperations/communication/ourUserException ../../PortableServer/POAOperations/communication/poa_Servant ../../PortableServer/POAOperations/communication/poa_comTester ../../PortableServer/POAOperations/communication/poa_comTesterHelper
// Copyright (C) 2005 Audrius Meskauskas ([email protected])
// Mauve is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.
// Mauve is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
package gnu.testlet.org.omg.PortableInterceptor.Interceptor;
import java.util.Properties;
import org.omg.CORBA.Any;
import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.CompletionStatus;
import org.omg.CORBA.INV_FLAG;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Object;
import org.omg.CORBA.Request;
import org.omg.CORBA.TCKind;
import org.omg.PortableInterceptor.Current;
import org.omg.PortableInterceptor.CurrentHelper;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
import gnu.testlet.org.omg.CORBA.Asserter;
import gnu.testlet.org.omg.PortableServer.POAOperations.communication.ourUserException;
import gnu.testlet.org.omg.PortableServer.POAOperations.communication.poa_Servant;
import gnu.testlet.org.omg.PortableServer.POAOperations.communication.poa_comTester;
import gnu.testlet.org.omg.PortableServer.POAOperations.communication.poa_comTesterHelper;
/**
* Test the basic work of the portable interceptor system.
*
* @author Audrius Meskauskas, Lithuania ([email protected])
*/
public class testInterceptors extends Asserter implements Testlet
{
public static Object fior;
public void test()
{
try
{
Properties initialisers = new Properties();
initialisers.setProperty(
"org.omg.PortableInterceptor.ORBInitializerClass." +
ucInitialiser.class.getName(),
ucInitialiser.class.getName()
);
// Create and initialize the ORB
final ORB orb = org.omg.CORBA.ORB.init(new String[ 0 ], initialisers);
assertTrue("PreInit", ucInitialiser.preInit);
assertTrue("PostInit", ucInitialiser.postInit);
// Create the general communication servant and register it
// with the ORB
poa_Servant tester = new poa_Servant();
POA rootPOA =
POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
Object object = rootPOA.servant_to_reference(tester);
// IOR must contain custom fragment, inserted by interceptor.
// Sun 1.4 had a bug that was fixed in 1.5.
String ior = orb.object_to_string(object);
assertTrue("IOR custom component (bug in 1.4, fixed in 1.5)",
ior.indexOf(
"45257200000020000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
) > 0
);
// Create the forwarding target and register it
// with the ORB
poa_Servant forw = new poa_Servant();
tester.theField(15);
forw.theField(16);
// Another orb without interceptors.
final ORB orbf = ORB.init(new String[ 0 ], null);
POA rootPOA2 =
POAHelper.narrow(orbf.resolve_initial_references("RootPOA"));
Object fobject = rootPOA2.servant_to_reference(forw);
// Storing the IOR reference for general communication.
fior = fobject;
rootPOA.the_POAManager().activate();
rootPOA2.the_POAManager().activate();
// Intercepting server ready and waiting ...
new Thread()
{
public void run()
{
// wait for invocations from clients
orb.run();
}
}.start();
new Thread()
{
public void run()
{
// wait for invocations from clients
orbf.run();
}
}.start();
// Make pause and do a local call.
Thread.sleep(1000);
// Saying local hello.
poa_comTester Tester = poa_comTesterHelper.narrow(object);
Any a0 = orb.create_any();
a0.insert_string("Initial value for slot 0");
Any a1 = orb.create_any();
a1.insert_string("Initial value for slot 1");
ORB orb2 = ORB.init(new String[ 0 ], initialisers);
try
{
// Set the initial slot values.
Current current =
CurrentHelper.narrow(orb.resolve_initial_references("PICurrent"));
Current current2 =
CurrentHelper.narrow(orb2.resolve_initial_references("PICurrent"));
current.set_slot(ucInitialiser.slot_0, a0);
current.set_slot(ucInitialiser.slot_1, a1);
current2.set_slot(ucInitialiser.slot_0, a0);
current2.set_slot(ucInitialiser.slot_1, a1);
}
catch (Exception e)
{
fail("Exception " + e + " while setting slots.");
e.printStackTrace();
}
String lHello = Tester.sayHello();
// Saying remote hello.
Object object2 = orb2.string_to_object(ior);
poa_comTester Tester2 = poa_comTesterHelper.narrow(object2);
String hello = Tester2.sayHello();
assertEquals("Local and remote must return the same", lHello, hello);
// Saying remote hello via DII.
Request rq =
Tester2._create_request(null, "sayHello", orb2.create_list(0),
orb2.create_named_value("", orb.create_any(), 0)
);
rq.set_return_type(orb2.get_primitive_tc(TCKind.tk_string));
rq.invoke();
assertEquals("Remote Stub and DII call must return the same", hello,
rq.return_value().extract_string()
);
// Saying local hello via DII.
rq =
Tester._create_request(null, "sayHello", orb2.create_list(0),
orb2.create_named_value("", orb.create_any(), 0)
);
rq.set_return_type(orb2.get_primitive_tc(TCKind.tk_string));
rq.invoke();
assertEquals("Local Stub and DII call must return the same", hello,
rq.return_value().extract_string()
);
// Throw remote system exception
try
{
Tester2.throwException(-1);
fail("BAD_OPERATION should be thrown");
}
catch (BAD_OPERATION ex)
{
assertEquals("Minor code", ex.minor, 456);
assertEquals("Completion status", CompletionStatus.COMPLETED_YES,
ex.completed
);
}
// Throw remote user exception
try
{
Tester2.throwException(24);
fail("UserException should be thrown");
}
catch (ourUserException ex)
{
assertEquals("Custom field", ex.ourField, 24);
}
// Throw local system exception
try
{
Tester.throwException(-1);
fail("BAD_OPERATION should be thrown");
}
catch (BAD_OPERATION ex)
{
assertEquals("Minor code", ex.minor, 456);
assertEquals("Completion status", CompletionStatus.COMPLETED_YES,
ex.completed
);
}
// Throw local user exception
try
{
Tester.throwException(24);
fail("UserException should be thrown");
}
catch (ourUserException ex)
{
assertEquals("Custom field", ex.ourField, 24);
}
// Remote server side interceptor throws an exception
try
{
Tester2.passCharacters("", "");
fail("INV_FLAG should be thrown");
}
catch (INV_FLAG ex)
{
assertEquals("Minor", 52, ex.minor);
assertEquals("Completion status",
CompletionStatus.COMPLETED_MAYBE, ex.completed
);
}
// Local server side interceptor throws an exception
try
{
Tester.passCharacters("", "");
fail("INV_FLAG should be thrown");
}
catch (INV_FLAG ex)
{
assertEquals("Minor", 52, ex.minor);
assertEquals("Completion status",
CompletionStatus.COMPLETED_MAYBE, ex.completed
);
}
assertEquals("Forwarding test, remote", 16, Tester2.theField());
assertEquals("Forwarding test, local", 16, Tester.theField());
assertEquals("Forwarding test, remote", 16, Tester2.theField());
assertEquals("Forwarding test, local", 16, Tester.theField());
// Destroy orbs:
orb.destroy();
orb2.destroy();
orbf.destroy();
assertTrue("Destroyed", ucClientRequestInterceptor.destroyed);
assertTrue("Destroyed", ucIorInterceptor.destroyed);
assertTrue("Destroyed", ucServerRequestInterceptor.destroyed);
-
- // Test the policy. Sun's 1.5.0_04 still does not operates
- // properly (Sun's bug 6314176).
- assertTrue("Sun's ACCEPTED bug 6314176", ucIorInterceptor.policyOK);
}
catch (Exception e)
{
fail("Exception " + e);
}
}
public void test(TestHarness harness)
{
// Set the loader of this class as a context class loader, ensuring that the
// CORBA implementation will be able to locate the interceptor classes.
ClassLoader previous = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try
{
h = harness;
test();
}
finally
{
Thread.currentThread().setContextClassLoader(previous);
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/com/zarcode/data/maint/CleanerTask.java b/src/com/zarcode/data/maint/CleanerTask.java
index ec8e6bf..c5c2b9a 100644
--- a/src/com/zarcode/data/maint/CleanerTask.java
+++ b/src/com/zarcode/data/maint/CleanerTask.java
@@ -1,309 +1,309 @@
package com.zarcode.data.maint;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.PhotoEntry;
import com.zarcode.app.AppCommon;
import com.zarcode.common.ApplicationProps;
import com.zarcode.common.EmailHelper;
import com.zarcode.common.Util;
import com.zarcode.data.dao.BuzzDao;
import com.zarcode.data.dao.FeedbackDao;
import com.zarcode.data.dao.PegCounterDao;
import com.zarcode.data.dao.UserDao;
import com.zarcode.data.gdata.PicasaClient;
import com.zarcode.data.model.BuzzMsgDO;
import com.zarcode.data.model.CommentDO;
import com.zarcode.data.model.FeedbackDO;
import com.zarcode.data.model.PegCounterDO;
import com.zarcode.data.model.ReadOnlyUserDO;
import com.zarcode.platform.model.AppPropDO;
public class CleanerTask extends HttpServlet {
private Logger logger = Logger.getLogger(CleanerTask.class.getName());
private StringBuilder report = null;
private static int MAX_DAYS_MESSAGE_IN_SYS = 90;
private static int MAX_DAYS_PEGCOUNTER_IN_SYS = 30;
private static int MAX_DAYS_FEEDBACK_IN_SYS = 30;
private static int MAX_DAYS_ANONYMOUS_USER_IN_SYS = 7;
private static long MSEC_IN_DAY = 86400000;
/**
* Cleans (or deletes) OLD Picasa photos.
* @return
*/
private int cleanPicasaPhotos() {
int i = 0;
int j = 0;
int totalPhotosDeleted = 0;
AlbumEntry album = null;
PhotoEntry photo = null;
List<PhotoEntry> photos = null;
PicasawebService service = new PicasawebService("DockedMobile");
Date createDate = null;
Calendar now = Calendar.getInstance();
long photoLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
int photosDeleted = 0;
try {
PicasaClient client = new PicasaClient(service);
List<AlbumEntry> albums = client.getAlbums();
if (albums != null && albums.size() > 0) {
for (i=0; i<albums.size(); i++) {
album = albums.get(i);
photos = client.getPhotos(album);
if (photos != null && photos.size() > 0) {
photosDeleted = 0;
for (j=0; j<photos.size(); j++) {
photo = photos.get(j);
createDate = photo.getTimestamp();
if (createDate.getTime() < photoLife) {
photo.delete();
photosDeleted++;
totalPhotosDeleted++;
}
}
}
}
}
}
catch (Exception e) {
String str = "[EXCEPTION ::: PICASA CLEANING FAILED]\n" + Util.getStackTrace(e);
report.append(str + "\n");
logger.severe(str);
}
return totalPhotosDeleted;
}
/**
* Cleans (or deletes) OLD Anonymous user objects.
*
* @return
*/
private int cleanAnonymousUsers() {
int i = 0;
UserDao userDao = null;
List<ReadOnlyUserDO> tempUsers = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
int anonymousUsersDeleted = 0;
long anonymousUserLife = now.getTimeInMillis() - (MAX_DAYS_ANONYMOUS_USER_IN_SYS * MSEC_IN_DAY);
userDao = new UserDao();
tempUsers = userDao.getAllReadOnlyUsers();
if (tempUsers != null && tempUsers.size() > 0) {
for (i=0; i<tempUsers.size(); i++) {
tempUser = tempUsers.get(i);
if (tempUser.getLastUpdate().getTime() < anonymousUserLife) {
userDao.deleteReadOnlyUser(tempUser);
anonymousUsersDeleted++;
}
}
}
return anonymousUsersDeleted;
}
/**
* Cleans (or deletes) OLD buzz messages.
*
* @return
*/
private int cleanBuzzMsgs() {
int i = 0;
int j = 0;
int buzzMsgsDeleted = 0;
BuzzDao eventDao = null;
UserDao userDao = null;
List<BuzzMsgDO> list = null;
List<ReadOnlyUserDO> tempUsers = null;
BuzzMsgDO msg = null;
CommentDO comment = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
try {
eventDao = new BuzzDao();
list = eventDao.getAllMsgs();
if (list != null && list.size() > 0) {
for (i=0; i<list.size(); i++) {
msg = list.get(i);
if (msg.getCreateDate().getTime() < msgLife) {
List<CommentDO> comments = eventDao.getComments4BuzzMsg(msg);
if (comments != null && comments.size() > 0) {
for (j=0; j<comments.size() ; j++) {
comment = comments.get(j);
eventDao.deleteComment(comment);
}
}
eventDao.deleteInstance(msg);
buzzMsgsDeleted++;
}
}
}
}
catch (Exception e) {
String str = "[EXCEPTION ::: PICASA CLEANING FAILED]\n" + Util.getStackTrace(e);
report.append(str + "\n");
logger.severe(str);
}
return buzzMsgsDeleted;
}
/**
* Cleans (or deletes) OLD peg counters.
*
* @return
*/
private int cleanPegCounters() {
int i = 0;
int pegCountersDeleted = 0;
PegCounterDao pegDao = null;
UserDao userDao = null;
List<PegCounterDO> list = null;
PegCounterDO peg = null;
Calendar now = Calendar.getInstance();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_PEGCOUNTER_IN_SYS * MSEC_IN_DAY);
try {
pegDao = new PegCounterDao();
list = pegDao.getAllPegCounters();
if (list != null && list.size() > 0) {
for (i=0; i<list.size(); i++) {
peg = list.get(i);
if (peg.getLastUpdate().getTime() < msgLife) {
pegDao.deleteInstance(peg);
pegCountersDeleted++;
}
}
}
}
catch (Exception e) {
String str = "[EXCEPTION ::: PICASA CLEANING FAILED]\n" + Util.getStackTrace(e);
report.append(str + "\n");
logger.severe(str);
}
return pegCountersDeleted;
}
private List<FeedbackDO> retrieveFeedback() {
int i = 0;
int pegCountersDeleted = 0;
FeedbackDao feedbackDao = null;
UserDao userDao = null;
List<FeedbackDO> list = null;
FeedbackDO feedback = null;
Calendar now = Calendar.getInstance();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_PEGCOUNTER_IN_SYS * MSEC_IN_DAY);
try {
feedbackDao = new FeedbackDao();
list = feedbackDao.getAll();
if (list != null && list.size() > 0) {
for (i=0; i<list.size(); i++) {
feedback = list.get(i);
feedbackDao.deleteInstance(feedback);
}
}
}
catch (Exception e) {
String str = "[EXCEPTION ::: PICASA CLEANING FAILED]\n" + Util.getStackTrace(e);
report.append(str + "\n");
logger.severe(str);
}
return list;
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
int i = 0;
BuzzDao eventDao = null;
UserDao userDao = null;
List<BuzzMsgDO> list = null;
List<ReadOnlyUserDO> tempUsers = null;
BuzzMsgDO msg = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
report = new StringBuilder();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
logger.info("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]");
report.append("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]\n");
report.append("----------------------------------------------------------\n");
int buzzMsgsDeleted = cleanBuzzMsgs();
logger.info("# of buzz msg(s) deleted: " + buzzMsgsDeleted);
report.append("# of buzz msg(s) deleted: " + buzzMsgsDeleted + "\n");
int pegCounterDeleted = cleanPegCounters();
logger.info("# of peg counter(s) deleted: " + pegCounterDeleted);
report.append("# of peg counter(s) deleted: " + pegCounterDeleted + "\n");
int photosDeleted = cleanPicasaPhotos();
logger.info("# of picasa photo(s) deleted: " + photosDeleted);
report.append("# of picasa photo(s) deleted: " + photosDeleted + "\n");
int anonymousUsersDeleted = cleanAnonymousUsers();
Calendar done = Calendar.getInstance();
logger.info("# of anonymous user(s) deleted: " + anonymousUsersDeleted);
report.append("# of anonymous user(s) deleted: " + anonymousUsersDeleted + "\n");
List<FeedbackDO> feedbackList = retrieveFeedback();
FeedbackDO item = null;
report.append("\n\nFeedback Report\n");
report.append("---------------\n\n");
if (feedbackList != null && feedbackList.size() > 0) {
for (i=0; i<feedbackList.size(); i++) {
item = feedbackList.get(i);
report.append("FROM: ");
report.append(item.getEmailAddr());
report.append(" DATE: ");
report.append(item.getCreateDate());
report.append("\n");
report.append("COMMENTS:\n\n");
report.append(item.getValue());
if ((i+1) < feedbackList.size()) {
report.append("\n\n***\n\n");
}
}
}
long duration = done.getTimeInMillis() - now.getTimeInMillis();
report.append("----------------------------------------------------------\n");
logger.info("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]");
report.append("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]\n");
EmailHelper.sendAppAlert("*** Docked CleanUp Report ***", report.toString(), AppCommon.APPNAME);
} // doGet
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
int i = 0;
BuzzDao eventDao = null;
UserDao userDao = null;
List<BuzzMsgDO> list = null;
List<ReadOnlyUserDO> tempUsers = null;
BuzzMsgDO msg = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
report = new StringBuilder();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
logger.info("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]");
report.append("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]\n");
report.append("----------------------------------------------------------\n");
int buzzMsgsDeleted = cleanBuzzMsgs();
logger.info("# of buzz msg(s) deleted: " + buzzMsgsDeleted);
report.append("# of buzz msg(s) deleted: " + buzzMsgsDeleted + "\n");
int pegCounterDeleted = cleanPegCounters();
logger.info("# of peg counter(s) deleted: " + pegCounterDeleted);
report.append("# of peg counter(s) deleted: " + pegCounterDeleted + "\n");
int photosDeleted = cleanPicasaPhotos();
logger.info("# of picasa photo(s) deleted: " + photosDeleted);
report.append("# of picasa photo(s) deleted: " + photosDeleted + "\n");
int anonymousUsersDeleted = cleanAnonymousUsers();
Calendar done = Calendar.getInstance();
logger.info("# of anonymous user(s) deleted: " + anonymousUsersDeleted);
report.append("# of anonymous user(s) deleted: " + anonymousUsersDeleted + "\n");
List<FeedbackDO> feedbackList = retrieveFeedback();
FeedbackDO item = null;
report.append("\n\nFeedback Report\n");
report.append("---------------\n\n");
if (feedbackList != null && feedbackList.size() > 0) {
for (i=0; i<feedbackList.size(); i++) {
item = feedbackList.get(i);
report.append("FROM: ");
report.append(item.getEmailAddr());
report.append(" DATE: ");
report.append(item.getCreateDate());
report.append("\n");
report.append("COMMENTS:\n\n");
report.append(item.getValue());
if ((i+1) < feedbackList.size()) {
report.append("\n\n***\n\n");
}
}
}
long duration = done.getTimeInMillis() - now.getTimeInMillis();
report.append("----------------------------------------------------------\n");
logger.info("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]");
report.append("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]\n");
EmailHelper.sendAppAlert("*** Docked CleanUp Report ***", report.toString(), AppCommon.APPNAME);
} // doGet
| public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
int i = 0;
BuzzDao eventDao = null;
UserDao userDao = null;
List<BuzzMsgDO> list = null;
List<ReadOnlyUserDO> tempUsers = null;
BuzzMsgDO msg = null;
ReadOnlyUserDO tempUser = null;
Calendar now = Calendar.getInstance();
report = new StringBuilder();
long msgLife = now.getTimeInMillis() - (MAX_DAYS_MESSAGE_IN_SYS * MSEC_IN_DAY);
logger.info("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]");
report.append("**** CLEANER: STARTING **** [ Timestamp :: " + now.getTimeInMillis() + " ]\n");
report.append("----------------------------------------------------------\n");
int buzzMsgsDeleted = cleanBuzzMsgs();
logger.info("# of buzz msg(s) deleted: " + buzzMsgsDeleted);
report.append("# of buzz msg(s) deleted: " + buzzMsgsDeleted + "\n");
int pegCounterDeleted = cleanPegCounters();
logger.info("# of peg counter(s) deleted: " + pegCounterDeleted);
report.append("# of peg counter(s) deleted: " + pegCounterDeleted + "\n");
int photosDeleted = cleanPicasaPhotos();
logger.info("# of picasa photo(s) deleted: " + photosDeleted);
report.append("# of picasa photo(s) deleted: " + photosDeleted + "\n");
int anonymousUsersDeleted = cleanAnonymousUsers();
Calendar done = Calendar.getInstance();
logger.info("# of anonymous user(s) deleted: " + anonymousUsersDeleted);
report.append("# of anonymous user(s) deleted: " + anonymousUsersDeleted + "\n");
List<FeedbackDO> feedbackList = retrieveFeedback();
FeedbackDO item = null;
report.append("\n\nFeedback Report\n");
report.append("---------------\n\n");
if (feedbackList != null && feedbackList.size() > 0) {
for (i=0; i<feedbackList.size(); i++) {
item = feedbackList.get(i);
report.append("FROM: ");
report.append(item.getEmailAddr());
report.append(" DATE: ");
report.append(item.getCreateDate());
report.append("\n");
report.append("COMMENTS:\n\n");
report.append(item.getValue());
if ((i+1) < feedbackList.size()) {
report.append("\n\n***\n\n");
}
}
}
long duration = done.getTimeInMillis() - now.getTimeInMillis();
report.append("----------------------------------------------------------\n");
logger.info("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]");
report.append("**** CLEANER: DONE **** [ Elapsed Msec(s): " + duration + " ]\n");
EmailHelper.sendAppAlert("*** Docked CleanUp Report ***", report.toString(), AppCommon.APPNAME);
} // doGet
|
diff --git a/pmd/src/net/sourceforge/pmd/lang/java/rule/strings/ConsecutiveLiteralAppendsRule.java b/pmd/src/net/sourceforge/pmd/lang/java/rule/strings/ConsecutiveLiteralAppendsRule.java
index 103465c51..91898ab8c 100644
--- a/pmd/src/net/sourceforge/pmd/lang/java/rule/strings/ConsecutiveLiteralAppendsRule.java
+++ b/pmd/src/net/sourceforge/pmd/lang/java/rule/strings/ConsecutiveLiteralAppendsRule.java
@@ -1,306 +1,306 @@
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.strings;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sourceforge.pmd.PropertyDescriptor;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAdditiveExpression;
import net.sourceforge.pmd.lang.java.ast.ASTArgumentList;
import net.sourceforge.pmd.lang.java.ast.ASTDoStatement;
import net.sourceforge.pmd.lang.java.ast.ASTForStatement;
import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTName;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
import net.sourceforge.pmd.lang.java.symboltable.NameOccurrence;
import net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration;
import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper;
import net.sourceforge.pmd.lang.rule.properties.IntegerProperty;
/**
* This rule finds concurrent calls to StringBuffer.append where String literals
* are used It would be much better to make these calls using one call to
* .append
* <p/>
* example:
* <p/>
* <pre>
* StringBuffer buf = new StringBuffer();
* buf.append("Hello");
* buf.append(" ").append("World");
* </pre>
* <p/>
* This would be more eloquently put as:
* <p/>
* <pre>
* StringBuffer buf = new StringBuffer();
* buf.append("Hello World");
* </pre>
* <p/>
* The rule takes one parameter, threshold, which defines the lower limit of
* consecutive appends before a violation is created. The default is 1.
*/
public class ConsecutiveLiteralAppendsRule extends AbstractJavaRule {
private final static Set<Class<?>> blockParents;
static {
blockParents = new HashSet<Class<?>>();
blockParents.add(ASTForStatement.class);
blockParents.add(ASTWhileStatement.class);
blockParents.add(ASTDoStatement.class);
blockParents.add(ASTIfStatement.class);
blockParents.add(ASTSwitchStatement.class);
blockParents.add(ASTMethodDeclaration.class);
}
private static final PropertyDescriptor thresholdDescriptor = new IntegerProperty("threshold", "?", 1, 1.0f);
private static final Map<String, PropertyDescriptor> propertyDescriptorsByName = asFixedMap(thresholdDescriptor);
private int threshold = 1;
@Override
public Object visit(ASTVariableDeclaratorId node, Object data) {
if (!isStringBuffer(node)) {
return data;
}
threshold = getIntProperty(thresholdDescriptor);
int concurrentCount = checkConstructor(node, data);
Node lastBlock = getFirstParentBlock(node);
Node currentBlock = lastBlock;
Map<VariableNameDeclaration, List<NameOccurrence>> decls = node.getScope().getVariableDeclarations();
Node rootNode = null;
// only want the constructor flagged if it's really containing strings
- if (concurrentCount == 1) {
+ if (concurrentCount >= 1) {
rootNode = node;
}
for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : decls.entrySet()) {
List<NameOccurrence> decl = entry.getValue();
for (NameOccurrence no : decl) {
Node n = no.getLocation();
currentBlock = getFirstParentBlock(n);
if (!InefficientStringBufferingRule.isInStringBufferOperation(n, 3, "append")) {
if (!no.isPartOfQualifiedName()) {
checkForViolation(rootNode, data, concurrentCount);
concurrentCount = 0;
}
continue;
}
ASTPrimaryExpression s = n.getFirstParentOfType(ASTPrimaryExpression.class);
int numChildren = s.jjtGetNumChildren();
for (int jx = 0; jx < numChildren; jx++) {
Node sn = s.jjtGetChild(jx);
if (!(sn instanceof ASTPrimarySuffix) || sn.getImage() != null) {
continue;
}
// see if it changed blocks
if (currentBlock != null && lastBlock != null && !currentBlock.equals(lastBlock)
|| currentBlock == null ^ lastBlock == null) {
checkForViolation(rootNode, data, concurrentCount);
concurrentCount = 0;
}
// if concurrent is 0 then we reset the root to report from
// here
if (concurrentCount == 0) {
rootNode = sn;
}
if (isAdditive(sn)) {
concurrentCount = processAdditive(data, concurrentCount, sn, rootNode);
if (concurrentCount != 0) {
rootNode = sn;
}
} else if (!isAppendingStringLiteral(sn)) {
checkForViolation(rootNode, data, concurrentCount);
concurrentCount = 0;
} else {
concurrentCount++;
}
lastBlock = currentBlock;
}
}
}
checkForViolation(rootNode, data, concurrentCount);
return data;
}
/**
* Determie if the constructor contains (or ends with) a String Literal
*
* @param node
* @return 1 if the constructor contains string argument, else 0
*/
private int checkConstructor(ASTVariableDeclaratorId node, Object data) {
Node parent = node.jjtGetParent();
if (parent.jjtGetNumChildren() >= 2) {
ASTArgumentList list = parent.jjtGetChild(1).getFirstChildOfType(ASTArgumentList.class);
if (list != null) {
ASTLiteral literal = list.getFirstChildOfType(ASTLiteral.class);
if (!isAdditive(list) && literal != null && literal.isStringLiteral()) {
return 1;
}
return processAdditive(data, 0, list, node);
}
}
return 0;
}
private int processAdditive(Object data, int concurrentCount, Node sn, Node rootNode) {
ASTAdditiveExpression additive = sn.getFirstChildOfType(ASTAdditiveExpression.class);
if (additive == null) {
return 0;
}
int count = concurrentCount;
boolean found = false;
for (int ix = 0; ix < additive.jjtGetNumChildren(); ix++) {
Node childNode = additive.jjtGetChild(ix);
if (childNode.jjtGetNumChildren() != 1 || childNode.findChildrenOfType(ASTName.class).size() != 0) {
if (!found) {
checkForViolation(rootNode, data, count);
found = true;
}
count = 0;
} else {
count++;
}
}
// no variables appended, compiler will take care of merging all the
// string concats, we really only have 1 then
if (!found) {
count = 1;
}
return count;
}
/**
* Checks to see if there is string concatenation in the node.
*
* This method checks if it's additive with respect to the append method
* only.
*
* @param n
* Node to check
* @return true if the node has an additive expression (i.e. "Hello " +
* Const.WORLD)
*/
private boolean isAdditive(Node n) {
List<ASTAdditiveExpression> lstAdditive = n.findChildrenOfType(ASTAdditiveExpression.class);
if (lstAdditive.isEmpty()) {
return false;
}
// if there are more than 1 set of arguments above us we're not in the
// append
// but a sub-method call
for (int ix = 0; ix < lstAdditive.size(); ix++) {
ASTAdditiveExpression expr = lstAdditive.get(ix);
if (expr.getParentsOfType(ASTArgumentList.class).size() != 1) {
return false;
}
}
return true;
}
/**
* Get the first parent. Keep track of the last node though. For If
* statements it's the only way we can differentiate between if's and else's
* For switches it's the only way we can differentiate between switches
*
* @param node The node to check
* @return The first parent block
*/
private Node getFirstParentBlock(Node node) {
Node parentNode = node.jjtGetParent();
Node lastNode = node;
while (parentNode != null && !blockParents.contains(parentNode.getClass())) {
lastNode = parentNode;
parentNode = parentNode.jjtGetParent();
}
if (parentNode != null && parentNode.getClass().equals(ASTIfStatement.class)) {
parentNode = lastNode;
} else if (parentNode != null && parentNode.getClass().equals(ASTSwitchStatement.class)) {
parentNode = getSwitchParent(parentNode, lastNode);
}
return parentNode;
}
/**
* Determine which SwitchLabel we belong to inside a switch
*
* @param parentNode The parent node we're looking at
* @param lastNode The last node processed
* @return The parent node for the switch statement
*/
private Node getSwitchParent(Node parentNode, Node lastNode) {
int allChildren = parentNode.jjtGetNumChildren();
ASTSwitchLabel label = null;
for (int ix = 0; ix < allChildren; ix++) {
Node n = parentNode.jjtGetChild(ix);
if (n.getClass().equals(ASTSwitchLabel.class)) {
label = (ASTSwitchLabel) n;
} else if (n.equals(lastNode)) {
parentNode = label;
break;
}
}
return parentNode;
}
/**
* Helper method checks to see if a violation occured, and adds a
* RuleViolation if it did
*/
private void checkForViolation(Node node, Object data, int concurrentCount) {
if (concurrentCount > threshold) {
String[] param = { String.valueOf(concurrentCount) };
addViolation(data, node, param);
}
}
private boolean isAppendingStringLiteral(Node node) {
Node n = node;
while (n.jjtGetNumChildren() != 0 && !n.getClass().equals(ASTLiteral.class)) {
n = n.jjtGetChild(0);
}
return n.getClass().equals(ASTLiteral.class);
}
private static boolean isStringBuffer(ASTVariableDeclaratorId node) {
if (node.getType() != null) {
return node.getType().equals(StringBuffer.class);
}
Node nn = node.getTypeNameNode();
if (nn.jjtGetNumChildren() == 0) {
return false;
}
return TypeHelper.isA((TypeNode) nn.jjtGetChild(0), StringBuffer.class);
}
@Override
protected Map<String, PropertyDescriptor> propertiesByName() {
return propertyDescriptorsByName;
}
}
\ No newline at end of file
diff --git a/pmd/src/net/sourceforge/pmd/lang/rule/AbstractRuleViolation.java b/pmd/src/net/sourceforge/pmd/lang/rule/AbstractRuleViolation.java
index 29328eab1..333598c76 100644
--- a/pmd/src/net/sourceforge/pmd/lang/rule/AbstractRuleViolation.java
+++ b/pmd/src/net/sourceforge/pmd/lang/rule/AbstractRuleViolation.java
@@ -1,134 +1,135 @@
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule;
import java.util.List;
import java.util.regex.Pattern;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.ast.Node;
import org.jaxen.JaxenException;
public abstract class AbstractRuleViolation implements RuleViolation {
protected Rule rule;
protected String description;
protected boolean suppressed;
protected String filename;
protected int beginLine;
protected int beginColumn;
protected int endLine;
protected int endColumn;
protected String packageName;
protected String className;
protected String methodName;
protected String variableName;
+ // FUTURE Fix to understand when a violation _must_ have a Node, and when it must not (to prevent erroneous Rules silently logging w/o a Node). Modify RuleViolationFactory to support identifying without a Node, and update Rule base classes too.
public AbstractRuleViolation(Rule rule, RuleContext ctx, Node node) {
this(rule, ctx, node, rule.getMessage());
}
public AbstractRuleViolation(Rule rule, RuleContext ctx, Node node, String specificMsg) {
this.rule = rule;
this.description = specificMsg;
this.filename = ctx.getSourceCodeFilename();
if (this.filename == null) {
this.filename = "";
}
if (node != null) {
this.beginLine = node.getBeginLine();
this.beginColumn = node.getBeginColumn();
this.endLine = node.getEndLine();
this.endColumn = node.getEndColumn();
}
this.packageName = "";
this.className = "";
this.methodName = "";
this.variableName = "";
// Apply Rule specific suppressions
if (node != null && rule != null) {
// Regex
String regex = rule.getStringProperty(Rule.VIOLATION_SUPPRESS_REGEX_PROPERTY);
if (regex != null && description != null) {
if (Pattern.matches(regex, description)) {
suppressed = true;
}
}
// XPath
if (!suppressed) {
String xpath = rule.getStringProperty(Rule.VIOLATION_SUPPRESS_XPATH_PROPERTY);
if (xpath != null) {
try {
List<Node> children = node.findChildNodesWithXPath(xpath);
if (children != null && !children.isEmpty()) {
suppressed = true;
}
} catch (JaxenException e) {
throw new RuntimeException("Violation suppression XPath failed: " + e.getLocalizedMessage(), e);
}
}
}
}
}
public Rule getRule() {
return rule;
}
public String getDescription() {
return description;
}
public boolean isSuppressed() {
return this.suppressed;
}
public String getFilename() {
return filename;
}
public int getBeginLine() {
return beginLine;
}
public int getBeginColumn() {
return beginColumn;
}
public int getEndLine() {
return endLine;
}
public int getEndColumn() {
return endColumn;
}
public String getPackageName() {
return packageName;
}
public String getClassName() {
return className;
}
public String getMethodName() {
return methodName;
}
public String getVariableName() {
return variableName;
}
public String toString() {
return getFilename() + ":" + getRule() + ":" + getDescription() + ":" + beginLine;
}
}
| false | false | null | null |
diff --git a/src/org/opensolaris/opengrok/search/scope/MainFrame.java b/src/org/opensolaris/opengrok/search/scope/MainFrame.java
index b2d7792..6a9ffd9 100644
--- a/src/org/opensolaris/opengrok/search/scope/MainFrame.java
+++ b/src/org/opensolaris/opengrok/search/scope/MainFrame.java
@@ -1,708 +1,709 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2005 Trond Norbye. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.search.scope;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import org.opensolaris.opengrok.configuration.Configuration;
import org.opensolaris.opengrok.configuration.RuntimeEnvironment;
import org.opensolaris.opengrok.search.Hit;
import org.opensolaris.opengrok.search.scope.editor.InternalEditor;
/**
* A small GUI frontend to the lucene database.
*
* @author Trond Norbye
*/
public class MainFrame extends javax.swing.JFrame {
static final long serialVersionUID = 1L;
private Integer searchSession;
private Boolean searching;
+ private Object searchingLock = new Object();
private int nhits;
private int shownhits;
/** Creates new form MainFrame */
public MainFrame() {
searchSession = 0;
searching = false;
initComponents();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension mySize = getPreferredSize();
setLocation(screenSize.width/2 - (mySize.width/2), screenSize.height/2 - (mySize.height/2));
if (indexDatabaseCombo.getItemCount() > 0) {
indexDatabaseCombo.setSelectedIndex(0);
} else {
searchButton.setEnabled(false);
}
searchButton.setEnabled(true);
// Search should be the default button, esc should be cancel
getRootPane().setDefaultButton(searchButton);
registerEscapeHandler(definitionField);
registerEscapeHandler(fileField);
registerEscapeHandler(fullField);
registerEscapeHandler(historyField);
registerEscapeHandler(symbolField);
registerEscapeHandler(symbolField);
registerEscapeHandler(searchButton);
// Create the editor list..
List<Editor> list = Config.getInstance().getAvailableEditors();
final JPopupMenu menu = new JPopupMenu();
// I would like the InternalEditor to be the first element in the menu if it exists
for (Editor ed : list) {
if (ed instanceof InternalEditor) {
JMenuItem item = new JMenuItem("View");
menu.add(item);
item.putClientProperty("editor", ed);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem)e.getSource();
displayFile((Editor)item.getClientProperty("editor"));
}
});
break;
}
}
// Add the other editors
for (Editor ed : list) {
if (!(ed instanceof InternalEditor) && !ed.getName().equalsIgnoreCase("Custom")) {
JMenuItem item = new JMenuItem("Open in " + ed.getName());
item.putClientProperty("editor", ed);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem)e.getSource();
displayFile((Editor)item.getClientProperty("editor"));
}
});
menu.add(item);
}
}
hitsTable.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
if (evt.isPopupTrigger() && hitsTable.getSelectedRow() != -1) {
menu.show(evt.getComponent(), evt.getX(), evt.getY());
}
}
public void mouseReleased(MouseEvent evt) {
if (evt.isPopupTrigger() && hitsTable.getSelectedRow() != -1) {
menu.show(evt.getComponent(), evt.getX(), evt.getY());
}
}
});
setDefaultColumnWidth();
}
private void registerEscapeHandler(JComponent field) {
Action escapeKeyAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
clearButtonActionPerformed(null);
}
};
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke((char)KeyEvent.VK_ESCAPE);
InputMap inputMap = field.getInputMap();
ActionMap actionMap = field.getActionMap();
if (inputMap != null && actionMap != null) {
inputMap.put(escapeKeyStroke, "escape");
actionMap.put("escape", escapeKeyAction);
}
}
private void displayFile(Editor editor) {
int rows[] = hitsTable.getSelectedRows();
if (rows != null) {
HitTableModel model = (HitTableModel)hitsTable.getModel();
for (int ii = 0; ii < rows.length; ++ii) {
Hit hit = model.getHitAt(rows[ii]);
if (hit.isBinary()) {
if (JOptionPane.showConfirmDialog(this, hit.getFilename() + " is a binary file. Really open?", "Really open file?", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
continue;
}
}
StringBuilder sb = new StringBuilder();
sb.append(RuntimeEnvironment.getInstance().getSourceRootPath());
sb.append(hit.getDirectory());
sb.append(File.separator);
sb.append(hit.getFilename());
try {
Integer lineno = null;
try {
lineno = Integer.parseInt(hit.getLineno());
} catch (Exception e) {
;
}
editor.displayFile(sb.toString(), lineno);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Failed to display file\n" + ex.getMessage(), "Failed to display file", JOptionPane.ERROR_MESSAGE);
}
}
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.JLabel jLabel1 = new javax.swing.JLabel();
fullField = new javax.swing.JTextField();
javax.swing.JLabel jLabel2 = new javax.swing.JLabel();
definitionField = new javax.swing.JTextField();
javax.swing.JLabel jLabel3 = new javax.swing.JLabel();
symbolField = new javax.swing.JTextField();
javax.swing.JLabel jLabel4 = new javax.swing.JLabel();
fileField = new javax.swing.JTextField();
javax.swing.JLabel jLabel5 = new javax.swing.JLabel();
historyField = new javax.swing.JTextField();
searchButton = new javax.swing.JButton();
javax.swing.JButton clearButton = new javax.swing.JButton();
javax.swing.JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
hitsTable = new javax.swing.JTable();
hitsTable.setDefaultRenderer(String.class, new AltRenderer());
summaryLabel = new javax.swing.JLabel();
javax.swing.JLabel jLabel6 = new javax.swing.JLabel();
indexDatabaseCombo = new javax.swing.JComboBox();
javax.swing.JButton browseIndexBtn = new javax.swing.JButton();
lbar = new javax.swing.JProgressBar();
moreButton = new javax.swing.JButton();
holdPath = new javax.swing.JToggleButton();
javax.swing.JMenuBar jMenuBar1 = new javax.swing.JMenuBar();
javax.swing.JMenu jMenu1 = new javax.swing.JMenu();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu jMenu2 = new javax.swing.JMenu();
javax.swing.JMenuItem editorMenuItem = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("OpenGrok");
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel1.setText("Full Search");
fullField.setFont(new java.awt.Font("DialogInput", 0, 12));
fullField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel2.setText("Definition");
definitionField.setFont(new java.awt.Font("DialogInput", 0, 12));
definitionField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel3.setText("Symbol");
symbolField.setFont(new java.awt.Font("DialogInput", 0, 12));
symbolField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel4.setText("File Path");
fileField.setFont(new java.awt.Font("DialogInput", 0, 12));
fileField.setText(Config.getInstance().getPath());
fileField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel5.setText("History");
historyField.setFont(new java.awt.Font("DialogInput", 0, 12));
historyField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
searchButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/opensolaris/opengrok/search/scope/q.gif"))); // NOI18N
searchButton.setText("Search");
searchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchButtonActionPerformed(evt);
}
});
clearButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/opensolaris/opengrok/search/scope/stp.gif"))); // NOI18N
clearButton.setText("Cancel");
clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearButtonActionPerformed(evt);
}
});
hitsTable.setModel(new HitTableModel());
hitsTable.setIntercellSpacing(new java.awt.Dimension(0, 0));
hitsTable.setMinimumSize(new java.awt.Dimension(10, 0));
hitsTable.setShowHorizontalLines(false);
hitsTable.setShowVerticalLines(false);
hitsTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
hitsTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(hitsTable);
summaryLabel.setFont(new java.awt.Font("Dialog", 0, 12));
summaryLabel.setText(" ");
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel6.setText("Configuration");
indexDatabaseCombo.setModel(new org.opensolaris.opengrok.search.scope.ConfigurationComboModel());
indexDatabaseCombo.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
indexDatabaseComboItemStateChanged(evt);
}
});
browseIndexBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/opensolaris/opengrok/search/scope/do.gif"))); // NOI18N
browseIndexBtn.setToolTipText("Open a index database");
browseIndexBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseIndexBtnActionPerformed(evt);
}
});
lbar.setForeground(new java.awt.Color(130, 153, 175));
lbar.setString("");
lbar.setStringPainted(true);
moreButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/opensolaris/opengrok/search/scope/more.gif"))); // NOI18N
moreButton.setToolTipText("More");
moreButton.setEnabled(false);
moreButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
moreButtonActionPerformed(evt);
}
});
holdPath.setFont(new java.awt.Font("Dialog", 0, 10));
holdPath.setSelected(Config.getInstance().getPathHold());
holdPath.setToolTipText("Remember the path");
holdPath.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
holdPathActionPerformed(evt);
}
});
jMenu1.setText("File");
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
jMenu1.add(exitMenuItem);
jMenuBar1.add(jMenu1);
jMenu2.setText("Options");
editorMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/opensolaris/opengrok/search/scope/p.gif"))); // NOI18N
editorMenuItem.setText("Editor...");
editorMenuItem.setIconTextGap(9);
editorMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
editorMenuItemActionPerformed(evt);
}
});
jMenu2.add(editorMenuItem);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jLabel6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(indexDatabaseCombo, 0, 516, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(browseIndexBtn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 32, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(searchButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(clearButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 199, Short.MAX_VALUE)
.add(lbar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 167, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(moreButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 29, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(historyField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 554, Short.MAX_VALUE)
.add(definitionField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 554, Short.MAX_VALUE)
.add(symbolField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 554, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(fileField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(holdPath, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 26, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(fullField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 554, Short.MAX_VALUE))
.addContainerGap())
.add(layout.createSequentialGroup()
.addContainerGap()
.add(summaryLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
.addContainerGap())
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 653, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel6)
.add(browseIndexBtn)
.add(indexDatabaseCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel1)
.add(fullField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(2, 2, 2)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel2)
.add(definitionField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(2, 2, 2)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel3)
.add(symbolField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(2, 2, 2)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel4)
.add(holdPath, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(fileField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(2, 2, 2)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel5)
.add(historyField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(clearButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(searchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(moreButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 27, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(lbar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 27, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
.add(0, 0, 0)
.add(summaryLabel))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void moreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moreButtonActionPerformed
if(!searching && shownhits < nhits) {
searching = true;
searchButton.setEnabled(false);
moreButton.setEnabled(false);
}
Thread t = new Thread() {
public void run() {
long start = System.currentTimeMillis();
int mySession = searchSession;
int inc = 7;
int i = shownhits;
int e = shownhits;
long fstart;
HitTableModel m = (HitTableModel)hitsTable.getModel();
for(; searching && i < nhits && (fstart = System.currentTimeMillis()) - start < 5000; i+=inc) {
e = i+inc;
if(e > nhits) {
e = nhits;
}
lbar.setValue((e*100)/nhits+1);
lbar.setString(i + "/" + nhits);
if(!m.more(i, e, searchSession)) {
summaryLabel.setText(" ");
lbar.setValue(0);
lbar.setString("");
nhits = 0;
searchButton.setEnabled(true);
moreButton.setEnabled(false);
return;
}
lbar.setString(e + "/" + nhits);
if(System.currentTimeMillis()-fstart < 300) {
inc = inc + inc/2;
}
}
long stop = System.currentTimeMillis();
if(nhits == 0) {
lbar.setString("0 found!");
shownhits = 0;
} else {
summaryLabel.setText("Took " + ((stop - start)/1000) + " sec");
shownhits = e;
if (i >= nhits) {
lbar.setValue(100);
lbar.setString(nhits + " found");
moreButton.setEnabled(false);
} else {
lbar.setString("First " + i + "/" + nhits);
moreButton.setEnabled(true);
}
}
- synchronized(searching) {
+ synchronized(searchingLock) {
searching = false;
searchButton.setEnabled(true);
}
}
};
t.start();
}//GEN-LAST:event_moreButtonActionPerformed
private void holdPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_holdPathActionPerformed
if(holdPath.isSelected()) {
Config.getInstance().setPath(fileField.getText().trim());
}
Config.getInstance().setPathHold(holdPath.isSelected());
}//GEN-LAST:event_holdPathActionPerformed
private void indexDatabaseComboItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_indexDatabaseComboItemStateChanged
File file = (File) evt.getItem();
try {
Configuration config = Configuration.read(file);
RuntimeEnvironment.getInstance().setConfiguration(config);
searchButton.setEnabled(true);
} catch (Exception exp) {
JOptionPane.showMessageDialog(this, "Failed to read configuration: " + exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
searchButton.setEnabled(false);
}
}//GEN-LAST:event_indexDatabaseComboItemStateChanged
private void browseIndexBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseIndexBtnActionPerformed
JFileChooser jfc = new JFileChooser();
if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
Configuration config = Configuration.read(jfc.getSelectedFile());
Config.getInstance().getRecentConfigurations().add(jfc.getSelectedFile());
RuntimeEnvironment.getInstance().setConfiguration(config);
((ConfigurationComboModel)indexDatabaseCombo.getModel()).refresh();
indexDatabaseCombo.getModel().setSelectedItem(jfc.getSelectedFile());
Config.getInstance().setCurrentConfiguration(jfc.getSelectedFile());
} catch (Exception exp) {
JOptionPane.showMessageDialog(this, "Failed to read configuration: " + exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}//GEN-LAST:event_browseIndexBtnActionPerformed
private void editorMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editorMenuItemActionPerformed
EditorConfigPanel pnl = new EditorConfigPanel();
pnl.setEditor(Config.getInstance().getEditor());
if (JOptionPane.showConfirmDialog(this, pnl, "Editor settings", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null) == JOptionPane.OK_OPTION) {
pnl.updateEditor();
Config.getInstance().setEditor(pnl.getEditor());
}
}//GEN-LAST:event_editorMenuItemActionPerformed
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed
private void updateSelectedFile() {
int rows[] = hitsTable.getSelectedRows();
if(rows != null && rows.length > 0) {
summaryLabel.setText(
((HitTableModel)hitsTable.getModel()).getHitAt(rows[0]).getPath());
}
}
private void hitsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_hitsTableMouseClicked
if (evt.getClickCount() == 2) {
displayFile(Config.getInstance().getEditor());
} else if (evt.getClickCount() == 1) {
updateSelectedFile();
}
}//GEN-LAST:event_hitsTableMouseClicked
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
- synchronized(searching) {
+ synchronized(searchingLock) {
searching = true;
};
searchButton.setEnabled(false);
moreButton.setEnabled(false);
SearchEngine se = new SearchEngine();
se.setDefinition(definitionField.getText().trim());
se.setFile(fileField.getText().trim());
se.setFreetext(fullField.getText().trim());
se.setHistory(historyField.getText().trim());
se.setSymbol(symbolField.getText().trim());
synchronized(searchSession) {
searchSession++;
};
final HitTableModel m = (HitTableModel)hitsTable.getModel();
m.reset();
m.setSearchEngine(se);
Thread t = new Thread() {
public void run() {
long start = System.currentTimeMillis();
int mySession;
nhits = m.search(mySession = searchSession);
setDefaultColumnWidth();
int inc = 7;
int i = 0;
int e = 0;
long fstart;
while(searching && i < nhits && (fstart = System.currentTimeMillis()) - start < 5000) {
i = e;
e = i+inc;
if(e > nhits) {
e = nhits;
}
lbar.setValue((e*100)/nhits+1);
lbar.setString(i + "/" + nhits);
if(!m.more(i, e, searchSession)) {
summaryLabel.setText(" ");
lbar.setValue(0);
lbar.setString("");
nhits = 0;
searchButton.setEnabled(true);
moreButton.setEnabled(false);
return;
}
lbar.setString(e + "/" + nhits);
if(System.currentTimeMillis()-fstart < 300) {
inc = inc + inc/2;
}
}
long stop = System.currentTimeMillis();
if(nhits == 0) {
lbar.setString("0 found!");
shownhits = 0;
} else {
summaryLabel.setText("Took " + ((stop - start)/1000) + " sec");
shownhits = e;
if (i >= nhits) {
lbar.setValue(100);
lbar.setString(nhits + " found");
moreButton.setEnabled(false);
} else {
lbar.setString("First " + i + "/" + nhits);
moreButton.setEnabled(true);
}
}
- synchronized(searching) {
+ synchronized(searchingLock) {
searching = false;
searchButton.setEnabled(true);
}
}
};
t.start();
}//GEN-LAST:event_searchButtonActionPerformed
private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
- synchronized(searching) {
+ synchronized(searchingLock) {
if(searching) {
searching = false;
return;
}
}
synchronized(searchSession) {
searchSession++;
};
definitionField.setText("");
if(!holdPath.isSelected()) fileField.setText("");
fullField.setText("");
historyField.setText("");
symbolField.setText("");
((HitTableModel)hitsTable.getModel()).reset();
summaryLabel.setText(" ");
lbar.setValue(0);
lbar.setString("");
}//GEN-LAST:event_clearButtonActionPerformed
private void setDefaultColumnWidth() {
int width = hitsTable.getWidth();
if (hitsTable.getColumnCount() == 2) {
hitsTable.getColumnModel().getColumn(0).setPreferredWidth((int)(width * 0.5));
hitsTable.getColumnModel().getColumn(1).setPreferredWidth((int)(width * 0.5));
} else {
hitsTable.getColumnModel().getColumn(0).setPreferredWidth((int)(width * 0.1));
hitsTable.getColumnModel().getColumn(1).setPreferredWidth((int)(width * 0.15));
hitsTable.getColumnModel().getColumn(2).setPreferredWidth((int)(width * 0.65));
hitsTable.getColumnModel().getColumn(3).setPreferredWidth((int)(width * 0.1));
}
}
/**
* Program entry point for the graphical interface version of the seach program
* @param args the command line arguments
*/
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField definitionField;
private javax.swing.JTextField fileField;
private javax.swing.JTextField fullField;
private javax.swing.JTextField historyField;
private javax.swing.JTable hitsTable;
javax.swing.JToggleButton holdPath;
private javax.swing.JComboBox indexDatabaseCombo;
javax.swing.JProgressBar lbar;
javax.swing.JButton moreButton;
private javax.swing.JButton searchButton;
private javax.swing.JLabel summaryLabel;
private javax.swing.JTextField symbolField;
// End of variables declaration//GEN-END:variables
}
| false | false | null | null |
diff --git a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/ControlListItem.java b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/ControlListItem.java
index 0cbc42dd..07a83ecf 100644
--- a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/ControlListItem.java
+++ b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/ControlListItem.java
@@ -1,275 +1,276 @@
/*******************************************************************************
* Copyright (c) 2005, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.commons.ui;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
/**
* Based on <code>org.eclipse.ui.internal.progress.ProgressInfoItem</code>.
*
* @author Steffen Pingel
+ * @since 3.7
*/
public abstract class ControlListItem extends Composite {
static String DARK_COLOR_KEY = "org.eclipse.mylyn.commons.ui.ControlListItem.DARK_COLOR"; //$NON-NLS-1$
interface IndexListener {
/**
* Select the item previous to the receiver.
*/
public void selectPrevious();
/**
* Select the next previous to the receiver.
*/
public void selectNext();
/**
* Select the receiver.
*/
public void select();
public void open();
}
IndexListener indexListener;
private int currentIndex;
private boolean selected;
private final MouseAdapter mouseListener;
private boolean isShowing = true;
private final MouseTrackAdapter mouseTrackListener;
private boolean hot;
static {
// Mac has different Gamma value
int shift = "carbon".equals(SWT.getPlatform()) ? -25 : -10;//$NON-NLS-1$
Color lightColor = Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND);
// Determine a dark color by shifting the list color
RGB darkRGB = new RGB(Math.max(0, lightColor.getRed() + shift), Math.max(0, lightColor.getGreen() + shift),
Math.max(0, lightColor.getBlue() + shift));
JFaceResources.getColorRegistry().put(DARK_COLOR_KEY, darkRGB);
}
/**
* Create a new instance of the receiver with the specified parent, style and info object/
*
* @param parent
* @param style
* @param progressInfo
*/
public ControlListItem(Composite parent, int style, Object element) {
super(parent, style | SWT.NO_FOCUS);
setData(element);
setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
mouseListener = doCreateMouseListener();
mouseTrackListener = doCreateMouseTrackListener();
createContent();
registerChild(this);
Control[] children = getChildren();
for (Control child : children) {
registerChild(child);
}
setHot(false);
refresh();
}
private MouseTrackAdapter doCreateMouseTrackListener() {
return new MouseTrackAdapter() {
private int enterCount;
@Override
public void mouseEnter(MouseEvent e) {
enterCount++;
updateHotState();
}
@Override
public void mouseExit(MouseEvent e) {
enterCount--;
getDisplay().asyncExec(new Runnable() {
public void run() {
if (!isDisposed()) {
updateHotState();
}
}
});
}
private void updateHotState() {
if (enterCount == 0) {
if (isHot()) {
setHot(false);
}
} else {
if (!isHot()) {
setHot(true);
}
}
}
};
}
private MouseAdapter doCreateMouseListener() {
return new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
if (indexListener != null) {
if (e.count == 2) {
indexListener.open();
} else {
indexListener.select();
}
}
}
};
}
/**
* Create the child widgets of the receiver.
*/
protected abstract void createContent();
public boolean isHot() {
return hot;
}
public void setHot(boolean hot) {
this.hot = hot;
}
protected void registerChild(Control child) {
child.addMouseListener(mouseListener);
child.addMouseTrackListener(mouseTrackListener);
}
/**
* Refresh the contents of the receiver.
*/
protected abstract void refresh();
/**
* Set the color base on the index
*
* @param index
*/
public void updateColors(int index) {
currentIndex = index;
if (selected) {
setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION));
setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT));
} else {
if (index % 2 == 0) {
setBackground(JFaceResources.getColorRegistry().get(DARK_COLOR_KEY));
} else {
setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
}
setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND));
}
}
@Override
public void setForeground(Color color) {
super.setForeground(color);
Control[] children = getChildren();
for (Control child : children) {
child.setForeground(color);
}
}
@Override
public void setBackground(Color color) {
super.setBackground(color);
Control[] children = getChildren();
for (Control child : children) {
child.setBackground(color);
}
}
/**
* Set the selection colors.
*
* @param select
* boolean that indicates whether or not to show selection.
*/
public void setSelected(boolean select) {
selected = select;
updateColors(currentIndex);
}
/**
* Set the listener for index changes.
*
* @param indexListener
*/
void setIndexListener(IndexListener indexListener) {
this.indexListener = indexListener;
}
/**
* Return whether or not the receiver is selected.
*
* @return boolean
*/
public boolean isSelected() {
return selected;
}
/**
* Set whether or not the receiver is being displayed based on the top and bottom of the currently visible area.
*
* @param top
* @param bottom
*/
void setDisplayed(int top, int bottom) {
int itemTop = getLocation().y;
int itemBottom = itemTop + getBounds().height;
setDisplayed(itemTop <= bottom && itemBottom > top);
}
/**
* Set whether or not the receiver is being displayed
*
* @param displayed
*/
private void setDisplayed(boolean displayed) {
// See if this element has been turned off
boolean refresh = !isShowing && displayed;
isShowing = displayed;
if (refresh) {
refresh();
}
}
}
diff --git a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/ControlListViewer.java b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/ControlListViewer.java
index 7ca81ddd..3b138d92 100644
--- a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/ControlListViewer.java
+++ b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/ControlListViewer.java
@@ -1,501 +1,502 @@
/*******************************************************************************
* Copyright (c) 2005, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.commons.ui;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Widget;
/**
* Based on {@link org.eclipse.ui.internal.progress.DetailedProgressViewer}.
*
* @author Steffen Pingel
+ * @since 3.7
*/
@SuppressWarnings("restriction")
public abstract class ControlListViewer extends StructuredViewer {
Composite control;
private final ScrolledComposite scrolled;
private final Composite noEntryArea;
protected boolean hasFocus;
/**
* Create a new instance of the receiver with a control that is a child of parent with style style.
*
* @param parent
* @param style
*/
public ControlListViewer(Composite parent, int style) {
scrolled = new ScrolledComposite(parent, style);
int height = JFaceResources.getDefaultFont().getFontData()[0].getHeight();
scrolled.getVerticalBar().setIncrement(height * 2);
scrolled.setExpandHorizontal(true);
scrolled.setExpandVertical(true);
control = new Composite(scrolled, SWT.NONE) {
@Override
public boolean setFocus() {
forceFocus();
return true;
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
updateSize(control);
}
}
};
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.horizontalSpacing = 0;
layout.verticalSpacing = 1;
control.setLayout(layout);
control.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
control.addControlListener(new ControlListener() {
public void controlMoved(ControlEvent e) {
updateVisibleItems();
}
public void controlResized(ControlEvent e) {
updateVisibleItems();
}
});
scrolled.setContent(control);
hookControl(control);
noEntryArea = new Composite(scrolled, SWT.NONE);
doCreateNoEntryArea(noEntryArea);
scrolled.setExpandHorizontal(true);
scrolled.setExpandVertical(true);
scrolled.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
updateSize(scrolled.getContent());
}
});
control.addTraverseListener(new TraverseListener() {
private boolean handleEvent = true;
public void keyTraversed(TraverseEvent event) {
if (!handleEvent) {
return;
}
switch (event.detail) {
case SWT.TRAVERSE_ARROW_PREVIOUS: {
Control[] children = control.getChildren();
if (children.length > 0) {
boolean selected = false;
for (int i = 0; i < children.length; i++) {
ControlListItem item = (ControlListItem) children[i];
if (item.isSelected()) {
selected = true;
if (i > 0) {
setSelection(new StructuredSelection(children[i - 1].getData()), true);
}
break;
}
}
if (!selected) {
setSelection(new StructuredSelection(children[children.length - 1].getData()), true);
}
}
break;
}
case SWT.TRAVERSE_ARROW_NEXT: {
Control[] children = control.getChildren();
if (children.length > 0) {
boolean selected = false;
for (int i = 0; i < children.length; i++) {
ControlListItem item = (ControlListItem) children[i];
if (item.isSelected()) {
selected = true;
if (i < children.length - 1) {
setSelection(new StructuredSelection(children[i + 1].getData()), true);
}
break;
}
}
if (!selected) {
setSelection(new StructuredSelection(children[0].getData()), true);
}
}
break;
}
default:
handleEvent = false;
event.doit = true;
Control control = ControlListViewer.this.control;
Shell shell = control.getShell();
while (control != null) {
if (control.traverse(event.detail)) {
break;
}
if (!event.doit || control == shell) {
break;
}
control = control.getParent();
}
handleEvent = true;
break;
}
}
});
}
protected void doCreateNoEntryArea(Composite parent) {
}
public void add(Object[] elements) {
ViewerComparator sorter = getComparator();
// Use a Set in case we are getting something added that exists
Set<Object> newItems = new HashSet<Object>(elements.length);
Control[] existingChildren = control.getChildren();
for (Control element : existingChildren) {
if (element.getData() != null) {
newItems.add(element.getData());
}
}
for (Object element : elements) {
if (element != null) {
newItems.add(element);
}
}
Object[] infos = new Object[newItems.size()];
newItems.toArray(infos);
if (sorter != null) {
sorter.sort(this, infos);
}
// Update with the new elements to prevent flash
for (Control element : existingChildren) {
((ControlListItem) element).dispose();
}
for (int i = 0; i < infos.length; i++) {
ControlListItem item = createNewItem(infos[i]);
item.updateColors(i);
}
control.layout(true);
doUpdateContent();
}
private void updateSize(Control control) {
if (control == null) {
return;
}
// XXX need a small offset in case the list has a scroll bar
Point size = control.computeSize(scrolled.getClientArea().width - 20, SWT.DEFAULT, true);
control.setSize(size);
scrolled.setMinSize(size);
}
protected void doUpdateContent() {
if (control.getChildren().length > 0) {
updateSize(control);
scrolled.setContent(control);
} else {
updateSize(noEntryArea);
scrolled.setContent(noEntryArea);
}
}
/**
* Create a new item for info.
*
* @param element
* @return ControlListItem
*/
private ControlListItem createNewItem(Object element) {
final ControlListItem item = doCreateItem(control, element);
// item.getChildren()[0].addPaintListener(new PaintListener() {
// public void paintControl(PaintEvent e) {
// if (hasFocus && item.isSelected()) {
// Point size = item.getSize();
// e.gc.setForeground(e.gc.getDevice().getSystemColor(SWT.COLOR_DARK_GRAY));
// e.gc.setLineDash(new int[] { 1, 2 });
// e.gc.drawRoundRectangle(0, 0, size.x - 1, size.y - 1, 5, 5);
// }
// }
// });
item.setIndexListener(new ControlListItem.IndexListener() {
public void selectNext() {
Control[] children = control.getChildren();
for (int i = 0; i < children.length; i++) {
if (item == children[i]) {
if (i < children.length - 1) {
setSelection(new StructuredSelection(children[i + 1].getData()));
}
break;
}
}
}
public void selectPrevious() {
Control[] children = control.getChildren();
for (int i = 0; i < children.length; i++) {
if (item == children[i]) {
if (i > 0) {
setSelection(new StructuredSelection(children[i - 1].getData()));
}
break;
}
}
}
public void select() {
setSelection(new StructuredSelection(item.getData()));
setFocus();
}
public void open() {
handleOpen();
}
});
// Refresh to populate with the current tasks
item.refresh();
return item;
}
protected abstract ControlListItem doCreateItem(Composite parent, Object element);
@Override
protected ControlListItem doFindInputItem(Object element) {
return null;
}
@Override
protected ControlListItem doFindItem(Object element) {
Control[] children = control.getChildren();
for (Control child : children) {
if (child.isDisposed() || child.getData() == null) {
continue;
}
if (child.getData().equals(element)) {
return (ControlListItem) child;
}
}
return null;
}
@Override
protected void doUpdateItem(Widget item, Object element, boolean fullMap) {
if (usingElementMap()) {
unmapElement(item);
}
item.dispose();
add(new Object[] { element });
}
@Override
public ScrolledComposite getControl() {
return scrolled;
}
@Override
protected List<?> getSelectionFromWidget() {
Control[] children = control.getChildren();
ArrayList<Object> selection = new ArrayList<Object>(children.length);
for (Control child : children) {
ControlListItem item = (ControlListItem) child;
if (item.isSelected() && item.getData() != null) {
selection.add(item.getData());
}
}
return selection;
}
protected void handleOpen() {
Control control = getControl();
if (control != null && !control.isDisposed()) {
ISelection selection = getSelection();
fireOpen(new OpenEvent(this, selection));
}
}
@Override
protected void inputChanged(Object input, Object oldInput) {
super.inputChanged(input, oldInput);
refreshAll();
doUpdateContent();
}
@Override
protected void internalRefresh(Object element) {
if (element == null) {
return;
}
if (element.equals(getRoot())) {
refreshAll();
return;
}
Widget widget = findItem(element);
if (widget == null) {
add(new Object[] { element });
return;
}
((ControlListItem) widget).refresh();
updateSize(control);
}
public void remove(Object[] elements) {
for (Object element : elements) {
Widget item = doFindItem(element);
if (item != null) {
unmapElement(element);
item.dispose();
}
}
Control[] existingChildren = control.getChildren();
for (int i = 0; i < existingChildren.length; i++) {
ControlListItem item = (ControlListItem) existingChildren[i];
item.updateColors(i);
}
control.layout(true);
doUpdateContent();
}
@Override
public void reveal(Object element) {
Control control = doFindItem(element);
if (control != null) {
revealControl(control);
}
}
private void revealControl(Control control) {
Rectangle clientArea = scrolled.getClientArea();
Point origin = scrolled.getOrigin();
Point location = control.getLocation();
Point size = control.getSize();
if (location.y + size.y > origin.y + clientArea.height) {
scrolled.setOrigin(origin.x, location.y + size.y - clientArea.height);
}
if (location.y < origin.y) {
scrolled.setOrigin(origin.x, location.y);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
protected void setSelectionToWidget(List list, boolean reveal) {
HashSet<Object> elements = new HashSet<Object>(list);
Control[] children = control.getChildren();
for (Control control : children) {
ControlListItem child = (ControlListItem) control;
boolean selected = elements.contains(child.getData());
if (selected != child.isSelected()) {
child.setSelected(selected);
}
if (reveal && selected) {
revealControl(child);
reveal = false;
}
}
}
/**
* Set focus on the current selection.
*/
public void setFocus() {
Control[] children = control.getChildren();
if (children.length > 0) {
// causes the item's tool bar to get focus when clicked which is undesirable
// for (Control element : children) {
// ControlListItem item = (ControlListItem) element;
// if (item.isSelected()) {
// if (item.setFocus()) {
// return;
// }
// }
// }
control.forceFocus();
} else {
noEntryArea.setFocus();
}
}
/**
* Refresh everything as the root is being refreshed.
*/
private void refreshAll() {
Object[] infos = getSortedChildren(getRoot());
Control[] existingChildren = control.getChildren();
for (Control element : existingChildren) {
element.dispose();
}
for (int i = 0; i < infos.length; i++) {
ControlListItem item = createNewItem(infos[i]);
item.updateColors(i);
}
control.layout(true);
doUpdateContent();
}
/**
* Set the virtual items to be visible or not depending on the displayed area.
*/
private void updateVisibleItems() {
Control[] children = control.getChildren();
int top = scrolled.getOrigin().y;
int bottom = top + scrolled.getParent().getBounds().height;
for (Control element : children) {
ControlListItem item = (ControlListItem) element;
item.setDisplayed(top, bottom);
}
}
}
diff --git a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/GradientColors.java b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/GradientColors.java
index 977fdf83..6efe23f7 100644
--- a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/GradientColors.java
+++ b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/commons/ui/GradientColors.java
@@ -1,186 +1,187 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Benjamin Pasero - initial API and implementation
* Tasktop Technologies - improvements
*******************************************************************************/
package org.eclipse.mylyn.commons.ui;
import org.eclipse.jface.resource.DeviceResourceException;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
/**
* Based on FormColors of UI Forms.
*
* @author Benjamin Pasero (initial contribution from RSSOwl, see bug 177974)
* @author Mik Kersten
+ * @since 3.7
*/
public class GradientColors {
private final Display display;
private Color titleText;
private Color gradientBegin;
private Color gradientEnd;
private Color border;
private final ResourceManager resourceManager;
public GradientColors(Display display, ResourceManager resourceManager) {
this.display = display;
this.resourceManager = resourceManager;
createColors();
}
private void createColors() {
createBorderColor();
createGradientColors();
// previously used SWT.COLOR_TITLE_INACTIVE_FOREGROUND, but too light on Windows XP
titleText = getColor(resourceManager, getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
}
public Color getGradientBegin() {
return gradientBegin;
}
public Color getGradientEnd() {
return gradientEnd;
}
public Color getBorder() {
return border;
}
public Color getTitleText() {
return titleText;
}
private void createBorderColor() {
RGB tbBorder = getSystemColor(SWT.COLOR_TITLE_BACKGROUND);
RGB bg = getImpliedBackground().getRGB();
// Group 1
// Rule: If at least 2 of the RGB values are equal to or between 180 and
// 255, then apply specified opacity for Group 1
// Examples: Vista, XP Silver, Wn High Con #2
// Keyline = TITLE_BACKGROUND @ 70% Opacity over LIST_BACKGROUND
if (testTwoPrimaryColors(tbBorder, 179, 256)) {
tbBorder = blend(tbBorder, bg, 70);
} else if (testTwoPrimaryColors(tbBorder, 120, 180)) {
tbBorder = blend(tbBorder, bg, 50);
} else {
tbBorder = blend(tbBorder, bg, 30);
}
border = getColor(resourceManager, tbBorder);
}
private void createGradientColors() {
RGB titleBg = getSystemColor(SWT.COLOR_TITLE_BACKGROUND);
Color bgColor = getImpliedBackground();
RGB bg = bgColor.getRGB();
RGB bottom, top;
// Group 1
// Rule: If at least 2 of the RGB values are equal to or between 180 and
// 255, then apply specified opacity for Group 1
// Examples: Vista, XP Silver, Wn High Con #2
// Gradient Bottom = TITLE_BACKGROUND @ 30% Opacity over LIST_BACKGROUND
// Gradient Top = TITLE BACKGROUND @ 0% Opacity over LIST_BACKGROUND
if (testTwoPrimaryColors(titleBg, 179, 256)) {
bottom = blend(titleBg, bg, 30);
top = bg;
}
// Group 2
// Rule: If at least 2 of the RGB values are equal to or between 121 and
// 179, then apply specified opacity for Group 2
// Examples: XP Olive, OSX Graphite, Linux GTK, Wn High Con Black
// Gradient Bottom = TITLE_BACKGROUND @ 20% Opacity over LIST_BACKGROUND
// Gradient Top = TITLE BACKGROUND @ 0% Opacity over LIST_BACKGROUND
else if (testTwoPrimaryColors(titleBg, 120, 180)) {
bottom = blend(titleBg, bg, 20);
top = bg;
}
// Group 3
// Rule: If at least 2 of the RGB values are equal to or between 0 and
// 120, then apply specified opacity for Group 3
// Examples: XP Default, Wn Classic Standard, Wn Marine, Wn Plum, OSX
// Aqua, Wn High Con White, Wn High Con #1
// Gradient Bottom = TITLE_BACKGROUND @ 10% Opacity over LIST_BACKGROUND
// Gradient Top = TITLE BACKGROUND @ 0% Opacity over LIST_BACKGROUND
else {
bottom = blend(titleBg, bg, 10);
top = bg;
}
gradientBegin = getColor(resourceManager, top);
gradientEnd = getColor(resourceManager, bottom);
}
private RGB blend(RGB c1, RGB c2, int ratio) {
int r = blend(c1.red, c2.red, ratio);
int g = blend(c1.green, c2.green, ratio);
int b = blend(c1.blue, c2.blue, ratio);
return new RGB(r, g, b);
}
private int blend(int v1, int v2, int ratio) {
int b = (ratio * v1 + (100 - ratio) * v2) / 100;
return Math.min(255, b);
}
private boolean testTwoPrimaryColors(RGB rgb, int from, int to) {
int total = 0;
if (testPrimaryColor(rgb.red, from, to)) {
total++;
}
if (testPrimaryColor(rgb.green, from, to)) {
total++;
}
if (testPrimaryColor(rgb.blue, from, to)) {
total++;
}
return total >= 2;
}
private boolean testPrimaryColor(int value, int from, int to) {
return value > from && value < to;
}
private RGB getSystemColor(int code) {
return getDisplay().getSystemColor(code).getRGB();
}
private Color getImpliedBackground() {
return display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
}
private Display getDisplay() {
return display;
}
private Color getColor(ResourceManager manager, RGB rgb) {
try {
return manager.createColor(rgb);
} catch (DeviceResourceException e) {
return manager.getDevice().getSystemColor(SWT.COLOR_BLACK);
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/org/esa/beam/atmosphere/operator/GlintCorrectionOperator.java b/src/main/java/org/esa/beam/atmosphere/operator/GlintCorrectionOperator.java
index 1770ae1..75e9de5 100644
--- a/src/main/java/org/esa/beam/atmosphere/operator/GlintCorrectionOperator.java
+++ b/src/main/java/org/esa/beam/atmosphere/operator/GlintCorrectionOperator.java
@@ -1,865 +1,865 @@
package org.esa.beam.atmosphere.operator;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.beam.PixelData;
import org.esa.beam.collocation.CollocateOp;
import org.esa.beam.dataio.envisat.EnvisatConstants;
import org.esa.beam.framework.datamodel.Band;
import org.esa.beam.framework.datamodel.FlagCoding;
import org.esa.beam.framework.datamodel.GeoPos;
import org.esa.beam.framework.datamodel.Mask;
import org.esa.beam.framework.datamodel.MetadataAttribute;
import org.esa.beam.framework.datamodel.PixelPos;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductData;
import org.esa.beam.framework.datamodel.ProductNodeGroup;
import org.esa.beam.framework.datamodel.RasterDataNode;
import org.esa.beam.framework.gpf.GPF;
import org.esa.beam.framework.gpf.Operator;
import org.esa.beam.framework.gpf.OperatorException;
import org.esa.beam.framework.gpf.OperatorSpi;
import org.esa.beam.framework.gpf.Tile;
import org.esa.beam.framework.gpf.annotations.OperatorMetadata;
import org.esa.beam.framework.gpf.annotations.Parameter;
import org.esa.beam.framework.gpf.annotations.SourceProduct;
import org.esa.beam.framework.gpf.annotations.TargetProduct;
import org.esa.beam.glint.operators.FlintOp;
import org.esa.beam.meris.radiometry.smilecorr.SmileCorrectionAuxdata;
import org.esa.beam.nn.NNffbpAlphaTabFast;
import org.esa.beam.util.ProductUtils;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.image.Raster;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.esa.beam.dataio.envisat.EnvisatConstants.*;
/**
* Main operator for the AGC Glint correction.
*
* @author Marco Peters, Olaf Danne
* @version $Revision: 2703 $ $Date: 2010-01-21 13:51:07 +0100 (Do, 21 Jan 2010) $
*/
@SuppressWarnings({"InstanceVariableMayNotBeInitialized", "MismatchedReadAndWriteOfArray"})
@OperatorMetadata(alias = "Meris.GlintCorrection",
version = "1.2.2",
authors = "Marco Peters, Roland Doerffer, Olaf Danne",
copyright = "(c) 2008 by Brockmann Consult",
description = "MERIS atmospheric correction using a neural net.")
public class GlintCorrectionOperator extends Operator {
public static final String GLINT_CORRECTION_VERSION = "1.2.2";
private static final String AGC_FLAG_BAND_NAME = "agc_flags";
private static final String RADIANCE_MERIS_BAND_NAME = "result_radiance_rr89";
private static final String VALID_EXPRESSION = String.format("!%s.INVALID", AGC_FLAG_BAND_NAME);
private static final String MERIS_ATMOSPHERIC_NET_NAME = "atmo_correct_meris/20x25x45_55990.1.net";
private static final String FLINT_ATMOSPHERIC_NET_NAME = "atmo_correct_flint/25x30x40_6936.3.net";
private static final String NORMALIZATION_NET_NAME = "atmo_normalization/90_2.8.net";
private static final String ATMO_AANN_NET = "atmo_aann/12x5x12_318.4.net";
private static final String[] REQUIRED_MERIS_TPG_NAMES = {
MERIS_SUN_ZENITH_DS_NAME,
MERIS_SUN_AZIMUTH_DS_NAME,
MERIS_VIEW_ZENITH_DS_NAME,
MERIS_VIEW_AZIMUTH_DS_NAME,
MERIS_DEM_ALTITUDE_DS_NAME,
"atm_press",
"ozone",
};
private static final String[] REQUIRED_AATSR_TPG_NAMES = AATSR_TIE_POINT_GRID_NAMES;
private static final String ANG_443_865 = "ang_443_865";
private static final String TAU_550 = "tau_550";
private static final String TAU_778 = "tau_778";
private static final String TAU_865 = "tau_865";
private static final String GLINT_RATIO = "glint_ratio";
private static final String FLINT_VALUE = "flint_value";
private static final String BTSM = "b_tsm";
private static final String ATOT = "a_tot";
private static final String[] TOSA_REFLEC_BAND_NAMES = {
"tosa_reflec_1", "tosa_reflec_2", "tosa_reflec_3", "tosa_reflec_4", "tosa_reflec_5",
"tosa_reflec_6", "tosa_reflec_7", "tosa_reflec_8", "tosa_reflec_9", "tosa_reflec_10",
null,
"tosa_reflec_12", "tosa_reflec_13",
null, null
};
private static final String[] AUTO_TOSA_REFLEC_BAND_NAMES = {
"tosa_reflec_auto_1", "tosa_reflec_auto_2", "tosa_reflec_auto_3", "tosa_reflec_auto_4",
"tosa_reflec_auto_5", "tosa_reflec_auto_6", "tosa_reflec_auto_7", "tosa_reflec_auto_8",
"tosa_reflec_auto_9", "tosa_reflec_auto_10",
null,
"tosa_reflec_auto_12", "tosa_reflec_auto_13",
null, null
};
private static final String TOSA_QUALITY_INDICATOR_BAND_NAME = "tosa_quality_indicator";
private static final String[] REFLEC_BAND_NAMES = {
"reflec_1", "reflec_2", "reflec_3", "reflec_4", "reflec_5",
"reflec_6", "reflec_7", "reflec_8", "reflec_9", "reflec_10",
null,
"reflec_12", "reflec_13",
null, null
};
private static final String[] NORM_REFLEC_BAND_NAMES = {
"norm_refl_1", "norm_refl_2", "norm_refl_3", "norm_refl_4", "norm_refl_5",
"norm_refl_6", "norm_refl_7", "norm_refl_8", "norm_refl_9", "norm_refl_10",
null,
"norm_refl_12", "norm_refl_13",
null, null
};
private static final String[] PATH_BAND_NAMES = {
"path_1", "path_2", "path_3", "path_4", "path_5",
"path_6", "path_7", "path_8", "path_9", "path_10",
null,
"path_12", "path_13",
null, null
};
private static final String[] TRANS_BAND_NAMES = {
"trans_1", "trans_2", "trans_3", "trans_4", "trans_5",
"trans_6", "trans_7", "trans_8", "trans_9", "trans_10",
null,
"trans_12", "trans_13",
null, null
};
@SourceProduct(label = "MERIS L1b input product", description = "The MERIS L1b input product.")
private Product merisProduct;
@SourceProduct(label = "AATSR L1b input product", description = "The AATSR L1b input product.",
optional = true)
private Product aatsrProduct;
private Product flintProduct;
@TargetProduct(description = "The atmospheric corrected output product.")
private Product targetProduct;
@Parameter(defaultValue = "false",
label = "Perform Smile-effect correction",
description = "Whether to perform Smile-effect correction.")
private boolean doSmileCorrection;
@Parameter(defaultValue = "true", label = "Output TOSA reflectance",
description = "Toggles the output of Top of Standard Atmosphere reflectance.")
private boolean outputTosa;
@Parameter(defaultValue = "false", label = "Output TOSA reflectance of auto assoc. neural net",
description = "Toggles the output of Top of Standard Atmosphere reflectance calculated by an auto associative neural net.")
private boolean outputAutoTosa;
@Parameter(defaultValue = "false",
label = "Output normalised bidirectional reflectances",
description = "Toggles the output of normalised reflectances.")
private boolean outputNormReflec;
@Parameter(defaultValue = "true", label = "Output water leaving reflectance",
description = "Toggles the output of water leaving reflectance.")
private boolean outputReflec;
@Parameter(defaultValue = "RADIANCE_REFLECTANCES", valueSet = {"RADIANCE_REFLECTANCES", "IRRADIANCE_REFLECTANCES"},
label = "Output water leaving reflectance as",
description = "Select if reflectances shall be written as radiances or irradiances. " +
"The irradiances are compatible with standard MERIS product.")
private ReflectanceEnum outputReflecAs;
@Parameter(defaultValue = "true", label = "Output path reflectance",
description = "Toggles the output of water leaving path reflectance.")
private boolean outputPath;
@Parameter(defaultValue = "true", label = "Output transmittance",
description = "Toggles the output of downwelling irradiance transmittance.")
private boolean outputTransmittance;
@Parameter(defaultValue = "false",
label = "Derive water leaving reflectance from path reflectance",
description = "Switch between computation of water leaving reflectance from path reflectance and direct use of neural net output.")
private boolean deriveRwFromPath;
@Parameter(defaultValue = "toa_reflec_10 > toa_reflec_6 AND toa_reflec_13 > 0.0475",
label = "Land detection expression",
description = "The arithmetic expression used for land detection.",
notEmpty = true, notNull = true)
private String landExpression;
@Parameter(defaultValue = "toa_reflec_14 > 0.2",
label = "Cloud/Ice detection expression",
description = "The arithmetic expression used for cloud/ice detection.",
notEmpty = true, notNull = true)
private String cloudIceExpression;
@Parameter(label = "MERIS net (full path required for other than default)",
defaultValue = MERIS_ATMOSPHERIC_NET_NAME,
description = "The file of the atmospheric net to be used instead of the default neural net.",
notNull = false)
private File atmoNetMerisFile;
@Parameter(defaultValue = "false", label = "Use FLINT value in neural net (requires AATSR L1b source product)",
description = "Toggles the usage of a FLINT value in neural net.")
private boolean useFlint;
@Parameter(label = "FLINT net (full path required for other than default)",
defaultValue = FLINT_ATMOSPHERIC_NET_NAME,
description = "The file of the atmospheric net to be used instead of the default neural net.",
notNull = false)
private File atmoNetFlintFile;
private Band validationBand;
public static final double NO_FLINT_VALUE = -1.0;
private String merisNeuralNetString;
private String flintNeuralNetString;
private String normalizationNeuralNetString;
private String atmoAaNeuralNetString;
private SmileCorrectionAuxdata smileAuxData;
private RasterDataNode l1FlagsNode;
private RasterDataNode solzenNode;
private RasterDataNode solaziNode;
private RasterDataNode satzenNode;
private RasterDataNode sataziNode;
private RasterDataNode detectorNode;
private RasterDataNode altitudeNode;
private RasterDataNode pressureNode;
private RasterDataNode ozoneNode;
private Band[] spectralNodes;
private int nadirColumnIndex;
private boolean isFullResolution;
@Override
public void initialize() throws OperatorException {
validateMerisProduct(merisProduct);
if (useFlint && aatsrProduct == null) {
throw new OperatorException("Missing required AATSR L1b product for FLINT computation.");
}
validateAatsrProduct(aatsrProduct);
if (useFlint && aatsrProduct != null) {
// create collocation product...
Map<String, Product> collocateInput = new HashMap<String, Product>(2);
collocateInput.put("masterProduct", merisProduct);
collocateInput.put("slaveProduct", aatsrProduct);
Product collocateProduct =
GPF.createProduct(OperatorSpi.getOperatorAlias(CollocateOp.class), GPF.NO_PARAMS, collocateInput);
// create FLINT product
Map<String, Product> flintInput = new HashMap<String, Product>(1);
flintInput.put("l1bCollocate", collocateProduct);
Map<String, Object> flintParameters = new HashMap<String, Object>();
flintProduct = GPF.createProduct(OperatorSpi.getOperatorAlias(FlintOp.class), flintParameters, flintInput);
validateFlintProduct(flintProduct);
}
l1FlagsNode = merisProduct.getRasterDataNode(MERIS_L1B_FLAGS_DS_NAME);
solzenNode = merisProduct.getRasterDataNode(MERIS_SUN_ZENITH_DS_NAME);
solaziNode = merisProduct.getRasterDataNode(MERIS_SUN_AZIMUTH_DS_NAME);
satzenNode = merisProduct.getRasterDataNode(MERIS_VIEW_ZENITH_DS_NAME);
sataziNode = merisProduct.getRasterDataNode(MERIS_VIEW_AZIMUTH_DS_NAME);
detectorNode = merisProduct.getRasterDataNode(MERIS_DETECTOR_INDEX_DS_NAME);
altitudeNode = merisProduct.getRasterDataNode(MERIS_DEM_ALTITUDE_DS_NAME);
pressureNode = merisProduct.getRasterDataNode("atm_press");
ozoneNode = merisProduct.getRasterDataNode("ozone");
spectralNodes = new Band[MERIS_L1B_SPECTRAL_BAND_NAMES.length];
for (int i = 0; i < MERIS_L1B_SPECTRAL_BAND_NAMES.length; i++) {
spectralNodes[i] = merisProduct.getBand(MERIS_L1B_SPECTRAL_BAND_NAMES[i]);
}
final int rasterHeight = merisProduct.getSceneRasterHeight();
final int rasterWidth = merisProduct.getSceneRasterWidth();
Product outputProduct = new Product(merisProduct.getName() + "_AC", "MERIS_L2_AC", rasterWidth, rasterHeight);
outputProduct.setStartTime(merisProduct.getStartTime());
outputProduct.setEndTime(merisProduct.getEndTime());
ProductUtils.copyMetadata(merisProduct, outputProduct);
ProductUtils.copyTiePointGrids(merisProduct, outputProduct);
ProductUtils.copyGeoCoding(merisProduct, outputProduct);
// copy altitude band if it exists and 'beam.envisat.usePixelGeoCoding' is set to true
if (Boolean.getBoolean("beam.envisat.usePixelGeoCoding") &&
merisProduct.containsBand(EnvisatConstants.MERIS_AMORGOS_L1B_ALTIUDE_BAND_NAME)) {
copyBandWithImage(outputProduct, EnvisatConstants.MERIS_AMORGOS_L1B_ALTIUDE_BAND_NAME);
}
setTargetProduct(outputProduct);
addTargetBands(outputProduct);
Band agcFlagsBand = outputProduct.addBand(AGC_FLAG_BAND_NAME, ProductData.TYPE_UINT16);
final FlagCoding agcFlagCoding = createAgcFlagCoding();
agcFlagsBand.setSampleCoding(agcFlagCoding);
outputProduct.getFlagCodingGroup().add(agcFlagCoding);
addAgcMasks(outputProduct);
final ToaReflectanceValidationOp validationOp = ToaReflectanceValidationOp.create(merisProduct,
landExpression,
cloudIceExpression);
validationBand = validationOp.getTargetProduct().getBandAt(0);
InputStream merisNeuralNetStream = getNeuralNetStream(MERIS_ATMOSPHERIC_NET_NAME, atmoNetMerisFile);
merisNeuralNetString = readNeuralNetFromStream(merisNeuralNetStream);
if (useFlint && aatsrProduct != null) {
InputStream neuralNetStream = getNeuralNetStream(FLINT_ATMOSPHERIC_NET_NAME, atmoNetFlintFile);
flintNeuralNetString = readNeuralNetFromStream(neuralNetStream);
}
if (outputNormReflec) {
final InputStream neuralNetStream = getClass().getResourceAsStream(NORMALIZATION_NET_NAME);
normalizationNeuralNetString = readNeuralNetFromStream(neuralNetStream);
}
final InputStream neuralNetStream = getClass().getResourceAsStream(ATMO_AANN_NET);
atmoAaNeuralNetString = readNeuralNetFromStream(neuralNetStream);
if (doSmileCorrection) {
try {
smileAuxData = SmileCorrectionAuxdata.loadAuxdata(merisProduct.getProductType());
} catch (IOException e) {
throw new OperatorException("Not able to load auxiliary data for SMILE correction.", e);
}
}
nadirColumnIndex = MerisFlightDirection.findNadirColumnIndex(merisProduct);
isFullResolution = isProductMerisFullResoultion(merisProduct);
ProductUtils.copyFlagBands(merisProduct, outputProduct);
for (Band srcBand : merisProduct.getBands()) {
if (srcBand.getFlagCoding() != null) {
Band targetBand = outputProduct.getBand(srcBand.getName());
targetBand.setSourceImage(srcBand.getSourceImage());
}
}
// copy detector index band
if (merisProduct.containsBand(EnvisatConstants.MERIS_DETECTOR_INDEX_DS_NAME)) {
copyBandWithImage(outputProduct, EnvisatConstants.MERIS_DETECTOR_INDEX_DS_NAME);
}
setTargetProduct(outputProduct);
}
@Override
public void computeTileStack(Map<Band, Tile> targetTiles, Rectangle targetRectangle, ProgressMonitor pm) throws
OperatorException {
pm.beginTask("Correcting atmosphere...", targetRectangle.height);
try {
final Map<String, ProductData> merisSampleDataMap = preLoadMerisSources(targetRectangle);
final Map<String, ProductData> targetSampleDataMap = getTargetSampleData(targetTiles);
NNffbpAlphaTabFast normalizationNet = null;
if (outputNormReflec) {
normalizationNet = new NNffbpAlphaTabFast(normalizationNeuralNetString);
}
NNffbpAlphaTabFast autoAssocNet = new NNffbpAlphaTabFast(atmoAaNeuralNetString);
GlintCorrection merisGlintCorrection = new GlintCorrection(new NNffbpAlphaTabFast(merisNeuralNetString),
smileAuxData, normalizationNet, autoAssocNet,
outputReflecAs);
GlintCorrection aatsrFlintCorrection = null;
if (useFlint && flintProduct != null) {
aatsrFlintCorrection = new GlintCorrection(new NNffbpAlphaTabFast(flintNeuralNetString), smileAuxData,
normalizationNet, autoAssocNet, outputReflecAs);
}
for (int y = 0; y < targetRectangle.getHeight(); y++) {
checkForCancellation();
final int lineIndex = y * targetRectangle.width;
final int pixelY = targetRectangle.y + y;
for (int x = 0; x < targetRectangle.getWidth(); x++) {
final int pixelIndex = lineIndex + x;
final PixelData inputData = loadMerisPixelData(merisSampleDataMap, pixelIndex);
final int pixelX = targetRectangle.x + x;
inputData.flintValue = getFlintValue(pixelX, pixelY);
inputData.pixelX = pixelX;
inputData.pixelY = pixelY;
GlintResult glintResult;
if (aatsrFlintCorrection != null && GlintCorrection.isFlintValueValid(inputData.flintValue)) {
glintResult = aatsrFlintCorrection.perform(inputData, deriveRwFromPath);
glintResult.raiseFlag(GlintCorrection.HAS_FLINT);
} else {
glintResult = merisGlintCorrection.perform(inputData, deriveRwFromPath);
}
fillTargetSampleData(targetSampleDataMap, pixelIndex, inputData, glintResult);
}
pm.worked(1);
}
commitSampleData(targetSampleDataMap, targetTiles);
} catch (Exception e) {
e.printStackTrace();
throw new OperatorException(e);
} finally {
pm.done();
}
}
private void copyBandWithImage(Product outputProduct, String bandName) {
Band targetBand = ProductUtils.copyBand(bandName, merisProduct, outputProduct);
Band sourceBand = merisProduct.getBand(bandName);
targetBand.setSourceImage(sourceBand.getSourceImage());
}
private static boolean isProductMerisFullResoultion(final Product product) {
final String productType = product.getProductType();
return productType.contains("FR") || productType.contains("FSG");
}
private double getFlintValue(int pixelX, int pixelY) {
if (flintProduct == null) {
return NO_FLINT_VALUE;
}
GeoPos geoPos = targetProduct.getGeoCoding().getGeoPos(new PixelPos(pixelX + 0.5f, pixelY + 0.5f), null);
PixelPos pixelPos = flintProduct.getGeoCoding().getPixelPos(geoPos, null);
if (!pixelPos.isValid() || pixelPos.x < 0.0f || pixelPos.y < 0.0f) {
return NO_FLINT_VALUE;
}
Band flintBand = flintProduct.getBand(RADIANCE_MERIS_BAND_NAME);
Rectangle rect = new Rectangle((int) Math.floor(pixelPos.x), (int) Math.floor(pixelPos.y), 1, 1);
Raster data = flintBand.getGeophysicalImage().getData(rect);
if (!flintBand.isPixelValid(rect.x, rect.y)) {
return NO_FLINT_VALUE;
}
return data.getSampleDouble(rect.x, rect.y, 0);
}
private static Map<String, ProductData> getTargetSampleData(Map<Band, Tile> targetTiles) {
final Map<String, ProductData> map = new HashMap<String, ProductData>(targetTiles.size());
for (Map.Entry<Band, Tile> bandTileEntry : targetTiles.entrySet()) {
final Band band = bandTileEntry.getKey();
final Tile tile = bandTileEntry.getValue();
map.put(band.getName(), tile.getRawSamples());
}
return map;
}
private static void commitSampleData(Map<String, ProductData> sampleDataMap, Map<Band, Tile> targetTiles) {
for (Map.Entry<Band, Tile> bandTileEntry : targetTiles.entrySet()) {
final Band band = bandTileEntry.getKey();
final Tile tile = bandTileEntry.getValue();
tile.setRawSamples(sampleDataMap.get(band.getName()));
}
}
private void fillTargetSampleData(Map<String, ProductData> targetSampleData, int pixelIndex, PixelData inputData,
GlintResult glintResult) {
final ProductData agcFlagTile = targetSampleData.get(AGC_FLAG_BAND_NAME);
agcFlagTile.setElemIntAt(pixelIndex, glintResult.getFlag());
final ProductData angTile = targetSampleData.get(ANG_443_865);
angTile.setElemDoubleAt(pixelIndex, glintResult.getAngstrom());
final ProductData tau550Tile = targetSampleData.get(TAU_550);
tau550Tile.setElemDoubleAt(pixelIndex, glintResult.getTau550());
final ProductData tau778Tile = targetSampleData.get(TAU_778);
tau778Tile.setElemDoubleAt(pixelIndex, glintResult.getTau778());
final ProductData tau865Tile = targetSampleData.get(TAU_865);
tau865Tile.setElemDoubleAt(pixelIndex, glintResult.getTau865());
if (flintProduct == null) {
// glint ratio available as output only for 'non-flint' case (RD, 28.10.09)
final ProductData glintTile = targetSampleData.get(GLINT_RATIO);
glintTile.setElemDoubleAt(pixelIndex, glintResult.getGlintRatio());
} else {
final ProductData flintTile = targetSampleData.get(FLINT_VALUE);
flintTile.setElemDoubleAt(pixelIndex, inputData.flintValue);
}
final ProductData btsmTile = targetSampleData.get(BTSM);
btsmTile.setElemDoubleAt(pixelIndex, glintResult.getBtsm());
final ProductData atotTile = targetSampleData.get(ATOT);
atotTile.setElemDoubleAt(pixelIndex, glintResult.getAtot());
if (outputTosa) {
fillTargetSample(TOSA_REFLEC_BAND_NAMES, pixelIndex, targetSampleData, glintResult.getTosaReflec());
final ProductData quality = targetSampleData.get(TOSA_QUALITY_INDICATOR_BAND_NAME);
quality.setElemDoubleAt(pixelIndex, glintResult.getTosaQualityIndicator());
}
if (outputAutoTosa) {
fillTargetSample(AUTO_TOSA_REFLEC_BAND_NAMES, pixelIndex, targetSampleData,
glintResult.getAutoTosaReflec());
}
if (outputReflec) {
fillTargetSample(REFLEC_BAND_NAMES, pixelIndex, targetSampleData, glintResult.getReflec());
}
if (outputNormReflec) {
fillTargetSample(NORM_REFLEC_BAND_NAMES, pixelIndex, targetSampleData, glintResult.getNormReflec());
}
if (outputPath) {
fillTargetSample(PATH_BAND_NAMES, pixelIndex, targetSampleData, glintResult.getPath());
}
if (outputTransmittance) {
fillTargetSample(TRANS_BAND_NAMES, pixelIndex, targetSampleData, glintResult.getTrans());
}
}
private void fillTargetSample(String[] bandNames, int pixelIndex,
Map<String, ProductData> targetData, double[] values) {
for (int i = 0; i < bandNames.length; i++) {
final String bandName = bandNames[i];
if (bandName != null) {
int bandIndex = i > 10 ? i - 1 : i;
final ProductData tile = targetData.get(bandName);
tile.setElemDoubleAt(pixelIndex, values[bandIndex]);
}
}
}
private PixelData loadMerisPixelData(Map<String, ProductData> sourceTileMap, int index) {
final PixelData pixelData = new PixelData();
pixelData.isFullResolution = isFullResolution;
pixelData.nadirColumnIndex = nadirColumnIndex;
pixelData.validation = sourceTileMap.get(validationBand.getName()).getElemIntAt(index);
pixelData.l1Flag = sourceTileMap.get(MERIS_L1B_FLAGS_DS_NAME).getElemIntAt(index);
pixelData.detectorIndex = sourceTileMap.get(MERIS_DETECTOR_INDEX_DS_NAME).getElemIntAt(index);
pixelData.solzen = getScaledValue(sourceTileMap, solzenNode, index);
pixelData.solazi = getScaledValue(sourceTileMap, solaziNode, index);
pixelData.satzen = getScaledValue(sourceTileMap, satzenNode, index);
pixelData.satazi = getScaledValue(sourceTileMap, sataziNode, index);
pixelData.altitude = getScaledValue(sourceTileMap, altitudeNode, index);
pixelData.pressure = getScaledValue(sourceTileMap, pressureNode, index);
pixelData.ozone = getScaledValue(sourceTileMap, ozoneNode, index);
pixelData.toa_radiance = new double[spectralNodes.length];
pixelData.solar_flux = new double[spectralNodes.length];
for (int i = 0; i < spectralNodes.length; i++) {
final Band spectralNode = spectralNodes[i];
pixelData.toa_radiance[i] = getScaledValue(sourceTileMap, spectralNode, index);
pixelData.solar_flux[i] = spectralNode.getSolarFlux();
}
return pixelData;
}
private static double getScaledValue(Map<String, ProductData> sourceTileMap, RasterDataNode rasterDataNode,
int index) {
double rawValue = sourceTileMap.get(rasterDataNode.getName()).getElemFloatAt(index);
rawValue = rasterDataNode.scale(rawValue);
return rawValue;
}
private Map<String, ProductData> preLoadMerisSources(Rectangle targetRectangle) {
final Map<String, ProductData> map = new HashMap<String, ProductData>(27);
final Tile validationTile = getSourceTile(validationBand, targetRectangle);
map.put(validationBand.getName(), validationTile.getRawSamples());
final Tile l1FlagTile = getSourceTile(l1FlagsNode, targetRectangle);
map.put(l1FlagTile.getRasterDataNode().getName(), l1FlagTile.getRawSamples());
final Tile solzenTile = getSourceTile(solzenNode, targetRectangle);
map.put(solzenTile.getRasterDataNode().getName(), solzenTile.getRawSamples());
final Tile solaziTile = getSourceTile(solaziNode, targetRectangle);
map.put(solaziTile.getRasterDataNode().getName(), solaziTile.getRawSamples());
final Tile satzenTile = getSourceTile(satzenNode, targetRectangle);
map.put(satzenTile.getRasterDataNode().getName(), satzenTile.getRawSamples());
final Tile sataziTile = getSourceTile(sataziNode, targetRectangle);
map.put(sataziTile.getRasterDataNode().getName(), sataziTile.getRawSamples());
final Tile detectorTile = getSourceTile(detectorNode, targetRectangle);
map.put(detectorTile.getRasterDataNode().getName(), detectorTile.getRawSamples());
final Tile altitudeTile = getSourceTile(altitudeNode, targetRectangle);
map.put(altitudeTile.getRasterDataNode().getName(), altitudeTile.getRawSamples());
final Tile pressureTile = getSourceTile(pressureNode, targetRectangle);
map.put(pressureTile.getRasterDataNode().getName(), pressureTile.getRawSamples());
final Tile ozoneTile = getSourceTile(ozoneNode, targetRectangle);
map.put(ozoneTile.getRasterDataNode().getName(), ozoneTile.getRawSamples());
for (RasterDataNode spectralNode : spectralNodes) {
final Tile spectralTile = getSourceTile(spectralNode, targetRectangle);
map.put(spectralTile.getRasterDataNode().getName(), spectralTile.getRawSamples());
}
return map;
}
private static FlagCoding createAgcFlagCoding() {
final FlagCoding flagCoding = new FlagCoding(AGC_FLAG_BAND_NAME);
flagCoding.setDescription("Atmosphere Correction - Flag Coding");
addFlagAttribute(flagCoding, "LAND", "Land pixels", GlintCorrection.LAND);
addFlagAttribute(flagCoding, "CLOUD_ICE", "Cloud or ice pixels", GlintCorrection.CLOUD_ICE);
addFlagAttribute(flagCoding, "ATC_OOR", "Atmospheric correction out of range", GlintCorrection.ATC_OOR);
addFlagAttribute(flagCoding, "TOA_OOR", "TOA out of range", GlintCorrection.TOA_OOR);
addFlagAttribute(flagCoding, "TOSA_OOR", "TOSA out of range", GlintCorrection.TOSA_OOR);
addFlagAttribute(flagCoding, "SOLZEN", "Large solar zenith angle", GlintCorrection.SOLZEN);
addFlagAttribute(flagCoding, "ANCIL", "Missing/OOR auxiliary data", GlintCorrection.ANCIL);
addFlagAttribute(flagCoding, "SUNGLINT", "Risk of sun glint", GlintCorrection.SUNGLINT);
addFlagAttribute(flagCoding, "HAS_FLINT", "Flint value available (pixel covered by MERIS/AATSR)",
GlintCorrection.HAS_FLINT);
addFlagAttribute(flagCoding, "INVALID", "Invalid pixels (LAND || CLOUD_ICE || l1_flags.INVALID)",
GlintCorrection.INVALID);
return flagCoding;
}
private static void addFlagAttribute(FlagCoding flagCoding, String name, String description, int value) {
MetadataAttribute attribute = new MetadataAttribute(name, ProductData.TYPE_UINT16);
attribute.getData().setElemInt(value);
attribute.setDescription(description);
flagCoding.addAttribute(attribute);
}
private void addTargetBands(Product product) {
final List<String> groupList = new ArrayList<String>();
if (outputAutoTosa) {
groupList.add("tosa_reflec_auto");
}
if (outputTosa) {
addSpectralTargetBands(product, TOSA_REFLEC_BAND_NAMES, "TOSA Reflectance at {0} nm", "sr^-1");
groupList.add("tosa_reflec");
addNonSpectralTargetBand(product, TOSA_QUALITY_INDICATOR_BAND_NAME, "Input spectrum out of range check",
"dl");
}
if (outputAutoTosa) {
addSpectralTargetBands(product, AUTO_TOSA_REFLEC_BAND_NAMES, "TOSA Reflectance at {0} nm", "sr^-1");
}
if (outputReflec) {
String reflecType;
if (ReflectanceEnum.RADIANCE_REFLECTANCES.equals(outputReflecAs)) {
reflecType = "radiance";
} else {
reflecType = "irradiance";
}
String descriptionPattern = "Water leaving " + reflecType + " reflectance at {0} nm";
addSpectralTargetBands(product, REFLEC_BAND_NAMES, descriptionPattern, "sr^-1");
groupList.add("reflec");
}
if (outputNormReflec) {
String descriptionPattern = "Normalised water leaving radiance reflectance at {0} nm";
addSpectralTargetBands(product, NORM_REFLEC_BAND_NAMES, descriptionPattern, "sr^-1");
groupList.add("norm_refl");
}
if (outputPath) {
addSpectralTargetBands(product, PATH_BAND_NAMES, "Water leaving radiance reflectance path at {0} nm",
"dxd");
groupList.add("path");
}
if (outputTransmittance) {
addSpectralTargetBands(product, TRANS_BAND_NAMES,
"Downwelling irradiance transmittance (Ed_Boa/Ed_Tosa) at {0} nm", "dl");
groupList.add("trans");
}
final StringBuilder sb = new StringBuilder();
final Iterator<String> iterator = groupList.iterator();
while (iterator.hasNext()) {
sb.append(iterator.next());
if (iterator.hasNext()) {
sb.append(":");
}
}
product.setAutoGrouping(sb.toString());
addNonSpectralTargetBand(product, TAU_550, "Spectral aerosol optical depth at 550", "dl");
addNonSpectralTargetBand(product, TAU_778, "Spectral aerosol optical depth at 778", "dl");
addNonSpectralTargetBand(product, TAU_865, "Spectral aerosol optical depth at 865", "dl");
if (flintProduct == null) {
addNonSpectralTargetBand(product, GLINT_RATIO, "Glint ratio", "dl");
} else {
addNonSpectralTargetBand(product, FLINT_VALUE, "Flint value", "1/sr");
}
addNonSpectralTargetBand(product, BTSM, "Total suspended matter scattering", "m^-1");
addNonSpectralTargetBand(product, ATOT, "Absorption at 443 nm of all water constituents", "m^-1");
addNonSpectralTargetBand(product, ANG_443_865, "\"Aerosol Angstrom coefficient\"", "dl");
}
private Band addNonSpectralTargetBand(Product product, String name, String description, String unit) {
final Band band = product.addBand(name, ProductData.TYPE_FLOAT32);
band.setDescription(description);
band.setUnit(unit);
band.setValidPixelExpression(VALID_EXPRESSION);
return band;
}
private void addSpectralTargetBands(Product product, String[] bandNames, String descriptionPattern, String unit) {
for (int i = 0; i < MERIS_L1B_SPECTRAL_BAND_NAMES.length; i++) {
String bandName = bandNames[i];
if (bandName != null) {
final Band radBand = merisProduct.getBandAt(i);
final String descr = MessageFormat.format(descriptionPattern, radBand.getSpectralWavelength());
final Band band = addNonSpectralTargetBand(product, bandName, descr, unit);
ProductUtils.copySpectralBandProperties(radBand, band);
}
}
}
private static void addAgcMasks(Product product) {
final ProductNodeGroup<Mask> maskGroup = product.getMaskGroup();
maskGroup.add(createMask(product, "agc_land", "Land pixels", "agc_flags.LAND", Color.GREEN, 0.5f));
maskGroup.add(createMask(product, "cloud_ice", "Cloud or ice pixels", "agc_flags.CLOUD_ICE",
Color.WHITE, 0.5f));
maskGroup.add(createMask(product, "atc_oor", "Atmospheric correction out of range", "agc_flags.ATC_OOR",
Color.ORANGE, 0.5f));
maskGroup.add(createMask(product, "toa_oor", "TOA out of range", "agc_flags.TOA_OOR", Color.MAGENTA, 0.5f));
maskGroup.add(createMask(product, "tosa_oor", "TOSA out of range", "agc_flags.TOSA_OOR", Color.CYAN, 0.5f));
maskGroup.add(createMask(product, "solzen", "Large solar zenith angle", "agc_flags.SOLZEN", Color.PINK, 0.5f));
maskGroup.add(createMask(product, "ancil", "Missing/OOR auxiliary data", "agc_flags.ANCIL", Color.BLUE, 0.5f));
maskGroup.add(createMask(product, "sunglint", "Risk of sun glint", "agc_flags.SUNGLINT", Color.YELLOW, 0.5f));
maskGroup.add(createMask(product, "has_flint", "Flint value computed (AATSR covered)", "agc_flags.HAS_FLINT",
Color.RED, 0.5f));
maskGroup.add(createMask(product, "agc_invalid", "Invalid pixels (LAND || CLOUD_ICE || l1_flags.INVALID)",
"agc_flags.INVALID", Color.RED, 0.5f));
}
private static Mask createMask(Product product, String name, String description, String expression, Color color,
float transparency) {
return Mask.BandMathsType.create(name, description,
product.getSceneRasterWidth(), product.getSceneRasterHeight(),
expression, color, transparency);
}
private InputStream getNeuralNetStream(String resourceNetName, File neuralNetFile) {
InputStream neuralNetStream;
- if (neuralNetFile.getName().equals(resourceNetName)) {
+ if (resourceNetName.contains(neuralNetFile.getName())) {
neuralNetStream = getClass().getResourceAsStream(resourceNetName);
} else {
try {
neuralNetStream = new FileInputStream(neuralNetFile);
} catch (FileNotFoundException e) {
throw new OperatorException(e);
}
}
return neuralNetStream;
}
private String readNeuralNetFromStream(InputStream neuralNetStream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(neuralNetStream));
try {
String line = reader.readLine();
final StringBuilder sb = new StringBuilder();
while (line != null) {
// have to append line terminator, cause it's not included in line
sb.append(line).append('\n');
line = reader.readLine();
}
return sb.toString();
} catch (IOException ioe) {
throw new OperatorException("Could not initialize neural net", ioe);
} finally {
try {
reader.close();
} catch (IOException ignore) {
}
}
}
private static void validateMerisProduct(final Product merisProduct) {
final String missedBand = validateMerisProductBands(merisProduct);
if (!missedBand.isEmpty()) {
String message = MessageFormat.format("Missing required band in product {0}: {1}",
merisProduct.getName(), missedBand);
throw new OperatorException(message);
}
final String missedTPG = validateMerisProductTpgs(merisProduct);
if (!missedTPG.isEmpty()) {
String message = MessageFormat.format("Missing required raster in product {0}: {1}",
merisProduct.getName(), missedTPG);
throw new OperatorException(message);
}
}
private static void validateAatsrProduct(final Product aatsrProduct) {
if (aatsrProduct != null) {
final String missedBand = validateAatsrProductBands(aatsrProduct);
if (!missedBand.isEmpty()) {
String message = MessageFormat.format("Missing required band in product {0}: {1}",
aatsrProduct.getName(), missedBand);
throw new OperatorException(message);
}
final String missedTPG = validateAatsrProductTpgs(aatsrProduct);
if (!missedTPG.isEmpty()) {
String message = MessageFormat.format("Missing required raster in product {0}: {1}",
aatsrProduct.getName(), missedTPG);
throw new OperatorException(message);
}
}
}
private static void validateFlintProduct(final Product flintProduct) {
if (flintProduct != null) {
if (!flintProduct.containsBand(RADIANCE_MERIS_BAND_NAME)) {
String message = MessageFormat.format("Missing required band in product {0}: {1}",
flintProduct.getName(), RADIANCE_MERIS_BAND_NAME);
throw new OperatorException(message);
}
}
}
private static String validateMerisProductBands(Product product) {
List<String> sourceBandNameList = Arrays.asList(product.getBandNames());
for (String bandName : MERIS_L1B_SPECTRAL_BAND_NAMES) {
if (!sourceBandNameList.contains(bandName)) {
return bandName;
}
}
if (!sourceBandNameList.contains(MERIS_L1B_FLAGS_DS_NAME)) {
return MERIS_L1B_FLAGS_DS_NAME;
}
return "";
}
private static String validateAatsrProductBands(Product product) {
List<String> sourceBandNameList = Arrays.asList(product.getBandNames());
for (String bandName : AATSR_L1B_BAND_NAMES) {
if (!sourceBandNameList.contains(bandName)) {
return bandName;
}
}
return "";
}
private static String validateMerisProductTpgs(Product product) {
List<String> sourceNodeNameList = new ArrayList<String>();
sourceNodeNameList.addAll(Arrays.asList(product.getTiePointGridNames()));
sourceNodeNameList.addAll(Arrays.asList(product.getBandNames()));
for (String tpgName : REQUIRED_MERIS_TPG_NAMES) {
if (!sourceNodeNameList.contains(tpgName)) {
return tpgName;
}
}
return "";
}
private static String validateAatsrProductTpgs(Product product) {
List<String> sourceNodeNameList = new ArrayList<String>();
sourceNodeNameList.addAll(Arrays.asList(product.getTiePointGridNames()));
sourceNodeNameList.addAll(Arrays.asList(product.getBandNames()));
for (String tpgName : REQUIRED_AATSR_TPG_NAMES) {
if (!sourceNodeNameList.contains(tpgName)) {
return tpgName;
}
}
return "";
}
public static class Spi extends OperatorSpi {
public Spi() {
super(GlintCorrectionOperator.class);
}
}
}
| true | false | null | null |
diff --git a/drools-camel-server/src/main/java/org/drools/server/Test.java b/drools-camel-server/src/main/java/org/drools/server/Test.java
index d4986496c..982ebd997 100644
--- a/drools-camel-server/src/main/java/org/drools/server/Test.java
+++ b/drools-camel-server/src/main/java/org/drools/server/Test.java
@@ -1,78 +1,78 @@
/*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import org.apache.camel.CamelContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
String msg = "Hello World";
System.out.println( "Sending Message:\n" + msg);
Test test = new Test();
String response = test.send( msg );
System.out.println( );
System.out.println( );
System.out.println( "Received Response:\n" + response);
}
public String send(String msg) {
- ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:camel-client.xml");
+ ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:/camel-client.xml");
String batch = "";
batch += "<batch-execution lookup=\"ksession1\">\n";
batch += " <insert out-identifier=\"message\">\n";
batch += " <org.test.Message>\n";
batch += " <text>" + msg + "</text>\n";
batch += " </org.test.Message>\n";
batch += " </insert>\n";
batch += "</batch-execution>\n";
Test test = new Test();
String response = test.execute( batch,
( CamelContext ) springContext.getBean( "camel" ) );
return response;
}
public String execute(String msg, CamelContext camelContext) {
String response = camelContext.createProducerTemplate().requestBody( "direct://kservice/rest", msg, String.class );
return response;
}
public String execute(SOAPMessage soapMessage, CamelContext camelContext) throws SOAPException, IOException {
Object object = camelContext.createProducerTemplate().requestBody( "direct://kservice/soap", soapMessage);
OutputStream out = new ByteArrayOutputStream();
SOAPMessage soapResponse = (SOAPMessage) object;
soapResponse.writeTo(out);
return out.toString();
}
}
| true | true | public String send(String msg) {
ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:camel-client.xml");
String batch = "";
batch += "<batch-execution lookup=\"ksession1\">\n";
batch += " <insert out-identifier=\"message\">\n";
batch += " <org.test.Message>\n";
batch += " <text>" + msg + "</text>\n";
batch += " </org.test.Message>\n";
batch += " </insert>\n";
batch += "</batch-execution>\n";
Test test = new Test();
String response = test.execute( batch,
( CamelContext ) springContext.getBean( "camel" ) );
return response;
}
| public String send(String msg) {
ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:/camel-client.xml");
String batch = "";
batch += "<batch-execution lookup=\"ksession1\">\n";
batch += " <insert out-identifier=\"message\">\n";
batch += " <org.test.Message>\n";
batch += " <text>" + msg + "</text>\n";
batch += " </org.test.Message>\n";
batch += " </insert>\n";
batch += "</batch-execution>\n";
Test test = new Test();
String response = test.execute( batch,
( CamelContext ) springContext.getBean( "camel" ) );
return response;
}
|
diff --git a/src/org/adaway/utils/Constants.java b/src/org/adaway/utils/Constants.java
index dc8a56da..cb4aa0b5 100644
--- a/src/org/adaway/utils/Constants.java
+++ b/src/org/adaway/utils/Constants.java
@@ -1,37 +1,37 @@
/*
* Copyright (C) 2011 Dominik Schürmann <[email protected]>
*
* This file is part of AdAway.
*
* AdAway is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AdAway is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AdAway. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.adaway.utils;
public class Constants {
public static final String TAG = "AdAway";
public static final String LOCALHOST_IPv4 = "127.0.0.1";
- public static final String LOCALHOST_HOSTNAME = "hostname";
+ public static final String LOCALHOST_HOSTNAME = "localhost";
public static final String DOWNLOADED_HOSTS_FILENAME = "hosts_downloaded";
public static final String HOSTS_FILENAME = "hosts";
public static final String LINE_SEPERATOR = System.getProperty("line.separator");
public static final String COMMAND_COPY = "cp -f";
public static final String COMMAND_CHOWN = "chown 0:0";
public static final String COMMAND_CHMOD = "chmod 644";
public static final String ANDROID_HOSTS_PATH = "/system/etc";
}
| true | false | null | null |
diff --git a/biz.aQute.bndlib.tests/src/test/TestEclipseRepo.java b/biz.aQute.bndlib.tests/src/test/TestEclipseRepo.java
deleted file mode 100644
index c155d2638..000000000
--- a/biz.aQute.bndlib.tests/src/test/TestEclipseRepo.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package test;
-
-import java.util.*;
-
-import junit.framework.*;
-import aQute.bnd.repo.eclipse.*;
-import aQute.libg.generics.*;
-
-public class TestEclipseRepo extends TestCase {
-
- public static void testSimple() {
- EclipseRepo er = new EclipseRepo();
- Map<String,String> map = Create.map();
- map.put("location", "test/eclipse");
- map.put("name", "eclipse-test");
- er.setProperties(map);
-
- System.err.println(er.list("*"));
- }
-}
| true | false | null | null |
diff --git a/modules/util/src/main/java/org/mortbay/util/ajax/JSON.java b/modules/util/src/main/java/org/mortbay/util/ajax/JSON.java
index 8a740bf84..690db004a 100644
--- a/modules/util/src/main/java/org/mortbay/util/ajax/JSON.java
+++ b/modules/util/src/main/java/org/mortbay/util/ajax/JSON.java
@@ -1,773 +1,773 @@
// ========================================================================
// Copyright 2006 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.mortbay.util.ajax;
import java.io.Externalizable;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.mortbay.log.Log;
import org.mortbay.util.IO;
import org.mortbay.util.LazyList;
import org.mortbay.util.Loader;
import org.mortbay.util.QuotedStringTokenizer;
import org.mortbay.util.TypeUtil;
/** JSON Parser and Generator.
*
* <p>This class provides some static methods to convert POJOs to and from JSON
* notation. The mapping from JSON to java is:<pre>
* object ==> Map
* array ==> Object[]
* number ==> Double or Long
* string ==> String
* null ==> null
* bool ==> Boolean
* </pre>
* </p><p>
* The java to JSON mapping is:<pre>
* String --> string
* Number --> number
* Map --> object
* List --> array
* Array --> array
* null --> null
* Boolean--> boolean
* Object --> string (dubious!)
* </pre>
* </p><p>
- * The interface {@link JSON.Convertable} may be implemented by classes that wish to externalize and
+ * The interface {@link JSON.Convertible} may be implemented by classes that wish to externalize and
* initialize specific fields to and from JSON objects. Only directed acyclic graphs of objects are supported.
* </p>
* <p>
* The interface {@link JSON.Generator} may be implemented by classes that know how to render themselves as JSON and
* the {@link #toString(Object)} method will use {@link JSON.Generator#addJSON(StringBuffer)} to generate the JSON.
* The class {@link JSON.Literal} may be used to hold pre-gnerated JSON object.
* </p>
* @author gregw
*
*/
public class JSON
{
private JSON(){}
public static String toString(Object object)
{
StringBuffer buffer = new StringBuffer();
append(buffer,object);
return buffer.toString();
}
public static String toString(Map object)
{
StringBuffer buffer = new StringBuffer();
appendMap(buffer,object);
return buffer.toString();
}
public static String toString(Object[] array)
{
StringBuffer buffer = new StringBuffer();
appendArray(buffer,array);
return buffer.toString();
}
/**
* @param s String containing JSON object or array.
* @param stripOuterComment If true, an outer comment around the JSON is ignored.
* @return A Map, Object array or primitive array parsed from the JSON.
*/
public static Object parse(String s,boolean stripOuterComment)
{
return parse(new Source(s),stripOuterComment);
}
/**
* @param s Stream containing JSON object or array.
* @param stripOuterComment If true, an outer comment around the JSON is ignored.
* @return A Map, Object array or primitive array parsed from the JSON.
*/
public static Object parse(InputStream in,boolean stripOuterComment) throws IOException
{
String s=IO.toString(in);
return parse(new Source(s),stripOuterComment);
}
/**
* @param s String containing JSON object or array.
* @return A Map, Object array or primitive array parsed from the JSON.
*/
public static Object parse(String s)
{
return parse(new Source(s),false);
}
/**
* @param s Stream containing JSON object or array.
* @return A Map, Object array or primitive array parsed from the JSON.
*/
public static Object parse(InputStream in) throws IOException
{
String s=IO.toString(in);
return parse(new Source(s),false);
}
/**
* Append object as JSON to string buffer.
* @param buffer
* @param object
*/
public static void append(StringBuffer buffer, Object object)
{
if (object==null)
buffer.append("null");
- else if (object instanceof Convertable)
- appendJSON(buffer, (Convertable)object);
+ else if (object instanceof Convertible)
+ appendJSON(buffer, (Convertible)object);
else if (object instanceof Generator)
appendJSON(buffer, (Generator)object);
else if (object instanceof Map)
appendMap(buffer, (Map)object);
else if (object instanceof List)
appendArray(buffer,((List) object).toArray ());
else if (object instanceof Collection)
appendArray(buffer,((Collection)object).toArray());
else if (object.getClass().isArray())
appendArray(buffer,object);
else if (object instanceof Number)
appendNumber(buffer,(Number)object);
else if (object instanceof Boolean)
appendBoolean(buffer,(Boolean)object);
else if (object instanceof String)
appendString(buffer,(String)object);
else
// TODO - maybe some bean stuff?
appendString(buffer,object.toString());
}
private static void appendNull(StringBuffer buffer)
{
buffer.append("null");
}
- private static void appendJSON(final StringBuffer buffer, Convertable converter)
+ private static void appendJSON(final StringBuffer buffer, Convertible converter)
{
buffer.append('{');
converter.toJSON(new Output(){
char c=0;
public void addClass(Class type)
{
if (c>0)
buffer.append(c);
buffer.append("\"class\":");
append(buffer,type.getName());
c=',';
}
public void add(String name, Object value)
{
if (c>0)
buffer.append(c);
QuotedStringTokenizer.quote(buffer,name);
buffer.append(':');
append(buffer,value);
c=',';
}
public void add(String name, double value)
{
if (c>0)
buffer.append(c);
QuotedStringTokenizer.quote(buffer,name);
buffer.append(':');
appendNumber(buffer,new Double(value));
c=',';
}
public void add(String name, long value)
{
if (c>0)
buffer.append(c);
QuotedStringTokenizer.quote(buffer,name);
buffer.append(':');
appendNumber(buffer,new Long(value));
c=',';
}
public void add(String name, boolean value)
{
if (c>0)
buffer.append(c);
QuotedStringTokenizer.quote(buffer,name);
buffer.append(':');
appendBoolean(buffer,value?Boolean.TRUE:Boolean.FALSE);
c=',';
}
});
buffer.append('}');
}
private static void appendJSON(StringBuffer buffer, Generator generator)
{
generator.addJSON(buffer);
}
private static void appendMap(StringBuffer buffer, Map object)
{
if (object==null)
{
appendNull(buffer);
return;
}
buffer.append('{');
Iterator iter = object.entrySet().iterator();
while(iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
QuotedStringTokenizer.quote(buffer,entry.getKey().toString());
buffer.append(':');
append(buffer,entry.getValue());
if (iter.hasNext())
buffer.append(',');
}
buffer.append('}');
}
private static void appendArray(StringBuffer buffer, Object array)
{
if (array==null)
{
appendNull(buffer);
return;
}
buffer.append('[');
int length = Array.getLength(array);
for (int i=0;i<length;i++)
{
if(i!=0)
buffer.append(',');
append(buffer,Array.get(array,i));
}
buffer.append(']');
}
private static void appendBoolean(StringBuffer buffer, Boolean b)
{
if (b==null)
{
appendNull(buffer);
return;
}
buffer.append(b.booleanValue()?"true":"false");
}
private static void appendNumber(StringBuffer buffer, Number number)
{
if (number==null)
{
appendNull(buffer);
return;
}
buffer.append(number);
}
private static void appendString(StringBuffer buffer, String string)
{
if (string==null)
{
appendNull(buffer);
return;
}
QuotedStringTokenizer.quote(buffer,string);
}
private static Object parse(Source source,boolean stripOuterComment)
{
int comment_state=0; // 0=no comment, 1="/", 2="/*", 3="/* *" -1="//"
int strip_state=stripOuterComment?1:0; // 0=no strip, 1=wait for /*, 2= wait for */
while(source.hasNext())
{
char c=source.peek();
// handle // or /* comment
if(comment_state==1)
{
switch(c)
{
case '/' :
comment_state=-1;
break;
case '*' :
comment_state=2;
if (strip_state==1)
{
comment_state=0;
strip_state=2;
}
}
}
// handle /* */ comment
else if (comment_state>1)
{
switch(c)
{
case '*' :
comment_state=3;
break;
case '/' :
if (comment_state==3)
comment_state=0;
else
comment_state=2;
break;
default:
comment_state=2;
}
}
// handle // comment
else if (comment_state<0)
{
switch(c)
{
case '\r' :
case '\n' :
comment_state=0;
break;
default:
break;
}
}
// handle unknown
else
{
switch(c)
{
case '{' :
return parseObject(source);
case '[' :
return parseArray(source);
case '"' :
return parseString(source);
case '-' :
return parseNumber(source);
case 'n' :
complete("null",source);
return null;
case 't' :
complete("true",source);
return Boolean.TRUE;
case 'f' :
complete("false",source);
return Boolean.FALSE;
case 'u' :
complete("undefined",source);
return null;
case '/' :
comment_state=1;
break;
case '*' :
if (strip_state==2)
{
complete("*/",source);
strip_state=0;
}
return null;
default :
if (Character.isDigit(c))
return parseNumber(source);
else if (Character.isWhitespace(c))
break;
throw new IllegalStateException("unknown char "+c);
}
}
source.next();
}
return null;
}
private static Object parseObject(Source source)
{
if (source.next()!='{')
throw new IllegalStateException();
Map map = new HashMap();
char next = seekTo("\"}",source);
while(source.hasNext())
{
if (next=='}')
{
source.next();
break;
}
String name=parseString(source);
seekTo(':',source);
source.next();
Object value=parse(source,false);
map.put(name,value);
seekTo(",}",source);
next=source.next();
if (next=='}')
break;
else
next = seekTo("\"}",source);
}
String classname = (String)map.get("class");
if (classname!=null)
{
try
{
Class c = Loader.loadClass(JSON.class,classname);
- if (c!=null && Convertable.class.isAssignableFrom(c));
+ if (c!=null && Convertible.class.isAssignableFrom(c));
{
try
{
- Convertable conv = (Convertable)c.newInstance();
+ Convertible conv = (Convertible)c.newInstance();
conv.fromJSON(map);
return conv;
}
catch(Exception e)
{
throw new IllegalArgumentException(e);
}
}
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
return map;
}
private static Object parseArray(Source source)
{
if (source.next()!='[')
throw new IllegalStateException();
ArrayList list=new ArrayList();
boolean coma=true;
while(source.hasNext())
{
char c=source.peek();
switch(c)
{
case ']':
source.next();
return list.toArray(new Object[list.size()]);
case ',':
if (coma)
throw new IllegalStateException();
coma=true;
source.next();
default:
if (Character.isWhitespace(c))
source.next();
else
{
coma=false;
list.add(parse(source,false));
}
}
}
throw new IllegalStateException("unexpected end of array");
}
private static String parseString(Source source)
{
if (source.next()!='"')
throw new IllegalStateException();
boolean escape=false;
StringBuffer b = new StringBuffer();
while(source.hasNext())
{
char c=source.next();
if (escape)
{
escape=false;
switch (c)
{
case 'n':
b.append('\n');
break;
case 'r':
b.append('\r');
break;
case 't':
b.append('\t');
break;
case 'f':
b.append('\f');
break;
case 'b':
b.append('\b');
break;
case 'u':
b.append((char)(
(TypeUtil.convertHexDigit((byte)source.next())<<24)+
(TypeUtil.convertHexDigit((byte)source.next())<<16)+
(TypeUtil.convertHexDigit((byte)source.next())<<8)+
(TypeUtil.convertHexDigit((byte)source.next()))
)
);
break;
default:
b.append(c);
}
}
else if (c=='\\')
{
escape=true;
continue;
}
else if (c=='\"')
break;
else
b.append(c);
}
return b.toString();
}
private static Number parseNumber(Source source)
{
int start=source.index();
int end=-1;
boolean is_double=false;
while(source.hasNext()&&end<0)
{
char c=source.peek();
switch(c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
source.next();
break;
case '.':
case 'e':
case 'E':
is_double=true;
source.next();
break;
default:
end=source.index();
}
}
String s = end>=0?source.from(start,end):source.from(start);
if (is_double)
return new Double(s);
else
return new Long(s);
}
private static void seekTo(char seek, Source source)
{
while(source.hasNext())
{
char c=source.peek();
if (c==seek)
return;
if (!Character.isWhitespace(c))
throw new IllegalStateException("Unexpected '"+c+" while seeking '"+seek+"'");
source.next();
}
throw new IllegalStateException("Expected '"+seek+"'");
}
private static char seekTo(String seek, Source source)
{
while(source.hasNext())
{
char c=source.peek();
if(seek.indexOf(c)>=0)
{
return c;
}
if (!Character.isWhitespace(c))
throw new IllegalStateException("Unexpected '"+c+"' while seeking one of '"+seek+"'");
source.next();
}
throw new IllegalStateException("Expected one of '"+seek+"'");
}
private static void complete(String seek, Source source)
{
int i=0;
while(source.hasNext()&& i<seek.length())
{
char c=source.next();
if(c!=seek.charAt(i++))
throw new IllegalStateException("Unexpected '"+c+" while seeking \""+seek+"\"");
}
if (i<seek.length())
throw new IllegalStateException("Expected \""+seek+"\"");
}
private static class Source
{
private final String string;
private int index;
Source(String s)
{
string=s;
}
boolean hasNext()
{
return (index<string.length());
}
char next()
{
return string.charAt(index++);
}
char peek()
{
return string.charAt(index);
}
int index()
{
return index;
}
String from(int mark)
{
return string.substring(mark,index);
}
String from(int mark,int end)
{
return string.substring(mark,end);
}
}
/* ------------------------------------------------------------ */
/**
- * JSON Output class for use by {@link Convertable}.
+ * JSON Output class for use by {@link Convertible}.
*/
public interface Output
{
public void addClass(Class c);
public void add(String name,Object value);
public void add(String name,double value);
public void add(String name,long value);
public void add(String name,boolean value);
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
- /** JSON Convertable object.
+ /** JSON Convertible object.
* Object can implement this interface in a similar way to the
* {@link Externalizable} interface is used to allow classes to
* provide their own serialization mechanism.
* <p>
- * A JSON.Convertable object may be written to a JSONObject
+ * A JSON.Convertible object may be written to a JSONObject
* or initialized from a Map of field names to values.
* <p>
- * If the JSON is to be convertable back to an Object, then
+ * If the JSON is to be convertible back to an Object, then
* the method {@link Output#addClass(Class)} must be called from within toJSON()
* @author gregw
*
*/
- public interface Convertable
+ public interface Convertible
{
public void toJSON(Output out) ;
public void fromJSON(Map object);
}
/* ------------------------------------------------------------ */
public interface Generator
{
public void addJSON(StringBuffer buffer);
}
/* ------------------------------------------------------------ */
/** A Literal JSON generator
* A utility instance of {@link JSON.Generator} that holds a pre-generated string on JSON text.
*/
public static class Literal implements Generator
{
private String _json;
/* ------------------------------------------------------------ */
/** Construct a literal JSON instance for use by {@link JSON#toString(Object)}.
* @param json A literal JSON string that will be parsed to check validity.
*/
public Literal(String json)
{
parse(json);
_json=json;
}
public String toString()
{
return _json;
}
public void addJSON(StringBuffer buffer)
{
buffer.append(_json);
}
}
}
diff --git a/modules/util/src/test/java/org/mortbay/util/ajax/JSONTest.java b/modules/util/src/test/java/org/mortbay/util/ajax/JSONTest.java
index ed2f10cbe..7b70acc6f 100644
--- a/modules/util/src/test/java/org/mortbay/util/ajax/JSONTest.java
+++ b/modules/util/src/test/java/org/mortbay/util/ajax/JSONTest.java
@@ -1,139 +1,139 @@
package org.mortbay.util.ajax;
import java.util.HashMap;
import java.util.Map;
import org.mortbay.util.ajax.JSON;
import org.mortbay.util.ajax.JSON.Output;
import junit.framework.TestCase;
public class JSONTest extends TestCase
{
public void testToString()
{
HashMap map = new HashMap();
HashMap obj6 = new HashMap();
HashMap obj7 = new HashMap();
Woggle w0 = new Woggle();
Woggle w1 = new Woggle();
w0.name="woggle0";
w0.nested=w1;
w0.number=100;
w1.name="woggle1";
w1.nested=null;
w1.number=101;
map.put("n1",null);
map.put("n2",new Integer(2));
map.put("n3",new Double(-0.00000000003));
map.put("n4","4\n\r\t\"4");
map.put("n5",new Object[]{"a",new Character('b'),new Integer(3),new String[]{},null,Boolean.TRUE,Boolean.FALSE});
map.put("n6",obj6);
map.put("n7",obj7);
map.put("n8",new int[]{1,2,3,4});
map.put("n9",new JSON.Literal("[{}, [], {}]"));
map.put("w0",w0);
obj7.put("x","value");
String s = JSON.toString(map);
System.err.println(s);
assertTrue(s.indexOf("\"n1\":null")>=0);
assertTrue(s.indexOf("\"n2\":2")>=0);
assertTrue(s.indexOf("\"n3\":-3.0E-11")>=0);
assertTrue(s.indexOf("\"n4\":\"4\\n")>=0);
assertTrue(s.indexOf("\"n5\":[\"a\",\"b\",")>=0);
assertTrue(s.indexOf("\"n6\":{}")>=0);
assertTrue(s.indexOf("\"n7\":{\"x\":\"value\"}")>=0);
assertTrue(s.indexOf("\"n8\":[1,2,3,4]")>=0);
assertTrue(s.indexOf("\"n9\":[{}, [], {}]")>=0);
assertTrue(s.indexOf("\"w0\":{\"class\":\"org.mortbay.util.ajax.JSONTest$Woggle\",\"name\":\"woggle0\",\"nested\":{\"class\":\"org.mortbay.util.ajax.JSONTest$Woggle\",\"name\":\"woggle1\",\"nested\":null,\"number\":101},\"number\":100}")>=0);
}
public void testParse()
{
String test="\n\n\n\t\t "+
"// ignore this ,a [ \" \n"+
"/* and this \n" +
"/* and * // this \n" +
"*/" +
"{ "+
"\"onehundred\" : 100 ,"+
"\"name\" : \"fred\" ," +
"\"empty\" : {} ," +
"\"map\" : {\"a\":-1.0e2} ," +
"\"array\" : [\"a\",-1.0e2,[],null,true,false] ," +
"\"w0\":{\"class\":\"org.mortbay.util.ajax.JSONTest$Woggle\",\"name\":\"woggle0\",\"nested\":{\"class\":\"org.mortbay.util.ajax.JSONTest$Woggle\",\"name\":\"woggle1\",\"nested\":null,\"number\":101},\"number\":100}" +
"}";
Map map = (Map)JSON.parse(test);
System.err.println(map);
assertEquals(new Long(100),map.get("onehundred"));
assertEquals("fred",map.get("name"));
assertTrue(map.get("array").getClass().isArray());
assertTrue(map.get("w0") instanceof Woggle);
assertTrue(((Woggle)map.get("w0")).nested instanceof Woggle);
test="{\"data\":{\"source\":\"15831407eqdaawf7\",\"widgetId\":\"Magnet_8\"},\"channel\":\"/magnets/moveStart\",\"connectionId\":null,\"clientId\":\"15831407eqdaawf7\"}";
map = (Map)JSON.parse(test);
}
public void testStripComment()
{
String test="\n\n\n\t\t "+
"// ignore this ,a [ \" \n"+
"/* "+
"{ "+
"\"onehundred\" : 100 ,"+
"\"name\" : \"fred\" ," +
"\"empty\" : {} ," +
"\"map\" : {\"a\":-1.0e2} ," +
"\"array\" : [\"a\",-1.0e2,[],null,true,false] ," +
"} */";
Object o = JSON.parse(test,false);
assertTrue(o==null);
o = JSON.parse(test,true);
assertTrue(o instanceof Map);
assertEquals("fred",((Map)o).get("name"));
}
- public static class Woggle implements JSON.Convertable
+ public static class Woggle implements JSON.Convertible
{
String name;
Woggle nested;
int number;
public Woggle()
{
}
public void fromJSON(Map object)
{
name=(String)object.get("name");
nested=(Woggle)object.get("nested");
number=((Number)object.get("number")).intValue();
}
public void toJSON(Output out)
{
out.addClass(Woggle.class);
out.add("name",name);
out.add("nested",nested);
out.add("number",number);
}
public String toString()
{
return name+"<<"+nested+">>"+number;
}
}
}
| false | false | null | null |
diff --git a/src/de/ueller/gpsmid/graphics/ImageCollector.java b/src/de/ueller/gpsmid/graphics/ImageCollector.java
index fd724706..e306db39 100644
--- a/src/de/ueller/gpsmid/graphics/ImageCollector.java
+++ b/src/de/ueller/gpsmid/graphics/ImageCollector.java
@@ -1,760 +1,766 @@
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* Copyright (c) 2008 Kai Krueger apmonkey at users dot sourceforge dot net
* See Copying
*/
package de.ueller.gpsmid.graphics;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import de.enough.polish.util.Locale;
import de.ueller.gps.Node;
import de.ueller.gpsmid.data.Configuration;
import de.ueller.gpsmid.data.Legend;
import de.ueller.gpsmid.data.PaintContext;
import de.ueller.gpsmid.data.PositionMark;
import de.ueller.gpsmid.data.ScreenContext;
import de.ueller.gpsmid.mapdata.DictReader;
import de.ueller.gpsmid.mapdata.Way;
import de.ueller.gpsmid.mapdata.WayDescription;
import de.ueller.gpsmid.routing.RouteInstructions;
import de.ueller.gpsmid.routing.RouteLineProducer;
import de.ueller.gpsmid.tile.Tile;
import de.ueller.gpsmid.ui.Trace;
import de.ueller.gpsmid.ui.TraceLayout;
import de.ueller.midlet.iconmenu.LayoutElement;
//#if polish.api.finland
import de.ueller.util.ETRSTM35FINconvert;
//#endif
import de.ueller.util.IntPoint;
import de.ueller.util.Logger;
import de.ueller.util.MoreMath;
import java.util.Enumeration;
/* This class collects all visible objects to an offline image for later painting.
* It is run in a low priority to avoid interrupting the GUI.
*/
public class ImageCollector implements Runnable {
private final static Logger logger = Logger.getInstance(ImageCollector.class,
Logger.TRACE);
/** hashtable of not painted single tiles */
public static java.util.Hashtable htNotPaintedSingleTiles = new java.util.Hashtable();
private volatile boolean shutdown = false;
private volatile boolean suspended = true;
private final Tile t[];
private Thread processorThread;
/** the next run of the createloop will take these parameters */
private final ScreenContext nextSc = new ScreenContext();
/** the next paint to screen */
// private ScreenContext currentVisibleSc = null;
private ScreenContext lastCreatedSc = null;
private final Image[] img = new Image[2];
private volatile PaintContext[] pc = new PaintContext[2];
public static volatile Node mapCenter = new Node();
public static volatile long icDuration = 0;
byte nextCreate = 1;
byte nextPaint = 0;
/** width of the double buffer image (including overscan) */
int xSize;
/** hight of the double buffer image (including overscan) */
int ySize;
/** offset x for overscan */
public int xScreenOverscan;
/** offset y for overscan */
public int yScreenOverscan;
int yScreenSize;
IntPoint newCenter = new IntPoint(0, 0);
IntPoint oldCenter = new IntPoint(0, 0);
float oldCourse;
private volatile boolean needRedraw = false;
public static volatile int createImageCount = 0;
private final Trace tr;
/** additional scale boost for Overview/Filter Map, bigger values load the tiles already when zoomed more out */
public static float overviewTileScaleBoost = 1.0f;
boolean collectorReady=false;
public int iDrawState = 0;
public ImageCollector(Tile[] t, int x, int y, Trace tr, Images i) {
super();
this.t = t;
this.tr = tr;
Node n = new Node(2f, 0f);
Projection p1 = ProjFactory.getInstance(n, 0, 1500, xSize, ySize);
if (p1.isOrthogonal()) {
// with overscan
xScreenOverscan = x*12/100;
yScreenOverscan = y*12/100;
if (tr.isShowingSplitIconMenu()) {
yScreenOverscan = 0;
}
xSize = x+2*xScreenOverscan;
ySize = y+2*yScreenOverscan;
} else {
// without overscan
xSize = x;
ySize = y;
xScreenOverscan = 0;
yScreenOverscan = 0;
}
if (tr.isShowingSplitScreen()) {
img[0] = Image.createImage(xSize, ySize / 2);
img[1] = Image.createImage(xSize, ySize / 2);
} else {
img[0] = Image.createImage(xSize, ySize);
img[1] = Image.createImage(xSize, ySize);
}
try {
pc[0] = new PaintContext(tr, i);
pc[0].setP(p1);
pc[0].state = PaintContext.STATE_READY;
pc[1] = new PaintContext(tr, i);
pc[1].setP(ProjFactory.getInstance(n, 0, 1500, xSize, ySize));
pc[1].state = PaintContext.STATE_READY;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nextSc.setP(ProjFactory.getInstance(mapCenter,
nextSc.course, nextSc.scale, xSize, ySize));
processorThread = new Thread(this, "ImageCollector");
processorThread.setPriority(Thread.MIN_PRIORITY);
processorThread.start();
}
public void run() {
PaintContext createPC = null;
final byte MAXCRASHES = 5;
byte crash = 0;
do {
try {
while (!shutdown) {
if (!needRedraw || suspended) {
synchronized (this) {
try {
/* FIXME: We still have some situations where redraw is not done automatically immediately,
* e.g. on Nokia 5800 after returning from another Displayable
* Therefore reduce the timeout for redrawing anyway from 30 seconds to 1 seconds
* if the last user interaction happened less than 1.5 secs before
if (Trace.getDurationSinceLastUserActionTime() > 1500 ) {
wait(30000);
} else {
wait(1000);
}
*/
wait(30000);
} catch (InterruptedException e) {
continue; // Recheck condition of the loop
}
}
}
needRedraw = false; //moved here and deleted from the bottom of this routine
//#debug debug
logger.debug("Redrawing Map");
iDrawState = 1;
synchronized (this) {
while (pc[nextCreate].state != PaintContext.STATE_READY && !shutdown) {
try {
// System.out.println("img not ready");
wait(1000);
} catch (InterruptedException e) {
}
}
if (suspended || shutdown) {
continue;
}
pc[nextCreate].state = PaintContext.STATE_IN_CREATE;
}
tr.resetClickableMarkers();
iDrawState = 2;
tr.requestRedraw();
createPC = pc[nextCreate];
long startTime = System.currentTimeMillis();
// create PaintContext
createPC.xSize = nextSc.xSize;
createPC.ySize = nextSc.ySize;
createPC.center = nextSc.center.copy();
mapCenter = nextSc.center.copy();
createPC.scale = nextSc.scale;
createPC.course = nextSc.course;
// Projection p = ProjFactory.getInstance(createPC.center,
// nextSc.course, nextSc.scale, xSize, ySize);
createPC.setP(nextSc.getP());
// p.inverse(xSize, 0, createPC.screenRU);
// p.inverse(0, ySize, createPC.screenLD);
// pcCollect.trace = nextSc.trace;
// pcCollect.dataReader = nextSc.dataReader;
// cleans the screen
createPC.g = img[nextCreate].getGraphics();
createPC.g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
createPC.g.fillRect(0, 0, xSize, ySize);
htNotPaintedSingleTiles.clear();
// createPC.g.setColor(0x00FF0000);
// createPC.g.drawRect(0, 0, xSize - 1, ySize - 1);
// createPC.g.drawRect(20, 20, xSize - 41, ySize - 41);
createPC.squareDstWithPenToWay = Float.MAX_VALUE;
createPC.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE;
createPC.squareDstWithPenToRoutePath = Float.MAX_VALUE;
createPC.squareDstToRoutePath = Float.MAX_VALUE;
createPC.dest = nextSc.dest;
createPC.waysPainted = 0;
// System.out.println("create " + pcCollect);
Way.setupDirectionalPenalty(createPC, tr.speed, tr.gpsRecenter && !tr.gpsRecenterInvalid);
float boost = Configuration.getMaxDetailBoostMultiplier();
/*
* layers containing highlighted path segments
*/
createPC.hlLayers = 0;
/*
* highlighted path is on top if gps recentered, but if not it might still come to top
* when we determine during painting that the cursor is closer than 25 meters at the route line.
*/
createPC.highlightedPathOnTop = tr.gpsRecenter;
/**
* At the moment we don't really have proper layer support
* in the data yet, so only split it into Area, Way and Node
* layers
*/
byte layersToRender[] = { Tile.LAYER_AREA, 1 | Tile.LAYER_AREA , 2 | Tile.LAYER_AREA,
3 | Tile.LAYER_AREA, 4 | Tile.LAYER_AREA, 0, 1, 2, 3, 4,
0 | Tile.LAYER_HIGHLIGHT, 1 | Tile.LAYER_HIGHLIGHT,
2 | Tile.LAYER_HIGHLIGHT, 3 | Tile.LAYER_HIGHLIGHT,
Tile.LAYER_NODE };
/**
* Draw each layer separately to enforce paint ordering:
*
* Go through the entire tile tree multiple times
* to get the drawing order correct.
*
* The first 5 layers correspond to drawing areas with the osm
* layer tag of (< -1, -1, 0, 1, >1),
* then next 5 layers are drawing streets with
* osm layer tag (< -1, -1, 0, 1, >1).
*
* Then we draw the highlighted streets
* and finally we draw the POI layer.
*
* So e. g. layer 7 corresponds to all streets that
* have no osm layer tag or layer = 0.
*/
for (byte layer = 0; layer < layersToRender.length; layer++) {
if (needRedraw &&
Configuration.getCfgBitState(Configuration.CFGBIT_SIMPLIFY_MAP_WHEN_BUSY) &&
((layer < 5 && layer > 1)
//#if polish.api.finland
// don't skip node layer where speed camera is if camera alert is on
|| (layer == 14 && !Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDCAMERA_ALERT))
//#else
|| (layer == 14)
//#endif
)) {
// EXPERIMENTAL
// skip update if next
// is queued
continue;
}
// render only highlight layers which actually have highlighted path segments
if (
(layersToRender[layer] & Tile.LAYER_HIGHLIGHT) > 0
&& layersToRender[layer] != Tile.LAYER_NODE
) {
/**
* as we do two passes for each way layer when gps recentered - one for the ways and one for the route line on top,
* we can use in the second pass the determined route path connection / idx
* to highlight the route line in the correct / prior route line color.
* when not gps recentered, this info will be by one image obsolete however
*/
if (layersToRender[layer] == Tile.LAYER_HIGHLIGHT /*(0 | Tile.LAYER_HIGHLIGHT) pointless bitwise operation*/) {
/*
* only take ImageCollector loops into account for dstToRoutePath if ways were painted
* otherwise this would trigger wrong route recalculations
*/
if (createPC.waysPainted != 0) {
//RouteInstructions.dstToRoutePath = createPC.getDstFromSquareDst(createPC.squareDstToRoutePath);
RouteInstructions.dstToRoutePath = createPC.getDstFromRouteSegment();
if (RouteInstructions.dstToRoutePath != RouteInstructions.DISTANCE_UNKNOWN) {
RouteInstructions.routePathConnection = createPC.routePathConnection;
RouteInstructions.pathIdxInRoutePathConnection = createPC.pathIdxInRoutePathConnection;
RouteInstructions.actualRoutePathWay = createPC.actualRoutePathWay;
// when we determine during painting that the cursor is closer than 25 meters at the route line, bring it to the top
if (RouteInstructions.dstToRoutePath < 25) {
createPC.highlightedPathOnTop = true;
}
}
//System.out.println("waysPainted: " + createPC.waysPainted);
} else {
// FIXME: Sometimes there are ImageCollector loop with no way pained even when ways would be there and tile data is fully loaded
// Update 2011-06-11: Might be fixed with the patch from gojkos at [ gpsmid-Bugs-3310178 ] Delayed map draw on LG cookie phone
// Update 2012-03-17 (patch from walter9): The image collector has been started twice. This seems to be fixed now in Trace.java.startImageCollector()
System.out.println("No ways painted in this ImageCollector loop");
}
}
byte relLayer = (byte)(((int)layersToRender[layer]) & 0x0000000F);
if ( (createPC.hlLayers & (1 << relLayer)) == 0) {
continue;
}
}
byte minTile = Legend.scaleToTile((int)(createPC.scale / (boost * overviewTileScaleBoost) ));
if (t[0] != null) {
t[0].paint(createPC, layersToRender[layer]);
}
if ((minTile >= 1) && (t[1] != null)) {
t[1].paint(createPC, layersToRender[layer]);
Thread.yield();
}
if ((minTile >= 2) && (t[2] != null)) {
t[2].paint(createPC, layersToRender[layer]);
Thread.yield();
}
if ((minTile >= 3) && (t[3] != null)) {
t[3].paint(createPC, layersToRender[layer]);
Thread.yield();
}
/**
* Drawing waypoints
*/
if (t[DictReader.GPXZOOMLEVEL] != null) {
t[DictReader.GPXZOOMLEVEL].paint(createPC, layersToRender[layer]);
}
if (suspended) {
// Don't continue rendering if suspended
createPC.state = PaintContext.STATE_READY;
break;
}
}
/**
* Drawing debuginfo for routing
*/
if (!suspended && t[DictReader.ROUTEZOOMLEVEL] != null
&& (Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_CONNECTIONS)
|| Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_TURN_RESTRICTIONS))) {
t[DictReader.ROUTEZOOMLEVEL].paint(createPC, (byte) 0);
}
//FIXME: Would it be also possible to add a check if requested single tiles are off-screen (or far offscreen, e.g. one display width / height) and remove those single tiles from the request queue?
if ( htNotPaintedSingleTiles.isEmpty() ) {
// No not displayed tile.
// The request queue can be cleared.
// This can happen when zooming far out and then zooming in again.
// Then many tiles will be queued which are not needed.
if ( Trace.getInstance().getDataReader() != null
// &&
// // do not clear the request queue while the route line is created, as this also requests single tiles
// !RouteLineProducer.isRunning()
) {
Trace.getInstance().getDataReader().clearRequestQueue();
}
}
iDrawState = 0;
icDuration = System.currentTimeMillis() - startTime;
//#mdebug
logger.info("Painting map took " + icDuration + " ms");
//#enddebug
System.out.println("Painting map took " + icDuration + " ms " + xSize + "/" + ySize);
createPC.state = PaintContext.STATE_READY;
lastCreatedSc=createPC.cloneToScreenContext();
if (!shutdown) {
newCollected();
}
createImageCount++;
//needRedraw = false;
tr.cleanup();
// System.out.println("create ready");
//System.gc();
}
} catch (OutOfMemoryError oome) {
if (createPC != null) {
createPC.state = PaintContext.STATE_READY;
}
String recoverZoomedIn = "";
crash++;
if(tr.scale > 10000 && crash < MAXCRASHES) {
tr.scale /= 1.5f;
recoverZoomedIn = Locale.get("imagecollector.ZoomingInToRecover")/* Zooming in to recover.*/;
}
logger.fatal(Locale.get("imagecollector.ImageCollectorRanOutOfMemory")/*ImageCollector ran out of memory: */ + oome.getMessage() + recoverZoomedIn);
} catch (Exception e) {
crash++;
logger.exception(Locale.get("imagecollector.ImageCollectorCrashed")/*ImageCollector thread crashed unexpectedly with error */, e);
}
if(crash >= MAXCRASHES) {
logger.fatal(Locale.get("imagecollector.ImageCollectorCrashedAborting")/*ImageCollector crashed too often. Aborting.*/);
}
} while (!shutdown && crash <MAXCRASHES);
processorThread = null;
synchronized (this) {
notifyAll();
}
}
public void suspend() {
suspended = true;
}
public void resume() {
suspended = false;
}
public synchronized void stop() {
shutdown = true;
notifyAll();
try {
while ((processorThread != null) && (processorThread.isAlive())) {
wait(1000);
}
} catch (InterruptedException e) {
//Nothing to do
}
}
+ public boolean isRunning() {
+ return !suspended && !shutdown;
+ }
+
+ /** copy the last created image to the real screen
+
public void restart() {
processorThread = new Thread(this, "ImageCollector");
processorThread.setPriority(Thread.MIN_PRIORITY);
processorThread.start();
}
/** copy the last created image to the real screen
* but with the last collected position and direction in the center
*/
public Node paint(PaintContext screenPc) {
PaintContext paintPC;
// System.out.println("paint this: " + screenPc);
// System.out.println("paint image: " + pc[nextPaint]);
if (suspended || !collectorReady) {
return new Node(0, 0);
}
// Define the parameters for the next image that will be created
nextSc.center = screenPc.center.copy();
nextSc.course = screenPc.course;
nextSc.scale = screenPc.scale;
nextSc.dest = screenPc.dest;
nextSc.xSize = screenPc.xSize;
nextSc.ySize = screenPc.ySize;
Projection p = ProjFactory.getInstance(nextSc.center, nextSc.course, nextSc.scale, xSize,
(screenPc.trace.isShowingSplitScreen()) ? (int) (ySize / 2) : ySize);
// System.out.println("p =" + p);
Projection p1 = ProjFactory.getInstance(nextSc.center,
pc[nextPaint].course, pc[nextPaint].scale, xSize,
(screenPc.trace.isShowingSplitScreen()) ? (int) (ySize / 2) : ySize);
// System.out.println("p =" + p1);
nextSc.setP(p);
screenPc.setP(p);
synchronized (this) {
if (pc[nextPaint].state != PaintContext.STATE_READY) {
logger.error(Locale.get("imagecollector.ImageCollectorNonReadyPaintContext")/*ImageCollector was trying to draw a non ready PaintContext */
+ pc[nextPaint].state);
return new Node(0, 0);
}
paintPC = pc[nextPaint];
paintPC.state = PaintContext.STATE_IN_PAINT;
}
int screenXCenter = xSize / 2 - xScreenOverscan;
int screenYCenter = ySize / 2 - yScreenOverscan;
if (paintPC.trace.isShowingSplitScreen()) {
screenYCenter = ySize / 4 - yScreenOverscan;
}
int newXCenter = screenXCenter;
int newYCenter = screenYCenter;
// return center of the map image drawn to the caller
Node getDrawnCenter = paintPC.center.copy();
if (p.isOrthogonal()) {
// maps can painted so that the hotspot is at the predefined point on the screen
// therfore the offset is useful in that case its not necessary to create a new image
// if the position has changed less then half of the offset
if (lastCreatedSc != null) {
p1.forward(lastCreatedSc.center, oldCenter);
newXCenter = oldCenter.x - p.getImageCenter().x + screenXCenter;
newYCenter = oldCenter.y - p.getImageCenter().y + screenYCenter;
// System.out.println("Paint pos = " + newXCenter + "/" +
// newYCenter);
// System.out.println("Paint ysize=" + ySize + " nextSc.xSize="
// + nextSc.ySize + " hotspot=" + p.getImageCenter());
}
screenPc.g.drawImage(img[nextPaint], newXCenter, newYCenter,
Graphics.VCENTER | Graphics.HCENTER);
// Test if the new center is around the middle of the screen, in which
// case we don't need to redraw (recreate a new image), as nothing has changed.
if ( Math.abs(newXCenter - screenXCenter) > 4
|| Math.abs(newYCenter - screenYCenter) > 4
|| paintPC.course != nextSc.course) {
// The center of the screen has moved or rotated, so need
// to redraw the map image
needRedraw = true;
// System.out.println("wakeup thread because course or position changed");
// System.out.println("Changed " + newXCenter + "->" +
// screenXCenter + " and " + newYCenter + "->" + screenYCenter);
}
} else {
screenPc.g.drawImage(img[nextPaint], screenXCenter,
screenYCenter, Graphics.VCENTER | Graphics.HCENTER);
p.forward(lastCreatedSc.center, oldCenter);
newXCenter = oldCenter.x - p.getImageCenter().x + screenXCenter;
newYCenter = oldCenter.y - p.getImageCenter().y + screenYCenter;
if ( Math.abs(newXCenter - screenXCenter) > 1
|| Math.abs(newYCenter - screenYCenter) > 1
|| paintPC.course != nextSc.course) {
needRedraw = true;
}
}
// screenPc.g.drawArc(newXCenter-14, newYCenter-14, 28, 28, 0, 360);
// if (p instanceof Proj3D){
// screenPc.g.setColor(255,50,50);
// IntPoint pt0 = new IntPoint();
// IntPoint pt1 = new IntPoint();
// Proj3D p3=(Proj3D)p;
// p.forward(p3.borderLD,pt0);
// p.forward(p3.borderLU,pt1);
// screenPc.g.drawLine(pt0.x, pt0.y, pt1.x, pt1.y);
// p.forward(p3.borderRU,pt0);
// screenPc.g.drawLine(pt0.x, pt0.y, pt1.x, pt1.y);
// p.forward(p3.borderRD,pt1);
// screenPc.g.drawLine(pt0.x, pt0.y, pt1.x, pt1.y);
// p.forward(p3.borderLD,pt0);
// screenPc.g.drawLine(pt0.x, pt0.y, pt1.x, pt1.y);
//
// }
String name = null;
Way wayForName = null;
/**
* used to check for pixel distances because checking for meters from
* converted pixels requires to be exactly on the pixel when zoomed out
* far
*/
final int SQUARE_MAXPIXELS = 5 * 5;
// Tolerance of 15 pixels converted to meters
float pixDest = 15 / paintPC.ppm;
if (pixDest < 15) {
pixDest = 15;
}
if (paintPC.trace.gpsRecenter) {
// Show closest routable way name if map is gpscentered and we are
// closer
// than SQUARE_MAXPIXELS or 30 m (including penalty) to it.
// If the routable way is too far away, we try the closest way.
if (paintPC.bUsedGpsCenter == false ) {
if (paintPC.squareDstWithPenToActualRoutableWay < SQUARE_MAXPIXELS
|| paintPC.getDstFromSquareDst(paintPC.squareDstWithPenToActualRoutableWay) < 30) {
wayForName = paintPC.actualRoutableWay;
} else if (paintPC.squareDstWithPenToWay < SQUARE_MAXPIXELS
|| paintPC.getDstFromSquareDst(paintPC.squareDstWithPenToWay) < 30) {
wayForName = paintPC.actualWay;
}
} else {
if (paintPC.getDstFromRouteableWay() < 100) {
wayForName = paintPC.actualRoutableWay;
} else if ( paintPC.getDstFromWay() < 100) {
wayForName = paintPC.actualWay;
}
}
} else if (paintPC.getDstFromSquareDst(paintPC.squareDstWithPenToWay) <= pixDest) {
// If not gpscentered show closest way name if it's no more than 15
// pixels away.
wayForName = paintPC.actualWay;
}
/*
* As we are double buffering pc, nothing should be writing to paintPC
* therefore it should be safe to access the volatile variable actualWay
*/
if (paintPC.actualWay != null) {
screenPc.actualWay = paintPC.actualWay;
screenPc.actualSingleTile = paintPC.actualSingleTile;
tr.actualWay = paintPC.actualWay;
tr.actualSingleTile = paintPC.actualSingleTile;
}
if (wayForName != null) {
int nummaxspeed;
String maxspeed = "";
String winter = "";
// store for OSM editing
if (wayForName.getMaxSpeed() != 0) {
nummaxspeed = wayForName.getMaxSpeed();
if (Configuration
.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (wayForName.getMaxSpeedWinter() > 0)) {
nummaxspeed = wayForName.getMaxSpeedWinter();
winter = Locale.get("imagecollector.Winter")/*W */;
}
if (nummaxspeed == Legend.MAXSPEED_MARKER_NONE) {
maxspeed = Locale.get("imagecollector.SL")/* SL:*/ + winter +
Locale.get("imagecollector.MaxSpeedNone")/*none*/;
} else if (nummaxspeed == Legend.MAXSPEED_MARKER_VARIABLE) {
maxspeed = Locale.get("imagecollector.SL")/* SL:*/ + winter +
Locale.get("imagecollector.MaxSpeedVariable")/*var*/;
} else if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
maxspeed = Locale.get("imagecollector.SL")/* SL:*/ + winter + nummaxspeed;
} else {
// Round up at this point, as the the previouse two
// conversions
// were rounded down already. (Seems to work better for
// speed limits of
// 20mph and 30mph)
maxspeed = Locale.get("imagecollector.SL")/* SL:*/ + winter + ((int)(nummaxspeed / 1.609344f + 0.5f));
}
}
if (wayForName.nameIdx != -1) {
name = screenPc.trace.getName(wayForName.nameIdx);
} else {
//#if polish.api.bigstyles
WayDescription wayDesc = Legend
.getWayDescription(wayForName.type);
//#else
WayDescription wayDesc = Legend
.getWayDescription((short) (wayForName.type & 0xff));
//#endif
name = Locale.get("imagecollector.unnamed")/*(unnamed */ + wayDesc.description + ")";
}
if (name == null) {
name = maxspeed;
} else {
name = name + maxspeed;
}
// If there's an URL associated with way, show a letter next to name
if (wayForName.urlIdx != -1) {
name = name + Locale.get("imagecollector.W")/* W*/;
}
// Show 'P' for phone number
if (wayForName.phoneIdx != -1) {
name = name + Locale.get("imagecollector.P")/* P*/;
}
}
// use the nearest routable way for the the speed limit detection if
// it's
// closer than 30 m or SQUARE_MAXPIXELS including penalty
if (paintPC.squareDstWithPenToActualRoutableWay < SQUARE_MAXPIXELS
|| paintPC
.getDstFromSquareDst(paintPC.squareDstWithPenToActualRoutableWay) < 30) {
tr.actualSpeedLimitWay = paintPC.actualRoutableWay;
} else {
tr.actualSpeedLimitWay = null;
}
boolean showLatLon = Configuration
.getCfgBitState(Configuration.CFGBIT_SHOWLATLON);
LayoutElement e = Trace.tl.ele[TraceLayout.WAYNAME];
if (showLatLon) {
//#if polish.api.finland
// show Finnish ETRS-TM35FIN coordinates
// FIXME: add a config option for selection of coordinates
if (false) {
PositionMark pmETRS = ETRSTM35FINconvert.latlonToEtrs(paintPC.center.radlat, paintPC.center.radlon);
e.setText(Locale.get("imagecollector.lat")/* lat: */
+ Float.toString(pmETRS.lat)
+ " " + Locale.get("imagecollector.lon")/* lon: */
+ Float.toString(pmETRS.lon));
} else {
//#endif
e.setText(Locale.get("imagecollector.lat")/* lat: */
+ Float.toString(paintPC.center.radlat
* MoreMath.FAC_RADTODEC)
+ " " + Locale.get("imagecollector.lon")/* lon: */
+ Float.toString(paintPC.center.radlon
* MoreMath.FAC_RADTODEC));
//#if polish.api.finland
}
//#endif
} else {
if (name != null && name.length() > 0) {
e.setText(name);
} else {
e.setText(" ");
}
}
if (paintPC.scale != screenPc.scale) {
// System.out.println("wakeup thread because scale changed");
needRedraw = true;
}
// when the projection has changed we must redraw
if (!paintPC.getP().getProjectionID().equals(screenPc.getP().getProjectionID()) ) {
// System.out.println("wakeup thread because projection changed");
needRedraw = true;
}
synchronized (this) {
paintPC.state = PaintContext.STATE_READY;
if (needRedraw) {
notify();
} else {
// System.out.println("No need to redraw after painting");
}
}
// currentVisibleSc=lastCreatedSc.cloneToScreenContext();
return getDrawnCenter;
}
private synchronized void newCollected() {
while ((pc[nextPaint].state != PaintContext.STATE_READY) || (pc[nextCreate].state != PaintContext.STATE_READY)) {
try {
wait(50);
} catch (InterruptedException e) {
}
}
collectorReady=true;
nextPaint = nextCreate;
nextCreate = (byte) ((nextCreate + 1) % 2);
tr.requestRedraw();
}
/**
* Inform the ImageCollector that new vector data is available
* and it's time to create a new image.
*/
public synchronized void newDataReady() {
needRedraw = true;
notify();
}
public Projection getCurrentProjection(){
return pc[nextPaint].getP();
// return currentVisibleSc.getP();
}
}
diff --git a/src/de/ueller/gpsmid/ui/Trace.java b/src/de/ueller/gpsmid/ui/Trace.java
index 14d4a1d1..c6b26de4 100644
--- a/src/de/ueller/gpsmid/ui/Trace.java
+++ b/src/de/ueller/gpsmid/ui/Trace.java
@@ -1,4480 +1,4480 @@
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* See file COPYING.
*/
package de.ueller.gpsmid.ui;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
//#if polish.api.fileconnection
import javax.microedition.io.file.FileConnection;
//#endif
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
//#if polish.android
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
//#else
import javax.microedition.lcdui.game.GameCanvas;
//#endif
import javax.microedition.midlet.MIDlet;
import de.enough.polish.util.Locale;
import de.ueller.gps.Node;
import de.ueller.gps.Satellite;
import de.ueller.gps.location.CellIdProvider;
import de.ueller.gps.location.Compass;
import de.ueller.gps.location.CompassProducer;
import de.ueller.gps.location.CompassReceiver;
import de.ueller.gps.location.GsmCell;
import de.ueller.gps.location.GetCompass;
import de.ueller.gps.location.LocationMsgProducer;
import de.ueller.gps.location.LocationMsgReceiver;
import de.ueller.gps.location.LocationMsgReceiverList;
import de.ueller.gps.location.LocationUpdateListener;
import de.ueller.gps.location.NmeaInput;
import de.ueller.gps.location.SECellId;
import de.ueller.gps.location.SirfInput;
//#if polish.api.osm-editing
import de.ueller.gpsmid.data.EditableWay;
//#endif
import de.ueller.gpsmid.data.Configuration;
import de.ueller.gpsmid.data.Gpx;
import de.ueller.gpsmid.data.Legend;
import de.ueller.gpsmid.data.PaintContext;
import de.ueller.gpsmid.data.Position;
import de.ueller.gpsmid.data.PositionMark;
import de.ueller.gpsmid.data.RoutePositionMark;
import de.ueller.gpsmid.data.SECellLocLogger;
import de.ueller.gpsmid.data.TrackPlayer;
import de.ueller.gpsmid.graphics.ImageCollector;
import de.ueller.gpsmid.graphics.Images;
import de.ueller.gpsmid.graphics.Proj2D;
import de.ueller.gpsmid.graphics.Proj3D;
import de.ueller.gpsmid.graphics.ProjFactory;
import de.ueller.gpsmid.graphics.Projection;
import de.ueller.gpsmid.mapdata.DictReader;
import de.ueller.gpsmid.mapdata.QueueDataReader;
import de.ueller.gpsmid.mapdata.QueueDictReader;
import de.ueller.gpsmid.mapdata.Way;
import de.ueller.gpsmid.mapdata.WaySegment;
import de.ueller.gpsmid.names.Names;
import de.ueller.gpsmid.names.Urls;
import de.ueller.gpsmid.routing.RouteConnectionTraces;
import de.ueller.gpsmid.routing.RouteHelpers;
import de.ueller.gpsmid.routing.RouteInstructions;
import de.ueller.gpsmid.routing.RouteLineProducer;
import de.ueller.gpsmid.routing.RouteNode;
import de.ueller.gpsmid.routing.RouteSyntax;
import de.ueller.gpsmid.routing.Routing;
import de.ueller.gpsmid.tile.Tile;
import de.ueller.gpsmid.tile.SingleTile;
import de.ueller.midlet.iconmenu.IconActionPerformer;
import de.ueller.midlet.iconmenu.LayoutElement;
import de.ueller.midlet.ui.CompletionListener;
import de.ueller.midlet.util.ImageCache;
import de.ueller.midlet.util.ImageTools;
import de.ueller.util.CancelMonitorInterface;
import de.ueller.util.DateTimeTools;
import de.ueller.util.HelperRoutines;
import de.ueller.util.IntPoint;
import de.ueller.util.Logger;
import de.ueller.util.MoreMath;
import de.ueller.util.ProjMath;
//#if polish.android
import de.enough.polish.android.lcdui.CanvasBridge;
import de.enough.polish.android.midlet.MidletBridge;
//#endif
/**
* Implements the main "Map" screen which displays the map, offers track recording etc.
* @author Harald Mueller
*
*/
public class Trace extends KeyCommandCanvas implements LocationMsgReceiver,
CompassReceiver, Runnable , GpsMidDisplayable, CompletionListener, IconActionPerformer {
/** Soft button for exiting the map screen */
protected static final int EXIT_CMD = 1;
protected static final int CONNECT_GPS_CMD = 2;
protected static final int DISCONNECT_GPS_CMD = 3;
protected static final int START_RECORD_CMD = 4;
protected static final int STOP_RECORD_CMD = 5;
protected static final int MANAGE_TRACKS_CMD = 6;
protected static final int SAVE_WAYP_CMD = 7;
protected static final int ENTER_WAYP_CMD = 8;
protected static final int MANAGE_WAYP_CMD = 9;
protected static final int ROUTING_TOGGLE_CMD = 10;
protected static final int CAMERA_CMD = 11;
protected static final int CLEAR_DEST_CMD = 12;
protected static final int SET_DEST_CMD = 13;
protected static final int MAPFEATURES_CMD = 14;
protected static final int RECORDINGS_CMD = 16;
protected static final int ROUTINGS_CMD = 17;
protected static final int OK_CMD =18;
protected static final int BACK_CMD = 19;
protected static final int ZOOM_IN_CMD = 20;
protected static final int ZOOM_OUT_CMD = 21;
protected static final int MANUAL_ROTATION_MODE_CMD = 22;
protected static final int TOGGLE_OVERLAY_CMD = 23;
protected static final int TOGGLE_BACKLIGHT_CMD = 24;
protected static final int TOGGLE_FULLSCREEN_CMD = 25;
protected static final int TOGGLE_MAP_PROJ_CMD = 26;
protected static final int TOGGLE_KEY_LOCK_CMD = 27;
protected static final int TOGGLE_RECORDING_CMD = 28;
protected static final int TOGGLE_RECORDING_SUSP_CMD = 29;
protected static final int RECENTER_GPS_CMD = 30;
protected static final int DATASCREEN_CMD = 31;
protected static final int OVERVIEW_MAP_CMD = 32;
protected static final int RETRIEVE_XML = 33;
protected static final int PAN_LEFT25_CMD = 34;
protected static final int PAN_RIGHT25_CMD = 35;
protected static final int PAN_UP25_CMD = 36;
protected static final int PAN_DOWN25_CMD = 37;
protected static final int PAN_LEFT2_CMD = 38;
protected static final int PAN_RIGHT2_CMD = 39;
protected static final int PAN_UP2_CMD = 40;
protected static final int PAN_DOWN2_CMD = 41;
protected static final int REFRESH_CMD = 42;
protected static final int SEARCH_CMD = 43;
protected static final int TOGGLE_AUDIO_REC = 44;
protected static final int ROUTING_START_CMD = 45;
protected static final int ROUTING_STOP_CMD = 46;
protected static final int ONLINE_INFO_CMD = 47;
protected static final int ROUTING_START_WITH_MODE_SELECT_CMD = 48;
protected static final int RETRIEVE_NODE = 49;
protected static final int ICON_MENU = 50;
protected static final int ABOUT_CMD = 51;
protected static final int SETUP_CMD = 52;
protected static final int SEND_MESSAGE_CMD = 53;
protected static final int SHOW_DEST_CMD = 54;
protected static final int EDIT_ADDR_CMD = 55;
protected static final int OPEN_URL_CMD = 56;
protected static final int SHOW_PREVIOUS_POSITION_CMD = 57;
protected static final int TOGGLE_GPS_CMD = 58;
protected static final int CELLID_LOCATION_CMD = 59;
protected static final int MANUAL_LOCATION_CMD = 60;
protected static final int EDIT_ENTITY = 61;
protected static final int NORTH_UP_CMD = 62;
protected static final int HELP_ONLINE_TOUCH_CMD = 63;
protected static final int HELP_ONLINE_WIKI_CMD = 64;
protected static final int KEYS_HELP_CMD = 65;
protected static final int ROUTE_TO_FAVORITE_CMD = 66;
protected static final int ROTATE_TRAVEL_MODE_CMD = 67;
protected static final int SAVE_PREDEF_WAYP_CMD = 68;
protected static final int TOUCH_HELP_CMD = 69;
protected static final int CMS_CMD = 70;
protected static final int TOGGLE_UNUSEABLEWAYS_DARKER = 71;
private final Command [] CMDS = new Command[72];
public static final int DATASCREEN_NONE = 0;
public static final int DATASCREEN_TACHO = 1;
public static final int DATASCREEN_TRIP = 2;
public static final int DATASCREEN_SATS = 3;
public final static int DISTANCE_GENERIC = 1;
public final static int DISTANCE_ALTITUDE = 2;
public final static int DISTANCE_ROAD = 3;
public final static int DISTANCE_AIR = 4;
public final static int DISTANCE_UNKNOWN = 5;
//#if polish.android
// FIXME should be set based on something like pixels per inch value
private final static int DRAGGEDMUCH_THRESHOLD = 24;
//#else
private final static int DRAGGEDMUCH_THRESHOLD = 8;
//#endif
// private SirfInput si;
private LocationMsgProducer locationProducer;
private LocationMsgProducer cellIDLocationProducer = null;
private CompassProducer compassProducer = null;
private volatile int compassDirection = 0;
private volatile int compassDeviation = 0;
private volatile int compassDeviated = 0;
private volatile int minX = 0;
private volatile int minY = 0;
private volatile int maxX = 0;
private volatile int maxY = 0;
private volatile int renderDiff = 0;
public byte solution = LocationMsgReceiver.STATUS_OFF;
public String solutionStr = Locale.get("solution.Off");
/** Flag if the user requested to be centered to the current GPS position (true)
* or if the user moved the map away from this position (false).
*/
public boolean gpsRecenter = true;
/** Flag if the gps position is not yet valid after recenter request
*/
public volatile boolean gpsRecenterInvalid = true;
/** Flag if the gps position is stale (last known position instead of current) after recenter request
*/
public volatile boolean gpsRecenterStale = true;
/** Flag if the map is autoZoomed
*/
public boolean autoZoomed = true;
private Position pos = new Position(0.0f, 0.0f,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis());
/**
* this node contains actually RAD coordinates
* although the constructor for Node(lat, lon) requires parameters in DEC format
* - e. g. "new Node(49.328010f, 11.352556f)"
*/
public Node center = new Node(49.328010f, 11.352556f);
private Node prevPositionNode = null;
// Projection projection;
private final GpsMid parent;
public static TraceLayout tl = null;
private String lastTitleMsg;
private String currentTitleMsg;
private volatile int currentTitleMsgOpenCount = 0;
private volatile int setTitleMsgTimeout = 0;
private String lastTitleMsgClock;
private String currentAlertTitle;
private String currentAlertMessage;
private volatile int currentAlertsOpenCount = 0;
private volatile int setAlertTimeout = 0;
private long lastBackLightOnTime = 0;
private volatile static long lastUserActionTime = 0;
private long collected = 0;
public PaintContext pc;
public float scale = Configuration.getRealBaseScale();
int showAddons = 0;
/** x position display was touched last time (on pointerPressed() ) */
private static int touchX = 0;
/** y position display was touched last time (on pointerPressed() ) */
private static int touchY = 0;
/** x position display was released last time (on pointerReleased() ) */
private static int touchReleaseX = 0;
/** y position display was released last time (on pointerReleased() ) */
private static int touchReleaseY = 0;
/** center when display was touched last time (on pointerReleased() ) */
private static Node centerPointerPressedN = new Node();
private static Node pickPointStart = new Node();
private static Node pickPointEnd = new Node();
private static Node centerNode = new Node();
/**
* time at which a pointer press occured to determine
* single / double / long taps
*/
private long pressedPointerTime;
/**
* indicates if the next release event is valid or the corresponding pointer pressing has already been handled
*/
private volatile boolean pointerActionDone;
/** timer checking for single tap */
private volatile TimerTask singleTapTimerTask = null;
/** timer checking for long tap */
private volatile TimerTask longTapTimerTask = null;
/** timer for returning to small buttons */
private volatile TimerTask bigButtonTimerTask = null;
/**
* Indicates that there was any drag event since the last pointerPressed
*/
private static volatile boolean pointerDragged = false;
/**
* Indicates that there was a rather far drag event since the last pointerPressed
*/
private static volatile boolean pointerDraggedMuch = false;
/** indicates whether we already are checking for a single tap in the TimerTask */
private static volatile boolean checkingForSingleTap = false;
private final int DOUBLETAP_MAXDELAY = 300;
private final int LONGTAP_DELAY = 1000;
/** Flag if a route is currently being calculated */
public volatile boolean routeCalc = false;
public Tile tiles[] = new Tile[DictReader.NUM_DICT_ZOOMLEVELS];
public volatile boolean baseTilesRead = false;
public Way actualSpeedLimitWay;
public volatile Way actualWay;
public volatile SingleTile actualSingleTile;
private long oldRecalculationTime;
/** List representing the submenu "Recordings" */
private List recordingsMenu = null;
/** Array of command numbers corresponding to the items in recordingsMenu */
private int[] recordingsMenuCmds = null;
/** List representing the submenu "Routing" */
private List routingsMenu = null;
private GuiTacho guiTacho = null;
private GuiTrip guiTrip = null;
private GuiSatellites guiSatellites = null;
private GuiWaypointSave guiWaypointSave = null;
private final GuiWaypointPredefined guiWaypointPredefined = null;
private static TraceIconMenu traceIconMenu = null;
private static GuiDiscover guiDiscover = null;
private static GuiDiscoverIconMenu guiDiscoverIconMenu = null;
private static CMSLayout cmsl = null;
private final static Logger logger = Logger.getInstance(Trace.class, Logger.DEBUG);
//#mdebug info
public static final String statMsg[] = { "no Start1:", "no Start2:",
"to long :", "interrupt:", "checksum :", "no End1 :",
"no End2 :" };
//#enddebug
/**
* Quality of Bluetooth reception, 0..100.
*/
private byte btquality;
private int[] statRecord;
/**
* Current speed from GPS in km/h.
*/
public volatile int speed;
public volatile float fspeed;
/**
* variables for setting course from GPS movement
* TODO: make speed threshold (currently courseMinSpeed)
* user-settable by transfer mode in the style file
* and/or in user menu
*/
// was three until release 0.7; less than three allows
// for course setting even with slow walking, while
// the heuristics filter away erratic courses
// I've even tested with 0.5f with good results --jkpj
private final float courseMinSpeed = 1.5f;
private volatile int prevCourse = -1;
private volatile int secondPrevCourse = -1;
private volatile int thirdPrevCourse = -1;
/**
* Current altitude from GPS in m.
*/
public volatile int altitude;
/**
* Flag if we're speeding
*/
private volatile boolean speeding = false;
private long lastTimeOfSpeedingSound = 0;
private long startTimeOfSpeedingSign = 0;
private int speedingSpeedLimit = 0;
//#if polish.api.finland
private volatile boolean cameraAlert = false;
private long startTimeOfCameraAlert = 0;
//#endif
private volatile boolean nodeAlert = false;
private volatile int alertNodeType = 0;
private long startTimeOfAlertSign = 0;
/**
* Current course from GPS in compass degrees, 0..359.
*/
private int course = 0;
private int coursegps = 0;
// is current course valid for deciding on how to route
private boolean courseValid = false;
public boolean atDest = false;
public boolean movedAwayFromDest = true;
private Names namesThread;
private Urls urlsThread;
private ImageCollector imageCollector;
private QueueDataReader tileReader;
private QueueDictReader dictReader;
private final Runtime runtime = Runtime.getRuntime();
private StringBuffer sbTemp = new StringBuffer();
private long lLastDragTime = 0;
private RoutePositionMark dest = null;
WaySegment waySegment = new WaySegment();
public Vector route = null;
private RouteInstructions ri = null;
private boolean running = false;
private static final int CENTERPOS = Graphics.HCENTER | Graphics.VCENTER;
public Gpx gpx;
public AudioRecorder audioRec;
private static volatile Trace traceInstance = null;
private volatile Routing routeEngine;
/*
private static Font smallBoldFont;
private static int smallBoldFontHeight;
*/
public boolean manualRotationMode = false;
public Vector locationUpdateListeners;
private Projection panProjection;
private boolean showingTraceIconMenu = false;
private boolean showingSplitSearch = false;
private boolean showingSplitSetup = false;
private boolean showingSplitCMS = false;
private GuiWaypointPredefinedForm mForm;
private Vector clickableMarkers;
private IntPoint centerP;
private GuiSearch guiSearch;
public class ClickableCoords {
int x;
int y;
String url;
String phone;
int nodeID;
}
private Trace() throws Exception {
//#debug
logger.info("init Trace");
this.parent = GpsMid.getInstance();
Configuration.setHasPointerEvents(hasPointerEvents());
CMDS[EXIT_CMD] = new Command(Locale.get("generic.Exit")/*Exit*/, Command.EXIT, 2);
CMDS[REFRESH_CMD] = new Command(Locale.get("trace.Refresh")/*Refresh*/, Command.ITEM, 4);
CMDS[SEARCH_CMD] = new Command(Locale.get("generic.Search")/*Search*/, Command.OK, 1);
CMDS[CONNECT_GPS_CMD] = new Command(Locale.get("trace.StartGPS")/*Start GPS*/,Command.ITEM, 2);
CMDS[DISCONNECT_GPS_CMD] = new Command(Locale.get("trace.StopGPS")/*Stop GPS*/,Command.ITEM, 2);
CMDS[TOGGLE_GPS_CMD] = new Command(Locale.get("trace.ToggleGPS")/*Toggle GPS*/,Command.ITEM, 2);
CMDS[START_RECORD_CMD] = new Command(Locale.get("trace.StartRecord")/*Start record*/,Command.ITEM, 4);
CMDS[STOP_RECORD_CMD] = new Command(Locale.get("trace.StopRecord")/*Stop record*/,Command.ITEM, 4);
CMDS[MANAGE_TRACKS_CMD] = new Command(Locale.get("trace.ManageTracks")/*Manage tracks*/,Command.ITEM, 5);
CMDS[SAVE_WAYP_CMD] = new Command(Locale.get("trace.SaveWaypoint")/*Save waypoint*/,Command.ITEM, 7);
CMDS[ENTER_WAYP_CMD] = new Command(Locale.get("trace.EnterWaypoint")/*Enter waypoint*/,Command.ITEM, 7);
CMDS[MANAGE_WAYP_CMD] = new Command(Locale.get("trace.ManageWaypoints")/*Manage waypoints*/,Command.ITEM, 7);
CMDS[ROUTING_TOGGLE_CMD] = new Command(Locale.get("trace.ToggleRouting")/*Toggle routing*/,Command.ITEM, 3);
CMDS[CAMERA_CMD] = new Command(Locale.get("trace.Camera")/*Camera*/,Command.ITEM, 9);
CMDS[CLEAR_DEST_CMD] = new Command(Locale.get("trace.ClearDestination")/*Clear destination*/,Command.ITEM, 10);
CMDS[SET_DEST_CMD] = new Command(Locale.get("trace.AsDestination")/*As destination*/,Command.ITEM, 11);
CMDS[MAPFEATURES_CMD] = new Command(Locale.get("trace.MapFeatures")/*Map Features*/,Command.ITEM, 12);
CMDS[RECORDINGS_CMD] = new Command(Locale.get("trace.Recordings")/*Recordings...*/,Command.ITEM, 4);
CMDS[ROUTINGS_CMD] = new Command(Locale.get("trace.Routing3")/*Routing...*/,Command.ITEM, 3);
CMDS[OK_CMD] = new Command(Locale.get("generic.OK")/*OK*/,Command.OK, 14);
CMDS[BACK_CMD] = new Command(Locale.get("generic.Back")/*Back*/,Command.BACK, 15);
CMDS[ZOOM_IN_CMD] = new Command(Locale.get("trace.ZoomIn")/*Zoom in*/,Command.ITEM, 100);
CMDS[ZOOM_OUT_CMD] = new Command(Locale.get("trace.ZoomOut")/*Zoom out*/,Command.ITEM, 100);
CMDS[MANUAL_ROTATION_MODE_CMD] = new Command(Locale.get("trace.ManualRotation2")/*Manual rotation mode*/,Command.ITEM, 100);
CMDS[TOGGLE_OVERLAY_CMD] = new Command(Locale.get("trace.NextOverlay")/*Next overlay*/,Command.ITEM, 100);
CMDS[TOGGLE_BACKLIGHT_CMD] = new Command(Locale.get("trace.KeepBacklight")/*Keep backlight on/off*/,Command.ITEM, 100);
CMDS[TOGGLE_FULLSCREEN_CMD] = new Command(Locale.get("trace.SwitchToFullscreen")/*Switch to fullscreen*/,Command.ITEM, 100);
CMDS[TOGGLE_MAP_PROJ_CMD] = new Command(Locale.get("trace.NextMapProjection")/*Next map projection*/,Command.ITEM, 100);
CMDS[TOGGLE_KEY_LOCK_CMD] = new Command(Locale.get("trace.ToggleKeylock")/*(De)Activate Keylock*/,Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_CMD] = new Command(Locale.get("trace.ToggleRecording")/*(De)Activate recording*/,Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_SUSP_CMD] = new Command(Locale.get("trace.SuspendRecording")/*Suspend recording*/,Command.ITEM, 100);
CMDS[RECENTER_GPS_CMD] = new Command(Locale.get("trace.RecenterOnGPS")/*Recenter on GPS*/,Command.ITEM, 100);
CMDS[SHOW_DEST_CMD] = new Command(Locale.get("trace.ShowDestination")/*Show destination*/,Command.ITEM, 100);
CMDS[SHOW_PREVIOUS_POSITION_CMD] = new Command(Locale.get("trace.ShowPreviousPosition")/*Previous position*/,Command.ITEM, 100);
CMDS[DATASCREEN_CMD] = new Command(Locale.get("trace.Tacho")/*Tacho*/, Command.ITEM, 15);
CMDS[OVERVIEW_MAP_CMD] = new Command(Locale.get("trace.OverviewFilterMap")/*Overview/Filter map*/, Command.ITEM, 20);
CMDS[RETRIEVE_XML] = new Command(Locale.get("trace.RetrieveXML")/*Retrieve XML*/,Command.ITEM, 200);
CMDS[EDIT_ENTITY] = new Command(Locale.get("traceiconmenu.EditPOI")/*Edit POI*/,Command.ITEM, 200);
CMDS[PAN_LEFT25_CMD] = new Command(Locale.get("trace.left25")/*left 25%*/,Command.ITEM, 100);
CMDS[PAN_RIGHT25_CMD] = new Command(Locale.get("trace.right25")/*right 25%*/,Command.ITEM, 100);
CMDS[PAN_UP25_CMD] = new Command(Locale.get("trace.up25")/*up 25%*/,Command.ITEM, 100);
CMDS[PAN_DOWN25_CMD] = new Command(Locale.get("trace.down25")/*down 25%*/,Command.ITEM, 100);
CMDS[PAN_LEFT2_CMD] = new Command(Locale.get("trace.left2")/*left 2*/,Command.ITEM, 100);
CMDS[PAN_RIGHT2_CMD] = new Command(Locale.get("trace.right2")/*right 2*/,Command.ITEM, 100);
CMDS[PAN_UP2_CMD] = new Command(Locale.get("trace.up2")/*up 2*/,Command.ITEM, 100);
CMDS[PAN_DOWN2_CMD] = new Command(Locale.get("trace.down2")/*down 2*/,Command.ITEM, 100);
CMDS[TOGGLE_AUDIO_REC] = new Command(Locale.get("trace.AudioRecording")/*Audio recording*/,Command.ITEM, 100);
CMDS[ROUTING_START_CMD] = new Command(Locale.get("trace.CalculateRoute")/*Calculate route*/,Command.ITEM, 100);
CMDS[ROUTING_STOP_CMD] = new Command(Locale.get("trace.StopRouting")/*Stop routing*/,Command.ITEM, 100);
CMDS[ONLINE_INFO_CMD] = new Command(Locale.get("trace.OnlineInfo")/*Online info*/,Command.ITEM, 100);
CMDS[ROUTING_START_WITH_MODE_SELECT_CMD] = new Command(Locale.get("trace.CalculateRoute2")/*Calculate route...*/,Command.ITEM, 100);
CMDS[RETRIEVE_NODE] = new Command(Locale.get("trace.AddPOI")/*Add POI to OSM...*/,Command.ITEM, 100);
CMDS[ICON_MENU] = new Command(Locale.get("trace.Menu")/*Menu*/,Command.OK, 100);
CMDS[SETUP_CMD] = new Command(Locale.get("trace.Setup")/*Setup*/, Command.ITEM, 25);
CMDS[ABOUT_CMD] = new Command(Locale.get("generic.About")/*About*/, Command.ITEM, 30);
//#if polish.api.wmapi
CMDS[SEND_MESSAGE_CMD] = new Command(Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/,Command.ITEM, 20);
//#endif
CMDS[EDIT_ADDR_CMD] = new Command(Locale.get("trace.AddAddrNode")/*Add Addr node*/,Command.ITEM,100);
CMDS[CELLID_LOCATION_CMD] = new Command(Locale.get("trace.CellidLocation")/*Set location from CellID*/,Command.ITEM,100);
CMDS[MANUAL_LOCATION_CMD] = new Command(Locale.get("trace.ManualLocation")/*Set location manually*/,Command.ITEM,100);
CMDS[HELP_ONLINE_TOUCH_CMD] = new Command(Locale.get("guidiscovericonmenu.Touch")/**/,Command.ITEM,100);
CMDS[HELP_ONLINE_WIKI_CMD] = new Command(Locale.get("guidiscovericonmenu.Wiki")/**/,Command.ITEM,100);
CMDS[KEYS_HELP_CMD] = new Command(Locale.get("guidiscover.KeyShortcuts")/**/,Command.ITEM,100);
CMDS[ROUTE_TO_FAVORITE_CMD] = new Command(Locale.get("guidiscover.KeyShortcuts")/**/,Command.ITEM,100);
CMDS[ROTATE_TRAVEL_MODE_CMD] = new Command(Locale.get("guiroute.TravelBy")/**/,Command.ITEM,100);
CMDS[TOUCH_HELP_CMD] = new Command(Locale.get("trace.touchhelp")/*Touchscreen functions*/,Command.ITEM,100);
CMDS[CMS_CMD] = new Command(Locale.get("trace.Tacho")/*Tacho*/, Command.ITEM, 100);
CMDS[TOGGLE_UNUSEABLEWAYS_DARKER] = new Command(Locale.get("trace.ToggleUnuseableWaysDarker")/*Toggle unuseable ways darker */, Command.ITEM, 100);
addAllCommands();
//#if polish.android
View androidView = (View) CanvasBridge.current();
androidView.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN
|| event.getAction() == KeyEvent.ACTION_UP)
{
- //eat menu code so the system won't handle it
- if (keyCode == KeyEvent.KEYCODE_MENU)
+ //eat menu code in the map screen so the system won't handle it
+ if (keyCode == KeyEvent.KEYCODE_MENU && imageCollector != null && imageCollector.isRunning())
{
if (event.getAction() == KeyEvent.ACTION_UP) {
commandAction(Trace.ICON_MENU);
}
return true;
}
}
return false;
}
});
//#endif
if (Legend.isValid) {
Configuration.loadKeyShortcuts(gameKeyCommand, singleKeyPressCommand,
repeatableKeyPressCommand, doubleKeyPressCommand, longKeyPressCommand,
nonReleasableKeyPressCommand, CMDS);
}
if (!Configuration.getCfgBitState(Configuration.CFGBIT_CANVAS_SPECIFIC_DEFAULTS_DONE)) {
if (getWidth() > 219) {
// if the map display is wide enough, show the clock in the map screen by default
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP, true);
// if the map display is wide enough, use big tab buttons by default
Configuration.setCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_BIG_TAB_BUTTONS, true);
}
if (Math.min(getWidth(), getHeight()) > 300) {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_NAVI_ARROWS_BIG, true);
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SHOW_TRAVEL_MODE_IN_MAP, true);
}
if (Math.max(getWidth(), getHeight()) > 400) {
Configuration.setBaseScale(24);
Configuration.setMinRouteLineWidth(5);
}
if (hasPointerEvents()) {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_LARGE_FONT, true);
}
Configuration.setCfgBitSavedState(Configuration.CFGBIT_CANVAS_SPECIFIC_DEFAULTS_DONE, true);
}
try {
if (Legend.isValid) {
startup();
}
} catch (Exception e) {
logger.fatal(Locale.get("trace.GotExceptionDuringStartup")/*Got an exception during startup: */ + e.getMessage());
e.printStackTrace();
return;
}
// setTitle("initTrace ready");
locationUpdateListeners = new Vector();
traceInstance = this;
}
public Command getCommand(int command) {
return CMDS[command];
}
/**
* Returns the instance of the map screen. If none exists yet,
* a new instance is generated
* @return Reference to singleton instance
*/
public static synchronized Trace getInstance() {
if (traceInstance == null) {
try {
traceInstance = new Trace();
} catch (Exception e) {
logger.exception(Locale.get("trace.FailedToInitialiseMapScreen")/*Failed to initialise Map screen*/, e);
}
}
return traceInstance;
}
public float getGpsLat() {
return pos.latitude;
}
public float getGpsLon() {
return pos.longitude;
}
public void stopCompass() {
if (compassProducer != null) {
compassProducer.close();
}
compassProducer = null;
}
public void startCompass() {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer == null) {
compassProducer = new GetCompass();
if (!compassProducer.init(this)) {
logger.info("Failed to init compass producer");
compassProducer = null;
} else if (!compassProducer.activate(this)) {
logger.info("Failed to activate compass producer");
compassProducer = null;
}
}
}
/**
* Starts the LocationProvider in the background
*/
public void run() {
try {
if (running) {
receiveMessage(Locale.get("trace.GpsStarterRunning")/*GPS starter already running*/);
return;
}
//#debug info
logger.info("start thread init locationprovider");
if (locationProducer != null) {
receiveMessage(Locale.get("trace.LocProvRunning")/*Location provider already running*/);
return;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_NONE) {
receiveMessage(Locale.get("trace.NoLocProv")/*"No location provider*/);
return;
}
running=true;
startCompass();
int locprov = Configuration.getLocationProvider();
receiveMessage(Locale.get("trace.ConnectTo")/*Connect to */ + Configuration.LOCATIONPROVIDER[locprov]);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_CELLID_STARTUP)) {
// Don't do initial lookup if we're going to start primary cellid location provider anyway
if (Configuration.getLocationProvider() != Configuration.LOCATIONPROVIDER_SECELL || !Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
commandAction(CELLID_LOCATION_CMD);
}
}
switch (locprov) {
case Configuration.LOCATIONPROVIDER_SIRF:
locationProducer = new SirfInput();
break;
case Configuration.LOCATIONPROVIDER_NMEA:
locationProducer = new NmeaInput();
break;
case Configuration.LOCATIONPROVIDER_SECELL:
if (cellIDLocationProducer != null) {
cellIDLocationProducer.close();
}
locationProducer = new SECellId();
break;
case Configuration.LOCATIONPROVIDER_JSR179:
//#if polish.api.locationapi
try {
String jsr179Version = null;
try {
jsr179Version = System.getProperty("microedition.location.version");
} catch (RuntimeException re) {
// Some phones throw exceptions if trying to access properties that don't
// exist, so we have to catch these and just ignore them.
} catch (Exception e) {
// As above
}
//#if polish.android
// FIXME current (2010-06, 2011-07 (2.2.1)) android j2mepolish doesn't give this info
//#else
if (jsr179Version != null && jsr179Version.length() > 0) {
//#endif
Class jsr179Class = Class.forName("de.ueller.gps.location.Jsr179Input");
locationProducer = (LocationMsgProducer) jsr179Class.newInstance();
//#if polish.android
//#else
}
//#endif
} catch (ClassNotFoundException cnfe) {
locationDecoderEnd();
logger.exception(Locale.get("trace.NoJSR179Support")/*Your phone does not support JSR179, please use a different location provider*/, cnfe);
running = false;
return;
}
//#else
// keep Eclipse happy
if (true) {
logger.error(Locale.get("trace.JSR179NotCompiledIn")/*JSR179 is not compiled in this version of GpsMid*/);
running = false;
return;
}
//#endif
break;
case Configuration.LOCATIONPROVIDER_ANDROID:
//#if polish.android
try {
Class AndroidLocationInputClass = Class.forName("de.ueller.gps.location.AndroidLocationInput");
locationProducer = (LocationMsgProducer) AndroidLocationInputClass.newInstance();
} catch (ClassNotFoundException cnfe) {
locationDecoderEnd();
logger.exception(Locale.get("trace.NoAndroidSupport")/*Your phone does not support Android location API, please use a different location provider*/, cnfe);
running = false;
return;
}
//#else
// keep Eclipse happy
if (true) {
logger.error(Locale.get("trace.AndroidNotCompiledIn")/*Location API for Android is not compiled in this version of GpsMid*/);
running = false;
return;
}
//#endif
break;
}
//#if polish.api.fileconnection
/**
* Allow for logging the raw data coming from the gps
*/
String url = Configuration.getGpsRawLoggerUrl();
//logger.error("Raw logging url: " + url);
if (url != null) {
try {
if (Configuration.getGpsRawLoggerEnable()) {
logger.info("Raw Location logging to: " + url);
url += "rawGpsLog" + HelperRoutines.formatSimpleDateNow() + ".txt";
//#if polish.android
de.enough.polish.android.io.Connection logCon = Connector.open(url);
//#else
javax.microedition.io.Connection logCon = Connector.open(url);
//#endif
if (logCon instanceof FileConnection) {
FileConnection fileCon = (FileConnection)logCon;
if (!fileCon.exists()) {
fileCon.create();
}
locationProducer.enableRawLogging(((FileConnection)logCon).openOutputStream());
} else {
logger.info("Raw logging of NMEA is only to filesystem supported");
}
}
/**
* Help out the OpenCellId.org project by gathering and logging
* data of cell ids together with current Gps location. This information
* can then be uploaded to their web site to determine the position of the
* cell towers. It currently only works for SE phones
*/
if (Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
SECellLocLogger secl = new SECellLocLogger();
if (secl.init()) {
locationProducer.addLocationMsgReceiver(secl);
}
}
} catch (IOException ioe) {
logger.exception(Locale.get("trace.CouldntOpenFileForRawLogging")/*Could not open file for raw logging of Gps data*/,ioe);
} catch (SecurityException se) {
logger.error(Locale.get("trace.PermissionWritingDataDenied")/*Permission to write data for NMEA raw logging was denied*/);
}
}
//#endif
if (locationProducer == null) {
logger.error(Locale.get("trace.ChooseDiffLocMethod")/*Your phone does not seem to support this method of location input, please choose a different one*/);
running = false;
return;
}
if (!locationProducer.init(this)) {
logger.info("Failed to initialise location producer");
running = false;
return;
}
if (!locationProducer.activate(this)) {
logger.info("Failed to activate location producer");
running = false;
return;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_CONNECT)) {
GpsMid.mNoiseMaker.playSound("CONNECT");
}
//#debug debug
logger.debug("rm connect, add disconnect");
removeCommand(CMDS[CONNECT_GPS_CMD]);
addCommand(CMDS[DISCONNECT_GPS_CMD]);
//#debug info
logger.info("end startLocationPovider thread");
// setTitle("lp="+Configuration.getLocationProvider() + " " + Configuration.getBtUrl());
} catch (SecurityException se) {
/**
* The application was not permitted to connect to the required resources
* Not much we can do here other than gracefully shutdown the thread *
*/
} catch (OutOfMemoryError oome) {
logger.fatal(Locale.get("trace.TraceThreadCrashOOM")/*Trace thread crashed as out of memory: */ + oome.getMessage());
oome.printStackTrace();
} catch (Exception e) {
logger.fatal(Locale.get("trace.TraceThreadCrashWith")/*Trace thread crashed unexpectedly with error */ + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
running = false;
} finally {
running = false;
}
running = false;
}
// add the command only if icon menus are not used
public void addCommand(Command c) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
super.addCommand(c);
}
}
public RoutePositionMark getDest() {
return dest;
}
// remove the command only if icon menus are not used
public void removeCommand(Command c) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
super.removeCommand(c);
}
}
public synchronized void pause() {
logger.debug("Pause application called");
if (imageCollector != null) {
if (! (routeCalc || route != null)) {
logger.debug("Suspending imageCollector");
imageCollector.suspend();
}
}
// don't pause if we're logging GPX or routing
if (locationProducer != null && !gpx.isRecordingTrk() && ! (routeCalc || route != null)) {
logger.debug("Closing locationProducer");
locationProducer.close();
// wait for locationProducer to close
int polling = 0;
while ((locationProducer != null) && (polling < 7)) {
polling++;
try {
wait(200);
} catch (InterruptedException e) {
break;
}
}
if (locationProducer != null) {
logger.error(Locale.get("trace.LocationProducerTookTooLong")/*LocationProducer took too long to close, giving up*/);
}
}
}
public void resumeAfterPause() {
logger.debug("resuming application after pause");
if (imageCollector != null) {
imageCollector.resume();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS) && !running && (locationProducer == null)) {
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
}
public void resume() {
logger.debug("resuming application");
if (imageCollector != null) {
imageCollector.resume();
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
public void autoRouteRecalculate() {
if ( gpsRecenter && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_AUTO_RECALC) ) {
if (Math.abs(System.currentTimeMillis()-oldRecalculationTime) >= 7000 ) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getRecalculationSound(), (byte) 5, (byte) 1 );
}
//#debug debug
logger.debug("autoRouteRecalculate");
// recalculate route
commandAction(ROUTING_START_CMD);
}
}
}
public boolean isGpsConnected() {
return (locationProducer != null && solution != LocationMsgReceiver.STATUS_OFF);
}
/**
* Adds all commands for a normal menu.
*/
public void addAllCommands() {
addCommand(CMDS[EXIT_CMD]);
addCommand(CMDS[SEARCH_CMD]);
if (isGpsConnected()) {
addCommand(CMDS[DISCONNECT_GPS_CMD]);
} else {
addCommand(CMDS[CONNECT_GPS_CMD]);
}
//TODO Cleanup addCommand(CMDS[MANAGE_TRACKS_CMD]);
//addCommand(CMDS[MAN_WAYP_CMD]);
addCommand(CMDS[ROUTINGS_CMD]);
addCommand(CMDS[RECORDINGS_CMD]);
addCommand(CMDS[MAPFEATURES_CMD]);
addCommand(CMDS[DATASCREEN_CMD]);
addCommand(CMDS[OVERVIEW_MAP_CMD]);
//#if polish.api.online
addCommand(CMDS[ONLINE_INFO_CMD]);
//#if polish.api.osm-editing
addCommand(CMDS[RETRIEVE_XML]);
addCommand(CMDS[EDIT_ENTITY]);
addCommand(CMDS[RETRIEVE_NODE]);
addCommand(CMDS[EDIT_ADDR_CMD]);
//#endif
//#endif
addCommand(CMDS[SETUP_CMD]);
addCommand(CMDS[ABOUT_CMD]);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
//#ifndef polish.android
super.addCommand(CMDS[ICON_MENU]);
//#endif
}
}
setCommandListener(this);
}
/**
* This method must remove all commands that were added by addAllCommands().
*/
public void removeAllCommands() {
//setCommandListener(null);
/* Although j2me documentation says removeCommand for a non-attached command is allowed
* this would crash MicroEmulator. Thus we only remove the commands attached.
*/
removeCommand(CMDS[EXIT_CMD]);
removeCommand(CMDS[SEARCH_CMD]);
if (isGpsConnected()) {
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
} else {
removeCommand(CMDS[CONNECT_GPS_CMD]);
}
//TODO Cleanup removeCommand(CMDS[MANAGE_TRACKS_CMD]);
//removeCommand(CMDS[MAN_WAYP_CMD]);
removeCommand(CMDS[MAPFEATURES_CMD]);
removeCommand(CMDS[RECORDINGS_CMD]);
removeCommand(CMDS[ROUTINGS_CMD]);
removeCommand(CMDS[DATASCREEN_CMD]);
removeCommand(CMDS[OVERVIEW_MAP_CMD]);
//#if polish.api.online
removeCommand(CMDS[ONLINE_INFO_CMD]);
//#if polish.api.osm-editing
removeCommand(CMDS[RETRIEVE_XML]);
removeCommand(CMDS[EDIT_ENTITY]);
removeCommand(CMDS[RETRIEVE_NODE]);
removeCommand(CMDS[EDIT_ADDR_CMD]);
//#endif
//#endif
removeCommand(CMDS[SETUP_CMD]);
removeCommand(CMDS[ABOUT_CMD]);
removeCommand(CMDS[CELLID_LOCATION_CMD]);
removeCommand(CMDS[MANUAL_LOCATION_CMD]);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
//#ifndef polish.android
super.removeCommand(CMDS[ICON_MENU]);
//#endif
}
}
}
/** Sets the Canvas to fullScreen or windowed mode
* when icon menus are active the Menu command gets removed
* so the Canvas will not unhide the menu bar first when pressing fire (e.g. on SE mobiles)
*/
public void setFullScreenMode(boolean fullScreen) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
//#ifndef polish.android
if (fullScreen) {
super.removeCommand(CMDS[ICON_MENU]);
} else
//#endif
{
//#ifndef polish.android
super.addCommand(CMDS[ICON_MENU]);
//#endif
}
}
//#if polish.android
if (fullScreen) {
MidletBridge.instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
MidletBridge.instance.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
//#else
super.setFullScreenMode(fullScreen);
//#endif
}
public void commandAction(int actionId) {
// take care we'll update actualWay
if (actionId == RETRIEVE_XML || actionId == EDIT_ADDR_CMD) {
repaint();
}
//#if polish.android
final int actionToRun = actionId;
// FIXME would be better to use AsyncTask,
// see http://developer.android.com/resources/articles/painless-threading.html
MidletBridge.instance.runOnUiThread(
new Runnable() {
public void run() {
commandAction(CMDS[actionToRun], null);
}
});
//#else
commandAction(CMDS[actionId], null);
//#endif
}
public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelIndexDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelIndexDiff = -1;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelIndexDiff = 1;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelIndexDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 5000)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelIndexDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (compassDeviation < 0) {
compassDeviation += 360;
}
deviateCompass();
course = compassDeviated;
updatePosition();
}
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
validateCourse();
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_SPLITSCREEN)
&& hasPointerEvents()) {
showingTraceIconMenu = false;
showingSplitCMS = false;
showingSplitSearch = true;
guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT);
guiSearch.sizeChanged(getWidth(), getHeight());
restartImageCollector();
} else {
guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT);
guiSearch.show();
}
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MANAGE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 5;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements;
if (gpx.isRecordingTrk()) {
noElements++;
elements = new String[noElements];
recordingsMenuCmds = new int[noElements];
recordingsMenuCmds[idx] = STOP_RECORD_CMD;
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop GPX tracklog*/;
if (gpx.isRecordingTrkSuspended()) {
recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD;
elements[idx++] = Locale.get("trace.ResumeRecording")/*Resume recording*/;
} else {
recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD;
elements[idx++] = Locale.get("trace.SuspendRecording")/*Suspend recording*/;
}
} else {
elements = new String[noElements];
recordingsMenuCmds = new int[noElements];
recordingsMenuCmds[idx] = START_RECORD_CMD;
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start GPX tracklog*/;
}
recordingsMenuCmds[idx] = SAVE_WAYP_CMD;
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
recordingsMenuCmds[idx] = ENTER_WAYP_CMD;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
recordingsMenuCmds[idx] = MANAGE_TRACKS_CMD;
elements[idx++] = Locale.get("trace.ManageTracks")/*Manage tracks*/;
recordingsMenuCmds[idx] = MANAGE_WAYP_CMD;
elements[idx++] = Locale.get("trace.ManageWaypoints")/*Manage waypoints*/;
//#if polish.api.mmapi
recordingsMenuCmds[idx] = CAMERA_CMD;
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC;
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC;
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
recordingsMenuCmds[idx] = SEND_MESSAGE_CMD;
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,
Choice.IMPLICIT, elements, null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = getPosMark();
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
showGuiWaypointSave(posMark);
}
*/
showGuiWaypointSave(posMark);
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
// if we clicked a clickable marker, get coords from the marker instead of tap
int x = centerP.x;
int y = centerP.y;
int xOverScan = 0;
int yOverScan = 0;
if (imageCollector != null) {
xOverScan = imageCollector.xScreenOverscan;
yOverScan = imageCollector.yScreenOverscan;
panProjection=imageCollector.getCurrentProjection();
} else {
panProjection = null;
}
ClickableCoords coords = getClickableMarker(x - xOverScan, y - yOverScan);
if (coords != null) {
x = coords.x;
y = coords.y;
}
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
centerNode=panProjection.inverse(x,
y, centerNode);
Position oPos = new Position(centerNode.radlat, centerNode.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc, true, coords != null ? coords.url : null,
coords != null ? coords.phone : null,
coords != null ? coords.nodeID : -1);
gWeb.show();
//#if 0
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
int recCmd = recordingsMenu.getSelectedIndex();
if (recCmd >= 0 && recCmd < recordingsMenuCmds.length) {
recCmd = recordingsMenuCmds[recCmd];
if (recCmd == STOP_RECORD_CMD) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else if (recCmd == START_RECORD_CMD) {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
} else if (recCmd == TOGGLE_RECORDING_SUSP_CMD) {
commandAction(TOGGLE_RECORDING_SUSP_CMD);
show();
} else {
commandAction(recCmd);
}
}
} else if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
Class GuiCameraClass = Class.forName("de.ueller.gpsmid.ui.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // Refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (!routeCalc || RouteLineProducer.isRunning()) { // if not in route calc or already producing the route line
// if the route line is currently being produced stop it
if (RouteLineProducer.isRunning()) {
RouteInstructions.abortRouteLineProduction();
}
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeEngine = new Routing(this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_UNUSEABLEWAYS_DARKER]) {
Configuration.setCfgBitState(Configuration.CFGBIT_DRAW_NON_TRAVELMODE_WAYS_DARKER,
!(Configuration.getCfgBitState(Configuration.CFGBIT_DRAW_NON_TRAVELMODE_WAYS_DARKER)),
false);
newDataReady();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[HELP_ONLINE_TOUCH_CMD]) {
GuiWebInfo.openUrl(GuiWebInfo.getStaticUrlForSite(Locale.get("guiwebinfo.helptouch")));
return;
}
if (c == CMDS[HELP_ONLINE_WIKI_CMD]) {
GuiWebInfo.openUrl(GuiWebInfo.getStaticUrlForSite(Locale.get("guiwebinfo.helpwiki")));
return;
}
if (c == CMDS[KEYS_HELP_CMD]) {
GuiKeyShortcuts gks = new GuiKeyShortcuts(this);
gks.show();
return;
}
if (c == CMDS[TOUCH_HELP_CMD]) {
TouchHelper th = new TouchHelper(this);
th.show();
return;
}
if (c == CMDS[NORTH_UP_CMD]) {
course = 0;
invalidateCourse();
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
invalidateCourse();
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
recordingsMenu = null; // Refresh recordings menu
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
return;
}
if (c == CMDS[CMS_CMD]) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_SPLITSCREEN)
&& hasPointerEvents()) {
cmsl = new CMSLayout(minX, 0 + getHeight() / 2, maxX, getHeight());
guiTrip = new GuiTrip();
guiTrip.init();
guiTacho = new GuiTacho();
guiTacho.init();
showingSplitCMS = true;
showingTraceIconMenu = false;
cmsl.setOnScreenButtonSize(false);
//cmsl.sizeChanged(getWidth(), getHeight());
restartImageCollector();
}
return;
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
if (isShowingSplitScreen()) {
stopShowingSplitScreen();
} else {
showIconMenu();
}
return;
}
if (c == CMDS[SETUP_CMD]) {
guiDiscover = new GuiDiscover(parent);
if (isShowingSplitIconMenu()) {
guiDiscoverIconMenu = new GuiDiscoverIconMenu(guiDiscover, guiDiscover);
showingTraceIconMenu = false;
showingSplitSetup = true;
showingSplitCMS = false;
guiDiscoverIconMenu.sizeChanged(getWidth(), getHeight());
restartImageCollector();
}
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellId();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((actualWay != null) && (actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)actualWay;
GuiOsmWayDisplay guiWay = new GuiOsmWayDisplay(eway, actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[EDIT_ENTITY]) {
// if we clicked a clickable marker, get coords from the marker instead of tap
int x = centerP.x;
int y = centerP.y;
int nodeID = -1;
int xOverScan = 0;
int yOverScan = 0;
if (imageCollector != null) {
xOverScan = imageCollector.xScreenOverscan;
yOverScan = imageCollector.yScreenOverscan;
panProjection=imageCollector.getCurrentProjection();
} else {
panProjection = null;
}
ClickableCoords coords = getClickableMarker(x - xOverScan, y - yOverScan);
if (coords != null) {
x = coords.x;
y = coords.y;
nodeID = coords.nodeID;
System.out.println("NodeID: " + nodeID);
}
if (Legend.enableEdits) {
// FIXME: do the following:
// * set a flag that default operation is OSM edit
// * do a search for nearby POIs, asking for type
// * when the user selects, open OSM editing
if (nodeID != -1) {
GuiOsmPoiDisplay guiNode = new GuiOsmPoiDisplay(nodeID, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
return;
} else {
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_EDIT_ENTITY);
guiSearch.show();
return;
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
if (Legend.enableEdits) {
GuiOsmPoiDisplay guiNode = new GuiOsmPoiDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
//if ((pc != null) && (pc.actualWay != null)) {
// streetName = getName(pc.actualWay.nameIdx);
//}
if (actualWay != null) {
streetName = getName(actualWay.nameIdx);
}
GuiOsmAddrDisplay guiAddr = new GuiOsmAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
if (c == CMDS[ROTATE_TRAVEL_MODE_CMD]) {
int mode = Configuration.getTravelModeNr();
mode++;
if (mode >= Legend.getTravelModes().length) {
mode = 0;
}
Configuration.setTravelMode(mode);
if (Configuration.getCfgBitState(Configuration.CFGBIT_DRAW_NON_TRAVELMODE_WAYS_DARKER)) {
newDataReady();
}
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
// Ensure that only one image collector runs at the same time.
if ( imageCollector != null ) {
imageCollector.stop();
// alert("FIXME", "Avoided duplicate ImageCollector", 1500);
}
// FIXME pass layout params to imagecollector
//setDisplayCoords();
//tl = new TraceLayout(minX, minY, maxX, maxY);
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
// wait until base tiles are read; otherwise there's apparently
// a race condition triggered on Symbian s60r3 phones, see
// https://sourceforge.net/support/tracker.php?aid=3284022
if (Legend.isValid) {
while (!baseTilesRead) {
try {
Thread.sleep(250);
} catch (InterruptedException e1) {
// nothing to do in that case
}
}
} else {
logger.fatal(Locale.get("legend.bigstyleserrtitle")/*Map format error*/ + " " + Configuration.getMapUrl());
commandAction(SETUP_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte) DictReader.GPXZOOMLEVEL);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void restart() {
shutdown();
setBaseTilesRead(false);
tiles = new Tile[6];
try {
startup();
} catch (Exception e) {
logger.fatal(Locale.get("trace.GotExceptionDuringStartup")/*Got an exception during startup: */ + e.getMessage());
e.printStackTrace();
return;
}
}
public void restartImageCollector() {
setDisplayCoords(getWidth(), getHeight());
updateLastUserActionTime();
if (imageCollector != null) {
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(minX, minY, maxX, maxY);
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
System.out.println("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
setDisplayCoords(w, h);
tl = new TraceLayout(minX, minY, maxX, maxY);
if (isShowingSplitIconMenu() && (traceIconMenu != null)) {
traceIconMenu.sizeChanged(w, h);
}
if (isShowingSplitSearch() && (guiSearch != null)) {
guiSearch.sizeChanged(w, h);
}
if (isShowingSplitSetup() && (guiDiscoverIconMenu != null)) {
guiDiscoverIconMenu.sizeChanged(w, h);
}
if (isShowingSplitCMS() && (cmsl != null)) {
cmsl.sizeChanged(w, h);
}
}
private void setDisplayCoords(int w, int h) {
maxX = w;
maxY = h;
if (isShowingSplitScreen()) {
maxY = h / 2;
renderDiff = 0;
}
}
// check if pointer operation coordinates are for some other function than trace
private boolean coordsForOthers(int x, int y) {
if (keyboardLocked) {
return false;
}
boolean notForTrace = (x > maxX);
if (isShowingSplitScreen()) {
if (y > maxY + renderDiff) {
notForTrace = true;
}
}
return notForTrace;
}
private void updateCMS(Graphics g) {
//LayoutElement e = null;
if (cmsl != null) {
int maxSpeed = 0;
if (actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
}
if (maxSpeed != 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
cmsl.ele[CMSLayout.SPEEDING_SIGN].setText(Integer.toString(maxSpeed));
} else {
cmsl.ele[CMSLayout.SPEEDING_SIGN].setText(Integer.toString((int)(maxSpeed / 1.609344f + 0.5f)));
}
}
if (guiTrip != null) {
int y = 48;
Position pos = getCurrentPosition();
//y = guiTrip.paintTrip(g, (cmsl.getMaxX() - cmsl.getMinX()), this.getWidth()/2, this.getWidth() / 2, this.getHeight() - 40, y, pos, getDestination(), this);
y = guiTrip.paintTrip(g, this.getWidth() / 4, this.getHeight()/2, this.getWidth() / 2, this.getHeight(), y, pos, getDestination(), this);
guiTrip.calcSun(this);
// Draw sunrise and sunset time
y += 24;
y = guiTrip.paintSun(g, this.getWidth() / 4,
this.getHeight()/2, this.getWidth()/2, this.getHeight(), y);
}
if (guiTacho != null) {
guiTacho.setValues(this, g);
guiTacho.paintTacho(g, this.getWidth() / 2,
this.getHeight() / 2, this.getWidth(), this.getHeight() / 4 * 3, getCurrentPosition());
}
}
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
if (!Legend.isValid) {
commandAction(SETUP_CMD);
}
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null && pc.getP() != null/*avoids exception at route calc*/) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
lLastDragTime = System.currentTimeMillis();
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
if (movedAwayFromDest
&& Configuration.getCfgBitState(Configuration.CFGBIT_STOP_ROUTING_AT_DESTINATION)) {
// stop routing
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
}
endRouting();
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ACCURACY) && pos.accuracy != Float.NaN && pos.accuracy > 0) {
eSolution.setText(solutionStr + "/" + (int) pos.accuracy);
} else {
eSolution.setText(solutionStr);
}
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// Display tile and paint state
if ( true ) {
sbTemp.setLength(0);
e = tl.ele[TraceLayout.REQUESTED_TILES];
if (tileReader.getRequestQueueSize() != 0) {
// Display the number of not yet loaded tiles.
sbTemp.append("T ");
sbTemp.append( tileReader.getRequestQueueSize());
}
if (imageCollector != null && imageCollector.iDrawState != 0 ) {
// Display a + if the image collector prepares the image.
if ( imageCollector.iDrawState == 1 )
sbTemp.append("+");
// Display a * if the image collector is drawing.
else if ( imageCollector.iDrawState == 2 )
sbTemp.append("*");
}
if (sbTemp.length() != 0 ) {
e.setText(sbTemp.toString());
}
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("guitacho.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + Locale.get("guitacho.mph"));
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_TRAVEL_MODE_IN_MAP)) {
e = tl.ele[TraceLayout.TRAVEL_MODE];
e.setText(Configuration.getTravelMode().getName());
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
if (Configuration.getCfgBitState(Configuration.CFGBIT_GPS_TIME)) {
if (pos.gpsTimeMillis != 0) {
e.setText(DateTimeTools.getClock(pos.gpsTimeMillis + Configuration.getTimeDiff()*1000*60, true));
} else if (Configuration.getCfgBitState(Configuration.CFGBIT_GPS_TIME_FALLBACK)) {
e.setText(DateTimeTools.getClock(System.currentTimeMillis() + Configuration.getTimeDiff()*1000*60, true));
} else {
e.setText(" ");
}
} else {
e.setText(DateTimeTools.getClock(System.currentTimeMillis() + Configuration.getTimeDiff()*1000*60, true));
}
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
if (isShowingSplitCMS()) {
updateCMS(g);
}
}
setAlertSign(Legend.getNodeTypeDesc((short) alertNodeType));
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) );
}
tl.ele[TraceLayout.RECORDINGS].setText("*");
tl.ele[TraceLayout.SEARCH].setText("_");
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
if (isShowingSplitTraceIconMenu() && traceIconMenu != null) {
traceIconMenu.paint(g);
}
if (isShowingSplitSearch() && guiSearch != null) {
guiSearch.paint(g);
}
if (isShowingSplitSetup() && guiDiscoverIconMenu != null) {
guiDiscoverIconMenu.paint(g);
}
if (isShowingSplitCMS() && cmsl != null) {
cmsl.paint(g);
}
}
public boolean isShowingSplitScreen() {
return showingTraceIconMenu || showingSplitSearch || showingSplitSetup || showingSplitCMS;
}
public static void clearTraceInstance() {
if (!Legend.isValid) {
traceInstance = null;
}
}
public boolean isShowingSplitSetup() {
return showingSplitSetup;
}
public boolean isShowingSplitCMS() {
return showingSplitCMS;
}
public void clearShowingSplitSetup() {
showingSplitSetup = false;
//restartImageCollector();
}
public void setShowingSplitTraceIconMenu() {
showingTraceIconMenu = true;
}
public boolean isShowingSplitIconMenu() {
return showingTraceIconMenu || showingSplitSetup;
}
public boolean isShowingSplitTraceIconMenu() {
return showingTraceIconMenu;
}
public boolean isShowingSplitSearch() {
return showingSplitSearch;
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = ((maxY - minY) - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
//speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
//#if polish.api.finland
String cameraString = "";
if (cameraAlert && startTimeOfCameraAlert == 0) {
startTimeOfCameraAlert = System.currentTimeMillis();
// FIXME get camera sound from config file, requires
// map format change to pass in legend
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
GpsMid.mNoiseMaker.immediateSound("CAMERA_ALERT");
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDCAMERA_ALERT)
&& cameraAlert) {
cameraString = Locale.get("trace.cameraText");
}
//#endif
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
//#if polish.api.finland
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(cameraString + Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(cameraString + Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f)));
}
if ((System.currentTimeMillis() - startTimeOfCameraAlert) >= 8000) {
cameraAlert = false;
startTimeOfCameraAlert = 0;
}
//#else
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f)));
}
//#endif
} else {
startTimeOfSpeedingSign = 0;
//#if polish.api.finland
startTimeOfCameraAlert = 0;
//#endif
}
}
private void setAlertSign(String alert) {
//FIXME use alert sign visual instead, get from legend after
// map format change
if (Configuration.getCfgBitState(Configuration.CFGBIT_NODEALERT_VISUAL)
&&
(
nodeAlert
||
(System.currentTimeMillis() - startTimeOfAlertSign) < 8000)
) {
if (nodeAlert && startTimeOfAlertSign == 0) {
startTimeOfAlertSign = System.currentTimeMillis();
//FIXME get sound from config file, requires
// map format change to pass in legend
if (Configuration.getCfgBitState(Configuration.CFGBIT_NODEALERT_SND)) {
GpsMid.mNoiseMaker.immediateSound("ALERT");
}
}
tl.ele[TraceLayout.SPEEDING_SIGN].setText(alert.substring(0,7));
if ((System.currentTimeMillis() - startTimeOfAlertSign) >= 8000) {
nodeAlert = false;
startTimeOfAlertSign = 0;
}
} else {
startTimeOfAlertSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
if (Legend.tileScaleLevelContainsRoutableWays[i]) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
StringBuffer c = new StringBuffer(5);
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c.append(Configuration.getCompassDirection(course));
}
// if tl shows big onscreen buttons add spaces to short compass directions
if (tl.bigOnScreenButtons) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c.setLength(0);
c.append('(').append(Configuration.getCompassDirection(0)).append(')');
}
while (c.length() <= 3) {
c.insert(0,' ').append(' ');
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c.toString());
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GsmCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL || Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = GetCompass.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
// Avoid exception after route calculation
if ( pc.getP() == null || imageCollector == null )
return;
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setStrokeStyle(Graphics.SOLID);
waySegment.drawWideLineSimple(
Legend.COLORS[Legend.COLOR_DEST_LINE],
new IntPoint(pc.getP().getImageCenter().x - imageCollector.xScreenOverscan, pc.getP().getImageCenter().y - imageCollector.yScreenOverscan),
new IntPoint(x, y),
Configuration.getDestLineWidth(), pc
);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
// Avoid exception after route calculation
if ( pc.getP() == null )
return;
centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public void deviateCompass() {
compassDeviated = (compassDirection + compassDeviation + 360) % 360;
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
deviateCompass();
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
//if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
// if (!Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
// updateCourse(compassDeviated);
// }
//repaint();
//}
// course = compassDeviated;
//}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_ALWAYS_ROTATE)
// if user is panning the map, don't rotate by compass
&& gpsRecenter
// if we have autoswitch, rotate by compass only when movement course is not valid
&& !(Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)
&& (fspeed >= courseMinSpeed && thirdPrevCourse != -1))) {
course = compassDeviated;
updatePosition();
}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public int getCourse() {
return course;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in that case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
// on 2011-04-11: jkpj switched from 1/4 rotation back to 3/4 rotation,
// returning to what it was supposed to do before 2010-11-30.
course = course + ((newcourse - course)*3)/4 + 360;
}
while (course > 360) {
course -= 360;
}
validateCourse();
}
public boolean isCourseValid() {
return courseValid;
}
private void invalidateCourse() {
courseValid = false;
}
private void validateCourse() {
courseValid = true;
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && !Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
thirdPrevCourse = secondPrevCourse;
secondPrevCourse = prevCourse;
// check for compass deviation auto-update, do it if set
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AUTOCALIBRATE)) {
compassDeviation = (int) pos.course - compassDirection;
deviateCompass();
}
} else if (prevCourse == -1) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
} // previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
secondPrevCourse = prevCourse;
updateCourse((int) pos.course);
} else {
secondPrevCourse = -1;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
}
}
prevCourse = (int) pos.course;
} else {
// speed under the minimum. If it went under the limit now, do a heuristic
// to decide a proper course.
// invalidate all prev courses
if (thirdPrevCourse != -1) {
// speed just went under the threshold
// - if the last readings are not within the 30 degree sector of
// the previous one, restore course to the third previous course,
// it's probable that it's more reliable than the last
// course, as we see that at traffic light stops
// an incorrect course is shown relatively often
if ((Math.abs(prevCourse - secondPrevCourse) < 15 || Math.abs(prevCourse - secondPrevCourse) > 345)
&& (Math.abs(thirdPrevCourse - secondPrevCourse) < 15 || Math.abs(thirdPrevCourse - secondPrevCourse) > 345)) {
// we're OK
} else {
updateCourse(thirdPrevCourse);
}
}
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
}
}
pos.altitude += Configuration.getAltitudeCorrection();
altitude = (int) (pos.altitude);
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
&& pos.speed != 0 // if speed is 0 do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
// autozoom in more at the last 200 m of the route
if (route != null && RouteInstructions.getDstRouteToDestination() <= 200) {
float newScale2 = newScale;
newScale2 = newScale / (1f + (200f - RouteInstructions.getDstRouteToDestination())/ 200f);
// fixed increased zoom for the last 100 m
newScale = Math.max(newScale2, newScale / 1.5f);
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
public void pointerPressed(int x, int y) {
//#if polish.android
previousBackPress = false;
//#endif
if (coordsForOthers(x, y)) {
// for icon menu
if (isShowingSplitTraceIconMenu() && traceIconMenu != null) {
traceIconMenu.pointerPressed(x, y);
return;
}
if (isShowingSplitSearch() && guiSearch != null) {
guiSearch.pointerPressed(x, y);
return;
}
if (isShowingSplitSetup() && guiDiscoverIconMenu != null) {
guiDiscoverIconMenu.pointerPressed(x, y);
return;
}
if (isShowingSplitCMS() && cmsl != null) {
cmsl.pointerPressed(x, y);
return;
}
}
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
return;
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
public void pointerReleased(int x, int y) {
if (coordsForOthers(x, y)) {
// for icon menu
if (isShowingSplitTraceIconMenu() && traceIconMenu != null) {
traceIconMenu.pointerReleased(x, y);
return;
}
if (isShowingSplitSearch() && guiSearch != null) {
guiSearch.pointerReleased(x, y);
return;
}
if (isShowingSplitSetup() && guiDiscoverIconMenu != null) {
guiDiscoverIconMenu.pointerReleased(x, y);
return;
}
if (isShowingSplitCMS() && cmsl != null) {
cmsl.pointerReleased(x, y);
return;
}
}
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
public void pointerDragged (int x, int y) {
if (coordsForOthers(x, y)) {
// for icon menu
if (isShowingSplitTraceIconMenu() && traceIconMenu != null) {
traceIconMenu.pointerDragged(x, y);
return;
}
if (isShowingSplitSearch() && guiSearch != null) {
guiSearch.pointerDragged(x, y);
return;
}
if (isShowingSplitSetup() && guiDiscoverIconMenu != null) {
guiDiscoverIconMenu.pointerDragged(x, y);
return;
}
if (isShowingSplitCMS() && cmsl != null) {
cmsl.pointerDragged(x, y);
return;
}
}
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > DRAGGEDMUCH_THRESHOLD
||
Math.abs(y - Trace.touchY) > DRAGGEDMUCH_THRESHOLD
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
long lCurrentTime = System.currentTimeMillis();
if ( lCurrentTime - lLastDragTime > 333) {
lLastDragTime = lCurrentTime;
repaint();
}
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
// check for clickable markers
// System.out.println("Checking for clickable markers");
boolean markerClicked = false;
ClickableCoords coords = getClickableMarker(x, y);
if (coords != null) {
markerClicked = true;
if (coords.url != null) {
GuiWebInfo.openUrl(coords.url);
return;
}
}
if (!markerClicked && !tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// to enable clickable markers only when single-tapped
//if (Configuration.getCfgBitState(Configuration.CFGBIT_CLICKABLE_MAPOBJECTS)) {
// newDataReady();
//}
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
// to enable clickable markers only when single-tapped
//if (Configuration.getCfgBitState(Configuration.CFGBIT_CLICKABLE_MAPOBJECTS)) {
// newDataReady();
//}
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 5000)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private ClickableCoords getClickableMarker(int x, int y) {
System.out.println("Click coords: " + x + " " + y);
if (clickableMarkers != null) {
for (int i = 0; i < clickableMarkers.size(); i++) {
ClickableCoords coords = (ClickableCoords)clickableMarkers.elementAt(i);
System.out.println("Marker coords: " + coords.x + " " + coords.y);
if (Math.abs(coords.x - x) <= Configuration.getTouchMarkerDiameter() / 2
&& Math.abs(coords.y - y) <= Configuration.getTouchMarkerDiameter() / 2) {
return coords;
}
}
}
return null;
}
private void longTap() {
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (!pointerDraggedMuch && Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
pointerActionDone = true;
//#debug debug
logger.debug("long tap map");
// if we clicked a clickable marker, get coords from the marker instead of tap
ClickableCoords coords = getClickableMarker(touchX, touchY);
if (coords != null) {
touchX = coords.x;
touchY = coords.y;
}
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
pickPointEnd=panProjection.inverse(touchX + imageCollector.xScreenOverscan,
touchY + imageCollector.yScreenOverscan, pickPointEnd);
Position oPos = new Position(pickPointEnd.radlat, pickPointEnd.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc, true, coords != null ? coords.url : null,
coords != null ? coords.phone : null,
coords != null ? coords.nodeID : -1);
gWeb.show();
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0 && tl.getElementAtPointer(touchX, touchY) == tl.getTouchedElement()) {
tl.clearTouchedElement();
repaint();
pointerActionDone = true;
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void setBaseTilesRead(boolean read) {
baseTilesRead = read;
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_GPS_TIME)) {
pos.gpsTimeMillis = 0;
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
if (status != LocationMsgReceiver.STATUS_ON
&& status != LocationMsgReceiver.STATUS_2D
&& status != LocationMsgReceiver.STATUS_3D
&& status != LocationMsgReceiver.STATUS_DGPS) {
// no fix, invalidate speed heuristic and GPS time
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
if (Configuration.getCfgBitState(Configuration.CFGBIT_GPS_TIME)) {
pos.gpsTimeMillis = 0;
}
}
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
// to update e.g. tacho
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
setDisplayCoords(getWidth(), getHeight());
tl = new TraceLayout(minX, minY, maxX, maxY);
}
public void resetSize() {
sizeChanged(getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public PositionMark getPosMark() {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
return posMark;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
RouteConnectionTraces.clear();
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
if (routeEngine != null) {
if (routeEngine.routeStartsAgainstMovingDirection) {
ri.forceAgainstDirection();
}
} else {
alert("Warning", "routeEngine==null", 3000);
}
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void stopShowingSplitScreen() {
showingSplitSetup = false;
showingTraceIconMenu = false;
showingSplitSearch = false;
showingSplitCMS = false;
resetSize();
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_SPLITSCREEN)
&& hasPointerEvents()) {
showingTraceIconMenu = true;
traceIconMenu.sizeChanged(getWidth(), getHeight());
restartImageCollector();
} else {
traceIconMenu.show();
}
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** paint big direction arrows for navigation */
public void setRouteIcon(PaintContext pc, int iconNumber, Image origIcon, int roundaboutExitNr) {
// FIXME would it be better for this to be an element in TraceLayout?
// Probably at least if the distance and optionally streetname
// are added to information shown
if (origIcon != null) {
int height = getHeight() / 7;
// FIXME: should keep aspect ratio
int width = height;
int x = (getHeight() >= 320 ? 5 : 30);
int y = 15 + getHeight()/40 + iconNumber * (height + getHeight()/40);
Image icon = ImageCache.getScaledImage(origIcon, width, height);
pc.g.drawImage(icon, x, y, Graphics.TOP|Graphics.LEFT);
if (roundaboutExitNr != 0) {
pc.g.setColor(0xFFFFFF);
Font font = Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_BOLD, Font.SIZE_LARGE);
pc.g.setFont(font);
int fontHeight = font.getHeight();
pc.g.drawString("" + roundaboutExitNr, x + width / 2, y + height / 2 - fontHeight/2, Graphics.TOP|Graphics.HCENTER);
}
}
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId, String choiceName) {
System.out.println("choiceName: " + choiceName);
if (!isShowingSplitScreen()) {
show();
}
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId == IconActionPerformer.BACK_ACTIONID) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_SPLITSCREEN)) {
stopShowingSplitScreen();
}
}
if (actionId == SAVE_PREDEF_WAYP_CMD && gpx != null && choiceName != null) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = getPosMark();
if (choiceName.indexOf("%s") != -1) {
mForm = new GuiWaypointPredefinedForm(this, this);
mForm.setData(choiceName, choiceName, TextField.ANY, posMark);
mForm.show();
} else if (choiceName.indexOf("%f") != -1) {
mForm = new GuiWaypointPredefinedForm(this, this);
mForm.setData(choiceName, choiceName, TextField.DECIMAL, posMark);
mForm.show();
} else {
posMark.displayName = choiceName;
}
gpx.addWayPt(posMark);
newDataReady();
}
return;
} else if (actionId == ROUTE_TO_FAVORITE_CMD && gpx != null && choiceName != null) {
// set destination from choiceName
choiceName += "*";
Vector wpt = gpx.listWayPoints();
PositionMark[] wayPts = new PositionMark[wpt.size()];
wpt.copyInto(wayPts);
PositionMark result = null;
for (int i = 0; i < wayPts.length; i++ ) {
if (choiceName.equals(wayPts[i].displayName)) {
result = wayPts[i];
}
}
if (result != null) {
RoutePositionMark pm1 = new RoutePositionMark(result.lat, result.lon);
setDestination(pm1);
commandAction(ROUTING_START_CMD);
}
} else if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.m");
}
int MajorUnit = meters / 1000;
int MinorUnit = meters % 1000;
// km.mm
//String MinorShort = (MinorUnit / 10 < 10 ? "0" : "") + (MinorUnit / 10);
// km.m
String MinorShort = Integer.toString((int)MinorUnit / 100);
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.km");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.m");
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.km");
}
} else {
return Integer.toString(meters) + Locale.get("guitacho.m");
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.yd");
}
int MajorUnit = (int)(meters / 1609.344f);
int MinorUnit = (int)(meters % 1609.344f + 0.5f);
// mi.dd
//String MinorShort = (MinorUnit / 16.09344f < 10.0f ? "0" : "") + (int)(MinorUnit / 16.09344f);
// mi.d
String MinorShort = Integer.toString((int)(MinorUnit / 160.9344f));
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.mi");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.yd");
} else {
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.mi");
}
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5f)) + Locale.get("guitacho.yd");
}
}
}
// FIXME: get and remember coordinates to keep track of distance
// to alert POI. Handle multiple alert POIs.
public void setNodeAlert(int type) {
if (!nodeAlert) {
nodeAlert = true;
alertNodeType = type;
}
}
//#if polish.api.finland
public void setCameraAlert(int type) {
if (!cameraAlert) {
cameraAlert = true;
}
}
//#endif
public void resetClickableMarkers() {
clickableMarkers = new Vector();
}
public void addClickableMarker(int x, int y, String url, String phone, int nodeID) {
ClickableCoords coords = new ClickableCoords();
coords.x = x - imageCollector.xScreenOverscan;
coords.y = y - imageCollector.yScreenOverscan;
coords.url = url;
coords.phone = phone;
coords.nodeID = nodeID;
clickableMarkers.addElement(coords);
}
}
| false | false | null | null |
diff --git a/parser/org/eclipse/cdt/internal/core/pdom/PDOMIndexerJob.java b/parser/org/eclipse/cdt/internal/core/pdom/PDOMIndexerJob.java
index 0b60bb329..f733be112 100644
--- a/parser/org/eclipse/cdt/internal/core/pdom/PDOMIndexerJob.java
+++ b/parser/org/eclipse/cdt/internal/core/pdom/PDOMIndexerJob.java
@@ -1,113 +1,116 @@
/*******************************************************************************
* Copyright (c) 2005, 2006 QNX Software Systems
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
+ * Markus Schorn (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.core.pdom;
import java.util.Iterator;
import java.util.LinkedList;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.IPDOMIndexer;
import org.eclipse.cdt.core.dom.IPDOMIndexerTask;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
/**
* @author dschaefer
*
*/
public class PDOMIndexerJob extends Job {
private final PDOMManager manager;
private LinkedList queue = new LinkedList();
private IPDOMIndexerTask currentTask;
private boolean isCancelling = false;
private Object taskMutex = new Object();
private IProgressMonitor monitor;
public PDOMIndexerJob(PDOMManager manager) {
super(CCorePlugin.getResourceString("pdom.indexer.name")); //$NON-NLS-1$
this.manager = manager;
setPriority(Job.LONG);
}
protected IStatus run(IProgressMonitor monitor) {
this.monitor = monitor;
long start = System.currentTimeMillis();
String taskName = CCorePlugin.getResourceString("pdom.indexer.task"); //$NON-NLS-1$
monitor.beginTask(taskName, IProgressMonitor.UNKNOWN);
fillQueue();
while (true) {
while (!queue.isEmpty()) {
synchronized (taskMutex) {
currentTask = (IPDOMIndexerTask)queue.removeFirst();
}
currentTask.run(monitor);
synchronized (taskMutex) {
+ // mschorn: currentTask must be set to null, otherwise cancelJobs() waits forever.
+ currentTask= null;
if (isCancelling) {
// TODO chance for confusion here is user cancels
// while project is getting deletes.
monitor.setCanceled(false);
isCancelling = false;
taskMutex.notify();
} else if (monitor.isCanceled())
return Status.CANCEL_STATUS;
}
}
if (manager.finishIndexerJob())
break;
else
fillQueue();
}
String showTimings = Platform.getDebugOption(CCorePlugin.PLUGIN_ID
+ "/debug/pdomtimings"); //$NON-NLS-1$
if (showTimings != null && showTimings.equalsIgnoreCase("true")) //$NON-NLS-1$
- System.out.println("PDOM Indexer Job Time: " + (System.currentTimeMillis() - start));
+ System.out.println("PDOM Indexer Job Time: " + (System.currentTimeMillis() - start)); //$NON-NLS-1$
return Status.OK_STATUS;
}
private void fillQueue() {
synchronized (taskMutex) {
IPDOMIndexerTask task = manager.getNextTask();
while (task != null) {
queue.addLast(task);
task = manager.getNextTask();
}
}
}
public void cancelJobs(IPDOMIndexer indexer) {
synchronized (taskMutex) {
for (Iterator i = queue.iterator(); i.hasNext();) {
IPDOMIndexerTask task = (IPDOMIndexerTask)i.next();
if (task.getIndexer().equals(indexer))
i.remove();
}
if (currentTask != null && currentTask.getIndexer().equals(indexer)) {
monitor.setCanceled(true);
isCancelling = true;
try {
taskMutex.wait();
} catch (InterruptedException e) {
}
}
}
}
}
| false | false | null | null |
diff --git a/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java b/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java
index 998f2560..3e672b89 100644
--- a/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java
+++ b/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java
@@ -1,515 +1,516 @@
package org.apache.maven.scm.provider.perforce;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.scm.CommandParameters;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.command.add.AddScmResult;
import org.apache.maven.scm.command.changelog.ChangeLogScmResult;
import org.apache.maven.scm.command.checkin.CheckInScmResult;
import org.apache.maven.scm.command.checkout.CheckOutScmResult;
import org.apache.maven.scm.command.diff.DiffScmResult;
import org.apache.maven.scm.command.edit.EditScmResult;
import org.apache.maven.scm.command.login.LoginScmResult;
import org.apache.maven.scm.command.remove.RemoveScmResult;
import org.apache.maven.scm.command.status.StatusScmResult;
import org.apache.maven.scm.command.tag.TagScmResult;
import org.apache.maven.scm.command.unedit.UnEditScmResult;
import org.apache.maven.scm.command.update.UpdateScmResult;
import org.apache.maven.scm.log.ScmLogger;
import org.apache.maven.scm.provider.AbstractScmProvider;
import org.apache.maven.scm.provider.ScmProviderRepository;
import org.apache.maven.scm.provider.perforce.command.PerforceInfoCommand;
import org.apache.maven.scm.provider.perforce.command.PerforceWhereCommand;
import org.apache.maven.scm.provider.perforce.command.add.PerforceAddCommand;
import org.apache.maven.scm.provider.perforce.command.changelog.PerforceChangeLogCommand;
import org.apache.maven.scm.provider.perforce.command.checkin.PerforceCheckInCommand;
import org.apache.maven.scm.provider.perforce.command.checkout.PerforceCheckOutCommand;
import org.apache.maven.scm.provider.perforce.command.diff.PerforceDiffCommand;
import org.apache.maven.scm.provider.perforce.command.edit.PerforceEditCommand;
import org.apache.maven.scm.provider.perforce.command.login.PerforceLoginCommand;
import org.apache.maven.scm.provider.perforce.command.remove.PerforceRemoveCommand;
import org.apache.maven.scm.provider.perforce.command.status.PerforceStatusCommand;
import org.apache.maven.scm.provider.perforce.command.tag.PerforceTagCommand;
import org.apache.maven.scm.provider.perforce.command.unedit.PerforceUnEditCommand;
import org.apache.maven.scm.provider.perforce.command.update.PerforceUpdateCommand;
import org.apache.maven.scm.provider.perforce.repository.PerforceScmProviderRepository;
import org.apache.maven.scm.repository.ScmRepositoryException;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.Commandline;
import sun.security.action.GetLongAction;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author <a href="mailto:[email protected]">Trygve Laugstøl </a>
* @author mperham
* @version $Id$
* @plexus.component role="org.apache.maven.scm.provider.ScmProvider" role-hint="perforce"
*/
public class PerforceScmProvider
extends AbstractScmProvider
{
// ----------------------------------------------------------------------
// ScmProvider Implementation
// ----------------------------------------------------------------------
public boolean requiresEditMode()
{
return true;
}
public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter )
throws ScmRepositoryException
{
String path;
int port = 0;
String host = null;
int i1 = scmSpecificUrl.indexOf( delimiter );
int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 );
if ( i1 > 0 )
{
int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter );
path = scmSpecificUrl.substring( lastDelimiter + 1 );
host = scmSpecificUrl.substring( 0, i1 );
// If there is tree parts in the scm url, the second is the port
if ( i2 >= 0 )
{
try
{
String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter );
port = Integer.parseInt( tmp );
}
catch ( NumberFormatException ex )
{
throw new ScmRepositoryException( "The port has to be a number." );
}
}
}
else
{
path = scmSpecificUrl;
}
String user = null;
String password = null;
if ( host != null && host.indexOf( "@" ) > 1 )
{
user = host.substring( 0, host.indexOf( "@" ) );
host = host.substring( host.indexOf( "@" ) + 1 );
}
if ( path.indexOf( "@" ) > 1 )
{
if ( host != null )
{
getLogger().warn( "Username as part of path is deprecated, the new format is " +
"scm:perforce:[username@]host:port:path_to_repository" );
}
user = path.substring( 0, path.indexOf( "@" ) );
path = path.substring( path.indexOf( "@" ) + 1 );
}
return new PerforceScmProviderRepository( host, port, path, user, password );
}
public String getScmType()
{
return "perforce";
}
/**
* @see org.apache.maven.scm.provider.AbstractScmProvider#changelog(org.apache.maven.scm.provider.ScmProviderRepository,org.apache.maven.scm.ScmFileSet,org.apache.maven.scm.CommandParameters)
*/
protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet,
CommandParameters parameters )
throws ScmException
{
PerforceChangeLogCommand command = new PerforceChangeLogCommand();
command.setLogger( getLogger() );
return (ChangeLogScmResult) command.execute( repository, fileSet, parameters );
}
protected AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceAddCommand command = new PerforceAddCommand();
command.setLogger( getLogger() );
return (AddScmResult) command.execute( repository, fileSet, params );
}
protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceRemoveCommand command = new PerforceRemoveCommand();
command.setLogger( getLogger() );
return (RemoveScmResult) command.execute( repository, fileSet, params );
}
protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceCheckInCommand command = new PerforceCheckInCommand();
command.setLogger( getLogger() );
return (CheckInScmResult) command.execute( repository, fileSet, params );
}
protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet,
CommandParameters params )
throws ScmException
{
PerforceCheckOutCommand command = new PerforceCheckOutCommand();
command.setLogger( getLogger() );
return (CheckOutScmResult) command.execute( repository, fileSet, params );
}
protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceDiffCommand command = new PerforceDiffCommand();
command.setLogger( getLogger() );
return (DiffScmResult) command.execute( repository, fileSet, params );
}
protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceEditCommand command = new PerforceEditCommand();
command.setLogger( getLogger() );
return (EditScmResult) command.execute( repository, fileSet, params );
}
protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceLoginCommand command = new PerforceLoginCommand();
command.setLogger( getLogger() );
return (LoginScmResult) command.execute( repository, fileSet, params );
}
protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceStatusCommand command = new PerforceStatusCommand();
command.setLogger( getLogger() );
return (StatusScmResult) command.execute( repository, fileSet, params );
}
protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceTagCommand command = new PerforceTagCommand();
command.setLogger( getLogger() );
return (TagScmResult) command.execute( repository, fileSet, params );
}
protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceUnEditCommand command = new PerforceUnEditCommand();
command.setLogger( getLogger() );
return (UnEditScmResult) command.execute( repository, fileSet, params );
}
protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params )
throws ScmException
{
PerforceUpdateCommand command = new PerforceUpdateCommand();
command.setLogger( getLogger() );
return (UpdateScmResult) command.execute( repository, fileSet, params );
}
public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir )
{
Commandline command = new Commandline();
command.setExecutable( "p4" );
if ( workingDir != null )
{
command.setWorkingDirectory( workingDir.getAbsolutePath() );
}
// SCM-209
// command.createArgument().setValue("-d");
// command.createArgument().setValue(workingDir.getAbsolutePath());
if ( repo.getHost() != null )
{
command.createArgument().setValue( "-p" );
String value = repo.getHost();
if ( repo.getPort() != 0 )
{
value += ":" + Integer.toString( repo.getPort() );
}
command.createArgument().setValue( value );
}
if ( StringUtils.isNotEmpty( repo.getUser() ) )
{
command.createArgument().setValue( "-u" );
command.createArgument().setValue( repo.getUser() );
}
if ( StringUtils.isNotEmpty( repo.getPassword() ) )
{
command.createArgument().setValue( "-P" );
command.createArgument().setValue( repo.getPassword() );
}
return command;
}
public static String clean( String string )
{
if ( string.indexOf( " -P " ) == -1 )
{
return string;
}
int idx = string.indexOf( " -P " ) + 4;
int end = string.indexOf( ' ', idx );
return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end );
}
/**
* Given a path like "//depot/foo/bar", returns the
* proper path to include everything beneath it.
* <p/>
* //depot/foo/bar -> //depot/foo/bar/...
* //depot/foo/bar/ -> //depot/foo/bar/...
* //depot/foo/bar/... -> //depot/foo/bar/...
*/
public static String getCanonicalRepoPath( String repoPath )
{
if ( repoPath.endsWith( "/..." ) )
{
return repoPath;
}
else if ( repoPath.endsWith( "/" ) )
{
return repoPath + "...";
}
else
{
return repoPath + "/...";
}
}
private static final String NEWLINE = "\r\n";
/*
* Clientspec name can be overridden with the system property below. I don't
* know of any way for this code to get access to maven's settings.xml so this
* is the best I can do.
*
* Sample clientspec:
Client: mperham-mikeperham-dt-maven
Root: d:\temp\target
Owner: mperham
View:
//depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/...
Description:
Created by maven-scm-provider-perforce
*/
public static String createClientspec(ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath )
{
String clientspecName = getClientspecName( logger, repo, workDir );
String userName = getUsername( logger, repo );
String rootDir;
try
{
// SCM-184
rootDir = workDir.getCanonicalPath();
}
catch ( IOException ex )
{
//getLogger().error("Error getting canonical path for working directory: " + workDir, ex);
rootDir = workDir.getAbsolutePath();
}
StringBuffer buf = new StringBuffer();
buf.append( "Client: " ).append( clientspecName ).append( NEWLINE );
buf.append( "Root: " ).append( rootDir ).append( NEWLINE );
buf.append( "Owner: " ).append( userName ).append( NEWLINE );
buf.append( "View:" ).append( NEWLINE );
buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) );
buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE );
buf.append( "Description:" ).append( NEWLINE );
buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE );
return buf.toString();
}
public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name";
public static String getClientspecName( ScmLogger logger,PerforceScmProviderRepository repo, File workDir )
{
String def = generateDefaultClientspecName( logger, repo, workDir );
// until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean )
String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def );
if ( l == null || "".equals( l.trim() ) )
{
return def;
}
return l;
}
private static String generateDefaultClientspecName(ScmLogger logger, PerforceScmProviderRepository repo, File workDir )
{
String username = getUsername( logger, repo );
String hostname;
String path;
try
{
hostname = InetAddress.getLocalHost().getHostName();
- path = workDir.getCanonicalPath();
+ // client specs cannot contain forward slashes; backslash is okay
+ path = workDir.getCanonicalPath().replace( '/', '\\' );
}
catch ( UnknownHostException e )
{
// Should never happen
throw new RuntimeException( e );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
return username + "-" + hostname + "-MavenSCM-" + path;
}
private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo )
{
String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" );
if ( username == null )
{
// os user != perforce user
username = repo.getUser();
if ( username == null )
{
username = System.getProperty( "user.name", "nouser" );
}
}
return username;
}
/**
* This is a "safe" method which handles cases where repo.getPath() is
* not actually a valid Perforce depot location. This is a frequent error
* due to branches and directory naming where dir name != artifactId.
*
* @param log the logging object to use
* @param repo the Perforce repo
* @param basedir the base directory we are operating in. If pom.xml exists in this directory,
* this method will verify <pre>repo.getPath()/pom.xml</pre> == <pre>p4 where basedir/pom.xml</pre>
* @return repo.getPath if it is determined to be accurate. The p4 where location otherwise.
*/
public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir )
{
PerforceWhereCommand where = new PerforceWhereCommand( log, repo );
// Handle an edge case where we release:prepare'd a module with an invalid SCM location.
// In this case, the release.properties will contain the invalid URL for checkout purposes
// during release:perform. In this case, the basedir is not the module root so we detect that
// and remove the trailing target/checkout directory.
if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) )
{
String dir = basedir.toString();
basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) );
log.debug( "Fixing checkout URL: " + basedir );
}
File pom = new File( basedir, "pom.xml" );
String loc = repo.getPath();
log.debug( "SCM path in pom: " + loc );
if ( pom.exists() )
{
loc = where.getDepotLocation( pom );
if ( loc == null )
{
loc = repo.getPath();
log.debug( "cannot find depot => using " + loc );
}
else if ( loc.endsWith( "/pom.xml" ) )
{
loc = loc.substring( 0, loc.length() - "/pom.xml".length() );
log.debug( "Actual POM location: " + loc );
if ( !repo.getPath().equals( loc ) )
{
log.info( "The SCM location in your pom.xml (" + repo.getPath() +
") is not equal to the depot location (" + loc +
"). This happens frequently with branches. " + "Ignoring the SCM location." );
}
}
}
return loc;
}
private static Boolean live = null;
public static boolean isLive()
{
if ( live == null )
{
if ( !Boolean.getBoolean( "maven.scm.testing" ) )
{
// We are not executing in the tests so we are live.
live = Boolean.TRUE;
}
else
{
// During unit tests, we need to check the local system
// to see if the user has Perforce installed. If not, we mark
// the provider as "not live" (or dead, I suppose!) and skip
// anything that requires an active server connection.
try
{
Commandline command = new Commandline();
command.setExecutable( "p4" );
Process proc = command.execute();
BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) );
String line;
while ( ( line = br.readLine() ) != null )
{
//System.out.println(line);
}
int rc = proc.exitValue();
live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE );
}
catch ( Exception e )
{
e.printStackTrace();
live = Boolean.FALSE;
}
}
}
return live.booleanValue();
}
}
| true | false | null | null |
diff --git a/products/amserver/source/com/sun/identity/sm/OrganizationConfigManager.java b/products/amserver/source/com/sun/identity/sm/OrganizationConfigManager.java
index a940220dc..8abc6607b 100644
--- a/products/amserver/source/com/sun/identity/sm/OrganizationConfigManager.java
+++ b/products/amserver/source/com/sun/identity/sm/OrganizationConfigManager.java
@@ -1,1740 +1,1742 @@
/**
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2005 Sun Microsystems Inc. All Rights Reserved
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* https://opensso.dev.java.net/public/CDDLv1.0.html or
* opensso/legal/CDDLv1.0.txt
* See the License for the specific language governing
* permission and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* Header Notice in each file and include the License file
* at opensso/legal/CDDLv1.0.txt.
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
- * $Id: OrganizationConfigManager.java,v 1.25 2009-01-28 05:35:03 ww203982 Exp $
+ * $Id: OrganizationConfigManager.java,v 1.26 2009-06-10 21:11:58 hengming Exp $
*
*/
package com.sun.identity.sm;
import com.iplanet.am.util.SystemProperties;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.Set;
import java.util.StringTokenizer;
import com.sun.identity.shared.ldap.util.DN;
import com.iplanet.sso.SSOException;
import com.iplanet.sso.SSOToken;
import com.iplanet.ums.IUMSConstants;
import com.sun.identity.authentication.util.ISAuthConstants;
+import com.sun.identity.common.CaseInsensitiveHashSet;
import com.sun.identity.idm.IdConstants;
import com.sun.identity.shared.Constants;
/**
* The class <code>OrganizationConfigManager</code> provides interfaces to
* manage an organization's configuration data. It provides interfaces to create
* and delete organizations, service attributes for organizations and service
* configuration parameters.
* <p>
* The organization configuration can be managed in a hierarchical manner, and a
* forward slash "/" will be used to separate the name hierarchy. Hence the root
* of the organization hierarchy will be represented by a single forward slash
* "/", and sub-organizations will be separated by "/". For example "/a/b/c"
* would represent a "c" sub-organization within "b" which would be a
* sub-organization of "a".
*
* @supported.all.api
*/
public class OrganizationConfigManager {
// Instance variables
private SSOToken token;
private String orgName;
private String orgDN;
private OrgConfigViaAMSDK amsdk;
private OrganizationConfigManagerImpl orgConfigImpl;
static String orgNamingAttrInLegacyMode;
static Pattern baseDNpattern = Pattern.compile(SMSEntry.getRootSuffix());
protected static final String SERVICES_NODE = SMSEntry.SERVICES_RDN
+ SMSEntry.COMMA + SMSEntry.getRootSuffix();
// set the special characters which are not in realm names.
static String specialCharsString = "*|(|)|!|/|=";
private static String SEPERATOR = "|";
private String CONF_ENABLED =
"sun-idrepo-amSDK-config-copyconfig-enabled";
private boolean copyOrgInitialized;
private boolean copyOrgEnabled;
private String amSDKOrgDN;
// sunOrganizationAlias in org DIT.
public static final String SUNORG_ALIAS = "sunOrganizationAliases";
// associatedDomain in org DIT.
private String SUNDNS_ALIAS = "sunDNSAliases";
// sunPreferredDomain in org DIT.
private String SUNPREF_DOMAIN = "sunPreferredDomain";
// inetDomainStatus in org DIT.
private String SUNORG_STATUS = "sunOrganizationStatus";
static {
initializeFlags();
}
/**
* Constructor to obtain an instance of
* <code>OrganizationConfigManager
* </code> for an organization by providing
* an authenticated identity of the user. The organization name would be "/"
* seperated to represent organization hierarchy.
*
* @param token
* single sign on token of authenticated user identity.
* @param orgName
* name of the organization. The value of <code>null
* </code> or
* "/" would represent the root organization.
*
* @throws SMSException
* if an error has occurred while getting the instance of
* <code>OrganizationConfigManager
* </code>.
*/
public OrganizationConfigManager(SSOToken token, String orgName)
throws SMSException {
// Copy instance variables
this.token = token;
this.orgName = orgName;
// Instantiate and validate
validateConfigImpl();
orgDN = orgConfigImpl.getOrgDN();
try {
if (migratedTo70 && !registeredForConfigNotifications) {
ServiceConfigManager scmr = new ServiceConfigManager(
ServiceManager.REALM_SERVICE, token);
scmr.addListener(new OrganizationConfigManagerListener());
registeredForConfigNotifications = true;
}
} catch (SMSException s) {
String installTime = SystemProperties.get(
Constants.SYS_PROPERTY_INSTALL_TIME, "false");
if (!installTime.equals("true")) {
SMSEntry.debug.warning("OrganizationConfigManager: "
+ "constructor. Unable to "
+ "construct ServiceConfigManager for idRepoService ", s);
}
throw s;
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager:Constructor", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
if (coexistMode) {
amsdk = new OrgConfigViaAMSDK(token, DNMapper
.realmNameToAMSDKName(orgDN), orgDN);
if (orgNamingAttrInLegacyMode == null) {
orgNamingAttrInLegacyMode = getNamingAttrForOrg();
}
}
}
/**
* Returns the fully qualified name of the
* organization from the root
*
* @return the name of the organization
*/
public String getOrganizationName() {
return (orgName);
}
/**
* Returns the services configured for the organization.
*
* @return service names configured for the organization.
* @throws SMSException
* if there is an error accessing the data store to read the
* configured services.
*
* @deprecated This method has been deprecated, use <code>
* getAssignedServices()</code>
* instead.
*/
public Set getConfiguredServices() throws SMSException {
return (getAssignedServices());
}
/**
* Returns a set of service schemas to be used for
* creation of an organization. The service schemas contain a list of
* attributes and their schema, and will be provided as
* <code>ServiceSchema</code>.
*
* @return Set of <code>ServiceSchema</code> to be used for creation of an
* organization.
* @throws SMSException
* if there is an error accessing the data store to read the
* service schemas.
*/
public Set getServiceSchemas() throws SMSException {
// Loop through the services and determine the
// organization creation schemas
Set serviceSchemaSet = null;
try {
Set serviceNames = getServiceNames(token);
serviceSchemaSet = new HashSet(serviceNames.size() * 2);
for (Iterator names = serviceNames.iterator(); names.hasNext();) {
ServiceSchemaManager ssm = new ServiceSchemaManager(
(String) names.next(), token);
ServiceSchema ss = ssm.getOrganizationCreationSchema();
if (ss != null) {
serviceSchemaSet.add(ss);
}
}
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager:getServiceSchemas"
+ " unable to get service schema", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"), ssoe,
"sms-INVALID_SSO_TOKEN"));
}
return (serviceSchemaSet);
}
/**
* Creates a sub-organization under the current
* organization and sets the specified attributes. The sub-organization
* created can be only one level below the current organization. For
* multiple levels this method must be called recursively with the
* corresponding <code>OrganizationConfigManager
* </code>. The organization
* name must not have forward slash ("/"). For eg., the actual organization
* name 'iplanet' cannot be 'iplan/et' because we are using '/' as the
* seperator here. The attributes for the organization can be <code>
* null</code>;
* else would contain service name as the key and another <code>Map</code>
* as the value that would contain the key-values pair for the services.
*
* @param subOrgName
* the name of the sub-organization.
* @param attributes
* Map of attributes for the organization per service. The
* parameter Map attributes contains another Map as its value,
* which then has attribute names and values. The way it is
* arranged is: Map::attributes --> Key: String::ServiceName
* Value: Map::svcAttributes Map::svcAttributes --> Key:
* String::AttributeName Value: Set::AttributeValues
*
* @return organization config manager of the newly created
* sub-organization.
* @throws SMSException
* if creation of sub-organization failed, or if creation of
* sub-organization is attempted when configuration is not
* migrated to realms.
*/
public OrganizationConfigManager createSubOrganization(String subOrgName,
Map attributes) throws SMSException {
validateConfigImpl();
/*
* Since the "Map attributes" can contain more than one service name,
* creation of the sub organization is be achieved in 2 steps. i) create
* the sub-organization without the attributes ii) for the service names
* in the Map call setAttributes(...)
*/
boolean orgExists = false;
String subOrgDN = normalizeDN(subOrgName, orgDN);
try {
// Check if realm exists, this throws SMSException
// if realm does not exist
// This is to avoid duplicate creation of realms.
new OrganizationConfigManager(token, subOrgDN);
SMSEntry.debug.error("OrganizationConfigManager::"
+ "createSubOrganization() " + "Realm Already Exists.. "
+ subOrgDN);
orgExists = true;
} catch (SMSException smse) {
// Realm does not exist, create it
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager::"
+ "createSubOrganization() "
+ "New Realm, creating realm: " + subOrgName + "-"
+ smse);
}
}
Object args[] = { subOrgName };
if (orgExists) {
throw (new SMSException(IUMSConstants.UMS_BUNDLE_NAME,
"sms-organization_already_exists1",
args));
}
StringTokenizer st =
new StringTokenizer(specialCharsString, SEPERATOR);
while (st.hasMoreTokens()) {
String obj = (String) st.nextToken();
if (subOrgName.indexOf(obj) > -1) {
SMSEntry.debug.error("OrganizationConfigManager::"+
"createSubOrganization() : Invalid realm name: "+
subOrgName);
SMSEntry.debug.error("OrganizationConfigManager::"+
"createSubOrganization() : Detected invalid chars: "+obj);
Object args1[] = {subOrgName};
throw (new SMSException(IUMSConstants.UMS_BUNDLE_NAME,
SMSEntry.bundle.getString("sms-invalid-org-name"),args1));
}
}
// If in legacy mode or (realm mode and copy org enabled)
// Create the AMSDK organization first
if ((coexistMode) || (realmEnabled && isCopyOrgEnabled())) {
amsdk.createSubOrganization(subOrgName);
}
if ((realmEnabled || subOrgDN.toLowerCase().startsWith(
SMSEntry.SUN_INTERNAL_REALM_PREFIX))
&& getSubOrganizationNames(subOrgName, false).isEmpty()) {
CreateServiceConfig.createOrganization(token, subOrgDN);
}
// Update the attributes
// If in coexistMode and serviceName is idRepoService
// the following call sets the attributes to AMSDK organization also.
OrganizationConfigManager ocm = getSubOrgConfigManager(subOrgName);
if ((attributes != null) && (!attributes.isEmpty())) {
for (Iterator svcNames = attributes.keySet().iterator(); svcNames
.hasNext();) {
String serviceName = (String) svcNames.next();
Map svcAttributes = (Map) attributes.get(serviceName);
if ((svcAttributes != null) && (!svcAttributes.isEmpty())) {
ocm.setAttributes(serviceName, svcAttributes);
}
}
}
// If in realm mode and not in legacy mode, default services needs
// to be added.
if (realmEnabled && !coexistMode) {
loadDefaultServices(token, ocm);
}
// If in realm mode and copy org enabled, default services needs
// to be registered for the newly created org/suborg and the
// amSDKOrgName/OpenSSO Organization is updated with the
// new suborg dn.
if (realmEnabled && isCopyOrgEnabled()) {
registerSvcsForOrg(subOrgName, subOrgDN);
OrganizationConfigManager subOrg =
getSubOrgConfigManager(subOrgName);
ServiceConfig s =
subOrg.getServiceConfig(ServiceManager.REALM_SERVICE);
if (s != null) {
try {
Iterator items = s.getSubConfigNames().iterator();
while (items.hasNext()) {
ServiceConfig subConfig =
s.getSubConfig((String) items.next());
if (subConfig.getSchemaID().equalsIgnoreCase(
IdConstants.AMSDK_PLUGIN_NAME)) {
Map amsdkConfig = new HashMap();
Set vals = new HashSet();
vals.add(orgNamingAttrInLegacyMode +
SMSEntry.EQUALS +
subOrgName + SMSEntry.COMMA + amSDKOrgDN);
amsdkConfig.put("amSDKOrgName", vals);
subConfig.setAttributes(amsdkConfig);
}
break;
}
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager::"+
"createSubOrganization:", ssoe);
throw (new SMSException(SMSEntry.bundle.getString(
"sms-INVALID_SSO_TOKEN"), "sms-INVALID_SSO_TOKEN"));
}
}
}
// Return the newly created organization config manager
return (ocm);
}
/**
* Returns the names of all sub-organizations.
*
* @return set of names of all sub-organizations.
* @throws SMSException
* if there is an error accessing the data store to read the
* sub-organization names.
*/
public Set getSubOrganizationNames() throws SMSException {
try {
return (getSubOrganizationNames("*", false));
} catch (SMSException s) {
SMSEntry.debug.error("OrganizationConfigManager: "
+ "getSubOrganizationNames() Unable to "
+ "get sub organization names ", s);
throw s;
}
}
/**
* Returns the names of all peer-organizations.
*
* @return set of names of all peer-organizations.
* @throws SMSException
* if there is an error accessing the data store to read the
* peer-organization names.
*/
public Set getPeerOrganizationNames() throws SMSException {
Set getPeerSet = Collections.EMPTY_SET;
if (realmEnabled) {
try {
OrganizationConfigManager ocmParent =
getParentOrgConfigManager();
getPeerSet = ocmParent.getSubOrganizationNames();
} catch (SMSException s) {
if (SMSEntry.debug.warningEnabled()) {
SMSEntry.debug.warning("OrganizationConfigManager: "
+ "getPeerOrganizationNames() Unable to "
+ "get Peer organization names ", s);
}
throw s;
}
}
return (getPeerSet);
}
/**
* Returns names of sub-organizations matching the
* given pattern. If the parameter <code>recursive</code> is set to
* <code>true</code>, search will be performed for the entire sub-tree.
* The pattern can contain "*" as the wildcard to represent zero or more
* characters.
*
* @param pattern
* pattern that will be used for searching, where "*" will be the
* wildcard.
* @param recursive
* if set to <code>true</code> the entire sub-tree will be
* searched for the organization names.
* @return names of sub-organizations matching the pattern.
* @throws SMSException
* if there is an error accessing the data store to read the
* sub-organization names.
*/
public Set getSubOrganizationNames(String pattern, boolean recursive)
throws SMSException {
validateConfigImpl();
try {
if (realmEnabled) {
return (orgConfigImpl.getSubOrganizationNames(token, pattern,
recursive));
} else {
// Must be in coexistence mode
return (amsdk.getSubOrganizationNames(pattern, recursive));
}
} catch (SMSException s) {
SMSEntry.debug.error("OrganizationConfigManager: "
+ "getSubOrganizationNames(String pattern, "
+ "boolean recursive) Unable to get sub organization "
+ "names for filter: " + pattern, s);
throw s;
}
}
/**
* Deletes the given sub-organization. If the
* parameter <code>recursive</code> is set to <code>true</code>, then
* the suborganization and the sub-tree will be deleted.
*
* If the parameter <code>recursive</code> is set to <code>false</code>
* then the sub-organization shall be deleted provided it is the leaf node.
* If there are entries beneath the sub-organization and if the parameter
* <code>recursive</code> is set to <code>false</code>, then an
* exception is thrown that this sub-organization cannot be deleted.
*
* @param subOrgName
* sub-organization name to be deleted.
* @param recursive
* if set to <code>true</code> the entire sub-tree will be
* deleted.
* @throws SMSException
* if the sub-organization name cannot be found, or if there are
* entries beneath the sub-organization and if the parameter
* <code>recursive</code> is set to <code>false</code>.
*/
public void deleteSubOrganization(String subOrgName, boolean recursive)
throws SMSException {
validateConfigImpl();
// Should not delete the root realm, should throw exception if
// attempted.
String subOrgDN = normalizeDN(subOrgName, orgDN);
if (subOrgDN.equals(SMSEntry.SLASH_STR) ||
subOrgDN.equalsIgnoreCase(SMSEntry.getRootSuffix()) ||
subOrgDN.equalsIgnoreCase(SERVICES_NODE)) {
Object parms[] = { orgName };
SMSEntry.debug.error(
"OrganizationConfigManager: deleteSubOrganization(" +
"Root realm "+orgName + " cannot be deleted. ");
throw (new SMSException(IUMSConstants.UMS_BUNDLE_NAME,
"sms-cannot_delete_rootsuffix",parms));
}
// Delete the sub-organization
OrganizationConfigManager subRlmConfigMgr =
getSubOrgConfigManager(subOrgName);
//set the filter "*" to be passed for the search.
Set subRlmSet =
subRlmConfigMgr.getSubOrganizationNames("*", true);
if (realmEnabled) {
try {
CachedSMSEntry cEntry = CachedSMSEntry.getInstance(token,
subOrgDN);
if (cEntry.isDirty()) {
cEntry.refresh();
}
SMSEntry entry = cEntry.getClonedSMSEntry();
if (!recursive) {
// Check if there are sub organization entries
// and if exist
// throw exception that this sub organization cannot be
// deleted.
if ((subRlmSet !=null) && (!subRlmSet.isEmpty())) {
throw (new SMSException(SMSEntry.bundle
.getString("sms-entries-exists"),
"sms-entries-exists"));
}
}
// Obtain the SMSEntry for the suborg and
// sub tree and delete it.
entry.delete(token);
cEntry.refresh(entry);
} catch (SSOException ssoe) {
SMSEntry.debug.error(
"OrganizationConfigManager: deleteSubOrganization(" +
"String subOrgName, boolean recursive) Unable to " +
"delete sub organization ", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
// If in legacy mode or (realm mode and copy org enabled)
// delete the corresponding organization.
if ((coexistMode) || (realmEnabled && isCopyOrgEnabled())) {
String amsdkName = DNMapper.realmNameToAMSDKName(subOrgDN);
if (!SMSEntry.getRootSuffix().equalsIgnoreCase(
SMSEntry.getAMSdkBaseDN())) {
String convOrg = subOrgName;
if (subOrgName.startsWith("/")) {
convOrg = DNMapper.convertToDN(subOrgName).toString();
}
amsdkName = convOrg + SMSEntry.COMMA + amSDKOrgDN;
}
amsdk.deleteSubOrganization(amsdkName);
}
}
/**
* Returns the <code>OrganizationConfigManager</code>
* for the given organization name.
*
* @param subOrgName
* the name of the organization.
* @return the configuration manager for the given organization.
*
* @throws SMSException
* if the organization name cannot be found or user doesn't have
* access to that organization.
*/
public OrganizationConfigManager getSubOrgConfigManager(String subOrgName)
throws SMSException {
validateConfigImpl();
// Normalize sub organization name
return (new OrganizationConfigManager(token, normalizeDN(subOrgName,
orgDN)));
}
/**
* Returns the organization creation attributes for
* the service.
*
* @param serviceName
* name of the service.
* @return map of organization creation attribute values for service
* @throws SMSException
* if there is an error accessing the data store to read the
* attributes of the service.
*/
public Map getAttributes(String serviceName) throws SMSException {
validateConfigImpl();
if (serviceName == null) {
return (Collections.EMPTY_MAP);
}
Map attrValues = null;
// Attributes can be obtained only if DIT is migrated to AM 7.0
if (migratedTo70) {
// Lowercase the service name
serviceName = serviceName.toLowerCase();
try {
CachedSMSEntry cEntry = CachedSMSEntry.getInstance(token,
orgDN);
if (cEntry.isDirty() || (coexistMode) ||
(realmEnabled && isCopyOrgEnabled())) {
// Since AMSDK org notifications will not be
// obtained, the entry must be read again
cEntry.refresh();
}
SMSEntry entry = cEntry.getSMSEntry();
Map map = SMSUtils.getAttrsFromEntry(entry);
if ((map != null) && (!map.isEmpty())) {
Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
String name = (String) itr.next();
if ((name.toLowerCase()).startsWith(serviceName)) {
Set values = (Set) map.get(name);
// Remove the serviceName and '-' and return only
// the attribute name,value.
String key = name
.substring(serviceName.length() + 1);
if (attrValues == null) {
attrValues = new HashMap();
}
attrValues.put(key, values);
}
}
}
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager: "
+ "getAttributes(String serviceName) Unable to "
+ "get Attributes", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
// If in coexistMode and serviceName is idRepoService
// get attributes from AMSDK organization
if ((coexistMode || (realmEnabled && isCopyOrgEnabled()))
&& serviceName
.equalsIgnoreCase(OrgConfigViaAMSDK.IDREPO_SERVICE)) {
Map amsdkMap = amsdk.getAttributes();
Map mergesdkMap = new HashMap(2);
if (amsdkMap != null && !amsdkMap.isEmpty()) {
Set mergeValues = new HashSet(2);
Iterator itr = amsdkMap.keySet().iterator();
while (itr.hasNext()) {
String key = (String) itr.next();
if (key.equalsIgnoreCase(SUNDNS_ALIAS) ||
key.equalsIgnoreCase(SUNPREF_DOMAIN) ||
key.equalsIgnoreCase(SUNORG_ALIAS)) {
buildSet(key, amsdkMap, mergeValues);
}
}
mergesdkMap.put(SUNORG_ALIAS, mergeValues);
mergesdkMap.put(SUNORG_STATUS,
(Set) amsdkMap.get(SUNORG_STATUS));
}
if (attrValues == null) {
attrValues = mergesdkMap;
} else {
attrValues.putAll(mergesdkMap);
}
}
return ((attrValues == null) ? Collections.EMPTY_MAP : attrValues);
}
/**
* Builds and returns the appropriate Set for the attributes to be
* merged from org and realm if the system is
* in intrusive mode (Both org DIT and realm DIT are present).
* This happens when the Copy Config flag is enabled.
*/
private Set buildSet(String attrName, Map attributes, Set resultSet) {
Set vals = (Set) attributes.get(attrName);
if ((vals != null) && !vals.isEmpty()) {
resultSet.addAll(vals);
}
return (resultSet);
}
/**
* Adds organization attributes for the service. If
* the attribute already exists, the values will be appended to it, provided
* it is a multi-valued attribute. It will throw exception if we try to add
* a value to an attribute which has the same value already.
*
* @param serviceName
* name of the service.
* @param attrName
* name of the attribute.
* @param values
* values for the attribute.
* @throws SMSException
* if we try to add a value to an attribute which has the same
* value already.
*/
public void addAttributeValues(String serviceName, String attrName,
Set values) throws SMSException {
validateConfigImpl();
if (serviceName == null || attrName == null) {
return;
}
if (migratedTo70) {
// Lowercase the servicename
serviceName = serviceName.toLowerCase();
try {
CachedSMSEntry cEntry = CachedSMSEntry.getInstance(token,
orgDN);
if (cEntry.isDirty()) {
cEntry.refresh();
}
SMSEntry e = cEntry.getClonedSMSEntry();
ServiceSchemaManager ssm = new ServiceSchemaManager(
serviceName, token);
ServiceSchema ss = ssm.getOrganizationCreationSchema();
if (ss == null) {
throw (new SMSException(SMSEntry.bundle
.getString("sms-SMSSchema_service_notfound"),
"sms-SMSSchema_service_notfound"));
}
Map map = new HashMap(2);
Set newValues = new HashSet(values);
Map allAttributes = ss.getAttributeDefaults();
Set existingValues = (Set)allAttributes.get(attrName);
if ((existingValues != null) && !existingValues.isEmpty()) {
newValues.addAll(existingValues);
}
map.put(attrName, newValues);
ss.validateAttributes(map);
SMSUtils.addAttribute(e, serviceName + "-" + attrName,
values, ss.getSearchableAttributeNames());
e.save(token);
cEntry.refresh(e);
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager: Unable "
+ "to add Attribute Values", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
// If in coexistMode and serviceName is idRepoService
// add the attributes to AMSDK organization
if (coexistMode
&& serviceName
.equalsIgnoreCase(OrgConfigViaAMSDK.IDREPO_SERVICE)) {
amsdk.addAttributeValues(attrName, values);
}
}
/**
* Sets/Creates organization attributes for the
* service. If the attributes already exists, the given attribute values
* will replace them.
*
* @param serviceName
* name of the service.
* @param attributes
* attribute-values pairs.
* @throws SMSException
* if the serviceName cannot be found.
*/
public void setAttributes(String serviceName, Map attributes)
throws SMSException {
validateConfigImpl();
if (serviceName == null) {
return;
}
if (migratedTo70) {
// Lowercase the serviceName
serviceName = serviceName.toLowerCase();
try {
CachedSMSEntry cEntry = CachedSMSEntry.getInstance(token,
orgDN);
if (cEntry.isDirty()) {
cEntry.refresh();
}
SMSEntry e = cEntry.getClonedSMSEntry();
if ((attributes != null) && (!attributes.isEmpty())) {
// Validate the attributes
ServiceSchemaManager ssm = new ServiceSchemaManager(
serviceName, token);
ServiceSchema ss = ssm.getOrganizationCreationSchema();
ss.validateAttributes(attributes);
// Normalize the attributes with service name
Map attrsMap = new HashMap();
Iterator itr = attributes.keySet().iterator();
while (itr.hasNext()) {
String name = (String) itr.next();
Set values = (Set) attributes.get(name);
/*
* To make the attributes qualified by service name we
* prefix the attribute names with the service name.
*/
attrsMap.put(serviceName + "-" + name, values);
}
// Look for old attrs. in the storage and add them too.
Map oldAttrs = getAttributes(serviceName);
Iterator it = oldAttrs.keySet().iterator();
while (it.hasNext()) {
String skey = (String) it.next();
if (!attributes.containsKey(skey))
attrsMap.put(serviceName + "-" + skey, oldAttrs
.get(skey));
}
// Set the attributes in SMSEntry
SMSUtils.setAttributeValuePairs(e, attrsMap, ss
.getSearchableAttributeNames());
String dataStore = SMSEntry.getDataStore(token);
// Add these OCs only for SunOne DS. Do not add the
// OCs for Active Directory.
// Will get WILL_NOT_PERFORM in AD.
if ((dataStore != null) && !dataStore.equals(
SMSEntry.DATASTORE_ACTIVE_DIR)
) {
// This is for storing organization attributes
// in top/default realm node. eg.,ou=services,o=isp
if (e.getDN().equalsIgnoreCase(SERVICES_NODE)) {
String[] ocVals = e
.getAttributeValues(SMSEntry.ATTR_OBJECTCLASS);
boolean exists = false;
for (int ic = 0; ocVals != null
&& ic < ocVals.length; ic++)
{
if (ocVals[ic].startsWith(
SMSEntry.OC_SERVICE_COMP)) {
// OC needs to be added outside the for loop
// else will throw concurrent mod exception
exists = true;
break;
}
}
if (!exists) {
e.addAttribute(SMSEntry.ATTR_OBJECTCLASS,
SMSEntry.OC_SERVICE_COMP);
}
} else if (e.getDN().startsWith(
SMSEntry.ORGANIZATION_RDN + SMSEntry.EQUALS)) {
// This is for storing organization attributes in
// organizations created via sdk through realm
// console.
String[] vals = e
.getAttributeValues(SMSEntry.ATTR_OBJECTCLASS);
boolean rsvcExists = false;
for (int n = 0; vals != null && n < vals.length;
n++) {
if (vals[n].equalsIgnoreCase(
SMSEntry.OC_REALM_SERVICE))
{
// OC needs to be added outside the for loop
// else will throw concurrent mod exception
rsvcExists = true;
break;
}
}
if (!rsvcExists) {
e.addAttribute(SMSEntry.ATTR_OBJECTCLASS,
SMSEntry.OC_REALM_SERVICE);
}
}
}
// Save in backend data store and refresh the cache
e.save(token);
cEntry.refresh(e);
}
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager: Unable "
+ "to set Attributes", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
// If in coexistMode and serviceName is idRepoService
// set the attributes to AMSDK organization
if ((coexistMode || (realmEnabled && isCopyOrgEnabled()))
&& serviceName
.equalsIgnoreCase(OrgConfigViaAMSDK.IDREPO_SERVICE)) {
amsdk.setAttributes(attributes);
}
}
/**
* Removes the given organization creation attribute
* for the service.
*
* @param serviceName
* name of service.
* @param attrName
* name of attribute.
* @throws SMSException
* if the organization attribute for the service to be removed
* cannot be found, or if the service name cannot be found.
*/
public void removeAttribute(String serviceName, String attrName)
throws SMSException {
validateConfigImpl();
if (serviceName == null || attrName == null) {
return;
}
if (migratedTo70) {
try {
CachedSMSEntry cEntry = CachedSMSEntry.getInstance(token,
orgDN);
if (cEntry.isDirty()) {
cEntry.refresh();
}
SMSEntry e = cEntry.getClonedSMSEntry();
SMSUtils.removeAttribute(e, serviceName.toLowerCase() + "-"
+ attrName);
e.save(token);
cEntry.refresh(e);
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager: Unable "
+ "to remove Attribute", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
// If in coexistMode and serviceName is idRepoService
// remove the attributes to AMSDK organization
if (coexistMode
&& serviceName
.equalsIgnoreCase(OrgConfigViaAMSDK.IDREPO_SERVICE)) {
amsdk.removeAttribute(attrName);
}
}
/**
* Removes the given organization creation attribute
* values for the service.
*
* @param serviceName
* name of service.
* @param attrName
* name of attribute.
* @param values
* attribute values to be removed.
* @throws SMSException
* if the organization attribute for the service to be removed
* cannot be found, or if the service name cannot be found, or
* if the value cannot be removed.
*/
public void removeAttributeValues(String serviceName, String attrName,
Set values) throws SMSException {
validateConfigImpl();
if (serviceName == null || attrName == null) {
return;
}
if (migratedTo70) {
try {
CachedSMSEntry cEntry = CachedSMSEntry.getInstance(token,
orgDN);
if (cEntry.isDirty()) {
cEntry.refresh();
}
SMSEntry e = cEntry.getClonedSMSEntry();
ServiceSchemaManager ssm = new ServiceSchemaManager(
serviceName, token);
ServiceSchema ss = ssm.getOrganizationCreationSchema();
Map map = new HashMap(2);
map.put(attrName, values);
ss.validateAttributes(map);
SMSUtils.removeAttributeValues(e, serviceName.toLowerCase()
+ "-" + attrName, values, ss
.getSearchableAttributeNames());
e.save(token);
cEntry.refresh(e);
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager: Unable "
+ "to remove Attribute Values", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
// If in coexistMode and serviceName is idRepoService
// remove the attributes to AMSDK organization
if (coexistMode
&& serviceName
.equalsIgnoreCase(OrgConfigViaAMSDK.IDREPO_SERVICE)) {
amsdk.removeAttributeValues(attrName, values);
}
}
/**
* Returns the service configuration object for the
* given service name.
*
* @param serviceName
* name of a service.
* @return service configuration object for the service.
* @throws SMSException
* if there is an error accessing the data store to read the
* service configuration, or if the service name cannot be
* found.
*/
public ServiceConfig getServiceConfig(String serviceName)
throws SMSException {
try {
ServiceConfigManager scmgr = new ServiceConfigManager(serviceName,
token);
ServiceConfig scg = scmgr.getOrganizationConfig(orgName, null);
return (scg);
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager: Unable to "
+ "get Service Config", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
/**
* Adds a service configuration object for the given
* service name for this organization. If the service has been already added
* a <code>SMSException</code> will be thrown.
*
* @param serviceName
* name of the service.
* @param attributes
* service configuration attributes.
* @return service configuration object.
* @throws SMSException
* if the service configuration has been added already.
*/
public ServiceConfig addServiceConfig(String serviceName, Map attributes)
throws SMSException {
try {
ServiceConfigManagerImpl scmi = ServiceConfigManagerImpl
.getInstance(token, serviceName, "1.0");
ServiceConfigImpl sci = scmi.getOrganizationConfig(token, orgName,
null);
if (sci == null || sci.isNewEntry()) {
ServiceConfigManager scm = new ServiceConfigManager(
serviceName, token);
return (scm.createOrganizationConfig(orgName, attributes));
} else {
SMSEntry.debug.error("OrganizationConfigManager: "
+ "ServiceConfig already exists: " + sci.getDN());
throw (new SMSException(SMSEntry.bundle
.getString("sms-service_already_exists1")));
}
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager: Unable to "
+ "add Service Config", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
/**
* Removes the service configuration object for the
* given service name for this organization.
*
* @param serviceName
* name of the service.
* @throws SMSException
* if the service name cannot be found, or not added to the
* organization.
*/
public void removeServiceConfig(String serviceName) throws SMSException {
try {
ServiceConfigManager scm = new ServiceConfigManager(serviceName,
token);
scm.deleteOrganizationConfig(orgName);
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager: Unable to "
+ "delete Service Config", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
/**
* Registers for changes to organization's
* configuration. The object will be called when configuration for this
* organization is changed.
*
* @param listener
* callback object that will be invoked when organization
* configuration has changed
* @return an ID of the registered listener.
*/
public String addListener(ServiceListener listener) {
return (orgConfigImpl.addListener(listener));
}
/**
* Removes the listener from the organization for the
* given listener ID. The ID was issued when the listener was registered.
*
* @param listenerID
* the listener ID issued when the listener was registered
*/
public void removeListener(String listenerID) {
orgConfigImpl.removeListener(listenerID);
}
/**
* Returns normalized DN for realm model
*/
private static String normalizeDN(String subOrgName, String orgDN) {
// Return orgDN if subOrgName is either null or empty
if (subOrgName == null || subOrgName.length() == 0) {
return (orgDN);
}
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager."
+ "normalizeDN()-subOrgName " + subOrgName);
}
String subOrgDN = null;
if (DN.isDN(subOrgName) && (!subOrgName.startsWith("///"))) {
int ndx = subOrgName.lastIndexOf(DNMapper.serviceDN);
if (ndx == -1) {
// Check for baseDN
ndx = subOrgName.lastIndexOf(SMSEntry.getRootSuffix());
}
if (ndx > 0) {
subOrgName = subOrgName.substring(0, ndx - 1);
}
subOrgDN = DNMapper.normalizeDN(subOrgName) + orgDN;
} else if (subOrgName.indexOf('/') != -1) {
String tmp = DNMapper.convertToDN(subOrgName).toString();
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager."
+ "normalizeDN()-slashConvertedString: " + tmp);
}
if (tmp != null && tmp.length() > 0) {
if (tmp.charAt(tmp.length() - 1) == ',') {
subOrgDN = tmp + DNMapper.serviceDN;
} else {
int dx = tmp.indexOf(SMSEntry.COMMA);
if (dx >= 0) {
subOrgDN = tmp + SMSEntry.COMMA + DNMapper.serviceDN;
} else {
subOrgDN = tmp + SMSEntry.COMMA + orgDN;
}
}
} else {
subOrgDN = orgDN;
}
} else if (subOrgName.startsWith(SMSEntry.SUN_INTERNAL_REALM_NAME)) {
subOrgDN = SMSEntry.ORG_PLACEHOLDER_RDN + subOrgName
+ SMSEntry.COMMA + DNMapper.serviceDN;
} else {
if (coexistMode) {
subOrgDN = orgNamingAttrInLegacyMode + SMSEntry.EQUALS
+ subOrgName + SMSEntry.COMMA
+ DNMapper.realmNameToAMSDKName(orgDN);
} else {
subOrgDN = SMSEntry.ORG_PLACEHOLDER_RDN + subOrgName
+ SMSEntry.COMMA + orgDN;
}
}
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager::"
+ "normalizeDN() suborgdn " + subOrgDN);
}
return (subOrgDN);
}
/**
* Returns all service names configured for AM
*/
static Set getServiceNames(SSOToken token) throws SMSException,
SSOException {
// Get the service names from ServiceManager
CachedSubEntries cse = CachedSubEntries.getInstance(token,
DNMapper.serviceDN);
return (cse.getSubEntries(token));
}
/**
* Returns a set of service names that can be assigned
* to a realm. This set excludes name of services that are already assigned
* to the realm and services that are required for the existence of a realm.
*
* @return a set of service names that can be assigned to a realm.
* @throws SMSException
* if there is an error accessing the data store to read the
* service configuration
*/
public Set getAssignableServices() throws SMSException {
// Get all service names, and remove the assigned services
// Set containing service names that has organization schema
Set orgSchemaServiceNames = new HashSet();
try {
for (Iterator names = getServiceNames(token).iterator(); names
.hasNext();) {
String serviceName = (String) names.next();
ServiceSchemaManagerImpl ssmi = ServiceSchemaManagerImpl
.getInstance(token, serviceName, "1.0");
if (ssmi.getSchema(SchemaType.ORGANIZATION) != null) {
// Need to check if the user has permission
// to add/assign the service
StringBuffer d = new StringBuffer(100);
// Need to construct
// "ou=default,ou=organizationconfig,ou=1.0,ou="
d.append(SMSEntry.PLACEHOLDER_RDN).append(SMSEntry.EQUALS)
.append(SMSUtils.DEFAULT).append(SMSEntry.COMMA)
.append(CreateServiceConfig.ORG_CONFIG_NODE)
.append(SMSEntry.PLACEHOLDER_RDN).append(
SMSEntry.EQUALS).append("1.0").append(
SMSEntry.COMMA).append(
SMSEntry.PLACEHOLDER_RDN).append(
SMSEntry.EQUALS);
// Append service name, and org name
d.append(serviceName);
if (!orgDN.equalsIgnoreCase(DNMapper.serviceDN)) {
d.append(SMSEntry.COMMA).append(SMSEntry.SERVICES_NODE);
}
d.append(SMSEntry.COMMA).append(orgDN);
try {
// The function will throw exception if
// user does not have permissions
SMSEntry.getDelegationPermission(token, d.toString(),
SMSEntry.modifyActionSet);
orgSchemaServiceNames.add(serviceName);
} catch (SMSException smse) {
if (smse.getExceptionCode() !=
SMSException.STATUS_NO_PERMISSION)
{
throw (smse);
}
}
}
}
// Need to remove mandatory services
// %%% TODO. Need to have SMS Service with this information
// orgSchemaServiceNames.removeAll(getMandatoryServices());
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager."
+ "getAssignableServices(): SSOException", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
// Remove assigned services
HashSet answer = new HashSet(orgSchemaServiceNames);
answer.removeAll(getAssignedServices());
return (answer);
}
/**
* Returns a set of service names that are assigned to
* a realm.
*
* @return a set of service names that are assigned to a realm.
* @throws SMSException
* if there is an error accessing the data store to read the
* service configuration
*/
public Set getAssignedServices() throws SMSException {
return (getAssignedServices(true));
}
/**
* Returns a set of service names that are assigned to a realm.
*
* @param includeMandatory
* <code>true</code> to include mandatory service names.
* @return a set of service names that are assigned to a realm.
* @throws SMSException
* if there is an error accessing the data store to read the
* service configuration
*/
public Set getAssignedServices(boolean includeMandatory)
throws SMSException {
validateConfigImpl();
Set assignedServices = Collections.EMPTY_SET;
if (coexistMode) {
// Get assigned services from OrgConfigViaAMSDK
assignedServices = amsdk.getAssignedServices();
} else {
// Get assigned service names from OrganizationConfigManagerImpl
assignedServices = orgConfigImpl.getAssignedServices(token);
}
if (!includeMandatory) {
// Get services assigned by default
Set ds = ServiceManager.requiredServices();
assignedServices.removeAll(ds);
}
return (assignedServices);
}
/**
* Assigns the given service to the orgnization with
* the respective attributes. If the service has been already added a <code>
* SMSException</code>
* will be thrown.
*
* @param serviceName
* name of the service
* @param attributes
* service configuration attributes
* @throws SMSException
* if the service configuration has been added already.
*/
public void assignService(String serviceName, Map attributes)
throws SMSException {
addServiceConfig(serviceName, attributes);
}
/**
* Returns attributes configured for the service.
*
* @param serviceName
* name of the service
* @return a map of attributes for the service
* @throws SMSException
* if there is an error accessing the data store to read the
* service configuration, or if the service name cannot be
* found.
*/
public Map getServiceAttributes(String serviceName) throws SMSException {
ServiceConfig scg = getServiceConfig(serviceName);
if (scg == null) {
Object args[] = { serviceName };
SMSEntry.debug.error(
"OrganizationConfigManager.getServiceAttributes() Unable " +
"to get service attributes. ");
throw (new SMSException(IUMSConstants.UMS_BUNDLE_NAME,
"sms-no-organization-schema",
args));
}
return (scg.getAttributes());
}
/**
* Unassigns the service from the organization.
*
* @param serviceName
* name of the service
* @throws SMSException
* if the service name cannot be found or assigned, or if the
* service is a mandatory service.
*/
public void unassignService(String serviceName) throws SMSException {
// if (coexistMode) {
// amsdk.unassignService(serviceName);
// } else {
removeServiceConfig(serviceName);
// }
}
/**
* Sets the attributes related to provided service.
* The assumption is that the service is already assigned to the
* organization. The attributes for the service are validated against the
* service schema.
*
* @param serviceName
* name of the service
* @param attributes
* attributes of the service
* @throws SMSException
* if the service name cannot be found or not assigned to the
* organization.
*/
public void modifyService(String serviceName, Map attributes)
throws SMSException {
try {
getServiceConfig(serviceName).setAttributes(attributes);
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager.modifyService "
+ "SSOException in modify service ", ssoe);
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
public String getNamingAttrForOrg() {
return OrgConfigViaAMSDK.getNamingAttrForOrg();
}
/**
* Returns the <code>OrganizationConfigManager</code>
* of the parent for the given organization name.
*
* @return the configuration manager of the parent for the given
* organization.
* @throws SMSException
* if user doesn't have access to that organization.
*/
public OrganizationConfigManager getParentOrgConfigManager()
throws SMSException {
OrganizationConfigManager ocm = null;
String parentDN = null;
if (DN.isDN(orgDN)) {
if (orgDN.equalsIgnoreCase(DNMapper.serviceDN)) {
return (this);
}
parentDN = (new DN(orgDN)).getParent().toString();
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager."
+ "getParentOrgConfigManager() parentDN : " + parentDN);
}
if (parentDN != null && parentDN.length() > 0) {
ocm = new OrganizationConfigManager(token, parentDN);
}
}
return ocm;
}
/**
* Loads default services to a newly created realm
*/
public static void loadDefaultServices(SSOToken token,
OrganizationConfigManager ocm) throws SMSException {
// Check if DIT has been migrated to 7.0
if (!migratedTo70) {
return;
}
Set defaultServices = ServiceManager.servicesAssignedByDefault();
// Load the default services automatically
OrganizationConfigManager parentOrg = ocm.getParentOrgConfigManager();
if (defaultServices == null) {
// There are no services to be loaded
return;
}
- Set assignedServices = parentOrg.getAssignedServices();
+ Set assignedServices = new CaseInsensitiveHashSet(
+ parentOrg.getAssignedServices());
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager"
+ "::loadDefaultServices " + "assignedServices : "
+ assignedServices);
}
boolean doAuthServiceLater = false;
String serviceName = null;
// Copy service configuration
Iterator items = defaultServices.iterator();
while (items.hasNext() || doAuthServiceLater) {
if (items.hasNext()) {
serviceName = (String) items.next();
if (serviceName.equals(ISAuthConstants.AUTH_SERVICE_NAME)) {
doAuthServiceLater = true;
continue;
}
} else if (doAuthServiceLater) {
serviceName = ISAuthConstants.AUTH_SERVICE_NAME;
doAuthServiceLater = false;
}
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager" +
"::loadDefaultServices:ServiceName " + serviceName);
}
try {
ServiceConfig sc = parentOrg.getServiceConfig(serviceName);
Map attrs = null;
if (sc != null && assignedServices.contains(serviceName)) {
attrs = sc.getAttributesWithoutDefaults();
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug
.message("OrganizationConfigManager"
+ "::loadDefaultServices "
+ "Copying service from parent: "
+ serviceName);
}
ServiceConfig scn = ocm
.addServiceConfig(serviceName, attrs);
// Copy sub-configurations, if any
copySubConfig(sc, scn);
}
} catch (SSOException ssoe) {
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message(
"OrganizationConfigManager.loadDefaultServices " +
"SSOException in loading default services ",
ssoe);
}
throw (new SMSException(SMSEntry.bundle
.getString("sms-INVALID_SSO_TOKEN"),
"sms-INVALID_SSO_TOKEN"));
}
}
}
/**
* Registers default services to newly created suborganizations.
*/
private void registerSvcsForOrg(String subOrgName, String subOrgDN)
{
try {
Set defaultServices =
ServiceManager.servicesAssignedByDefault();
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager::"+
"registerSvcsForOrg. "+
"defaultServices : " + defaultServices);
}
// Register the default services to the newly created orgs,so
// they will be marked with the OC sunRegisteredServiceName.
if (defaultServices != null) {
Set assignedServices = amsdk.getAssignedServices();
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager::" +
"registerSvcsForOrg:assignedServices: " +
assignedServices);
}
Iterator items = defaultServices.iterator();
String serviceName = null;
if (SMSEntry.getRootSuffix().equalsIgnoreCase(
SMSEntry.getAMSdkBaseDN())) {
amsdk = new OrgConfigViaAMSDK(token,
orgNamingAttrInLegacyMode + SMSEntry.EQUALS +
subOrgName + SMSEntry.COMMA +
DNMapper.realmNameToAMSDKName(orgDN), subOrgDN);
} else {
amsdk = new OrgConfigViaAMSDK(token,
orgNamingAttrInLegacyMode + SMSEntry.EQUALS +
subOrgName + SMSEntry.COMMA + amSDKOrgDN, subOrgDN);
}
while (items.hasNext()) {
serviceName = (String) items.next();
if (assignedServices.contains(serviceName)) {
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message(
"OrganizationConfigManager::"+
"registerSvcsForOrg:ServiceName : " +
serviceName);
}
amsdk.assignService(serviceName);
}
}
}
} catch (SMSException smse) {
// Unable to load default services
if (SMSEntry.debug.warningEnabled()) {
SMSEntry.debug.warning("OrganizationConfigManager::" +
"registerSvcsForOrg. " +
"SMSException in registering services: ", smse);
}
}
}
/**
* Copies service configurations recursively from source to destination
*/
static void copySubConfig(ServiceConfig from, ServiceConfig to)
throws SMSException, SSOException {
Set subConfigNames = from.getSubConfigNames();
for (Iterator items = subConfigNames.iterator(); items.hasNext();) {
String subConfigName = (String) items.next();
ServiceConfig scf = from.getSubConfig(subConfigName);
to.addSubConfig(subConfigName, scf.getSchemaID(),
scf.getPriority(), scf.getAttributesWithoutDefaults());
ServiceConfig sct = to.getSubConfig(subConfigName);
copySubConfig(scf, sct);
}
}
/**
* Determines whether an organization ought to be created for each
* realm in realm only mode of installation based on the boolean flag
* in amSDK plugin.
* This requirement is for portal customers.
*/
protected boolean isCopyOrgEnabled() {
if (copyOrgInitialized) {
return (copyOrgEnabled);
}
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager: "+
"in isCopyOrgEnabled() ");
}
// Check if AMSDK is configured for the realm
try {
ServiceConfig s = getServiceConfig(ServiceManager.REALM_SERVICE);
if (s != null) {
Iterator items = s.getSubConfigNames().iterator();
while (items.hasNext()) {
String name = items.next().toString();
ServiceConfig subConfig = s.getSubConfig(name);
if (subConfig == null) {
SMSEntry.debug.error("OrganizationConfigManager.is" +
"CopyOrgEnabled. SubConfig is NULL: " +
"SC Name: " + name + " For org: " + orgDN);
return (false);
}
if (subConfig.getSchemaID().equalsIgnoreCase(
IdConstants.AMSDK_PLUGIN_NAME)) {
Map configMap = subConfig.getAttributes();
if ((configMap != null) && !configMap.isEmpty()) {
// Get the amsdkOrgName from the amSDKRepo to build
// OrgConfigViaSDK instance.
Set orgs = (Set) configMap.get("amSDKOrgName");
if (orgs != null && !orgs.isEmpty()) {
amSDKOrgDN = (String) orgs.iterator().next();
Set cfgs = (Set) configMap.get(CONF_ENABLED);
if ( (cfgs != null) && (!cfgs.isEmpty()) &&
(cfgs.contains("true")) &&
(amSDKOrgDN !=null) ) {
amsdk = new OrgConfigViaAMSDK(token,
amSDKOrgDN, orgDN);
if (orgNamingAttrInLegacyMode == null) {
orgNamingAttrInLegacyMode =
getNamingAttrForOrg();
}
copyOrgEnabled = true;
}
break;
}
}
}
}
}
} catch (SSOException sse) {
// Use default values i.e., false
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager:" +
"isCopyOrgEnabled() Unable to get service: " +
ServiceManager.REALM_SERVICE, sse);
}
} catch (SMSException e) {
// Use default values i.e., false
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager:" +
"isCopyOrgEnabled() Unable to get service: " +
ServiceManager.REALM_SERVICE, e);
}
}
copyOrgInitialized = true;
if (SMSEntry.debug.messageEnabled()) {
SMSEntry.debug.message("OrganizationConfigManager: "+
"copyOrgEnabled == " + copyOrgEnabled);
}
return (copyOrgEnabled);
}
static void initializeFlags() {
realmEnabled = ServiceManager.isRealmEnabled();
coexistMode = ServiceManager.isCoexistenceMode();
migratedTo70 = ServiceManager.isConfigMigratedTo70();
}
void validateConfigImpl() throws SMSException {
// Instantiate the OrgConfigImpl and cache it
if ((orgConfigImpl == null) || !orgConfigImpl.isValid()) {
try {
orgConfigImpl = OrganizationConfigManagerImpl.getInstance(
token, orgName);
} catch (SSOException ssoe) {
throw (new SMSException(ssoe, "sms-INVALID_SSO_TOKEN"));
}
}
}
class OrganizationConfigManagerListener implements ServiceListener {
public void schemaChanged(String serviceName, String version) {
// Call ServiceManager to notify
ServiceManager.schemaChanged();
// If naming service has changed, reload the AM Servers
if (serviceName.equalsIgnoreCase(ServiceManager.PLATFORM_SERVICE)) {
ServiceManager.accessManagerServers = null;
}
}
public void globalConfigChanged(String serviceName, String version,
String groupName, String serviceComponent, int type) {
if (serviceName.equalsIgnoreCase(ServiceManager.REALM_SERVICE)) {
try {
ServiceManager.checkFlags(token);
} catch (SSOException ssoe) {
SMSEntry.debug.error("OrganizationConfigManager: "
+ "globalConfigChanged ", ssoe);
} catch (SMSException smse) {
SMSEntry.debug.error("OrganizationConfigManager: "
+ "globalConfigChanged ", smse);
}
realmEnabled = ServiceManager.isRealmEnabled();
coexistMode = ServiceManager.isCoexistenceMode();
migratedTo70 = ServiceManager.isConfigMigratedTo70();
}
}
public void organizationConfigChanged(String serviceName,
String version, String orgName, String groupName,
String serviceComponent, int type) {
// Reset the cached configuration in OrgConfigViaAMSDK
if (serviceName.equalsIgnoreCase(OrgConfigViaAMSDK.IDREPO_SERVICE))
{
OrgConfigViaAMSDK.attributeMappings = new HashMap();
OrgConfigViaAMSDK.reverseAttributeMappings = new HashMap();
}
}
}
// ******* Static Variables ************
// To determine if notification object has been registered for config
// changes
private static boolean registeredForConfigNotifications;
// Realm & Co-existence modes
private static boolean realmEnabled;
private static boolean coexistMode;
private static boolean migratedTo70;
}
| false | false | null | null |
diff --git a/rhogen-wizard/src/rhogenwizard/sdk/task/run/RunReleaseRhoconnectAppTask.java b/rhogen-wizard/src/rhogenwizard/sdk/task/run/RunReleaseRhoconnectAppTask.java
index 46dfc41..688091e 100644
--- a/rhogen-wizard/src/rhogenwizard/sdk/task/run/RunReleaseRhoconnectAppTask.java
+++ b/rhogen-wizard/src/rhogenwizard/sdk/task/run/RunReleaseRhoconnectAppTask.java
@@ -1,37 +1,37 @@
package rhogenwizard.sdk.task.run;
import rhogenwizard.OSHelper;
import rhogenwizard.SysCommandExecutor;
import rhogenwizard.sdk.task.RubyExecTask;
import rhogenwizard.sdk.task.RunTask;
import rhogenwizard.sdk.task.SeqRunTask;
import rhogenwizard.sdk.task.StopSyncAppTask;
import rhogenwizard.sdk.task.StoreLastSyncRunAppTask;
public class RunReleaseRhoconnectAppTask extends SeqRunTask
{
private static RunTask[] getTasks(final String workDir)
{
- RunTask redisStartbgTask = new RubyExecTask(workDir, SysCommandExecutor.RUBY_BAT, "rhoconnect",
- "redis-startbg");
- RunTask rhoconnectStartbgTask;
+ RunTask redisStartbgTask = new RubyExecTask(workDir, SysCommandExecutor.RUBY_BAT, "rhoconnect", "redis-startbg");
+ RunTask rhoconnectStartbgTask = null;
+
if (OSHelper.isWindows())
{
- rhoconnectStartbgTask = new RubyExecTask(workDir, SysCommandExecutor.RUBY_BAT, "start",
- "rhoconnect", "start");
+ rhoconnectStartbgTask = new RubyExecTask(workDir, SysCommandExecutor.RUBY_BAT, "start", "cmd", "/c",
+ "rhoconnect", "start&&exit");
}
else
{
rhoconnectStartbgTask = new RubyExecTask(workDir, SysCommandExecutor.RUBY_BAT, "osascript", "-e",
"tell app \"Terminal\"\ndo script \"cd " + workDir + "&&rhoconnect start&&exit\"\nend tell");
}
return new RunTask[] { new StopSyncAppTask(), new StoreLastSyncRunAppTask(workDir), redisStartbgTask,
rhoconnectStartbgTask };
}
public RunReleaseRhoconnectAppTask(String workDir)
{
super(getTasks(workDir));
}
}
| false | false | null | null |