diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/TrackerExperiment/src/tracker/Tracker.java b/TrackerExperiment/src/tracker/Tracker.java
index ea34f83..07ad22c 100644
--- a/TrackerExperiment/src/tracker/Tracker.java
+++ b/TrackerExperiment/src/tracker/Tracker.java
@@ -1,85 +1,89 @@
package tracker;
import com.sun.squawk.util.MathUtils;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.camera.AxisCameraException;
import edu.wpi.first.wpilibj.image.BinaryImage;
import edu.wpi.first.wpilibj.image.ColorImage;
import edu.wpi.first.wpilibj.image.CriteriaCollection;
import edu.wpi.first.wpilibj.image.NIVision;
import edu.wpi.first.wpilibj.image.NIVisionException;
import edu.wpi.first.wpilibj.image.ParticleAnalysisReport;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Tracker extends IterativeRobot {
private static final double FOCAL_LENGTH = 240.0 / Math.tan(47.0 / 180.0 * Math.PI);
private AxisCamera camera = AxisCamera.getInstance();
private CriteriaCollection cc;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
cc = new CriteriaCollection();
cc.addCriteria(NIVision.MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, 30, 400, false);
cc.addCriteria(NIVision.MeasurementType.IMAQ_MT_BOUNDING_RECT_HEIGHT, 40, 400, false);
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
try {
ColorImage img = camera.getImage();
BinaryImage thresholdImg = img.thresholdRGB(0, 100, 230, 255, 230, 255);
BinaryImage bigsImg = thresholdImg.removeSmallObjects(false, 2);
BinaryImage convexHullImg = bigsImg.convexHull(false);
BinaryImage filteredImg = convexHullImg.particleFilter(cc);
ParticleAnalysisReport[] reports = filteredImg.getOrderedParticleAnalysisReports();
if (filteredImg.getNumberParticles() >= 1) {
ParticleAnalysisReport report = reports[0];
//double offset = reports[0].center_mass_x - (img.getWidth() / 2);
int rectUpper = 240 - report.boundingRectTop;
int rectLower = 240 - (report.boundingRectTop - report.boundingRectHeight);
double phi = MathUtils.atan(rectUpper / FOCAL_LENGTH);
double theta = MathUtils.atan(rectLower / FOCAL_LENGTH);
SmartDashboard.putNumber("Phi: ", phi / Math.PI * 180.0);
SmartDashboard.putNumber("Theta: ", theta / Math.PI * 180.0);
+ double tanTheta = Math.tan(theta);
+ double tanPhi = Math.tan(phi);
+ SmartDashboard.putNumber("Distance", -32 / (tanPhi - tanTheta));
+ SmartDashboard.putNumber("Height", -(16 * tanTheta + 16 * tanPhi) / (tanTheta - tanPhi));
//chassis.drive((-offset / 200), (offset / 200));
}
filteredImg.free();
convexHullImg.free();
bigsImg.free();
thresholdImg.free();
img.free();
Timer.delay(0.05);
} catch (AxisCameraException ex) {
ex.printStackTrace();
} catch (NIVisionException ex) {
ex.printStackTrace();
}
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
}
}
| true | true | public void teleopPeriodic() {
try {
ColorImage img = camera.getImage();
BinaryImage thresholdImg = img.thresholdRGB(0, 100, 230, 255, 230, 255);
BinaryImage bigsImg = thresholdImg.removeSmallObjects(false, 2);
BinaryImage convexHullImg = bigsImg.convexHull(false);
BinaryImage filteredImg = convexHullImg.particleFilter(cc);
ParticleAnalysisReport[] reports = filteredImg.getOrderedParticleAnalysisReports();
if (filteredImg.getNumberParticles() >= 1) {
ParticleAnalysisReport report = reports[0];
//double offset = reports[0].center_mass_x - (img.getWidth() / 2);
int rectUpper = 240 - report.boundingRectTop;
int rectLower = 240 - (report.boundingRectTop - report.boundingRectHeight);
double phi = MathUtils.atan(rectUpper / FOCAL_LENGTH);
double theta = MathUtils.atan(rectLower / FOCAL_LENGTH);
SmartDashboard.putNumber("Phi: ", phi / Math.PI * 180.0);
SmartDashboard.putNumber("Theta: ", theta / Math.PI * 180.0);
//chassis.drive((-offset / 200), (offset / 200));
}
filteredImg.free();
convexHullImg.free();
bigsImg.free();
thresholdImg.free();
img.free();
Timer.delay(0.05);
} catch (AxisCameraException ex) {
ex.printStackTrace();
} catch (NIVisionException ex) {
ex.printStackTrace();
}
}
| public void teleopPeriodic() {
try {
ColorImage img = camera.getImage();
BinaryImage thresholdImg = img.thresholdRGB(0, 100, 230, 255, 230, 255);
BinaryImage bigsImg = thresholdImg.removeSmallObjects(false, 2);
BinaryImage convexHullImg = bigsImg.convexHull(false);
BinaryImage filteredImg = convexHullImg.particleFilter(cc);
ParticleAnalysisReport[] reports = filteredImg.getOrderedParticleAnalysisReports();
if (filteredImg.getNumberParticles() >= 1) {
ParticleAnalysisReport report = reports[0];
//double offset = reports[0].center_mass_x - (img.getWidth() / 2);
int rectUpper = 240 - report.boundingRectTop;
int rectLower = 240 - (report.boundingRectTop - report.boundingRectHeight);
double phi = MathUtils.atan(rectUpper / FOCAL_LENGTH);
double theta = MathUtils.atan(rectLower / FOCAL_LENGTH);
SmartDashboard.putNumber("Phi: ", phi / Math.PI * 180.0);
SmartDashboard.putNumber("Theta: ", theta / Math.PI * 180.0);
double tanTheta = Math.tan(theta);
double tanPhi = Math.tan(phi);
SmartDashboard.putNumber("Distance", -32 / (tanPhi - tanTheta));
SmartDashboard.putNumber("Height", -(16 * tanTheta + 16 * tanPhi) / (tanTheta - tanPhi));
//chassis.drive((-offset / 200), (offset / 200));
}
filteredImg.free();
convexHullImg.free();
bigsImg.free();
thresholdImg.free();
img.free();
Timer.delay(0.05);
} catch (AxisCameraException ex) {
ex.printStackTrace();
} catch (NIVisionException ex) {
ex.printStackTrace();
}
}
|
diff --git a/proxy/src/main/java/org/fedoraproject/candlepin/model/RulesCurator.java b/proxy/src/main/java/org/fedoraproject/candlepin/model/RulesCurator.java
index 3de7f038c..0eb18c27a 100644
--- a/proxy/src/main/java/org/fedoraproject/candlepin/model/RulesCurator.java
+++ b/proxy/src/main/java/org/fedoraproject/candlepin/model/RulesCurator.java
@@ -1,62 +1,62 @@
package org.fedoraproject.candlepin.model;
import com.wideplay.warp.persist.Transactional;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
public class RulesCurator extends AbstractHibernateCurator<Rules> {
protected RulesCurator() {
super(Rules.class);
}
@Transactional
// This seems lame...
public Rules update(Rules updatedRules) {
List<Rules> existingRuleSet = findAll();
if (existingRuleSet.size() == 0) {
return create(updatedRules);
}
for (Rules rule: existingRuleSet) {
delete(rule);
}
create(updatedRules);
return updatedRules;
}
private void initiateRulesFromFile() {
String path = "/rules/satellite-rules.js";
- InputStream is = path.getClass().getResourceAsStream(path);
+ InputStream is = this.getClass().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Rules rules = new Rules(builder.toString());
create(rules);
}
public Rules getRules() {
List<Rules> existingRuleSet = findAll();
if (existingRuleSet.size() == 0) {
initiateRulesFromFile();
existingRuleSet = findAll();
}
return existingRuleSet.get(0);
}
}
| true | true | private void initiateRulesFromFile() {
String path = "/rules/satellite-rules.js";
InputStream is = path.getClass().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Rules rules = new Rules(builder.toString());
create(rules);
}
| private void initiateRulesFromFile() {
String path = "/rules/satellite-rules.js";
InputStream is = this.getClass().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Rules rules = new Rules(builder.toString());
create(rules);
}
|
diff --git a/compile-testing/src/main/java/com/google/testing/compile/JavaSourcesSubject.java b/compile-testing/src/main/java/com/google/testing/compile/JavaSourcesSubject.java
index 13d65eb..8e66c3d 100644
--- a/compile-testing/src/main/java/com/google/testing/compile/JavaSourcesSubject.java
+++ b/compile-testing/src/main/java/com/google/testing/compile/JavaSourcesSubject.java
@@ -1,333 +1,333 @@
/*
* Copyright (C) 2013 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.testing.compile;
import java.io.IOException;
import java.util.Arrays;
import javax.annotation.CheckReturnValue;
import javax.annotation.processing.Processor;
import javax.tools.Diagnostic;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import org.truth0.FailureStrategy;
import org.truth0.subjects.Subject;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
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.io.ByteStreams;
import com.sun.source.tree.CompilationUnitTree;
/**
* A <a href="https://github.com/truth0/truth">Truth</a> {@link Subject} that evaluates the result
* of a {@code javac} compilation.
*
* @author Gregory Kick
*/
public final class JavaSourcesSubject
extends Subject<JavaSourcesSubject, Iterable<? extends JavaFileObject>> {
JavaSourcesSubject(FailureStrategy failureStrategy, Iterable<? extends JavaFileObject> subject) {
super(failureStrategy, subject);
}
public interface ChainingClause<T> {
T and();
}
public interface FileClause extends ChainingClause<UnuccessfulCompilationClause> {
LineClause in(JavaFileObject file);
}
public interface LineClause extends ChainingClause<UnuccessfulCompilationClause> {
ColumnClause onLine(long lineNumber);
}
public interface ColumnClause extends ChainingClause<UnuccessfulCompilationClause> {
ChainingClause<UnuccessfulCompilationClause> atColumn(long columnNumber);
}
public interface GeneratedPredicateClause {
SuccessfulCompilationClause generatesSources(JavaFileObject first, JavaFileObject... rest);
SuccessfulCompilationClause generatesFiles(JavaFileObject first, JavaFileObject... rest);
}
public interface SuccessfulCompilationClause extends ChainingClause<GeneratedPredicateClause> {}
public interface UnuccessfulCompilationClause {
FileClause hasError(String message);
}
@CheckReturnValue
public CompilationClause processedWith(Processor first, Processor... rest) {
return new CompilationClause(Lists.asList(first, rest));
}
private CompilationClause newCompilationClause(Iterable<? extends Processor> processors) {
return new CompilationClause(processors);
}
public final class CompilationClause {
private final ImmutableSet<Processor> processors;
private CompilationClause() {
this(ImmutableSet.<Processor>of());
}
private CompilationClause(Iterable<? extends Processor> processors) {
this.processors = ImmutableSet.copyOf(processors);
}
public SuccessfulCompilationClause hasNoErrors() {
Compilation.Result result = Compilation.compile(processors, getSubject());
ImmutableList<Diagnostic<? extends JavaFileObject>> errors =
result.diagnosticsByKind.get(Kind.ERROR);
if (!errors.isEmpty()) {
StringBuilder message = new StringBuilder("Compilation produced the following errors:\n");
Joiner.on("\n").appendTo(message, errors);
failureStrategy.fail(message.toString());
}
return new SuccessfulCompilationBuilder(result);
}
public FileClause hasError(String message) {
Compilation.Result result = Compilation.compile(processors, getSubject());
return new UnsuccessfulCompilationBuilder(result).hasError(message);
}
}
public SuccessfulCompilationClause hasNoErrors() {
return new CompilationClause().hasNoErrors();
}
public FileClause hasError(String message) {
return new CompilationClause().hasError(message);
}
private final class UnsuccessfulCompilationBuilder implements UnuccessfulCompilationClause {
private final Compilation.Result result;
UnsuccessfulCompilationBuilder(Compilation.Result result) {
this.result = result;
}
@Override
public FileClause hasError(final String message) {
FluentIterable<Diagnostic<? extends JavaFileObject>> diagnostics =
FluentIterable.from(result.diagnosticsByKind.get(Kind.ERROR));
final FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsWithMessage =
diagnostics.filter(new Predicate<Diagnostic<?>>() {
@Override
public boolean apply(Diagnostic<?> input) {
return message.equals(input.getMessage(null));
}
});
if (diagnosticsWithMessage.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error with message \"%s\", but only found %s", message,
diagnostics.transform(
new Function<Diagnostic<?>, String>() {
@Override public String apply(Diagnostic<?> input) {
return "\"" + input.getMessage(null) + "\"";
}
})));
}
return new FileClause() {
@Override
public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
@Override
public LineClause in(final JavaFileObject file) {
FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsInFile =
diagnosticsWithMessage.filter(new Predicate<Diagnostic<? extends FileObject>>() {
@Override
public boolean apply(Diagnostic<? extends FileObject> input) {
return file.toUri().getPath().equals(input.getSource().toUri().getPath());
}
});
if (diagnosticsInFile.isEmpty()) {
failureStrategy.fail(String.format(
- "Expeceted an error in %s, but only found errors in ", file.getName(),
+ "Expected an error in %s, but only found errors in ", file.getName(),
diagnosticsWithMessage.transform(
new Function<Diagnostic<? extends FileObject>, String>() {
@Override public String apply(Diagnostic<? extends FileObject> input) {
return input.getSource().getName();
}
})));
}
return new LineClause() {
@Override public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
@Override public ColumnClause onLine(final long lineNumber) {
final FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsOnLine =
diagnosticsWithMessage.filter(new Predicate<Diagnostic<?>>() {
@Override
public boolean apply(Diagnostic<?> input) {
return lineNumber == input.getLineNumber();
}
});
if (diagnosticsOnLine.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error on line %d, but only found errors on line(s) %s",
lineNumber, diagnosticsOnLine.transform(
new Function<Diagnostic<?>, Long>() {
@Override public Long apply(Diagnostic<?> input) {
return input.getLineNumber();
}
})));
}
return new ColumnClause() {
@Override
public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
@Override
public ChainingClause<UnuccessfulCompilationClause> atColumn(
final long columnNumber) {
FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsAtColumn =
diagnosticsOnLine.filter(new Predicate<Diagnostic<?>>() {
@Override
public boolean apply(Diagnostic<?> input) {
return columnNumber == input.getColumnNumber();
}
});
if (diagnosticsAtColumn.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error at column %d, but only found errors at column(s) %s",
columnNumber, diagnosticsOnLine.transform(
new Function<Diagnostic<?>, Long>() {
@Override public Long apply(Diagnostic<?> input) {
return input.getColumnNumber();
}
})));
}
return new ChainingClause<JavaSourcesSubject.UnuccessfulCompilationClause>() {
@Override public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
};
}
};
}
};
}
};
}
}
private final class SuccessfulCompilationBuilder implements SuccessfulCompilationClause,
GeneratedPredicateClause {
private final Compilation.Result result;
SuccessfulCompilationBuilder(Compilation.Result result) {
this.result = result;
}
@Override
public GeneratedPredicateClause and() {
return this;
}
@Override
public SuccessfulCompilationClause generatesSources(JavaFileObject first,
JavaFileObject... rest) {
ImmutableList<JavaFileObject> generatedSources =
result.generatedFilesByKind.get(JavaFileObject.Kind.SOURCE);
Iterable<? extends CompilationUnitTree> actualCompilationUnits =
Compilation.parse(generatedSources);
final EqualityScanner scanner = new EqualityScanner();
for (final CompilationUnitTree expected : Compilation.parse(Lists.asList(first, rest))) {
Optional<? extends CompilationUnitTree> found =
Iterables.tryFind(actualCompilationUnits, new Predicate<CompilationUnitTree>() {
@Override
public boolean apply(CompilationUnitTree input) {
return scanner.visitCompilationUnit(expected, input);
}
});
if (!found.isPresent()) {
failureStrategy.fail("Did not find a source file coresponding to "
+ expected.getSourceFile().getName());
}
}
return this;
}
@Override
public SuccessfulCompilationClause generatesFiles(JavaFileObject first,
JavaFileObject... rest) {
for (JavaFileObject expected : Lists.asList(first, rest)) {
if (!wasGenerated(result, expected)) {
failureStrategy.fail("Did not find a generated file corresponding to "
+ expected.getName());
}
}
return this;
}
boolean wasGenerated(Compilation.Result result, JavaFileObject expected) {
for (JavaFileObject generated : result.generatedFilesByKind.get(expected.getKind())) {
try {
if (Arrays.equals(
ByteStreams.toByteArray(expected.openInputStream()),
ByteStreams.toByteArray(generated.openInputStream()))) {
return true;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return false;
}
}
public static final class SingleSourceAdapter
extends Subject<SingleSourceAdapter, JavaFileObject> {
private final JavaSourcesSubject delegate;
SingleSourceAdapter(FailureStrategy failureStrategy,
JavaFileObject subject) {
super(failureStrategy, subject);
this.delegate =
new JavaSourcesSubject(failureStrategy, ImmutableList.of(subject));
}
@CheckReturnValue
public CompilationClause processedWith(Processor first, Processor... rest) {
return delegate.newCompilationClause(Lists.asList(first, rest));
}
public SuccessfulCompilationClause hasNoErrors() {
return delegate.hasNoErrors();
}
public FileClause hasError(String message) {
return delegate.hasError(message);
}
}
}
| true | true | public FileClause hasError(final String message) {
FluentIterable<Diagnostic<? extends JavaFileObject>> diagnostics =
FluentIterable.from(result.diagnosticsByKind.get(Kind.ERROR));
final FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsWithMessage =
diagnostics.filter(new Predicate<Diagnostic<?>>() {
@Override
public boolean apply(Diagnostic<?> input) {
return message.equals(input.getMessage(null));
}
});
if (diagnosticsWithMessage.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error with message \"%s\", but only found %s", message,
diagnostics.transform(
new Function<Diagnostic<?>, String>() {
@Override public String apply(Diagnostic<?> input) {
return "\"" + input.getMessage(null) + "\"";
}
})));
}
return new FileClause() {
@Override
public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
@Override
public LineClause in(final JavaFileObject file) {
FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsInFile =
diagnosticsWithMessage.filter(new Predicate<Diagnostic<? extends FileObject>>() {
@Override
public boolean apply(Diagnostic<? extends FileObject> input) {
return file.toUri().getPath().equals(input.getSource().toUri().getPath());
}
});
if (diagnosticsInFile.isEmpty()) {
failureStrategy.fail(String.format(
"Expeceted an error in %s, but only found errors in ", file.getName(),
diagnosticsWithMessage.transform(
new Function<Diagnostic<? extends FileObject>, String>() {
@Override public String apply(Diagnostic<? extends FileObject> input) {
return input.getSource().getName();
}
})));
}
return new LineClause() {
@Override public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
@Override public ColumnClause onLine(final long lineNumber) {
final FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsOnLine =
diagnosticsWithMessage.filter(new Predicate<Diagnostic<?>>() {
@Override
public boolean apply(Diagnostic<?> input) {
return lineNumber == input.getLineNumber();
}
});
if (diagnosticsOnLine.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error on line %d, but only found errors on line(s) %s",
lineNumber, diagnosticsOnLine.transform(
new Function<Diagnostic<?>, Long>() {
@Override public Long apply(Diagnostic<?> input) {
return input.getLineNumber();
}
})));
}
return new ColumnClause() {
@Override
public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
@Override
public ChainingClause<UnuccessfulCompilationClause> atColumn(
final long columnNumber) {
FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsAtColumn =
diagnosticsOnLine.filter(new Predicate<Diagnostic<?>>() {
@Override
public boolean apply(Diagnostic<?> input) {
return columnNumber == input.getColumnNumber();
}
});
if (diagnosticsAtColumn.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error at column %d, but only found errors at column(s) %s",
columnNumber, diagnosticsOnLine.transform(
new Function<Diagnostic<?>, Long>() {
@Override public Long apply(Diagnostic<?> input) {
return input.getColumnNumber();
}
})));
}
return new ChainingClause<JavaSourcesSubject.UnuccessfulCompilationClause>() {
@Override public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
};
}
};
}
};
}
};
}
| public FileClause hasError(final String message) {
FluentIterable<Diagnostic<? extends JavaFileObject>> diagnostics =
FluentIterable.from(result.diagnosticsByKind.get(Kind.ERROR));
final FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsWithMessage =
diagnostics.filter(new Predicate<Diagnostic<?>>() {
@Override
public boolean apply(Diagnostic<?> input) {
return message.equals(input.getMessage(null));
}
});
if (diagnosticsWithMessage.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error with message \"%s\", but only found %s", message,
diagnostics.transform(
new Function<Diagnostic<?>, String>() {
@Override public String apply(Diagnostic<?> input) {
return "\"" + input.getMessage(null) + "\"";
}
})));
}
return new FileClause() {
@Override
public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
@Override
public LineClause in(final JavaFileObject file) {
FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsInFile =
diagnosticsWithMessage.filter(new Predicate<Diagnostic<? extends FileObject>>() {
@Override
public boolean apply(Diagnostic<? extends FileObject> input) {
return file.toUri().getPath().equals(input.getSource().toUri().getPath());
}
});
if (diagnosticsInFile.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error in %s, but only found errors in ", file.getName(),
diagnosticsWithMessage.transform(
new Function<Diagnostic<? extends FileObject>, String>() {
@Override public String apply(Diagnostic<? extends FileObject> input) {
return input.getSource().getName();
}
})));
}
return new LineClause() {
@Override public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
@Override public ColumnClause onLine(final long lineNumber) {
final FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsOnLine =
diagnosticsWithMessage.filter(new Predicate<Diagnostic<?>>() {
@Override
public boolean apply(Diagnostic<?> input) {
return lineNumber == input.getLineNumber();
}
});
if (diagnosticsOnLine.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error on line %d, but only found errors on line(s) %s",
lineNumber, diagnosticsOnLine.transform(
new Function<Diagnostic<?>, Long>() {
@Override public Long apply(Diagnostic<?> input) {
return input.getLineNumber();
}
})));
}
return new ColumnClause() {
@Override
public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
@Override
public ChainingClause<UnuccessfulCompilationClause> atColumn(
final long columnNumber) {
FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsAtColumn =
diagnosticsOnLine.filter(new Predicate<Diagnostic<?>>() {
@Override
public boolean apply(Diagnostic<?> input) {
return columnNumber == input.getColumnNumber();
}
});
if (diagnosticsAtColumn.isEmpty()) {
failureStrategy.fail(String.format(
"Expected an error at column %d, but only found errors at column(s) %s",
columnNumber, diagnosticsOnLine.transform(
new Function<Diagnostic<?>, Long>() {
@Override public Long apply(Diagnostic<?> input) {
return input.getColumnNumber();
}
})));
}
return new ChainingClause<JavaSourcesSubject.UnuccessfulCompilationClause>() {
@Override public UnuccessfulCompilationClause and() {
return UnsuccessfulCompilationBuilder.this;
}
};
}
};
}
};
}
};
}
|
diff --git a/src/Main.java b/src/Main.java
index 7d5e90f..326f945 100644
--- a/src/Main.java
+++ b/src/Main.java
@@ -1,5 +1,5 @@
public class Main {
public static void main(String[] args) {
- System.out.println("1+1=2");
+ System.out.println("1+1=7");
}
}
| true | true | public static void main(String[] args) {
System.out.println("1+1=2");
}
| public static void main(String[] args) {
System.out.println("1+1=7");
}
|
diff --git a/src/web/org/codehaus/groovy/grails/web/pages/Parse.java b/src/web/org/codehaus/groovy/grails/web/pages/Parse.java
index 6b5649a90..9892171d4 100644
--- a/src/web/org/codehaus/groovy/grails/web/pages/Parse.java
+++ b/src/web/org/codehaus/groovy/grails/web/pages/Parse.java
@@ -1,666 +1,666 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* 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.codehaus.groovy.grails.web.pages;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.*;
import org.codehaus.groovy.grails.web.taglib.GrailsTagRegistry;
import org.codehaus.groovy.grails.web.taglib.GroovySyntaxTag;
import org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* NOTE: Based on work done by the GSP standalone project (https://gsp.dev.java.net/)
*
* Parsing implementation for GSP files
*
* @author Troy Heninger
* @author Graeme Rocher
*
* Date: Jan 10, 2004
*
*/
public class Parse implements Tokens {
public static final Log LOG = LogFactory.getLog(Parse.class);
private static final Pattern PARA_BREAK = Pattern.compile("/p>\\s*<p[^>]*>", Pattern.CASE_INSENSITIVE);
private static final Pattern ROW_BREAK = Pattern.compile("((/td>\\s*</tr>\\s*<)?tr[^>]*>\\s*<)?td[^>]*>", Pattern.CASE_INSENSITIVE);
private static final Pattern PARSE_TAG_FIRST_PASS = Pattern.compile("(\\s*(\\S+)\\s*=\\s*[\"]([^\"]*)[\"][\\s|>]{1}){1}");
private static final Pattern PARSE_TAG_SECOND_PASS = Pattern.compile("(\\s*(\\S+)\\s*=\\s*[']([^']*)['][\\s|>]{1}){1}");
private Scan scan;
private GSPWriter out;
private String className;
private boolean finalPass = false;
private int tagIndex;
private Map tagContext;
private List tagMetaStack = new ArrayList();
private GrailsTagRegistry tagRegistry = GrailsTagRegistry.getInstance();
private boolean bufferWhiteSpace ;
private StringBuffer whiteSpaceBuffer = new StringBuffer();
private int currentOutputLine = 1;
private String contentType = DEFAULT_CONTENT_TYPE;
private boolean doNextScan = true;
private int state;
private static final String START_MULTILINE_STRING = "'''";
private static final String END_MULTILINE_STRING = "'''";
private static final String DEFAULT_CONTENT_TYPE = "text/html;charset=UTF-8";
private Map constants = new TreeMap();
private int constantCount = 0;
private final String pageName;
private static final String EMPTY_MULTILINE_STRING = "''''''";
public static final String[] DEFAULT_IMPORTS = new String[] {
"org.codehaus.groovy.grails.web.pages.GroovyPage",
"org.codehaus.groovy.grails.web.taglib.*",
"org.springframework.web.util.*",
"grails.util.GrailsUtil"
};
private static final String CONFIG_PROPERTY_DEFAULT_CODEC = "grails.views.default.codec";
private static final String CONFIG_PROPERTY_GSP_ENCODING = "grails.views.gsp.encoding";
private String codecName;
private static final String IMPORT_DIRECTIVE = "import";
private static final String CONTENT_TYPE_DIRECTIVE = "contentType";
private static final String DEFAULT_CODEC_DIRECTIVE = "defaultCodec";
private String gspEncoding;
public static final String GROOVY_SOURCE_CHAR_ENCODING = "UTF-8";
public String getContentType() {
return this.contentType;
}
public int getCurrentOutputLineNumber() {
return currentOutputLine;
}
class TagMeta {
String name;
String namespace;
Object instance;
boolean isDynamic;
boolean hasAttributes;
int lineNumber;
public String toString() {
return "<"+namespace+":"+name+">";
}
}
public Parse(String name, String filename, InputStream in) throws IOException {
Map config = ConfigurationHolder.getFlatConfig();
// Get the GSP file encoding from Config, or fall back to system file.encoding if none set
Object gspEnc = config.get(CONFIG_PROPERTY_GSP_ENCODING);
if ((gspEnc != null) && (gspEnc.toString().trim().length() > 0)) {
gspEncoding = gspEnc.toString();
} else {
gspEncoding = System.getProperty("file.encoding", "us-ascii");
}
if(LOG.isDebugEnabled()) {
LOG.debug("GSP file encoding set to: " + gspEncoding);
}
scan = new Scan(readStream(in));
this.pageName = filename;
makeName(name);
Object o = config.get(CONFIG_PROPERTY_DEFAULT_CODEC);
lookupCodec(o);
} // Parse()
private void lookupCodec(Object o) {
if(o!=null) {
String codecName = o.toString();
GrailsApplication app = ApplicationHolder.getApplication();
if(app != null) {
GrailsClass codecClass = app.getArtefactByLogicalPropertyName(CodecArtefactHandler.TYPE, codecName);
if(codecClass == null) codecClass = app.getArtefactByLogicalPropertyName(CodecArtefactHandler.TYPE, codecName.toUpperCase());
if(codecClass != null) {
this.codecName = codecClass.getFullName();
}
}
}
}
public int[] getLineNumberMatrix() {
return out.getLineNumbers();
}
public InputStream parse() {
StringWriter sw = new StringWriter();
out = new GSPWriter(sw,this);
page();
finalPass = true;
scan.reset();
page();
// This gets bytes in system's default encoding
InputStream in = null;
try {
in = new ByteArrayInputStream(sw.toString().getBytes(GROOVY_SOURCE_CHAR_ENCODING));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Grails cannot run unless your environment supports UTF-8!");
}
//System.out.println("Compiled GSP into Groovy code: " + sw.toString());
if(LOG.isDebugEnabled()) {
LOG.debug("Compiled GSP into Groovy code: " + sw.toString());
}
scan = null;
return in;
}
private void declare(boolean gsp) {
if (finalPass) return;
if (LOG.isDebugEnabled()) LOG.debug("parse: declare");
out.println();
write(scan.getToken().trim(), gsp);
out.println();
out.println();
} // declare()
private void direct() {
if (finalPass) return;
if (LOG.isDebugEnabled()) LOG.debug("parse: direct");
String text = scan.getToken();
text = text.trim();
directPage(text);
} // direct()
private void directPage(String text) {
text = text.trim();
// LOG.debug("directPage(" + text + ')');
Pattern pat = Pattern.compile("(\\w+)\\s*=\\s*\"([^\"]*)\"");
Matcher mat = pat.matcher(text);
for (int ix = 0;;) {
if (!mat.find(ix)) return;
String name = mat.group(1);
String value = mat.group(2);
if (name.equals(IMPORT_DIRECTIVE)) pageImport(value);
if (name.equals(CONTENT_TYPE_DIRECTIVE)) contentType(value);
if (name.equals(DEFAULT_CODEC_DIRECTIVE)) lookupCodec(value);
ix = mat.end();
}
} // directPage()
private void contentType(String value) {
this.contentType = value;
}
private void scriptletExpr() {
if (!finalPass) return;
if (LOG.isDebugEnabled()) LOG.debug("parse: expr");
String text = scan.getToken().trim();
out.printlnToResponse(text);
}
private void expr() {
if (!finalPass) return;
if (LOG.isDebugEnabled()) LOG.debug("parse: expr");
String text = scan.getToken().trim();
if(codecName != null) {
out.printlnToResponse("Codec.encode("+text+")");
}
else {
out.printlnToResponse(text);
}
} // expr()
private void html() {
if (!finalPass) return;
if (LOG.isDebugEnabled()) LOG.debug("parse: html");
String text = scan.getToken();
if(Pattern.compile("\\S").matcher(text).find())
bufferWhiteSpace = false;
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
String[] lines = text.split("\\n");
if(lines.length == 1 && !StringUtils.isBlank(lines[0])) {
out.printlnToResponse('\'' + escapeGroovy(lines[0]) + '\'');
}
else {
pw.print(START_MULTILINE_STRING);
boolean hasContent = false;
boolean firstLine = true;
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
final String content = escapeGroovy(line);
if(!StringUtils.isEmpty(content)) {
if(!hasContent) {
hasContent = true;
break;
}
}
}
if(hasContent) {
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
final String content = escapeGroovy(line);
if(firstLine) {
pw.print(content);
firstLine = false;
}
else {
pw.println();
pw.print(content);
}
}
}
pw.print(END_MULTILINE_STRING);
pw.println();
if(hasContent && !bufferWhiteSpace) {
final String constantValue = sw.toString();
final String constantName = "STATIC_HTML_CONTENT_" + constantCount++;
constants.put(constantName, constantValue);
out.printlnToResponse(constantName);
}
}
} // html()
private void makeName(String uri) {
String name;
int slash = uri.lastIndexOf('/');
if (slash > -1) {
name = uri.substring(slash + 1);
uri = uri.substring(0,(uri.length() - 1) - name.length());
while(uri.endsWith("/")) {
uri = uri.substring(0,uri.length() -1);
}
slash = uri.lastIndexOf('/');
if(slash > -1) {
name = uri.substring(slash + 1) + '_' + name;
}
}
else {
name = uri;
}
StringBuffer buf = new StringBuffer(name.length());
for (int ix = 0, ixz = name.length(); ix < ixz; ix++) {
char c = name.charAt(ix);
if (c < '0' || (c > '9' && c < '@') || (c > 'Z' && c < '_') || (c > '_' && c < 'a') || c > 'z') c = '_';
else if (ix == 0 && c >= '0' && c <= '9') c = '_';
buf.append(c);
}
className = buf.toString();
} // makeName()
private static boolean match(CharSequence pat, CharSequence text, int start) {
int ix = start, ixz = text.length(), ixy = start + pat.length();
if (ixz > ixy) ixz = ixy;
if (pat.length() > ixz - start) return false;
for (; ix < ixz; ix++) {
if (Character.toLowerCase(text.charAt(ix)) != Character.toLowerCase(pat.charAt(ix - start))) {
return false;
}
}
return true;
} // match()
private static int match(Pattern pat, CharSequence text, int start) {
Matcher mat = pat.matcher(text);
if (mat.find(start) && mat.start() == start) {
return mat.end();
}
return 0;
} // match()
private void page() {
if (LOG.isDebugEnabled()) LOG.debug("parse: page");
if (finalPass) {
out.println();
out.print("class ");
out.print(className);
out.println(" extends GroovyPage {");
out.println("public Object run() {");
}
loop: for (;;) {
if(doNextScan)
state = scan.nextToken();
else
doNextScan = true;
switch (state) {
case EOF: break loop;
case HTML: html(); break;
case JEXPR: scriptletExpr(); break;
case JSCRIPT: script(false); break;
case JDIRECT: direct(); break;
case JDECLAR: declare(false); break;
case GEXPR: expr(); break;
case GSCRIPT: script(true); break;
case GDIRECT: direct(); break;
case GDECLAR: declare(true); break;
case GSTART_TAG: startTag(); break;
case GEND_TAG: endTag(); break;
}
}
if (finalPass) {
if(!tagMetaStack.isEmpty()) {
TagMeta tag = (TagMeta)tagMetaStack.iterator().next();
throw new GrailsTagException("Grails tags were not closed! ["+tagMetaStack+"] in GSP "+pageName+"", pageName, tag.lineNumber);
}
out.println("}");
for (Iterator i = constants.keySet().iterator(); i.hasNext();) {
String name = (String) i.next();
out.println("static final " + name + " = " + constants.get(name));
}
out.println("}");
}
else {
for (int i = 0; i < DEFAULT_IMPORTS.length; i++) {
out.print("import ");
out.println(DEFAULT_IMPORTS[i]);
}
if(codecName != null) {
out.print("import ");
out.print(codecName);
out.println(" as Codec");
}
}
} // page()
private void endTag() {
if (!finalPass) return;
String tagName = scan.getToken().trim();
String ns = scan.getNamespace();
if(tagMetaStack.isEmpty())
throw new GrailsTagException("Found closing Grails tag with no opening ["+tagName+"]");
TagMeta tm = (TagMeta)tagMetaStack.remove(this.tagMetaStack.size() - 1);
String lastInStack = tm.name;
String lastNamespaceInStack = tm.namespace;
// if the tag name is blank then it has been closed by the start tag ie <tag />
if(StringUtils.isBlank(tagName))
tagName = lastInStack;
if(!lastInStack.equals(tagName) ||
!lastNamespaceInStack.equals(ns)) {
throw new GrailsTagException("Grails tag ["+lastNamespaceInStack+":"+lastInStack+"] was not closed");
}
if(GroovyPage.DEFAULT_NAMESPACE.equals(ns) && tagRegistry.isSyntaxTag(tagName)) {
if(tm.instance instanceof GroovySyntaxTag) {
GroovySyntaxTag tag = (GroovySyntaxTag)tm.instance;
if(tag.isBufferWhiteSpace())
bufferWhiteSpace = true;
tag.doEndTag();
}
else {
throw new GrailsTagException("Grails tag ["+tagName+"] was not closed");
}
}
else {
out.println("}");
if(tm.hasAttributes) {
out.println("invokeTag('"+tagName+"','"+ns+"',attrs"+tagIndex+",body"+tagIndex+")");
}
else {
out.println("invokeTag('"+tagName+"','"+ns+"',[:],body"+tagIndex+")");
}
}
tagIndex--;
}
private void startTag() {
if (!finalPass) return;
tagIndex++;
String text;
StringBuffer buf = new StringBuffer( scan.getToken().trim() );
String ns = scan.getNamespace();
state = scan.nextToken();
while(state != HTML && state != GEND_TAG && state != EOF) {
if(state == GTAG_EXPR) {
buf.append("${");
buf.append(scan.getToken().trim());
buf.append("}");
}
else {
buf.append(scan.getToken().trim());
}
state = scan.nextToken();
}
doNextScan = false;
text = buf.toString();
String tagName;
Map attrs = new TreeMap();
- text = text.replaceAll("[\r\n]", " "); // this line added TODO query this
+ text = text.replaceAll("[\r\n\t]", " "); // this line added TODO query this
if(text.indexOf(' ') > -1) { // ignores carriage returns and new lines
int i = text.indexOf(' ');
tagName = text.substring(0,i);
String attrTokens = text.substring(i,text.length());
attrTokens += '>'; // closing bracket marker
// do first pass parse which retrieves double quoted attributes
Matcher m = PARSE_TAG_FIRST_PASS.matcher(attrTokens);
populateAttributesFromMatcher(m,attrs);
// do second pass parse which retrieves single quoted attributes
m = PARSE_TAG_SECOND_PASS.matcher(attrTokens);
populateAttributesFromMatcher(m,attrs);
}
else {
tagName = text;
}
if(state == EOF){
throw new GrailsTagException("Unexpected end of file encountered parsing Tag [" + tagName + "] for " + className + ". Are you missing a closing brace '}'?");
}
TagMeta tm = new TagMeta();
tm.name = tagName;
tm.namespace = ns;
tm.hasAttributes = !attrs.isEmpty();
tm.lineNumber = getCurrentOutputLineNumber();
tagMetaStack.add(tm);
if (GroovyPage.DEFAULT_NAMESPACE.equals(ns) && tagRegistry.isSyntaxTag(tagName)) {
if(this.tagContext == null) {
this.tagContext = new HashMap();
this.tagContext.put(GroovyPage.OUT,out);
}
GroovySyntaxTag tag = (GroovySyntaxTag)tagRegistry.newTag(tagName);
tag.init(tagContext);
tag.setAttributes(attrs);
if(!tag.hasPrecedingContent() && !bufferWhiteSpace) {
throw new GrailsTagException("Tag ["+tag.getName()+"] cannot have non-whitespace characters directly preceding it.");
}
else if(!tag.hasPrecedingContent() && bufferWhiteSpace) {
whiteSpaceBuffer.delete(0,whiteSpaceBuffer.length());
bufferWhiteSpace = false;
} else {
if(whiteSpaceBuffer.length() > 0) {
out.printlnToResponse(whiteSpaceBuffer.toString());
whiteSpaceBuffer.delete(0,whiteSpaceBuffer.length());
}
bufferWhiteSpace = false;
}
tag.doStartTag();
tm.instance = tag;
}
else {
if(attrs.size() > 0) {
out.print("attrs"+tagIndex+" = [");
for (Iterator i = attrs.keySet().iterator(); i.hasNext();) {
String name = (String) i.next();
out.print(name);
out.print(':');
out.print(attrs.get(name));
if(i.hasNext())
out.print(',');
else
out.println(']');
}
}
out.println("body"+tagIndex+" = new GroovyPageTagBody(this,binding.webRequest) {" );
}
}
private void populateAttributesFromMatcher(Matcher m, Map attrs) {
while(m.find()) {
String name = m.group(2);
String val = m.group(3);
name = '\"' + name + '\"';
if(val.startsWith("${") && val.endsWith("}")) {
val = val.substring(2,val.length() -1);
}
else if(!(val.startsWith("[") && val.endsWith("]"))) {
val = '\"' + val + '\"';
}
attrs.put(name,val);
}
}
private void pageImport(String value) {
// LOG.debug("pageImport(" + value + ')');
String[] imports = Pattern.compile(";").split(value.subSequence(0, value.length()));
for (int ix = 0; ix < imports.length; ix++) {
out.print("import ");
out.print(imports[ix]);
out.println();
}
} // pageImport()
private String escapeGroovy(CharSequence text) {
StringBuffer buf = new StringBuffer();
for (int ix = 0, ixz = text.length(); ix < ixz; ix++) {
char c = text.charAt(ix);
String rep = null;
if (c == '\n') {
incrementLineNumber();
rep = "\\n";
}
else if (c == '\r') rep = "\\r";
else if (c == '\t') rep = "\\t";
else if (c == '\'') rep = "\\'";
else if (c == '\\') rep = "\\\\";
if (rep != null) buf.append(rep);
else buf.append(c);
}
return buf.toString();
}
private String readStream(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] buf = new byte[8192];
for (;;) {
int read = in.read(buf);
if (read <= 0) break;
out.write(buf, 0, read);
}
return out.toString( gspEncoding);
} finally {
out.close();
in.close();
}
} // readStream()
private void script(boolean gsp) {
if (!finalPass) return;
if (LOG.isDebugEnabled()) LOG.debug("parse: script");
out.println();
write(scan.getToken().trim(), gsp);
out.println();
out.println();
} // script()
private void write(CharSequence text, boolean gsp) {
if (!gsp) {
out.print(text);
return;
}
for (int ix = 0, ixz = text.length(); ix < ixz; ix++) {
char c = text.charAt(ix);
String rep = null;
if (Character.isWhitespace(c)) {
for (ix++; ix < ixz; ix++) {
if (Character.isWhitespace(text.charAt(ix))) continue;
ix--;
rep = " ";
break;
}
} else if (c == '&') {
if (match(";", text, ix)) {
rep = ";";
ix += 5;
} else if (match("&", text, ix)) {
rep = "&";
ix += 4;
} else if (match("<", text, ix)) {
rep = "<";
ix += 3;
} else if (match(">", text, ix)) {
rep = ">";
ix += 3;
}
} else if (c == '<') {
if (match("<br>", text, ix) || match("<hr>", text, ix)) {
rep = "\n";
incrementLineNumber();
ix += 3;
} else {
int end = match(PARA_BREAK, text, ix);
if (end <= 0) end = match(ROW_BREAK, text, ix);
if (end > 0) {
rep = "\n";
incrementLineNumber();
ix = end;
}
}
}
if (rep != null) out.print(rep);
else out.print(c);
}
} // write()
private void incrementLineNumber() {
currentOutputLine++;
}
} // Parse
| true | true | private void startTag() {
if (!finalPass) return;
tagIndex++;
String text;
StringBuffer buf = new StringBuffer( scan.getToken().trim() );
String ns = scan.getNamespace();
state = scan.nextToken();
while(state != HTML && state != GEND_TAG && state != EOF) {
if(state == GTAG_EXPR) {
buf.append("${");
buf.append(scan.getToken().trim());
buf.append("}");
}
else {
buf.append(scan.getToken().trim());
}
state = scan.nextToken();
}
doNextScan = false;
text = buf.toString();
String tagName;
Map attrs = new TreeMap();
text = text.replaceAll("[\r\n]", " "); // this line added TODO query this
if(text.indexOf(' ') > -1) { // ignores carriage returns and new lines
int i = text.indexOf(' ');
tagName = text.substring(0,i);
String attrTokens = text.substring(i,text.length());
attrTokens += '>'; // closing bracket marker
// do first pass parse which retrieves double quoted attributes
Matcher m = PARSE_TAG_FIRST_PASS.matcher(attrTokens);
populateAttributesFromMatcher(m,attrs);
// do second pass parse which retrieves single quoted attributes
m = PARSE_TAG_SECOND_PASS.matcher(attrTokens);
populateAttributesFromMatcher(m,attrs);
}
else {
tagName = text;
}
if(state == EOF){
throw new GrailsTagException("Unexpected end of file encountered parsing Tag [" + tagName + "] for " + className + ". Are you missing a closing brace '}'?");
}
TagMeta tm = new TagMeta();
tm.name = tagName;
tm.namespace = ns;
tm.hasAttributes = !attrs.isEmpty();
tm.lineNumber = getCurrentOutputLineNumber();
tagMetaStack.add(tm);
if (GroovyPage.DEFAULT_NAMESPACE.equals(ns) && tagRegistry.isSyntaxTag(tagName)) {
if(this.tagContext == null) {
this.tagContext = new HashMap();
this.tagContext.put(GroovyPage.OUT,out);
}
GroovySyntaxTag tag = (GroovySyntaxTag)tagRegistry.newTag(tagName);
tag.init(tagContext);
tag.setAttributes(attrs);
if(!tag.hasPrecedingContent() && !bufferWhiteSpace) {
throw new GrailsTagException("Tag ["+tag.getName()+"] cannot have non-whitespace characters directly preceding it.");
}
else if(!tag.hasPrecedingContent() && bufferWhiteSpace) {
whiteSpaceBuffer.delete(0,whiteSpaceBuffer.length());
bufferWhiteSpace = false;
} else {
if(whiteSpaceBuffer.length() > 0) {
out.printlnToResponse(whiteSpaceBuffer.toString());
whiteSpaceBuffer.delete(0,whiteSpaceBuffer.length());
}
bufferWhiteSpace = false;
}
tag.doStartTag();
tm.instance = tag;
}
else {
if(attrs.size() > 0) {
out.print("attrs"+tagIndex+" = [");
for (Iterator i = attrs.keySet().iterator(); i.hasNext();) {
String name = (String) i.next();
out.print(name);
out.print(':');
out.print(attrs.get(name));
if(i.hasNext())
out.print(',');
else
out.println(']');
}
}
out.println("body"+tagIndex+" = new GroovyPageTagBody(this,binding.webRequest) {" );
}
}
| private void startTag() {
if (!finalPass) return;
tagIndex++;
String text;
StringBuffer buf = new StringBuffer( scan.getToken().trim() );
String ns = scan.getNamespace();
state = scan.nextToken();
while(state != HTML && state != GEND_TAG && state != EOF) {
if(state == GTAG_EXPR) {
buf.append("${");
buf.append(scan.getToken().trim());
buf.append("}");
}
else {
buf.append(scan.getToken().trim());
}
state = scan.nextToken();
}
doNextScan = false;
text = buf.toString();
String tagName;
Map attrs = new TreeMap();
text = text.replaceAll("[\r\n\t]", " "); // this line added TODO query this
if(text.indexOf(' ') > -1) { // ignores carriage returns and new lines
int i = text.indexOf(' ');
tagName = text.substring(0,i);
String attrTokens = text.substring(i,text.length());
attrTokens += '>'; // closing bracket marker
// do first pass parse which retrieves double quoted attributes
Matcher m = PARSE_TAG_FIRST_PASS.matcher(attrTokens);
populateAttributesFromMatcher(m,attrs);
// do second pass parse which retrieves single quoted attributes
m = PARSE_TAG_SECOND_PASS.matcher(attrTokens);
populateAttributesFromMatcher(m,attrs);
}
else {
tagName = text;
}
if(state == EOF){
throw new GrailsTagException("Unexpected end of file encountered parsing Tag [" + tagName + "] for " + className + ". Are you missing a closing brace '}'?");
}
TagMeta tm = new TagMeta();
tm.name = tagName;
tm.namespace = ns;
tm.hasAttributes = !attrs.isEmpty();
tm.lineNumber = getCurrentOutputLineNumber();
tagMetaStack.add(tm);
if (GroovyPage.DEFAULT_NAMESPACE.equals(ns) && tagRegistry.isSyntaxTag(tagName)) {
if(this.tagContext == null) {
this.tagContext = new HashMap();
this.tagContext.put(GroovyPage.OUT,out);
}
GroovySyntaxTag tag = (GroovySyntaxTag)tagRegistry.newTag(tagName);
tag.init(tagContext);
tag.setAttributes(attrs);
if(!tag.hasPrecedingContent() && !bufferWhiteSpace) {
throw new GrailsTagException("Tag ["+tag.getName()+"] cannot have non-whitespace characters directly preceding it.");
}
else if(!tag.hasPrecedingContent() && bufferWhiteSpace) {
whiteSpaceBuffer.delete(0,whiteSpaceBuffer.length());
bufferWhiteSpace = false;
} else {
if(whiteSpaceBuffer.length() > 0) {
out.printlnToResponse(whiteSpaceBuffer.toString());
whiteSpaceBuffer.delete(0,whiteSpaceBuffer.length());
}
bufferWhiteSpace = false;
}
tag.doStartTag();
tm.instance = tag;
}
else {
if(attrs.size() > 0) {
out.print("attrs"+tagIndex+" = [");
for (Iterator i = attrs.keySet().iterator(); i.hasNext();) {
String name = (String) i.next();
out.print(name);
out.print(':');
out.print(attrs.get(name));
if(i.hasNext())
out.print(',');
else
out.println(']');
}
}
out.println("body"+tagIndex+" = new GroovyPageTagBody(this,binding.webRequest) {" );
}
}
|
diff --git a/src/openblocks/common/tileentity/TileEntityXPDrain.java b/src/openblocks/common/tileentity/TileEntityXPDrain.java
index 35ecbac4..0b1c2861 100644
--- a/src/openblocks/common/tileentity/TileEntityXPDrain.java
+++ b/src/openblocks/common/tileentity/TileEntityXPDrain.java
@@ -1,109 +1,110 @@
package openblocks.common.tileentity;
import java.lang.ref.WeakReference;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidHandler;
import openblocks.OpenBlocks;
import openmods.OpenMods;
import openmods.tileentity.OpenTileEntity;
import openmods.utils.EnchantmentUtils;
public class TileEntityXPDrain extends OpenTileEntity {
private WeakReference<TileEntity> targetTank;
@Override
public void updateEntity() {
super.updateEntity();
if (OpenMods.proxy.getTicks(worldObj) % 100 == 0) {
searchForTank();
}
if (targetTank != null) {
TileEntity tile = targetTank.get();
if (!(tile instanceof IFluidHandler) || tile.isInvalid()) {
targetTank = null;
} else {
if (!worldObj.isRemote) {
IFluidHandler tank = (IFluidHandler)tile;
for (EntityPlayer player : getPlayersOnGrid()) {
FluidStack xpStack = OpenBlocks.XP_FLUID.copy();
- int xpToDrain = Math.min(4, player.experienceTotal);
+ int experience = (int)(EnchantmentUtils.getExperienceForLevel(player.experienceLevel) + (player.experience * player.xpBarCap()));
+ int xpToDrain = Math.min(4, experience);
xpStack.amount = EnchantmentUtils.XPToLiquidRatio(xpToDrain);
/*
* We should simulate and then check the amount of XP to
* be drained,
* if one is zero and the other is not, we don't apply
* the draining.
*/
int filled = tank.fill(ForgeDirection.UP, xpStack, false);
int theoreticalDrain = EnchantmentUtils.liquidToXPRatio(filled);
if (theoreticalDrain <= 0 && filled > 0 || filled <= 0 && theoreticalDrain > 0) {
// Regardless of ratio, this will protect against
// infini-loops caused by
// rounding.
// ALERT: There is a return here, if code is added
// under this for-loop
// In the future, it could have unexpected outcomes.
// Don't change the code
// :P - NC
return;
}
// Limit the stack to what we got last time. Keeps
// things all sync'ed.
// I realize that the update loop is single threaded,
// but I'm paranoid.
// What're you going to do.
xpStack.amount = filled;
filled = tank.fill(ForgeDirection.UP, xpStack, true);
if (filled > 0) {
if (OpenMods.proxy.getTicks(worldObj) % 4 == 0) {
worldObj.playSoundEffect(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5, "random.orb", 0.1F, 0.5F * ((worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.7F + 1.8F));
}
int xpDrained = EnchantmentUtils.liquidToXPRatio(filled);
while (xpDrained > 0) {
player.experienceTotal--;
- player.experienceLevel = EnchantmentUtils.getLevelForExperience(player.experienceTotal);
+ player.experienceLevel = EnchantmentUtils.getLevelForExperience(experience - xpToDrain);
int expForLevel = EnchantmentUtils.getExperienceForLevel(player.experienceLevel);
- player.experience = (float)(player.experienceTotal - expForLevel) / (float)player.xpBarCap();
+ player.experience = (float)((experience-xpToDrain) - expForLevel) / (float)player.xpBarCap();
xpDrained--;
}
}
}
}
}
}
}
public void searchForTank() {
targetTank = null;
for (int y = yCoord - 1; y > 0; y--) {
boolean isAir = worldObj.isAirBlock(xCoord, y, zCoord);
if (!isAir) {
TileEntity te = worldObj.getBlockTileEntity(xCoord, y, zCoord);
if (!(te instanceof IFluidHandler) && te != null) {
Block block = te.getBlockType();
if (block.isOpaqueCube()) { return; }
} else {
targetTank = new WeakReference<TileEntity>(te);
return;
}
}
}
}
@SuppressWarnings("unchecked")
protected List<EntityPlayer> getPlayersOnGrid() {
AxisAlignedBB bb = AxisAlignedBB.getAABBPool().getAABB(xCoord, yCoord, zCoord, xCoord + 1, yCoord + 1, zCoord + 1);
return worldObj.getEntitiesWithinAABB(EntityPlayer.class, bb);
}
}
| false | true | public void updateEntity() {
super.updateEntity();
if (OpenMods.proxy.getTicks(worldObj) % 100 == 0) {
searchForTank();
}
if (targetTank != null) {
TileEntity tile = targetTank.get();
if (!(tile instanceof IFluidHandler) || tile.isInvalid()) {
targetTank = null;
} else {
if (!worldObj.isRemote) {
IFluidHandler tank = (IFluidHandler)tile;
for (EntityPlayer player : getPlayersOnGrid()) {
FluidStack xpStack = OpenBlocks.XP_FLUID.copy();
int xpToDrain = Math.min(4, player.experienceTotal);
xpStack.amount = EnchantmentUtils.XPToLiquidRatio(xpToDrain);
/*
* We should simulate and then check the amount of XP to
* be drained,
* if one is zero and the other is not, we don't apply
* the draining.
*/
int filled = tank.fill(ForgeDirection.UP, xpStack, false);
int theoreticalDrain = EnchantmentUtils.liquidToXPRatio(filled);
if (theoreticalDrain <= 0 && filled > 0 || filled <= 0 && theoreticalDrain > 0) {
// Regardless of ratio, this will protect against
// infini-loops caused by
// rounding.
// ALERT: There is a return here, if code is added
// under this for-loop
// In the future, it could have unexpected outcomes.
// Don't change the code
// :P - NC
return;
}
// Limit the stack to what we got last time. Keeps
// things all sync'ed.
// I realize that the update loop is single threaded,
// but I'm paranoid.
// What're you going to do.
xpStack.amount = filled;
filled = tank.fill(ForgeDirection.UP, xpStack, true);
if (filled > 0) {
if (OpenMods.proxy.getTicks(worldObj) % 4 == 0) {
worldObj.playSoundEffect(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5, "random.orb", 0.1F, 0.5F * ((worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.7F + 1.8F));
}
int xpDrained = EnchantmentUtils.liquidToXPRatio(filled);
while (xpDrained > 0) {
player.experienceTotal--;
player.experienceLevel = EnchantmentUtils.getLevelForExperience(player.experienceTotal);
int expForLevel = EnchantmentUtils.getExperienceForLevel(player.experienceLevel);
player.experience = (float)(player.experienceTotal - expForLevel) / (float)player.xpBarCap();
xpDrained--;
}
}
}
}
}
}
}
| public void updateEntity() {
super.updateEntity();
if (OpenMods.proxy.getTicks(worldObj) % 100 == 0) {
searchForTank();
}
if (targetTank != null) {
TileEntity tile = targetTank.get();
if (!(tile instanceof IFluidHandler) || tile.isInvalid()) {
targetTank = null;
} else {
if (!worldObj.isRemote) {
IFluidHandler tank = (IFluidHandler)tile;
for (EntityPlayer player : getPlayersOnGrid()) {
FluidStack xpStack = OpenBlocks.XP_FLUID.copy();
int experience = (int)(EnchantmentUtils.getExperienceForLevel(player.experienceLevel) + (player.experience * player.xpBarCap()));
int xpToDrain = Math.min(4, experience);
xpStack.amount = EnchantmentUtils.XPToLiquidRatio(xpToDrain);
/*
* We should simulate and then check the amount of XP to
* be drained,
* if one is zero and the other is not, we don't apply
* the draining.
*/
int filled = tank.fill(ForgeDirection.UP, xpStack, false);
int theoreticalDrain = EnchantmentUtils.liquidToXPRatio(filled);
if (theoreticalDrain <= 0 && filled > 0 || filled <= 0 && theoreticalDrain > 0) {
// Regardless of ratio, this will protect against
// infini-loops caused by
// rounding.
// ALERT: There is a return here, if code is added
// under this for-loop
// In the future, it could have unexpected outcomes.
// Don't change the code
// :P - NC
return;
}
// Limit the stack to what we got last time. Keeps
// things all sync'ed.
// I realize that the update loop is single threaded,
// but I'm paranoid.
// What're you going to do.
xpStack.amount = filled;
filled = tank.fill(ForgeDirection.UP, xpStack, true);
if (filled > 0) {
if (OpenMods.proxy.getTicks(worldObj) % 4 == 0) {
worldObj.playSoundEffect(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5, "random.orb", 0.1F, 0.5F * ((worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.7F + 1.8F));
}
int xpDrained = EnchantmentUtils.liquidToXPRatio(filled);
while (xpDrained > 0) {
player.experienceTotal--;
player.experienceLevel = EnchantmentUtils.getLevelForExperience(experience - xpToDrain);
int expForLevel = EnchantmentUtils.getExperienceForLevel(player.experienceLevel);
player.experience = (float)((experience-xpToDrain) - expForLevel) / (float)player.xpBarCap();
xpDrained--;
}
}
}
}
}
}
}
|
diff --git a/cloudfoundry-caldecott-lib/src/main/java/org/cloudfoundry/caldecott/client/TunnelHandler.java b/cloudfoundry-caldecott-lib/src/main/java/org/cloudfoundry/caldecott/client/TunnelHandler.java
index b2793a3..85f496c 100644
--- a/cloudfoundry-caldecott-lib/src/main/java/org/cloudfoundry/caldecott/client/TunnelHandler.java
+++ b/cloudfoundry-caldecott-lib/src/main/java/org/cloudfoundry/caldecott/client/TunnelHandler.java
@@ -1,186 +1,186 @@
/*
* Copyright 2009-2012 the original author or authors.
*
* 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.cloudfoundry.caldecott.client;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cloudfoundry.caldecott.TunnelException;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.client.HttpStatusCodeException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Observable;
/**
* The class responsible for handling the actual tunneling communications between a data access client and the
* Caldecott server app.
*
* @author Thomas Risberg
*/
public class TunnelHandler extends Observable {
protected final Log logger = LogFactory.getLog(getClass());
// configuration options
private final Socket socket;
private final TunnelFactory tunnelFactory;
private final TaskExecutor taskExecutor;
// variables to keep state for the tunnel setup
private Client client;
private Tunnel tunnel;
// variable to keep handler active
// this is volatile since it can we altered by another thread via poke()
private volatile boolean shutdown = false;
public TunnelHandler(Socket socket, TunnelFactory tunnelFactory, TaskExecutor taskExecutor) {
this.socket = socket;
this.tunnelFactory = tunnelFactory;
this.taskExecutor = taskExecutor;
try {
this.socket.setSoTimeout(0);
} catch (SocketException ignore) {}
}
public void start() {
client = new SocketClient(socket);
tunnel = tunnelFactory.createTunnel();
taskExecutor.execute(new Writer());
taskExecutor.execute(new Reader());
if (logger.isDebugEnabled()) {
logger.debug("Completed start of: " + this.getClass().getSimpleName() + " with " + countObservers() + " observers");
}
}
public void poke() {
if (client.isIdle()) {
shutdown = true;
}
}
public void stop() {
try {
InputStream is = socket.getInputStream();
if (is != null) {
is.close();
}
} catch (IOException ignore) {}
try {
OutputStream os = socket.getOutputStream();
if (os != null) {
os.close();
}
} catch (IOException ignore) {}
if (logger.isDebugEnabled()) {
logger.debug("Closing tunnel: " + tunnel.toString());
}
tunnel.close();
if (logger.isDebugEnabled()) {
logger.debug("Notifying observers: " + countObservers());
}
setChanged();
notifyObservers("CLOSED");
}
private class Writer implements Runnable {
public void run() {
if (logger.isDebugEnabled()) {
logger.debug("Starting new writer thread: " + this);
}
try {
while (client.isOpen()) {
byte[] in = client.read();
if (in.length > 0) {
tunnel.write(in);
}
if (shutdown && client.isIdle()) {
if (logger.isDebugEnabled()) {
logger.debug("Shutdown requested and idle connection thread will be closed: " + this);
}
client.forceClose();
stop();
}
}
} catch (IOException e) {
throw new TunnelException("Error while processing streams", e);
}
if (!shutdown) {
stop();
}
if (logger.isDebugEnabled()) {
logger.debug("Completed writer thread for: " + this);
}
}
}
private class Reader implements Runnable {
public void run() {
if (logger.isDebugEnabled()) {
logger.debug("Starting new reader thread: " + this);
}
boolean retry = false;
try {
while (client.isOpen()) {
try {
byte[] out = tunnel.read(retry);
retry = false;
client.write(out);
} catch (HttpStatusCodeException hsce) {
- if (hsce.getStatusCode().value() == 504) {
+ if (hsce.getStatusCode().value() == 504 || hsce.getStatusCode().value() == 502) {
retry = true;
if (logger.isTraceEnabled()) {
logger.trace("Retrying tunnel read after receiving " + hsce.getStatusCode().value());
}
}
else if (hsce.getStatusCode().value() == 404) {
retry = false;
if (logger.isDebugEnabled()) {
logger.debug("Tunnel error - [" + hsce.getStatusCode().value() + "] " + hsce.getStatusText());
}
}
else if (hsce.getStatusCode().value() == 410) {
retry = false;
if (logger.isDebugEnabled()) {
logger.debug("Tunnel error - [" + hsce.getStatusCode().value() + "] " + hsce.getStatusText());
}
}
else {
logger.warn("Received HTTP Error: [" + hsce.getStatusCode().value() + "] " + hsce.getStatusText());
throw new TunnelException("Error while reading from tunnel", hsce);
}
}
}
} catch (IOException ioe) {
throw new TunnelException("Error while processing streams", ioe);
}
if (logger.isDebugEnabled()) {
logger.debug("Completed reader thread for: " + this);
}
}
}
}
| true | true | public void run() {
if (logger.isDebugEnabled()) {
logger.debug("Starting new reader thread: " + this);
}
boolean retry = false;
try {
while (client.isOpen()) {
try {
byte[] out = tunnel.read(retry);
retry = false;
client.write(out);
} catch (HttpStatusCodeException hsce) {
if (hsce.getStatusCode().value() == 504) {
retry = true;
if (logger.isTraceEnabled()) {
logger.trace("Retrying tunnel read after receiving " + hsce.getStatusCode().value());
}
}
else if (hsce.getStatusCode().value() == 404) {
retry = false;
if (logger.isDebugEnabled()) {
logger.debug("Tunnel error - [" + hsce.getStatusCode().value() + "] " + hsce.getStatusText());
}
}
else if (hsce.getStatusCode().value() == 410) {
retry = false;
if (logger.isDebugEnabled()) {
logger.debug("Tunnel error - [" + hsce.getStatusCode().value() + "] " + hsce.getStatusText());
}
}
else {
logger.warn("Received HTTP Error: [" + hsce.getStatusCode().value() + "] " + hsce.getStatusText());
throw new TunnelException("Error while reading from tunnel", hsce);
}
}
}
} catch (IOException ioe) {
throw new TunnelException("Error while processing streams", ioe);
}
if (logger.isDebugEnabled()) {
logger.debug("Completed reader thread for: " + this);
}
}
| public void run() {
if (logger.isDebugEnabled()) {
logger.debug("Starting new reader thread: " + this);
}
boolean retry = false;
try {
while (client.isOpen()) {
try {
byte[] out = tunnel.read(retry);
retry = false;
client.write(out);
} catch (HttpStatusCodeException hsce) {
if (hsce.getStatusCode().value() == 504 || hsce.getStatusCode().value() == 502) {
retry = true;
if (logger.isTraceEnabled()) {
logger.trace("Retrying tunnel read after receiving " + hsce.getStatusCode().value());
}
}
else if (hsce.getStatusCode().value() == 404) {
retry = false;
if (logger.isDebugEnabled()) {
logger.debug("Tunnel error - [" + hsce.getStatusCode().value() + "] " + hsce.getStatusText());
}
}
else if (hsce.getStatusCode().value() == 410) {
retry = false;
if (logger.isDebugEnabled()) {
logger.debug("Tunnel error - [" + hsce.getStatusCode().value() + "] " + hsce.getStatusText());
}
}
else {
logger.warn("Received HTTP Error: [" + hsce.getStatusCode().value() + "] " + hsce.getStatusText());
throw new TunnelException("Error while reading from tunnel", hsce);
}
}
}
} catch (IOException ioe) {
throw new TunnelException("Error while processing streams", ioe);
}
if (logger.isDebugEnabled()) {
logger.debug("Completed reader thread for: " + this);
}
}
|
diff --git a/cadpage/src/net/anei/cadpage/parsers/OR/ORCrookCountyParser.java b/cadpage/src/net/anei/cadpage/parsers/OR/ORCrookCountyParser.java
index 3d3dea922..1363bb0cc 100644
--- a/cadpage/src/net/anei/cadpage/parsers/OR/ORCrookCountyParser.java
+++ b/cadpage/src/net/anei/cadpage/parsers/OR/ORCrookCountyParser.java
@@ -1,42 +1,42 @@
package net.anei.cadpage.parsers.OR;
import net.anei.cadpage.SmsMsgInfo.Data;
import net.anei.cadpage.parsers.FieldProgramParser;
/*
Prineville, OR
Contact: [email protected]
Sender:[email protected]
[NEW INCIDENT] INCIDENT NEW\n3/9/2011 1003\nEVENT # 1103090013 PFD\nTEST-FIRE - TEST INCIDENT\nPRIORITY 2 \nLOCATION 387 NE 3RD ST\nCITY PRINEVILLE\nAPT \nPREMISE
[UNIT DISPATCH] UNIT DISPATCH\n3/9/2011 1203\nUNITS 1291 \nEVENT # 1103090021 PFD\nFSMK - SMOKE UNKNOWN FIRE S...\nPRIORITY 1 \nLOCATION 1231 SE 5TH ST\nCITY PRI
[NEW INCIDENT] INCIDENT NEW\n3/9/2011 1203\nEVENT # 1103090021 PFD\nFSMK - SMOKE UNKNOWN FIRE S...\nPRIORITY 1 \nLOCATION 1231 SE 5TH ST\nCITY PRINEVILLE\nAPT \nP
(NEW INCIDENT) INCIDENT NEW\n3/9/2011 1203\nEVENT # 1103090021 PFD\nFSMK - SMOKE UNKNOWN FIRE S...\nPRIORITY 1 \nLOCATION 1231 SE 5TH ST\nCITY PRINEVILLE\nAPT \nP
(NEW INCIDENT) INCIDENT NEW\n3/9/2011 1203\nEVENT # 1103090021 PFD\nFSMK - SMOKE UNKNOWN FIRE S...\nPRIORITY 1 \nLOCATION 1231 SE 5TH ST\nCITY PRINEVILLE\nAPT \nP
*/
public class ORCrookCountyParser extends FieldProgramParser {
public ORCrookCountyParser() {
super("CROOK COUNTY", "OR",
"SKIP SKIP UNITS:UNIT EVENT:ID! CALL! PRIORITY:SKIP! LOCATION:ADDR! CITY:CITY! APT:APT");
}
@Override
public String getFilter() {
return "[email protected]";
}
@Override
protected boolean parseMsg(String body, Data data) {
if (!body.startsWith("INCIDENT NEW\n") && !body.startsWith("UNIT DISPATCH\n")) return false;
body = body.replace("\nEVENT # ","\nEVENT:").replace("\nUNITS ","\nUNITS:")
.replace("\nPRIORITY ","\nPRIORITY:").replace("\nLOCATION ","\nLOCATION:")
- .replace("\nCITY ","\nCITY:").replace("\nAPT ","\nAPT:");
+ .replace("\nCITY ","\nCITY:").replace("\nAPT \n","\nAPT:");
return parseFields(body.split("\n"), data);
}
}
| true | true | protected boolean parseMsg(String body, Data data) {
if (!body.startsWith("INCIDENT NEW\n") && !body.startsWith("UNIT DISPATCH\n")) return false;
body = body.replace("\nEVENT # ","\nEVENT:").replace("\nUNITS ","\nUNITS:")
.replace("\nPRIORITY ","\nPRIORITY:").replace("\nLOCATION ","\nLOCATION:")
.replace("\nCITY ","\nCITY:").replace("\nAPT ","\nAPT:");
return parseFields(body.split("\n"), data);
}
| protected boolean parseMsg(String body, Data data) {
if (!body.startsWith("INCIDENT NEW\n") && !body.startsWith("UNIT DISPATCH\n")) return false;
body = body.replace("\nEVENT # ","\nEVENT:").replace("\nUNITS ","\nUNITS:")
.replace("\nPRIORITY ","\nPRIORITY:").replace("\nLOCATION ","\nLOCATION:")
.replace("\nCITY ","\nCITY:").replace("\nAPT \n","\nAPT:");
return parseFields(body.split("\n"), data);
}
|
diff --git a/src/com/themagpi/android/MagPiApplication.java b/src/com/themagpi/android/MagPiApplication.java
index 7b0ebd1..c867017 100644
--- a/src/com/themagpi/android/MagPiApplication.java
+++ b/src/com/themagpi/android/MagPiApplication.java
@@ -1,22 +1,21 @@
package com.themagpi.android;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.app.Application;
public class MagPiApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Create global configuration and initialize ImageLoader with this configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
- .enableLogging()
.memoryCacheSize(41943040)
.discCacheSize(104857600)
.threadPoolSize(10)
.build();
ImageLoader.getInstance().init(config);
}
}
| true | true | public void onCreate() {
super.onCreate();
// Create global configuration and initialize ImageLoader with this configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.enableLogging()
.memoryCacheSize(41943040)
.discCacheSize(104857600)
.threadPoolSize(10)
.build();
ImageLoader.getInstance().init(config);
}
| public void onCreate() {
super.onCreate();
// Create global configuration and initialize ImageLoader with this configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.memoryCacheSize(41943040)
.discCacheSize(104857600)
.threadPoolSize(10)
.build();
ImageLoader.getInstance().init(config);
}
|
diff --git a/impl/src/main/java/org/richfaces/skin/AbstractSkinFactory.java b/impl/src/main/java/org/richfaces/skin/AbstractSkinFactory.java
index 3c43ea4a0..e909a7d6f 100644
--- a/impl/src/main/java/org/richfaces/skin/AbstractSkinFactory.java
+++ b/impl/src/main/java/org/richfaces/skin/AbstractSkinFactory.java
@@ -1,175 +1,175 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt 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.richfaces.skin;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import org.ajax4jsf.Messages;
import org.richfaces.el.util.ELUtils;
import org.richfaces.util.PropertiesUtil;
/**
* @author Nick Belaevski
*
*/
public abstract class AbstractSkinFactory extends SkinFactory {
private final class SkinBuilder implements Callable<Skin> {
private String skinName;
SkinBuilder(String skinName) {
super();
this.skinName = skinName;
}
public Skin call() throws Exception {
return buildSkin(FacesContext.getCurrentInstance(), skinName);
}
}
/**
* Resource Uri for properties file with default values of skin parameters.
*/
private static final String DEFAULT_SKIN_PATH = "META-INF/skins/%s.skin.properties";
// private static final String[] DEFAULT_SKIN_PATHS = { DEFAULT_SKIN_PATH };
private static final String USER_SKIN_PATH = "%s.skin.properties";
/**
* Path in jar to pre-defined vendor and custom user-defined skins
* definitions. in this realisation "META-INF/skins/" for vendor , "" -
* user-defined.
*/
private static final String[] SKINS_PATHS = {DEFAULT_SKIN_PATH, USER_SKIN_PATH};
private ConcurrentMap<String, FutureTask<Skin>> skins = new ConcurrentHashMap<String, FutureTask<Skin>>();
protected void processProperties(FacesContext context, Map<Object, Object> properties) {
ELContext elContext = context.getELContext();
// replace all EL-expressions by prepared ValueBinding ?
Application app = context.getApplication();
for (Entry<Object, Object> entry : properties.entrySet()) {
Object propertyObject = entry.getValue();
if (propertyObject instanceof String) {
String property = (String) propertyObject;
if (ELUtils.isValueReference(property)) {
ExpressionFactory expressionFactory = app.getExpressionFactory();
entry.setValue(expressionFactory.createValueExpression(elContext, property, Object.class));
} else {
entry.setValue(property);
}
}
}
}
/**
* Factory method for build skin from properties files. for given skin name,
* search in classpath all resources with name 'name'.skin.properties and
* append in content to default properties. First, get it from
* META-INF/skins/ , next - from root package. for any place search order
* determined by {@link java.lang.ClassLoader } realisation.
*
* @param name name for builded skin.
* @param defaultProperties
* @return skin instance for current name
* @throws SkinNotFoundException -
* if no skin properies found for name.
*/
protected Skin buildSkin(FacesContext context, String name) throws SkinNotFoundException {
Properties skinParams = loadProperties(name, SKINS_PATHS);
processProperties(context, skinParams);
return new SkinImpl(skinParams, name);
}
/**
* @param name
* @param paths
* @return
* @throws SkinNotFoundException
*/
protected Properties loadProperties(String name, String[] paths) throws SkinNotFoundException {
// Get properties for concrete skin.
Properties skinProperties = new Properties();
int loadedPropertiesCount = 0;
for (int i = 0; i < paths.length; i++) {
String skinPropertiesLocation = paths[i].replaceAll("%s", name);
if (PropertiesUtil.loadProperties(skinProperties, skinPropertiesLocation)) {
loadedPropertiesCount++;
}
}
if (loadedPropertiesCount == 0) {
throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR, name));
}
return skinProperties;
}
@Override
public Skin getSkin(FacesContext context, String name) {
if (null == name) {
throw new SkinNotFoundException(Messages.getMessage(Messages.NULL_SKIN_NAME_ERROR));
}
FutureTask<Skin> skinFuture = skins.get(name);
if (skinFuture == null) {
FutureTask<Skin> newSkinFuture = new FutureTask<Skin>(new SkinBuilder(name));
skinFuture = skins.putIfAbsent(name, newSkinFuture);
if (skinFuture == null) {
skinFuture = newSkinFuture;
}
}
try {
skinFuture.run();
return skinFuture.get();
} catch (InterruptedException e) {
- throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR), e);
+ throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR, name), e);
} catch (ExecutionException e) {
- throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR), e);
+ throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR, name), e);
}
}
}
| false | true | public Skin getSkin(FacesContext context, String name) {
if (null == name) {
throw new SkinNotFoundException(Messages.getMessage(Messages.NULL_SKIN_NAME_ERROR));
}
FutureTask<Skin> skinFuture = skins.get(name);
if (skinFuture == null) {
FutureTask<Skin> newSkinFuture = new FutureTask<Skin>(new SkinBuilder(name));
skinFuture = skins.putIfAbsent(name, newSkinFuture);
if (skinFuture == null) {
skinFuture = newSkinFuture;
}
}
try {
skinFuture.run();
return skinFuture.get();
} catch (InterruptedException e) {
throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR), e);
} catch (ExecutionException e) {
throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR), e);
}
}
| public Skin getSkin(FacesContext context, String name) {
if (null == name) {
throw new SkinNotFoundException(Messages.getMessage(Messages.NULL_SKIN_NAME_ERROR));
}
FutureTask<Skin> skinFuture = skins.get(name);
if (skinFuture == null) {
FutureTask<Skin> newSkinFuture = new FutureTask<Skin>(new SkinBuilder(name));
skinFuture = skins.putIfAbsent(name, newSkinFuture);
if (skinFuture == null) {
skinFuture = newSkinFuture;
}
}
try {
skinFuture.run();
return skinFuture.get();
} catch (InterruptedException e) {
throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR, name), e);
} catch (ExecutionException e) {
throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR, name), e);
}
}
|
diff --git a/h2/src/test/org/h2/test/jdbcx/TestConnectionPool.java b/h2/src/test/org/h2/test/jdbcx/TestConnectionPool.java
index 5ff13744d..0dd3a5df6 100644
--- a/h2/src/test/org/h2/test/jdbcx/TestConnectionPool.java
+++ b/h2/src/test/org/h2/test/jdbcx/TestConnectionPool.java
@@ -1,248 +1,248 @@
/*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.jdbcx;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcConnectionPool;
import org.h2.jdbcx.JdbcDataSource;
import org.h2.test.TestBase;
import org.h2.util.Task;
/**
* This class tests the JdbcConnectionPool.
*/
public class TestConnectionPool extends TestBase {
/**
* Run just this test.
*
* @param a ignored
*/
public static void main(String... a) throws Exception {
TestBase.createCaller().init().test();
}
@Override
public void test() throws Exception {
deleteDb("connectionPool");
testShutdown();
testWrongUrl();
testTimeout();
testUncommittedTransaction();
testPerformance();
testKeepOpen();
testConnect();
testThreads();
deleteDb("connectionPool");
deleteDb("connectionPool2");
}
private void testShutdown() throws SQLException {
String url = getURL("connectionPool2", true), user = getUser();
String password = getPassword();
JdbcConnectionPool cp = JdbcConnectionPool.create(url, user, password);
StringWriter w = new StringWriter();
cp.setLogWriter(new PrintWriter(w));
Connection conn1 = cp.getConnection();
Connection conn2 = cp.getConnection();
conn1.close();
conn2.createStatement().execute("shutdown immediately");
cp.dispose();
assertTrue(w.toString().length() > 0);
cp.dispose();
}
private void testWrongUrl() {
JdbcConnectionPool cp = JdbcConnectionPool.create(
"jdbc:wrong:url", "", "");
try {
cp.getConnection();
} catch (SQLException e) {
assertEquals(8001, e.getErrorCode());
}
cp.dispose();
}
private void testTimeout() throws Exception {
String url = getURL("connectionPool", true), user = getUser();
String password = getPassword();
final JdbcConnectionPool man = JdbcConnectionPool.create(url, user, password);
man.setLoginTimeout(1);
createClassProxy(man.getClass());
assertThrows(IllegalArgumentException.class, man).
setMaxConnections(-1);
man.setMaxConnections(2);
// connection 1 (of 2)
Connection conn = man.getConnection();
Task t = new Task() {
@Override
public void call() {
while (!stop) {
// this calls notifyAll
man.setMaxConnections(1);
man.setMaxConnections(2);
}
}
};
t.execute();
long time = System.currentTimeMillis();
try {
// connection 2 (of 1 or 2) may fail
man.getConnection();
// connection 3 (of 1 or 2) must fail
man.getConnection();
fail();
} catch (SQLException e) {
assertTrue(e.toString().toLowerCase().contains("timeout"));
time = System.currentTimeMillis() - time;
assertTrue("timeout after " + time + " ms", time > 1000);
} finally {
conn.close();
t.get();
}
man.dispose();
}
private void testUncommittedTransaction() throws SQLException {
String url = getURL("connectionPool", true), user = getUser();
String password = getPassword();
JdbcConnectionPool man = JdbcConnectionPool.create(url, user, password);
assertEquals(30, man.getLoginTimeout());
man.setLoginTimeout(1);
assertEquals(1, man.getLoginTimeout());
man.setLoginTimeout(0);
assertEquals(30, man.getLoginTimeout());
assertEquals(10, man.getMaxConnections());
PrintWriter old = man.getLogWriter();
PrintWriter pw = new PrintWriter(new StringWriter());
man.setLogWriter(pw);
assertTrue(pw == man.getLogWriter());
man.setLogWriter(old);
Connection conn1 = man.getConnection();
assertTrue(conn1.getAutoCommit());
conn1.setAutoCommit(false);
conn1.close();
assertTrue(conn1.isClosed());
Connection conn2 = man.getConnection();
assertTrue(conn2.getAutoCommit());
conn2.close();
man.dispose();
}
private void testPerformance() throws SQLException {
String url = getURL("connectionPool", true), user = getUser();
String password = getPassword();
JdbcConnectionPool man = JdbcConnectionPool.create(url, user, password);
Connection conn = man.getConnection();
int len = 1000;
long time = System.currentTimeMillis();
for (int i = 0; i < len; i++) {
man.getConnection().close();
}
man.dispose();
trace((int) (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
for (int i = 0; i < len; i++) {
DriverManager.getConnection(url, user, password).close();
}
trace((int) (System.currentTimeMillis() - time));
conn.close();
}
private void testKeepOpen() throws Exception {
JdbcConnectionPool man = getConnectionPool(1);
Connection conn = man.getConnection();
Statement stat = conn.createStatement();
stat.execute("create local temporary table test(id int)");
conn.close();
conn = man.getConnection();
stat = conn.createStatement();
stat.execute("select * from test");
conn.close();
man.dispose();
}
private void testThreads() throws Exception {
final int len = getSize(4, 20);
final JdbcConnectionPool man = getConnectionPool(len - 2);
final boolean[] stop = { false };
/**
* This class gets and returns connections from the pool.
*/
class TestRunner implements Runnable {
@Override
public void run() {
try {
while (!stop[0]) {
Connection conn = man.getConnection();
if (man.getActiveConnections() >= len + 1) {
throw new Exception("a: " +
man.getActiveConnections() +
- " is not smaller than b: " + len + 1);
+ " is not smaller than b: " + (len + 1));
}
Statement stat = conn.createStatement();
stat.execute("SELECT 1 FROM DUAL");
conn.close();
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thread[] threads = new Thread[len];
for (int i = 0; i < len; i++) {
threads[i] = new Thread(new TestRunner());
threads[i].start();
}
Thread.sleep(1000);
stop[0] = true;
for (int i = 0; i < len; i++) {
threads[i].join();
}
assertEquals(0, man.getActiveConnections());
man.dispose();
}
private JdbcConnectionPool getConnectionPool(int poolSize) {
JdbcDataSource ds = new JdbcDataSource();
ds.setURL(getURL("connectionPool", true));
ds.setUser(getUser());
ds.setPassword(getPassword());
JdbcConnectionPool pool = JdbcConnectionPool.create(ds);
pool.setMaxConnections(poolSize);
return pool;
}
private void testConnect() throws SQLException {
JdbcConnectionPool pool = getConnectionPool(3);
for (int i = 0; i < 100; i++) {
Connection conn = pool.getConnection();
conn.close();
}
pool.dispose();
DataSource ds = pool;
assertThrows(IllegalStateException.class, ds).
getConnection();
assertThrows(UnsupportedOperationException.class, ds).
getConnection(null, null);
}
}
| true | true | private void testThreads() throws Exception {
final int len = getSize(4, 20);
final JdbcConnectionPool man = getConnectionPool(len - 2);
final boolean[] stop = { false };
/**
* This class gets and returns connections from the pool.
*/
class TestRunner implements Runnable {
@Override
public void run() {
try {
while (!stop[0]) {
Connection conn = man.getConnection();
if (man.getActiveConnections() >= len + 1) {
throw new Exception("a: " +
man.getActiveConnections() +
" is not smaller than b: " + len + 1);
}
Statement stat = conn.createStatement();
stat.execute("SELECT 1 FROM DUAL");
conn.close();
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thread[] threads = new Thread[len];
for (int i = 0; i < len; i++) {
threads[i] = new Thread(new TestRunner());
threads[i].start();
}
Thread.sleep(1000);
stop[0] = true;
for (int i = 0; i < len; i++) {
threads[i].join();
}
assertEquals(0, man.getActiveConnections());
man.dispose();
}
| private void testThreads() throws Exception {
final int len = getSize(4, 20);
final JdbcConnectionPool man = getConnectionPool(len - 2);
final boolean[] stop = { false };
/**
* This class gets and returns connections from the pool.
*/
class TestRunner implements Runnable {
@Override
public void run() {
try {
while (!stop[0]) {
Connection conn = man.getConnection();
if (man.getActiveConnections() >= len + 1) {
throw new Exception("a: " +
man.getActiveConnections() +
" is not smaller than b: " + (len + 1));
}
Statement stat = conn.createStatement();
stat.execute("SELECT 1 FROM DUAL");
conn.close();
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thread[] threads = new Thread[len];
for (int i = 0; i < len; i++) {
threads[i] = new Thread(new TestRunner());
threads[i].start();
}
Thread.sleep(1000);
stop[0] = true;
for (int i = 0; i < len; i++) {
threads[i].join();
}
assertEquals(0, man.getActiveConnections());
man.dispose();
}
|
diff --git a/src/edu/cmu/cs/in/hoop/hoops/save/HoopCSVWriter.java b/src/edu/cmu/cs/in/hoop/hoops/save/HoopCSVWriter.java
index 591722f2..37173ebb 100644
--- a/src/edu/cmu/cs/in/hoop/hoops/save/HoopCSVWriter.java
+++ b/src/edu/cmu/cs/in/hoop/hoops/save/HoopCSVWriter.java
@@ -1,155 +1,156 @@
/**
* Author: Martin van Velsen <[email protected]>
*
* This program 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 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 edu.cmu.cs.in.hoop.hoops.save;
import java.util.ArrayList;
import edu.cmu.cs.in.base.kv.HoopKV;
import edu.cmu.cs.in.base.HoopDataType;
import edu.cmu.cs.in.base.HoopLink;
import edu.cmu.cs.in.hoop.hoops.base.HoopBase;
import edu.cmu.cs.in.hoop.properties.types.HoopBooleanSerializable;
import edu.cmu.cs.in.hoop.properties.types.HoopEnumSerializable;
/**
* http://stackoverflow.com/questions/769621/dealing-with-commas-in-a-csv-file
*/
public class HoopCSVWriter extends HoopFileSaveBase
{
private static final long serialVersionUID = -6882137805233073782L;
private HoopEnumSerializable writeMode=null; // APPEND, OVERWRITE
private HoopEnumSerializable mode=null; // TAB,COMMA,DASH
private HoopBooleanSerializable includeHeader=null;
/**
*
*/
public HoopCSVWriter ()
{
setClassName ("HoopCSVWriter");
debug ("HoopCSVWriter ()");
setHoopDescription ("Save KVs in CSV format");
setFileExtension ("csv");
writeMode=new HoopEnumSerializable (this,"writeMode","OVERWRITE,APPEND");
mode=new HoopEnumSerializable (this,"mode","COMMA,TAB,DASH,PIPE");
includeHeader=new HoopBooleanSerializable (this,"includeHeader",false);
}
/**
*
*/
public String getSeparatorChar ()
{
if (mode.getValue().equalsIgnoreCase("TAB")==true)
return ("\t");
if (mode.getValue().equalsIgnoreCase("COMMA")==true)
return (",");
if (mode.getValue().equalsIgnoreCase("DASH")==true)
return ("-");
if (mode.getValue().equalsIgnoreCase("PIPE")==true)
return ("|");
return (",");
}
/**
*
*/
public Boolean runHoop (HoopBase inHoop)
{
debug ("runHoop ()");
String sepChar=getSeparatorChar ();
debug ("Writing CSV file using separator: " + mode.getValue() + ": " + sepChar);
StringBuffer formatted=new StringBuffer ();
if ((this.getExecutionCount()==0) && (includeHeader.getPropValue()==true))
{
ArrayList <HoopDataType> types=inHoop.getTypes();
for (int n=0;n<types.size();n++)
{
if (n>0)
{
formatted.append(sepChar);
}
HoopDataType aType=types.get(n);
formatted.append (aType.getTypeValue());
formatted.append("(");
formatted.append(aType.typeToString());
formatted.append(")");
}
formatted.append("\n");
}
ArrayList <HoopKV> inData=inHoop.getData();
if (inData!=null)
{
for (int t=0;t<inData.size();t++)
{
HoopKV aKV=inData.get(t);
formatted.append(aKV.getKeyString ());
ArrayList<Object> vals=aKV.getValuesRaw();
for (int i=0;i<vals.size();i++)
{
formatted.append(sepChar);
formatted.append(vals.get(i));
}
formatted.append("\n");
StringBuffer aStatus=new StringBuffer ();
aStatus.append (" R: ");
aStatus.append (t+1);
aStatus.append (" out of ");
aStatus.append (inData.size());
}
+ String filePath = URI.getValue() + "." + URI.getFileExtension();
if (writeMode.getValue().equals("OVERWRITE")==true)
{
- HoopLink.fManager.saveContents (this.projectToFullPath(URI.getValue()),formatted.toString());
+ HoopLink.fManager.saveContents (this.projectToFullPath(filePath),formatted.toString());
}
else
{
- HoopLink.fManager.appendContents (this.projectToFullPath(URI.getValue()),formatted.toString());
+ HoopLink.fManager.appendContents (this.projectToFullPath(filePath),formatted.toString());
}
}
return (true);
}
/**
*
*/
public HoopBase copy ()
{
return (new HoopCSVWriter ());
}
}
| false | true | public Boolean runHoop (HoopBase inHoop)
{
debug ("runHoop ()");
String sepChar=getSeparatorChar ();
debug ("Writing CSV file using separator: " + mode.getValue() + ": " + sepChar);
StringBuffer formatted=new StringBuffer ();
if ((this.getExecutionCount()==0) && (includeHeader.getPropValue()==true))
{
ArrayList <HoopDataType> types=inHoop.getTypes();
for (int n=0;n<types.size();n++)
{
if (n>0)
{
formatted.append(sepChar);
}
HoopDataType aType=types.get(n);
formatted.append (aType.getTypeValue());
formatted.append("(");
formatted.append(aType.typeToString());
formatted.append(")");
}
formatted.append("\n");
}
ArrayList <HoopKV> inData=inHoop.getData();
if (inData!=null)
{
for (int t=0;t<inData.size();t++)
{
HoopKV aKV=inData.get(t);
formatted.append(aKV.getKeyString ());
ArrayList<Object> vals=aKV.getValuesRaw();
for (int i=0;i<vals.size();i++)
{
formatted.append(sepChar);
formatted.append(vals.get(i));
}
formatted.append("\n");
StringBuffer aStatus=new StringBuffer ();
aStatus.append (" R: ");
aStatus.append (t+1);
aStatus.append (" out of ");
aStatus.append (inData.size());
}
if (writeMode.getValue().equals("OVERWRITE")==true)
{
HoopLink.fManager.saveContents (this.projectToFullPath(URI.getValue()),formatted.toString());
}
else
{
HoopLink.fManager.appendContents (this.projectToFullPath(URI.getValue()),formatted.toString());
}
}
return (true);
}
| public Boolean runHoop (HoopBase inHoop)
{
debug ("runHoop ()");
String sepChar=getSeparatorChar ();
debug ("Writing CSV file using separator: " + mode.getValue() + ": " + sepChar);
StringBuffer formatted=new StringBuffer ();
if ((this.getExecutionCount()==0) && (includeHeader.getPropValue()==true))
{
ArrayList <HoopDataType> types=inHoop.getTypes();
for (int n=0;n<types.size();n++)
{
if (n>0)
{
formatted.append(sepChar);
}
HoopDataType aType=types.get(n);
formatted.append (aType.getTypeValue());
formatted.append("(");
formatted.append(aType.typeToString());
formatted.append(")");
}
formatted.append("\n");
}
ArrayList <HoopKV> inData=inHoop.getData();
if (inData!=null)
{
for (int t=0;t<inData.size();t++)
{
HoopKV aKV=inData.get(t);
formatted.append(aKV.getKeyString ());
ArrayList<Object> vals=aKV.getValuesRaw();
for (int i=0;i<vals.size();i++)
{
formatted.append(sepChar);
formatted.append(vals.get(i));
}
formatted.append("\n");
StringBuffer aStatus=new StringBuffer ();
aStatus.append (" R: ");
aStatus.append (t+1);
aStatus.append (" out of ");
aStatus.append (inData.size());
}
String filePath = URI.getValue() + "." + URI.getFileExtension();
if (writeMode.getValue().equals("OVERWRITE")==true)
{
HoopLink.fManager.saveContents (this.projectToFullPath(filePath),formatted.toString());
}
else
{
HoopLink.fManager.appendContents (this.projectToFullPath(filePath),formatted.toString());
}
}
return (true);
}
|
diff --git a/josm-todo/src/org/openstreetmap/josm/plugins/todo/TodoDialog.java b/josm-todo/src/org/openstreetmap/josm/plugins/todo/TodoDialog.java
index 2b02a8f..8a1db30 100644
--- a/josm-todo/src/org/openstreetmap/josm/plugins/todo/TodoDialog.java
+++ b/josm-todo/src/org/openstreetmap/josm/plugins/todo/TodoDialog.java
@@ -1,394 +1,395 @@
package org.openstreetmap.josm.plugins.todo;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.Collection;
import javax.swing.AbstractAction;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.actions.AutoScaleAction;
import org.openstreetmap.josm.data.SelectionChangedListener;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.event.DatasetEventManager.FireMode;
import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
import org.openstreetmap.josm.gui.OsmPrimitivRenderer;
import org.openstreetmap.josm.gui.SideButton;
import org.openstreetmap.josm.gui.dialogs.ToggleDialog;
import org.openstreetmap.josm.gui.widgets.ListPopupMenu;
import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
import org.openstreetmap.josm.tools.ImageProvider;
import org.openstreetmap.josm.tools.Shortcut;
public class TodoDialog extends ToggleDialog {
private static final long serialVersionUID = 3590739974800809827L;
private TodoListModel model;
private JList lstPrimitives;
private final TodoPopup popupMenu;
private AddAction actAdd;
private MarkSelectedAction actMarkSelected;
/**
* Builds the content panel for this dialog
*/
protected void buildContentPanel() {
DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
model = new TodoListModel(selectionModel);
lstPrimitives = new JList(model);
lstPrimitives.setSelectionModel(selectionModel);
lstPrimitives.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lstPrimitives.setCellRenderer(new OsmPrimitivRenderer());
lstPrimitives.setTransferHandler(null);
// the select action
SelectAction actSelect;
final SideButton selectButton = new SideButton(actSelect = new SelectAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actSelect);
// the add button
final SideButton addButton = new SideButton(actAdd = new AddAction(model));
+ actAdd.updateEnabledState();
// the pass button
PassAction actPass;
final SideButton passButton = new SideButton(actPass = new PassAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actPass);
Main.registerActionShortcut(actPass, Shortcut.registerShortcut("subwindow:todo:pass",
tr("Pass over element without marking it"), KeyEvent.VK_OPEN_BRACKET, Shortcut.DIRECT));
// the mark button
MarkAction actMark;
final SideButton markButton = new SideButton(actMark = new MarkAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actMark);
Main.registerActionShortcut(actMark, Shortcut.registerShortcut("subwindow:todo:mark",
tr("Mark element done"), KeyEvent.VK_CLOSE_BRACKET, Shortcut.DIRECT));
createLayout(lstPrimitives, true, Arrays.asList(new SideButton[] {
selectButton, addButton, passButton, markButton
}));
}
public TodoDialog() {
super(tr("Todo list"), "todo", tr("Open the todo list."),
Shortcut.registerShortcut("subwindow:todo", tr("Toggle: {0}", tr("Todo list")),
KeyEvent.VK_T, Shortcut.CTRL_SHIFT), 150);
buildContentPanel();
lstPrimitives.addMouseListener(new DblClickHandler());
lstPrimitives.addMouseListener(new TodoPopupLauncher());
popupMenu = new TodoPopup(lstPrimitives);
}
protected static void selectAndZoom(OsmPrimitive object) {
if (object == null) return;
if (Main.map == null || Main.map.mapView == null || Main.map.mapView.getEditLayer() == null) return;
Main.map.mapView.getEditLayer().data.setSelected(object);
AutoScaleAction.autoScale("selection");
}
protected static void selectAndZoom(Collection<OsmPrimitive> object) {
if (object == null) return;
if (Main.map == null || Main.map.mapView == null || Main.map.mapView.getEditLayer() == null) return;
Main.map.mapView.getEditLayer().data.setSelected(object);
AutoScaleAction.autoScale("selection");
}
protected void updateTitle() {
setTitle(model.getSummary());
}
@Override
public void showNotify() {
SelectionEventManager.getInstance().addSelectionListener(actAdd, FireMode.IN_EDT_CONSOLIDATED);
SelectionEventManager.getInstance().addSelectionListener(actMarkSelected, FireMode.IN_EDT_CONSOLIDATED);
}
private class SelectAction extends AbstractAction implements ListSelectionListener {
private final TodoListModel model;
public SelectAction(TodoListModel model) {
this.model = model;
putValue(NAME, tr("Zoom"));
putValue(SHORT_DESCRIPTION, tr("Zoom to the selected item in the todo list."));
putValue(SMALL_ICON, ImageProvider.get("dialogs","zoom-best-fit"));
updateEnabledState();
}
@Override
public void actionPerformed(ActionEvent e) {
selectAndZoom(model.getSelected());
}
public void updateEnabledState() {
setEnabled(model.getSelected() != null);
}
@Override
public void valueChanged(ListSelectionEvent e) {
updateEnabledState();
}
}
private class SelectUnmarkedAction extends AbstractAction implements ListSelectionListener {
private final TodoListModel model;
public SelectUnmarkedAction(TodoListModel model) {
this.model = model;
putValue(NAME, tr("Select all Unmarked and Zoom"));
putValue(SHORT_DESCRIPTION, tr("Select and zoom to all of the unmarked items in the todo list."));
putValue(SMALL_ICON, ImageProvider.get("dialogs","zoom-best-fit"));
updateEnabledState();
}
@Override
public void actionPerformed(ActionEvent e) {
selectAndZoom(model.getTodoList());
}
public void updateEnabledState() {
setEnabled(model.getSize() > 0);
}
@Override
public void valueChanged(ListSelectionEvent e) {
updateEnabledState();
}
}
private class PassAction extends AbstractAction implements ListSelectionListener {
private final TodoListModel model;
public PassAction(TodoListModel model) {
this.model = model;
putValue(NAME, tr("Pass"));
putValue(SHORT_DESCRIPTION, tr("Moves on to the next item but leaves this item in the todo list. ([)."));
putValue(SMALL_ICON, ImageProvider.get("dialogs","zoom-best-fit"));
updateEnabledState();
}
@Override
public void actionPerformed(ActionEvent e) {
model.incrementSelection();
selectAndZoom(model.getSelected());
}
public void updateEnabledState() {
setEnabled(model.getSize() > 0);
}
@Override
public void valueChanged(ListSelectionEvent e) {
updateEnabledState();
}
}
private class AddAction extends AbstractAction implements SelectionChangedListener {
private final TodoListModel model;
public AddAction(TodoListModel model) {
this.model = model;
putValue(NAME, tr("Add"));
putValue(SHORT_DESCRIPTION, tr("Add the selected items to the todo list."));
putValue(SMALL_ICON, ImageProvider.get("dialogs","add"));
updateEnabledState();
}
@Override
public void actionPerformed(ActionEvent e) {
if (Main.map == null || Main.map.mapView == null || Main.map.mapView.getEditLayer() == null) return;
Collection<OsmPrimitive> sel = Main.map.mapView.getEditLayer().data.getSelected();
model.addItems(sel);
updateTitle();
}
public void updateEnabledState() {
if (Main.map == null || Main.map.mapView == null || Main.map.mapView.getEditLayer() == null) {
setEnabled(false);
} else {
setEnabled(!Main.map.mapView.getEditLayer().data.selectionEmpty());
}
}
@Override
public void selectionChanged(Collection<? extends OsmPrimitive> arg) {
updateEnabledState();
}
}
private class MarkSelectedAction extends AbstractAction implements SelectionChangedListener {
private final TodoListModel model;
public MarkSelectedAction(TodoListModel model) {
this.model = model;
putValue(NAME, tr("Mark selected"));
putValue(SHORT_DESCRIPTION, tr("Mark the selected items (on the map) as done in the todo list."));
putValue(SMALL_ICON, ImageProvider.get("dialogs","select"));
updateEnabledState();
}
@Override
public void actionPerformed(ActionEvent e) {
if (Main.map == null || Main.map.mapView == null || Main.map.mapView.getEditLayer() == null) return;
Collection<OsmPrimitive> sel = Main.map.mapView.getEditLayer().data.getSelected();
model.markItems(sel);
updateTitle();
}
public void updateEnabledState() {
if (Main.map == null || Main.map.mapView == null || Main.map.mapView.getEditLayer() == null) {
setEnabled(false);
} else {
setEnabled(!Main.map.mapView.getEditLayer().data.selectionEmpty());
}
}
@Override
public void selectionChanged(Collection<? extends OsmPrimitive> arg) {
updateEnabledState();
}
}
private class MarkAction extends AbstractAction implements ListSelectionListener {
TodoListModel model;
public MarkAction(TodoListModel model) {
this.model = model;
putValue(NAME, tr("Mark"));
putValue(SHORT_DESCRIPTION, tr("Mark the selected item in the todo list as done. (])."));
putValue(SMALL_ICON, ImageProvider.get("dialogs","check"));
updateEnabledState();
}
@Override
public void actionPerformed(ActionEvent arg0) {
model.markSelected();
selectAndZoom(model.getSelected());
updateTitle();
}
public void updateEnabledState() {
setEnabled(model.getSelected() != null);
}
@Override
public void valueChanged(ListSelectionEvent arg0) {
updateEnabledState();
}
}
private class MarkAllAction extends AbstractAction {
TodoListModel model;
public MarkAllAction(TodoListModel model) {
this.model = model;
putValue(NAME, tr("Mark all"));
putValue(SHORT_DESCRIPTION, tr("Mark all items in the todo list as done."));
putValue(SMALL_ICON, ImageProvider.get("dialogs","todo"));
}
@Override
public void actionPerformed(ActionEvent arg0) {
model.markAll();
selectAndZoom(model.getSelected());
updateTitle();
}
}
private class UnmarkAllAction extends AbstractAction {
TodoListModel model;
public UnmarkAllAction(TodoListModel model) {
this.model = model;
putValue(NAME, tr("Unmark all"));
putValue(SHORT_DESCRIPTION, tr("Unmark all items in the todo list that have been marked as done."));
putValue(SMALL_ICON, ImageProvider.get("dialogs","refresh"));
}
@Override
public void actionPerformed(ActionEvent arg0) {
model.unmarkAll();
updateTitle();
}
}
private class ClearAction extends AbstractAction {
TodoListModel model;
public ClearAction(TodoListModel model) {
this.model = model;
putValue(NAME, tr("Clear the todo list"));
putValue(SHORT_DESCRIPTION, tr("Remove all items (marked and unmarked) from the todo list."));
putValue(SMALL_ICON, ImageProvider.get("dialogs","remove"));
}
@Override
public void actionPerformed(ActionEvent arg0) {
model.clear();
updateTitle();
}
}
/**
* Responds to double clicks on the list of selected objects
*/
class DblClickHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() < 2 || ! SwingUtilities.isLeftMouseButton(e)) return;
selectAndZoom(model.getSelected());
}
}
/**
* The popup menu launcher.
*/
class TodoPopupLauncher extends PopupMenuLauncher {
@Override
public void launch(MouseEvent evt) {
int idx = lstPrimitives.locationToIndex(evt.getPoint());
if(idx >= 0) model.setSelected((OsmPrimitive)model.getElementAt(idx));
popupMenu.show(lstPrimitives, evt.getX(), evt.getY());
}
}
/**
* A right-click popup context menu for setting options and performing other functions on the todo list items.
*/
class TodoPopup extends ListPopupMenu {
public TodoPopup(JList list) {
super(list);
add(new SelectAction(model));
add(new MarkAction(model));
addSeparator();
add(new MarkAllAction(model));
add(new UnmarkAllAction(model));
add(new ClearAction(model));
addSeparator();
add(actMarkSelected = new MarkSelectedAction(model));
add(new SelectUnmarkedAction(model));
}
}
}
| true | true | protected void buildContentPanel() {
DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
model = new TodoListModel(selectionModel);
lstPrimitives = new JList(model);
lstPrimitives.setSelectionModel(selectionModel);
lstPrimitives.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lstPrimitives.setCellRenderer(new OsmPrimitivRenderer());
lstPrimitives.setTransferHandler(null);
// the select action
SelectAction actSelect;
final SideButton selectButton = new SideButton(actSelect = new SelectAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actSelect);
// the add button
final SideButton addButton = new SideButton(actAdd = new AddAction(model));
// the pass button
PassAction actPass;
final SideButton passButton = new SideButton(actPass = new PassAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actPass);
Main.registerActionShortcut(actPass, Shortcut.registerShortcut("subwindow:todo:pass",
tr("Pass over element without marking it"), KeyEvent.VK_OPEN_BRACKET, Shortcut.DIRECT));
// the mark button
MarkAction actMark;
final SideButton markButton = new SideButton(actMark = new MarkAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actMark);
Main.registerActionShortcut(actMark, Shortcut.registerShortcut("subwindow:todo:mark",
tr("Mark element done"), KeyEvent.VK_CLOSE_BRACKET, Shortcut.DIRECT));
createLayout(lstPrimitives, true, Arrays.asList(new SideButton[] {
selectButton, addButton, passButton, markButton
}));
}
| protected void buildContentPanel() {
DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
model = new TodoListModel(selectionModel);
lstPrimitives = new JList(model);
lstPrimitives.setSelectionModel(selectionModel);
lstPrimitives.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lstPrimitives.setCellRenderer(new OsmPrimitivRenderer());
lstPrimitives.setTransferHandler(null);
// the select action
SelectAction actSelect;
final SideButton selectButton = new SideButton(actSelect = new SelectAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actSelect);
// the add button
final SideButton addButton = new SideButton(actAdd = new AddAction(model));
actAdd.updateEnabledState();
// the pass button
PassAction actPass;
final SideButton passButton = new SideButton(actPass = new PassAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actPass);
Main.registerActionShortcut(actPass, Shortcut.registerShortcut("subwindow:todo:pass",
tr("Pass over element without marking it"), KeyEvent.VK_OPEN_BRACKET, Shortcut.DIRECT));
// the mark button
MarkAction actMark;
final SideButton markButton = new SideButton(actMark = new MarkAction(model));
lstPrimitives.getSelectionModel().addListSelectionListener(actMark);
Main.registerActionShortcut(actMark, Shortcut.registerShortcut("subwindow:todo:mark",
tr("Mark element done"), KeyEvent.VK_CLOSE_BRACKET, Shortcut.DIRECT));
createLayout(lstPrimitives, true, Arrays.asList(new SideButton[] {
selectButton, addButton, passButton, markButton
}));
}
|
diff --git a/io-impl/impl/src/main/java/org/cytoscape/io/internal/read/xgmml/handler/AttributeValueUtil.java b/io-impl/impl/src/main/java/org/cytoscape/io/internal/read/xgmml/handler/AttributeValueUtil.java
index b5e444d5b..95a170b08 100644
--- a/io-impl/impl/src/main/java/org/cytoscape/io/internal/read/xgmml/handler/AttributeValueUtil.java
+++ b/io-impl/impl/src/main/java/org/cytoscape/io/internal/read/xgmml/handler/AttributeValueUtil.java
@@ -1,321 +1,319 @@
/*
Copyright (c) 2006, 2011, The Cytoscape Consortium (www.cytoscape.org)
This library 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
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. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. 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 library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.cytoscape.io.internal.read.xgmml.handler;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.cytoscape.io.internal.read.xgmml.MetadataEntries;
import org.cytoscape.io.internal.read.xgmml.MetadataParser;
import org.cytoscape.io.internal.read.xgmml.ObjectType;
import org.cytoscape.io.internal.read.xgmml.ObjectTypeMap;
import org.cytoscape.io.internal.read.xgmml.ParseState;
import org.cytoscape.io.internal.util.SUIDUpdater;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyRow;
import org.cytoscape.model.CyTable;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.VirtualColumnInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXParseException;
public class AttributeValueUtil {
static final String ATTR_NAME = "name";
static final String ATTR_LABEL = "label";
static final String ATTR_VALUE = "value";
static final String LOCKED_VISUAL_PROPS = "lockedVisualProperties";
static final Pattern XLINK_PATTERN = Pattern.compile(".*#(-?\\d+)");
private Locator locator;
private final ReadDataManager manager;
private final ObjectTypeMap typeMap;
protected static final Logger logger = LoggerFactory.getLogger(AttributeValueUtil.class);
public AttributeValueUtil(final ReadDataManager manager) {
this.manager = manager;
this.typeMap = new ObjectTypeMap();
}
public void setLocator(Locator locator) {
this.locator = locator;
}
public void setMetaData(CyNetwork network) {
MetadataParser mdp = new MetadataParser(network);
if (manager.RDFType != null) mdp.setMetadata(MetadataEntries.TYPE, manager.RDFType);
if (manager.RDFDate != null) mdp.setMetadata(MetadataEntries.DATE, manager.RDFDate);
if (manager.RDFTitle != null) mdp.setMetadata(MetadataEntries.TITLE, manager.RDFTitle);
if (manager.RDFDescription != null) mdp.setMetadata(MetadataEntries.DESCRIPTION, manager.RDFDescription);
if (manager.RDFSource != null) mdp.setMetadata(MetadataEntries.SOURCE, manager.RDFSource);
if (manager.RDFFormat != null) mdp.setMetadata(MetadataEntries.FORMAT, manager.RDFFormat);
if (manager.RDFIdentifier != null) mdp.setMetadata(MetadataEntries.IDENTIFIER, manager.RDFIdentifier);
}
/********************************************************************
* Routines to handle attributes
*******************************************************************/
/**
* Return the string attribute value for the attribute indicated by "key".
* If no such attribute exists, return null. In particular, this routine
* looks for an attribute with a <b>name</b> or <b>label</b> of <i>key</i>
* and returns the <b>value</b> of that attribute.
*
* @param atts
* the attributes
* @param key
* the specific attribute to get
* @return the value for "key" or null if no such attribute exists
*/
protected String getAttributeValue(Attributes atts, String key) {
String name = atts.getValue(ATTR_NAME);
if (name == null) name = atts.getValue(ATTR_LABEL);
if (name != null && name.equals(key))
return atts.getValue(ATTR_VALUE);
else
return null;
}
/**
* Return the typed attribute value for the passed attribute. In this case, the caller has already determined that
* this is the correct attribute and we just lookup the value. This routine is responsible for type conversion
* consistent with the passed argument.
*
* @param type the ObjectType of the value
* @param atts the attributes
* @param name the attribute name
* @return the value of the attribute in the appropriate type
*/
protected Object getTypedAttributeValue(ObjectType type, Attributes atts, String name) throws SAXParseException {
String value = atts.getValue("value");
try {
return typeMap.getTypedValue(type, value, name);
} catch (Exception e) {
throw new SAXParseException("Unable to convert '" + value + "' to type " + type.toString(), locator);
}
}
/**
* Return the attribute value for the attribute indicated by "key". If no
* such attribute exists, return null.
*
* @param atts
* the attributes
* @param key
* the specific attribute to get
* @return the value for "key" or null if no such attribute exists
*/
protected String getAttribute(Attributes atts, String key) {
return atts.getValue(key);
}
/**
* Return the attribute value for the attribute indicated by "key". If no
* such attribute exists, return null.
*
* @param atts
* the attributes
* @param key
* the specific attribute to get
* @param ns
* the namespace for the attribute we're interested in
* @return the value for "key" or null if no such attribute exists
*/
protected String getAttributeNS(Attributes atts, String key, String ns) {
if (atts.getValue(ns, key) != null)
return atts.getValue(ns, key);
else
return atts.getValue(key);
}
protected ParseState handleAttribute(Attributes atts) throws SAXParseException {
ParseState parseState = ParseState.NONE;
final String name = atts.getValue("name");
final String type = atts.getValue("type");
- final String equationStr = atts.getValue("cy:equation");
- final boolean isEquation = equationStr != null ? Boolean.parseBoolean(equationStr) : false;
- final String hiddenStr = atts.getValue("cy:hidden");
- final boolean isHidden = hiddenStr != null ? Boolean.parseBoolean(hiddenStr) : false;
+ final boolean isEquation = ObjectTypeMap.fromXGMMLBoolean(atts.getValue("cy:equation"));
+ final boolean isHidden = ObjectTypeMap.fromXGMMLBoolean(atts.getValue("cy:hidden"));
final CyIdentifiable curElement = manager.getCurrentElement();
CyNetwork curNet = manager.getCurrentNetwork();
// This is necessary, because external edges of 2.x Groups may be written
// under the group subgraph, but the edge will be created on the root-network only,
if (curElement instanceof CyNode || curElement instanceof CyEdge) {
boolean containsElement = (curElement instanceof CyNode && curNet.containsNode((CyNode) curElement));
containsElement |= (curElement instanceof CyEdge && curNet.containsEdge((CyEdge) curElement));
// So if the current network does not contain this element, the CyRootNetwork should contain it
if (!containsElement)
curNet = manager.getRootNetwork();
}
CyRow row = null;
if (isHidden) {
row = curNet.getRow(curElement, CyNetwork.HIDDEN_ATTRS);
} else {
// TODO: What are the rules here?
// Node/edge attributes are always shared, except "selected"?
// Network name must be local, right? What about other network attributes?
if (CyNetwork.SELECTED.equals(name) || (curElement instanceof CyNetwork))
row = curNet.getRow(curElement, CyNetwork.LOCAL_ATTRS);
else
row = curNet.getRow(curElement, CyNetwork.DEFAULT_ATTRS); // Will be created in the shared table
}
CyTable table = row.getTable();
CyColumn column = table.getColumn(name);
if (column != null) {
// Check if it's a virtual column
// It's necessary because the source row may not exist yet, which would throw an exception
// when the value is set. Doing this forces the creation of the source row.
final VirtualColumnInfo info = column.getVirtualColumnInfo();
if (info.isVirtual()) {
final CyTable srcTable = info.getSourceTable();
final CyColumn srcColumn = srcTable.getColumn(info.getSourceColumn());
final Class<?> jkColType = table.getColumn(info.getTargetJoinKey()).getType();
final Object jkValue = row.get(info.getTargetJoinKey(), jkColType);
final Collection<CyRow> srcRowList = srcTable.getMatchingRows(info.getSourceJoinKey(), jkValue);
final CyRow srcRow;
if (srcRowList == null || srcRowList.isEmpty()) {
if (info.getTargetJoinKey().equals(CyIdentifiable.SUID)) {
// Try to create the row
srcRow = srcTable.getRow(jkValue);
} else {
logger.error("Unable to import virtual column \"" + name + "\": The source table \""
+ srcTable.getTitle() + "\" does not have any matching rows for join key \""
+ info.getSourceJoinKey() + "=" + jkValue + "\".");
return parseState;
}
} else {
srcRow = srcRowList.iterator().next();
}
// Use the source table instead
table = srcTable;
column = srcColumn;
row = srcRow;
}
}
Object value = null;
ObjectType objType = typeMap.getType(type);
if (isEquation) {
// It is an equation...
String formula = atts.getValue("value");
if (name != null && formula != null) {
manager.addEquationString(row, name, formula);
}
} else {
// Regular attribute value...
value = getTypedAttributeValue(objType, atts, name);
}
switch (objType) {
case BOOLEAN:
if (name != null) setAttribute(row, name, Boolean.class, (Boolean) value);
break;
case REAL:
if (name != null) {
if (SUIDUpdater.isUpdatable(name))
setAttribute(row, name, Long.class, (Long) value);
else
setAttribute(row, name, Double.class, (Double) value);
}
break;
case INTEGER:
if (name != null) setAttribute(row, name, Integer.class, (Integer) value);
break;
case STRING:
if (name != null) setAttribute(row, name, String.class, (String) value);
break;
// We need to be *very* careful. Because we duplicate attributes for
// each network we write out, we wind up reading and processing each
// attribute multiple times, once for each network. This isn't a problem
// for "base" attributes, but is a significant problem for attributes
// like LIST and MAP where we add to the attribute as we parse. So, we
// must make sure to clear out any existing values before we parse.
case LIST:
manager.currentAttributeID = name;
manager.setCurrentRow(row);
if (column != null && List.class.isAssignableFrom(column.getType()))
row.set(name, null);
return ParseState.LIST_ATT;
}
return parseState;
}
private <T> void setAttribute(final CyRow row, final String name, final Class<T> type, final T value) {
if (name != null) {
final CyTable table = row.getTable();
final CyColumn column = table.getColumn(name);
if (column == null) {
table.createColumn(name, type, false);
} else if (column.getVirtualColumnInfo().isVirtual()) {
logger.warn("Cannot set value to virtual column \"" + name + "\".");
return;
}
if (value != null) {
row.set(name, value);
}
}
}
public static Long getIdFromXLink(String href) {
Matcher matcher = XLINK_PATTERN.matcher(href);
return matcher.matches() ? Long.valueOf(matcher.group(1)) : null;
}
}
| true | true | protected ParseState handleAttribute(Attributes atts) throws SAXParseException {
ParseState parseState = ParseState.NONE;
final String name = atts.getValue("name");
final String type = atts.getValue("type");
final String equationStr = atts.getValue("cy:equation");
final boolean isEquation = equationStr != null ? Boolean.parseBoolean(equationStr) : false;
final String hiddenStr = atts.getValue("cy:hidden");
final boolean isHidden = hiddenStr != null ? Boolean.parseBoolean(hiddenStr) : false;
final CyIdentifiable curElement = manager.getCurrentElement();
CyNetwork curNet = manager.getCurrentNetwork();
// This is necessary, because external edges of 2.x Groups may be written
// under the group subgraph, but the edge will be created on the root-network only,
if (curElement instanceof CyNode || curElement instanceof CyEdge) {
boolean containsElement = (curElement instanceof CyNode && curNet.containsNode((CyNode) curElement));
containsElement |= (curElement instanceof CyEdge && curNet.containsEdge((CyEdge) curElement));
// So if the current network does not contain this element, the CyRootNetwork should contain it
if (!containsElement)
curNet = manager.getRootNetwork();
}
CyRow row = null;
if (isHidden) {
row = curNet.getRow(curElement, CyNetwork.HIDDEN_ATTRS);
} else {
// TODO: What are the rules here?
// Node/edge attributes are always shared, except "selected"?
// Network name must be local, right? What about other network attributes?
if (CyNetwork.SELECTED.equals(name) || (curElement instanceof CyNetwork))
row = curNet.getRow(curElement, CyNetwork.LOCAL_ATTRS);
else
row = curNet.getRow(curElement, CyNetwork.DEFAULT_ATTRS); // Will be created in the shared table
}
CyTable table = row.getTable();
CyColumn column = table.getColumn(name);
if (column != null) {
// Check if it's a virtual column
// It's necessary because the source row may not exist yet, which would throw an exception
// when the value is set. Doing this forces the creation of the source row.
final VirtualColumnInfo info = column.getVirtualColumnInfo();
if (info.isVirtual()) {
final CyTable srcTable = info.getSourceTable();
final CyColumn srcColumn = srcTable.getColumn(info.getSourceColumn());
final Class<?> jkColType = table.getColumn(info.getTargetJoinKey()).getType();
final Object jkValue = row.get(info.getTargetJoinKey(), jkColType);
final Collection<CyRow> srcRowList = srcTable.getMatchingRows(info.getSourceJoinKey(), jkValue);
final CyRow srcRow;
if (srcRowList == null || srcRowList.isEmpty()) {
if (info.getTargetJoinKey().equals(CyIdentifiable.SUID)) {
// Try to create the row
srcRow = srcTable.getRow(jkValue);
} else {
logger.error("Unable to import virtual column \"" + name + "\": The source table \""
+ srcTable.getTitle() + "\" does not have any matching rows for join key \""
+ info.getSourceJoinKey() + "=" + jkValue + "\".");
return parseState;
}
} else {
srcRow = srcRowList.iterator().next();
}
// Use the source table instead
table = srcTable;
column = srcColumn;
row = srcRow;
}
}
Object value = null;
ObjectType objType = typeMap.getType(type);
if (isEquation) {
// It is an equation...
String formula = atts.getValue("value");
if (name != null && formula != null) {
manager.addEquationString(row, name, formula);
}
} else {
// Regular attribute value...
value = getTypedAttributeValue(objType, atts, name);
}
switch (objType) {
case BOOLEAN:
if (name != null) setAttribute(row, name, Boolean.class, (Boolean) value);
break;
case REAL:
if (name != null) {
if (SUIDUpdater.isUpdatable(name))
setAttribute(row, name, Long.class, (Long) value);
else
setAttribute(row, name, Double.class, (Double) value);
}
break;
case INTEGER:
if (name != null) setAttribute(row, name, Integer.class, (Integer) value);
break;
case STRING:
if (name != null) setAttribute(row, name, String.class, (String) value);
break;
// We need to be *very* careful. Because we duplicate attributes for
// each network we write out, we wind up reading and processing each
// attribute multiple times, once for each network. This isn't a problem
// for "base" attributes, but is a significant problem for attributes
// like LIST and MAP where we add to the attribute as we parse. So, we
// must make sure to clear out any existing values before we parse.
case LIST:
manager.currentAttributeID = name;
manager.setCurrentRow(row);
if (column != null && List.class.isAssignableFrom(column.getType()))
row.set(name, null);
return ParseState.LIST_ATT;
}
return parseState;
}
| protected ParseState handleAttribute(Attributes atts) throws SAXParseException {
ParseState parseState = ParseState.NONE;
final String name = atts.getValue("name");
final String type = atts.getValue("type");
final boolean isEquation = ObjectTypeMap.fromXGMMLBoolean(atts.getValue("cy:equation"));
final boolean isHidden = ObjectTypeMap.fromXGMMLBoolean(atts.getValue("cy:hidden"));
final CyIdentifiable curElement = manager.getCurrentElement();
CyNetwork curNet = manager.getCurrentNetwork();
// This is necessary, because external edges of 2.x Groups may be written
// under the group subgraph, but the edge will be created on the root-network only,
if (curElement instanceof CyNode || curElement instanceof CyEdge) {
boolean containsElement = (curElement instanceof CyNode && curNet.containsNode((CyNode) curElement));
containsElement |= (curElement instanceof CyEdge && curNet.containsEdge((CyEdge) curElement));
// So if the current network does not contain this element, the CyRootNetwork should contain it
if (!containsElement)
curNet = manager.getRootNetwork();
}
CyRow row = null;
if (isHidden) {
row = curNet.getRow(curElement, CyNetwork.HIDDEN_ATTRS);
} else {
// TODO: What are the rules here?
// Node/edge attributes are always shared, except "selected"?
// Network name must be local, right? What about other network attributes?
if (CyNetwork.SELECTED.equals(name) || (curElement instanceof CyNetwork))
row = curNet.getRow(curElement, CyNetwork.LOCAL_ATTRS);
else
row = curNet.getRow(curElement, CyNetwork.DEFAULT_ATTRS); // Will be created in the shared table
}
CyTable table = row.getTable();
CyColumn column = table.getColumn(name);
if (column != null) {
// Check if it's a virtual column
// It's necessary because the source row may not exist yet, which would throw an exception
// when the value is set. Doing this forces the creation of the source row.
final VirtualColumnInfo info = column.getVirtualColumnInfo();
if (info.isVirtual()) {
final CyTable srcTable = info.getSourceTable();
final CyColumn srcColumn = srcTable.getColumn(info.getSourceColumn());
final Class<?> jkColType = table.getColumn(info.getTargetJoinKey()).getType();
final Object jkValue = row.get(info.getTargetJoinKey(), jkColType);
final Collection<CyRow> srcRowList = srcTable.getMatchingRows(info.getSourceJoinKey(), jkValue);
final CyRow srcRow;
if (srcRowList == null || srcRowList.isEmpty()) {
if (info.getTargetJoinKey().equals(CyIdentifiable.SUID)) {
// Try to create the row
srcRow = srcTable.getRow(jkValue);
} else {
logger.error("Unable to import virtual column \"" + name + "\": The source table \""
+ srcTable.getTitle() + "\" does not have any matching rows for join key \""
+ info.getSourceJoinKey() + "=" + jkValue + "\".");
return parseState;
}
} else {
srcRow = srcRowList.iterator().next();
}
// Use the source table instead
table = srcTable;
column = srcColumn;
row = srcRow;
}
}
Object value = null;
ObjectType objType = typeMap.getType(type);
if (isEquation) {
// It is an equation...
String formula = atts.getValue("value");
if (name != null && formula != null) {
manager.addEquationString(row, name, formula);
}
} else {
// Regular attribute value...
value = getTypedAttributeValue(objType, atts, name);
}
switch (objType) {
case BOOLEAN:
if (name != null) setAttribute(row, name, Boolean.class, (Boolean) value);
break;
case REAL:
if (name != null) {
if (SUIDUpdater.isUpdatable(name))
setAttribute(row, name, Long.class, (Long) value);
else
setAttribute(row, name, Double.class, (Double) value);
}
break;
case INTEGER:
if (name != null) setAttribute(row, name, Integer.class, (Integer) value);
break;
case STRING:
if (name != null) setAttribute(row, name, String.class, (String) value);
break;
// We need to be *very* careful. Because we duplicate attributes for
// each network we write out, we wind up reading and processing each
// attribute multiple times, once for each network. This isn't a problem
// for "base" attributes, but is a significant problem for attributes
// like LIST and MAP where we add to the attribute as we parse. So, we
// must make sure to clear out any existing values before we parse.
case LIST:
manager.currentAttributeID = name;
manager.setCurrentRow(row);
if (column != null && List.class.isAssignableFrom(column.getType()))
row.set(name, null);
return ParseState.LIST_ATT;
}
return parseState;
}
|
diff --git a/test/src/org/broad/igv/data/HostedDataTest.java b/test/src/org/broad/igv/data/HostedDataTest.java
index f0123ccf6..46e738683 100644
--- a/test/src/org/broad/igv/data/HostedDataTest.java
+++ b/test/src/org/broad/igv/data/HostedDataTest.java
@@ -1,258 +1,264 @@
/*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
package org.broad.igv.data;
import org.broad.igv.AbstractHeadlessTest;
import org.broad.igv.PreferenceManager;
import org.broad.igv.feature.FeatureDB;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeListItem;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.sam.reader.BAMHttpReader;
import org.broad.igv.track.TrackLoader;
import org.broad.igv.ui.ResourceTree;
import org.broad.igv.ui.action.LoadFromServerAction;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.TestUtils;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.w3c.dom.Document;
import util.LongRunning;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.junit.Assert.*;
/**
* Test loading the data we host. Sometimes it gets corrupted,
* or we make backwards-incompatible changes
* <p/>
* User: jacob
* Date: 2012-Jul-27
*/
public class HostedDataTest extends AbstractHeadlessTest {
@Rule
public TestRule testTimeout = new Timeout((int) 1200e4);
private PrintStream errorWriter = System.out;
/**
* Test loading all the data hosted for each genome
*
* @throws Exception
*/
@Category(LongRunning.class)
@Test
public void testLoadServerData() throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd-HH-mm-ss");
Date date = new Date();
String outPath = TestUtils.DATA_DIR + "failed_loaded_files_" + dateFormat.format(date) + ".txt";
errorWriter = new PrintStream(outPath);
List<GenomeListItem> serverSideGenomeList = getServerGenomes();
Map<ResourceLocator, Exception> failedFiles = new LinkedHashMap<ResourceLocator, Exception>(10);
Set<ResourceLocator> loadedResources = new HashSet<ResourceLocator>(1000);
LinkedHashSet<String> nodeURLs;
int counter = 0;
//Large BAM files have have index files ~10 Mb, don't want to use
//too much space on disk at once
int clearInterval = 50;
DefaultMutableTreeNode maxNode = null;
int maxChildCount = -1;
for (GenomeListItem genomeItem : serverSideGenomeList) {
//Do this within the loop, both to make sure we get a fresh genome
//and not use too much disk space
GenomeManager.getInstance().clearGenomeCache();
String genomeURL = LoadFromServerAction.getGenomeDataURL(genomeItem.getId());
TrackLoader loader = new TrackLoader();
- Genome curGenome = GenomeManager.getInstance().loadGenome(genomeItem.getLocation(), null);
+ Genome curGenome = null;
+ try {
+ curGenome = GenomeManager.getInstance().loadGenome(genomeItem.getLocation(), null);
+ } catch (IOException e) {
+ recordError(new ResourceLocator(genomeItem.getLocation()), e, failedFiles);
+ continue;
+ }
errorWriter.println("Genome: " + curGenome.getId());
try {
nodeURLs = LoadFromServerAction.getNodeURLs(genomeURL);
if (nodeURLs == null) {
errorWriter.println("Warning: No Data found for " + genomeURL);
continue;
}
} catch (Exception e) {
recordError(genomeURL, e, failedFiles);
continue;
}
for (String nodeURL : nodeURLs) {
errorWriter.println("NodeURL: " + nodeURL);
try {
Document xmlDocument = LoadFromServerAction.createMasterDocument(Arrays.asList(nodeURL));
DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode("HostedDataTest");
ResourceTree.buildLocatorTree(treeNode, xmlDocument.getDocumentElement(),
Collections.<ResourceLocator>emptySet(), null);
Enumeration enumeration = treeNode.depthFirstEnumeration();
while (enumeration.hasMoreElements()) {
Object nextEl = enumeration.nextElement();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) nextEl;
Object userObject = node.getUserObject();
//Get resource locator from tree
//don't load resources we've already tried (same file can be listed multiple times)
ResourceTree.CheckableResource checkableResource;
ResourceLocator locator;
if (userObject instanceof ResourceTree.CheckableResource) {
checkableResource = (ResourceTree.CheckableResource) userObject;
locator = checkableResource.getResourceLocator();
if (locator.getPath() == null || loadedResources.contains(locator)) {
continue;
} else {
loadedResources.add(locator);
}
} else {
continue;
}
// int childCount = node.getChildCount();
// if(childCount > 0){
// System.out.println(node.getUserObject() + " Children: " + childCount);
// if(childCount > maxChildCount){
// maxChildCount = childCount;
// maxNode = node;
// }
// }
FeatureDB.clearFeatures();
try {
// if(locator.getServerURL() != null){
// //System.out.println("server url " + locator.getServerURL());
// //System.out.println("path " + locator.getPath());
// }else{
// continue;
// }
// errorWriter.println("Loading " + locator);
loader.load(locator, curGenome);
} catch (Exception e) {
recordError(locator, e, failedFiles);
}
counter = (counter + 1) % clearInterval;
if (counter == 0) {
BAMHttpReader.cleanTempDir(1l);
}
}
} catch (Exception e) {
recordError(nodeURL, e, failedFiles);
}
}
}
//System.out.println("Max Node: " + maxNode + ". Children: " + maxChildCount);
for (Map.Entry<ResourceLocator, Exception> entry : failedFiles.entrySet()) {
ResourceLocator item = entry.getKey();
errorWriter.println(formatLocator(item) + "\terror: " + entry.getValue().getMessage());
}
errorWriter.flush();
errorWriter.close();
assertEquals(0, failedFiles.size());
}
private String formatLocator(ResourceLocator locator) {
return String.format("Name: %s\tPath: %s\t serverURL: %s",
locator.getName(), locator.getPath(), locator.getServerURL());
}
private void recordError(String path, Exception e, Map<ResourceLocator, Exception> failures) {
ResourceLocator locator = new ResourceLocator(path);
recordError(locator, e, failures);
}
private void recordError(ResourceLocator locator, Exception e, Map<ResourceLocator, Exception> failures) {
failures.put(locator, e);
errorWriter.println(formatLocator(locator) + "\terror: " + e.getMessage());
errorWriter.println("StackTrace: ");
for (StackTraceElement el : e.getStackTrace()) {
errorWriter.println(el);
}
errorWriter.flush();
}
private List<GenomeListItem> getServerGenomes() throws IOException {
String genomeListPath = PreferenceManager.DEFAULT_GENOME_URL;
PreferenceManager.getInstance().overrideGenomeServerURL(genomeListPath);
List<GenomeListItem> serverSideItemList = GenomeManager.getInstance().getServerGenomeArchiveList(null);
assertNotNull("Could not retrieve genome list from server", serverSideItemList);
assertTrue("Genome list empty", serverSideItemList.size() > 0);
return serverSideItemList;
}
@Ignore
@Test
public void testLoadServerGenomes() throws Exception {
List<GenomeListItem> serverSideItemList = getServerGenomes();
Map<GenomeListItem, Exception> failedGenomes = new LinkedHashMap<GenomeListItem, Exception>(10);
int count = 0;
for (GenomeListItem genome : serverSideItemList) {
try {
count++;
tstLoadGenome(genome.getLocation());
Runtime.getRuntime().gc();
} catch (Exception e) {
failedGenomes.put(genome, e);
}
}
errorWriter.println("Attempted to load " + count + " genomes");
errorWriter.println(failedGenomes.size() + " of them failed");
for (Map.Entry<GenomeListItem, Exception> entry : failedGenomes.entrySet()) {
GenomeListItem item = entry.getKey();
System.out.println(String.format("Exception loading (%s\t%s\t%s): %s", item.getDisplayableName(),
item.getLocation(), item.getId(), entry.getValue()));
}
assertEquals(0, failedGenomes.size());
}
public void tstLoadGenome(String path) throws Exception {
FeatureDB.clearFeatures();
Genome genome = GenomeManager.getInstance().loadGenome(path, null);
assertTrue(genome.getAllChromosomeNames().size() > 0);
}
}
| true | true | public void testLoadServerData() throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd-HH-mm-ss");
Date date = new Date();
String outPath = TestUtils.DATA_DIR + "failed_loaded_files_" + dateFormat.format(date) + ".txt";
errorWriter = new PrintStream(outPath);
List<GenomeListItem> serverSideGenomeList = getServerGenomes();
Map<ResourceLocator, Exception> failedFiles = new LinkedHashMap<ResourceLocator, Exception>(10);
Set<ResourceLocator> loadedResources = new HashSet<ResourceLocator>(1000);
LinkedHashSet<String> nodeURLs;
int counter = 0;
//Large BAM files have have index files ~10 Mb, don't want to use
//too much space on disk at once
int clearInterval = 50;
DefaultMutableTreeNode maxNode = null;
int maxChildCount = -1;
for (GenomeListItem genomeItem : serverSideGenomeList) {
//Do this within the loop, both to make sure we get a fresh genome
//and not use too much disk space
GenomeManager.getInstance().clearGenomeCache();
String genomeURL = LoadFromServerAction.getGenomeDataURL(genomeItem.getId());
TrackLoader loader = new TrackLoader();
Genome curGenome = GenomeManager.getInstance().loadGenome(genomeItem.getLocation(), null);
errorWriter.println("Genome: " + curGenome.getId());
try {
nodeURLs = LoadFromServerAction.getNodeURLs(genomeURL);
if (nodeURLs == null) {
errorWriter.println("Warning: No Data found for " + genomeURL);
continue;
}
} catch (Exception e) {
recordError(genomeURL, e, failedFiles);
continue;
}
for (String nodeURL : nodeURLs) {
errorWriter.println("NodeURL: " + nodeURL);
try {
Document xmlDocument = LoadFromServerAction.createMasterDocument(Arrays.asList(nodeURL));
DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode("HostedDataTest");
ResourceTree.buildLocatorTree(treeNode, xmlDocument.getDocumentElement(),
Collections.<ResourceLocator>emptySet(), null);
Enumeration enumeration = treeNode.depthFirstEnumeration();
while (enumeration.hasMoreElements()) {
Object nextEl = enumeration.nextElement();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) nextEl;
Object userObject = node.getUserObject();
//Get resource locator from tree
//don't load resources we've already tried (same file can be listed multiple times)
ResourceTree.CheckableResource checkableResource;
ResourceLocator locator;
if (userObject instanceof ResourceTree.CheckableResource) {
checkableResource = (ResourceTree.CheckableResource) userObject;
locator = checkableResource.getResourceLocator();
if (locator.getPath() == null || loadedResources.contains(locator)) {
continue;
} else {
loadedResources.add(locator);
}
} else {
continue;
}
// int childCount = node.getChildCount();
// if(childCount > 0){
// System.out.println(node.getUserObject() + " Children: " + childCount);
// if(childCount > maxChildCount){
// maxChildCount = childCount;
// maxNode = node;
// }
// }
FeatureDB.clearFeatures();
try {
// if(locator.getServerURL() != null){
// //System.out.println("server url " + locator.getServerURL());
// //System.out.println("path " + locator.getPath());
// }else{
// continue;
// }
// errorWriter.println("Loading " + locator);
loader.load(locator, curGenome);
} catch (Exception e) {
recordError(locator, e, failedFiles);
}
counter = (counter + 1) % clearInterval;
if (counter == 0) {
BAMHttpReader.cleanTempDir(1l);
}
}
} catch (Exception e) {
recordError(nodeURL, e, failedFiles);
}
}
}
//System.out.println("Max Node: " + maxNode + ". Children: " + maxChildCount);
for (Map.Entry<ResourceLocator, Exception> entry : failedFiles.entrySet()) {
ResourceLocator item = entry.getKey();
errorWriter.println(formatLocator(item) + "\terror: " + entry.getValue().getMessage());
}
errorWriter.flush();
errorWriter.close();
assertEquals(0, failedFiles.size());
}
| public void testLoadServerData() throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd-HH-mm-ss");
Date date = new Date();
String outPath = TestUtils.DATA_DIR + "failed_loaded_files_" + dateFormat.format(date) + ".txt";
errorWriter = new PrintStream(outPath);
List<GenomeListItem> serverSideGenomeList = getServerGenomes();
Map<ResourceLocator, Exception> failedFiles = new LinkedHashMap<ResourceLocator, Exception>(10);
Set<ResourceLocator> loadedResources = new HashSet<ResourceLocator>(1000);
LinkedHashSet<String> nodeURLs;
int counter = 0;
//Large BAM files have have index files ~10 Mb, don't want to use
//too much space on disk at once
int clearInterval = 50;
DefaultMutableTreeNode maxNode = null;
int maxChildCount = -1;
for (GenomeListItem genomeItem : serverSideGenomeList) {
//Do this within the loop, both to make sure we get a fresh genome
//and not use too much disk space
GenomeManager.getInstance().clearGenomeCache();
String genomeURL = LoadFromServerAction.getGenomeDataURL(genomeItem.getId());
TrackLoader loader = new TrackLoader();
Genome curGenome = null;
try {
curGenome = GenomeManager.getInstance().loadGenome(genomeItem.getLocation(), null);
} catch (IOException e) {
recordError(new ResourceLocator(genomeItem.getLocation()), e, failedFiles);
continue;
}
errorWriter.println("Genome: " + curGenome.getId());
try {
nodeURLs = LoadFromServerAction.getNodeURLs(genomeURL);
if (nodeURLs == null) {
errorWriter.println("Warning: No Data found for " + genomeURL);
continue;
}
} catch (Exception e) {
recordError(genomeURL, e, failedFiles);
continue;
}
for (String nodeURL : nodeURLs) {
errorWriter.println("NodeURL: " + nodeURL);
try {
Document xmlDocument = LoadFromServerAction.createMasterDocument(Arrays.asList(nodeURL));
DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode("HostedDataTest");
ResourceTree.buildLocatorTree(treeNode, xmlDocument.getDocumentElement(),
Collections.<ResourceLocator>emptySet(), null);
Enumeration enumeration = treeNode.depthFirstEnumeration();
while (enumeration.hasMoreElements()) {
Object nextEl = enumeration.nextElement();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) nextEl;
Object userObject = node.getUserObject();
//Get resource locator from tree
//don't load resources we've already tried (same file can be listed multiple times)
ResourceTree.CheckableResource checkableResource;
ResourceLocator locator;
if (userObject instanceof ResourceTree.CheckableResource) {
checkableResource = (ResourceTree.CheckableResource) userObject;
locator = checkableResource.getResourceLocator();
if (locator.getPath() == null || loadedResources.contains(locator)) {
continue;
} else {
loadedResources.add(locator);
}
} else {
continue;
}
// int childCount = node.getChildCount();
// if(childCount > 0){
// System.out.println(node.getUserObject() + " Children: " + childCount);
// if(childCount > maxChildCount){
// maxChildCount = childCount;
// maxNode = node;
// }
// }
FeatureDB.clearFeatures();
try {
// if(locator.getServerURL() != null){
// //System.out.println("server url " + locator.getServerURL());
// //System.out.println("path " + locator.getPath());
// }else{
// continue;
// }
// errorWriter.println("Loading " + locator);
loader.load(locator, curGenome);
} catch (Exception e) {
recordError(locator, e, failedFiles);
}
counter = (counter + 1) % clearInterval;
if (counter == 0) {
BAMHttpReader.cleanTempDir(1l);
}
}
} catch (Exception e) {
recordError(nodeURL, e, failedFiles);
}
}
}
//System.out.println("Max Node: " + maxNode + ". Children: " + maxChildCount);
for (Map.Entry<ResourceLocator, Exception> entry : failedFiles.entrySet()) {
ResourceLocator item = entry.getKey();
errorWriter.println(formatLocator(item) + "\terror: " + entry.getValue().getMessage());
}
errorWriter.flush();
errorWriter.close();
assertEquals(0, failedFiles.size());
}
|
diff --git a/src/mypackage/Gardenshift.java b/src/mypackage/Gardenshift.java
index d6c12c4..979adf5 100644
--- a/src/mypackage/Gardenshift.java
+++ b/src/mypackage/Gardenshift.java
@@ -1,1753 +1,1754 @@
/*
* Gardenshift Webservices with Resteasy for Jboss
*
*
* Author Comment Modified
*
* Hilay Khatri Add new user with email/username validation 06-11-2012
*
* Hilay Khatri Insert user details in mongoDB 06-11-2012
*
* Hilay Khatri Show all users personal information 06-11-2012
*
* Hilay Khatri Show information of a particular user 06-11-2012
*
* Hilay Khatri Update personal records 06-11-2012
*
* Hilay Khatri Authenticate user 06-11-2012
*
*/
package mypackage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
//import javax.ws.rs.core.Response;
import sun.misc.BASE64Encoder;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import java.util.Date;
import java.sql.Timestamp;
@Path("/")
public class Gardenshift {
public DB db;
public Mongo mongo;
public Gardenshift() {
try {
mongo = new Mongo("127.3.119.1", 27017);
// mongo = new Mongo("localhost", 27017);
db = mongo.getDB("gardenshift");
db.authenticate("admin", "redhat".toCharArray());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MongoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Path("adduser")
@POST
public Response adduser(@FormParam("username") String userID,
@FormParam("password") String password,
@FormParam("email") String emailAdd) {
/*
* Adds a new username to the database.
*/
Boolean userExists = false; // See if username already exists
Boolean emailExists = false; // See if email already exists
Boolean validEmail = false; // See if valid email address
Boolean validUsername = false; // See if valid email address
String user, email; // Stores username and email retrieved from mongoDB
// for verification
String msg = ""; // Error message
try {
// userClass newUser = new userClass();
validEmail = isValidEmailAddress(emailAdd);
if (userID.length() < 6) {
msg = "Username should not be less than 6 characters";
return Response.status(200).entity(msg).build();
}
if (validEmail) {
DBCollection collection = db.getCollection("users");
BasicDBObject document = new BasicDBObject();
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
user = obj.getString("username");
email = obj.getString("email");
if (user.equals(userID)) {
userExists = true;
msg = "failure-user already exists";
}
if (email.equals(emailAdd)) {
emailExists = true;
msg = "failure-email already exists";
}
}
// If username or email is unique, create a new user
if (userExists == false && emailExists == false) {
msg = "Success-user created";
document.put("username", userID);
document.put("password",
encryptPassword(password, "SHA-1", "UTF-8"));
document.put("creation_date", new Date().toString());
document.put("email", emailAdd);
document.put("name", "");
+ document.put("status", new ArrayList());
document.put("picture", "http://www.worldbiofuelsmarkets.com/EF/Images/blank_profile_pic.jpg");
document.put("zipcode", ""); // HTML5 Geolocation API can
// also be used
BasicDBObject feedback = new BasicDBObject();
feedback.put("from", "");
feedback.put("text", "");
document.put("feedback", feedback);
document.put("notifications_read", new ArrayList());
document.put("notifications_unread", new ArrayList());
document.put("bulletin", new ArrayList());
document.put("bulletin_archive", new ArrayList());
BasicDBObject friends = new BasicDBObject();
friends.put("friends_username", "");
friends.put("status", "");
- friends.put("friends", friends);
+ document.put("friends", friends);
// BasicDBObject user_crops = new BasicDBObject();
// user_crops.put("crop_name", "");
// user_crops.put("crop_expected_quantity", "");
// user_crops.put("crop_harvest_date", "");
// user_crops.put("crop_harvested", "");
// user_crops.put("pictures", "");
// user_crops.put("videos", "");
// user_crops.put("comments", "");
// document.put("user_crops", user_crops);
- document.put("user_crops", new ArrayList());
+ document.put("user_crops", new ArrayList());
collection.insert(document);
}
}
else {
msg = "Invalid Email Address";
return Response.status(200).entity(msg).build();
}
} catch (UnknownHostException e) {
Response.status(500);
} catch (MongoException e) {
Response.status(500);
} catch (Exception e) {
// TODO Auto-generated catch block
Response.status(500);
}
return Response.status(200).entity(msg).build();
}
/*
* This method encrypts the password using SHA-1 algorithm and UTF-8
* encoding.
*/
private static String encryptPassword(String plaintext, String algorithm,
String encoding) throws Exception {
MessageDigest msgDigest = null;
String hashValue = null;
try {
msgDigest = MessageDigest.getInstance(algorithm);
msgDigest.update(plaintext.getBytes(encoding));
byte rawByte[] = msgDigest.digest();
hashValue = (new BASE64Encoder()).encode(rawByte);
} catch (NoSuchAlgorithmException e) {
System.out.println("No Such Algorithm Exists");
} catch (UnsupportedEncodingException e) {
System.out.println("The Encoding Is Not Supported");
}
return hashValue;
}
@Path("authenticate")
@POST
public Response authenticate(@FormParam("username") String userID,
@FormParam("password") String password) {
/*
* This method authenticates the user
*/
String msg = "false";
try {
DBCollection collection = db.getCollection("users");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("username", userID);
BasicDBObject keys = new BasicDBObject();
keys.put("password", 1);
DBCursor cursor = collection.find(searchQuery, keys);
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
String result = obj.getString("password");
System.out.println("function=" + encryptPassword(password, "SHA-1", "UTF-8") + "from database=" + result);
if (result.equals(encryptPassword(password, "SHA-1", "UTF-8"))) {
msg = "true";
}
}
} catch (UnknownHostException e) {
Response.status(500);
} catch (MongoException e) {
Response.status(500);
} catch (Exception e) {
// TODO Auto-generated catch block
Response.status(500);
}
return Response.status(200).entity(msg).build();
}
// @Path("user_info")
// @POST
// public Response insert(@FormParam("username") String userID,
// @FormParam("name") String name, @FormParam("phone") String phone,
// @FormParam("address") String address, @FormParam("gender") String gender,
// @FormParam("dob") String dob) {
//
// /*
// * Stores user's personal information in the database
// */
//
// try {
//
//
// DBCollection collection = db.getCollection("users");
// BasicDBObject document = new BasicDBObject();
//
// document.put("username", userID);
// document.put("name", name);
// document.put("address", address); //HTML5 Geolocation API can also be
// used
// document.put("gender", gender);
// document.put("phone", phone);
// document.put("dob", dob);
//
// collection.insert(document);
//
// } catch (MongoException e) {
// Response.status(500);
// }
//
// return Response.status(200).entity("Inserted").build();
//
//
// }
//
@GET
@Path("/user_details/{username}")
@Produces("application/json")
public Response showUserDetails(@PathParam("username") String username) {
/*
* Displays information for a user
*/
String msg = "";
try {
BasicDBObject searchQuery = new BasicDBObject();
DBCollection collection = db.getCollection("users");
searchQuery.put("username",
java.util.regex.Pattern.compile(username));
DBCursor cursor = collection.find(searchQuery);
if (cursor.hasNext() == false) {
msg = "null";
return Response.status(200).entity(msg).build();
}
while (cursor.hasNext()) {
msg += cursor.next();
}
} catch (MongoException e) {
Response.status(500);
}
return Response.status(200).entity(msg).build();
}
@GET
@Path("/user_available/{username}")
@Produces("application/json")
public Response isUserAvailable(@PathParam("username") String username) {
/*
* checks if use is available
*/
String msg = "";
try {
BasicDBObject searchQuery = new BasicDBObject();
DBCollection collection = db.getCollection("users");
searchQuery.put("username",
username);
DBCursor cursor = collection.find(searchQuery);
if (cursor.hasNext() == false) {
msg = "null";
return Response.status(200).entity(msg).build();
}
while (cursor.hasNext()) {
msg += cursor.next();
}
} catch (MongoException e) {
Response.status(500);
}
return Response.status(200).entity(msg).build();
}
@GET
@Path("/user_search/{data}")
@Produces("application/json")
public Response searchUser(@PathParam("data") String data) {
/*
* Displays information for a user
*/
String msg = "";
try {
DBCollection collection = db.getCollection("users");
List<BasicDBObject> searchQuery = new ArrayList<BasicDBObject>();
searchQuery.add(new BasicDBObject("username", data));
searchQuery.add(new BasicDBObject("email", data));
searchQuery.add(new BasicDBObject("zipcode", data));
searchQuery.add(new BasicDBObject("name", data));
BasicDBObject sQuery = new BasicDBObject();
sQuery.put("$or", searchQuery);
DBCursor cursor = collection.find(sQuery);
if (cursor.hasNext() == false) {
msg = "null";
return Response.status(200).entity(msg).build();
}
while (cursor.hasNext()) {
msg += cursor.next();
}
} catch (MongoException e) {
Response.status(500);
}
return Response.status(200).entity(msg).build();
}
@GET
@Path("/user_details/all")
@Produces("application/json")
public Response showAllUserDetails() {
/*
* Displays information of all users
*/
String msg = "[";
try {
DBCollection collection = db.getCollection("users");
DBCursor cursor = collection.find();
if (cursor.hasNext() == false) {
msg = "null";
}
while (cursor.hasNext()) {
msg += cursor.next() + ",";
}
} catch (Exception e) {
}
msg = msg.substring(0, msg.length() - 1);
msg += "]";
return Response.status(200).entity(msg).build();
}
@Path("updateuser")
@POST
public Response update(@FormParam("username") String username,
@FormParam("name") String name,
@FormParam("zip") String zip,
@FormParam("email") String email) {
/*
* Stores user's personal information in the database
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject newDocument = new BasicDBObject().append("$set",
new BasicDBObject().append("name", name).append("email", email).append("zipcode", zip));
System.out.println(newDocument);
collection.update(
new BasicDBObject().append("username", username),
newDocument);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
@Path("change_picture")
@POST
public Response change_picture(@FormParam("username") String username,
@FormParam("url") String url)
{
/*
* Stores user's personal information in the database
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject newDocument = new BasicDBObject().append("$set",
new BasicDBObject().append("picture", url));
collection.update(
new BasicDBObject().append("username", username),
newDocument);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
@Path("status")
@POST
public Response updateStatus(@FormParam("username") String username,
@FormParam("status_txt") String status_txt )
{
/*
* Add a new status to user's database
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject update = new BasicDBObject();
update.put("username", username);
BasicDBObject document = new BasicDBObject();
document.put("text", status_txt);
document.put("date", new Date().toString());
BasicDBObject temp = new BasicDBObject();
temp.put("$push", new BasicDBObject("status", document));
collection.update(update, temp, true, true);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
@GET
@Path("delete_status/{username}/{date}")
@Produces("application/json")
public Response delete_userstatus(@PathParam("date") String date, @PathParam("username") String username) {
/*
* This method deletes a particular status entry from user
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject update = new BasicDBObject();
update.put("username", username);
// check if the entry is not a duplicate
BasicDBObject document = new BasicDBObject();
document.put("date", date);
BasicDBObject temp = new BasicDBObject();
temp.put("$pull", new BasicDBObject("status", document));
collection.update(update, temp, true, true);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
@GET
@Path("deleteuser/{username}")
@Produces("application/json")
public Response deleteUser(@PathParam("username") String username) {
/*
* This method deletes a particular crop entry
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject searchquery = new BasicDBObject();
searchquery.put("username", username);
collection.remove(searchquery);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
// @POST
// @Path("/upload")
// @Consumes("multipart/form-data")
// public Response uploadFile(@MultipartForm FileUploadForm form) {
//
// String fileName = "/home/hilaykhatri/test211.txt";
//
// try {
// writeFile(form.getData(), fileName);
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// System.out.println("Done");
//
// return Response.status(200)
// .entity("uploadFile is called, Uploaded file name : " +
// fileName).build();
//
// }
//
// // save to somewhere
// private void writeFile(byte[] content, String filename) throws
// IOException {
//
//
//
// DBCollection collection = db.getCollection("images");
//
//
//
// // create a "photo" namespace
// GridFS gfsPhoto = new GridFS(db, "photo");
//
// // get image file from local drive
// GridFSInputFile gfsFile = gfsPhoto.createFile(content);
//
// // set a new filename for identify purpose
// gfsFile.setFilename("hilay");
//
// // save the image file into mongoDB
// gfsFile.save();
//
// // print the result
// DBCursor cursor = gfsPhoto.getFileList();
// while (cursor.hasNext()) {
// System.out.println(cursor.next());
// }
//
// // get image file by it's filename
// GridFSDBFile imageForOutput = gfsPhoto.findOne("hilay");
//
// // save it into a new image file
// imageForOutput.writeTo("/home/hilaykhatri/test1hilay.txt");
//
// System.out.println("Done");
//
// }
@GET
@Path("/userCropSearch/{cropname}")
@Produces("application/json")
public Response showUserByCrop(@PathParam("cropname") String cropname) {
/*
* Displays information for a user
*/
String msg = "[";
try {
BasicDBObject searchQuery = new BasicDBObject();
BasicDBObject keys = new BasicDBObject();
DBCollection collection = db.getCollection("users");
keys.put("username", 1);
keys.put("email", 1);
keys.put("zipcode", 1);
keys.put("user_crops.crop_name", 1);
searchQuery.put("user_crops.crop_name",
java.util.regex.Pattern.compile(cropname));
DBCursor cursor = collection.find(searchQuery, keys);
if (cursor.hasNext() == false) {
msg = "null";
return Response.status(200).entity(msg).build();
}
while (cursor.hasNext()) {
msg += cursor.next() + ",";
}
} catch (MongoException e) {
Response.status(500);
}
msg = msg.substring(0, msg.length() - 1);
msg += "]";
return Response.status(200).entity(msg).build();
}
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
// Add a crop grown by user
@GET
@Path("create_usercrop/{username}/{name}/{quantity}/{date}/{comment}")
@Produces("application/json")
public Response addusercrop(
@PathParam("name") String name,
@PathParam("username") String username,
@PathParam("quantity") String quantity,
@PathParam("date") String date,
@PathParam("comment") String comment) {
try {
DBCollection collection = db.getCollection("users");
BasicDBObject update = new BasicDBObject();
update.put("username", username);
BasicDBObject document = new BasicDBObject();
document.put("crop_name", name);
document.put("crop_expected_quantity", quantity);
document.put("crop_harvest_date",date);
document.put("comments",comment);
BasicDBObject temp = new BasicDBObject();
temp.put("$push", new BasicDBObject("user_crops", document));
collection.update(update, temp, true, true);
return Response.status(200).entity("success").build();
}
catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
// Delete a crop grown by user
@GET
@Path("delete_usercrop/{username}/{crop_name}")
@Produces("application/json")
public Response delete_usercrop(@PathParam("crop_name") String crop_name, @PathParam("username") String username) {
/*
* This method deletes a particular crop entry
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject update = new BasicDBObject();
update.put("username", username);
// check if the entry is not a duplicate
BasicDBObject document = new BasicDBObject();
document.put("crop_name", crop_name);
BasicDBObject temp = new BasicDBObject();
temp.put("$pull", new BasicDBObject("user_crops", document));
collection.update(update, temp, true, true);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
//Update an existing crop grown by user
@GET
@Path("update_usercrop/{username}/{name}/{quantity}/{date}/{comment}")
@Produces("application/json")
public Response updateusercrop(
@PathParam("name") String name,
@PathParam("username") String username,
@PathParam("quantity") String quantity,
@PathParam("date") String date,
@PathParam("comment") String comment) {
try{
DBCollection collection = db.getCollection("users");
BasicDBObject update = new BasicDBObject();
update.put("username", username);
BasicDBObject document = new BasicDBObject();
document.put("crop_name", name);
BasicDBObject temp = new BasicDBObject();
temp.put("$pull", new BasicDBObject("user_crops", document));
collection.update(update, temp, true, true);
Thread.sleep(3000);
DBCollection collection1 = db.getCollection("users");
BasicDBObject update1 = new BasicDBObject();
update1.put("username", username);
BasicDBObject document1 = new BasicDBObject();
document1.put("crop_name", name);
document1.put("crop_expected_quantity", quantity);
document1.put("crop_harvest_date",date);
document1.put("comments",comment);
BasicDBObject temp1 = new BasicDBObject();
temp1.put("$push", new BasicDBObject("user_crops", document1));
collection1.update(update1, temp1, true, true);
return Response.status(503).entity("success").build();
} catch(Exception E){
return Response.status(503).entity("failed").build();
}
}
// Crops API===============================================
@GET
@Path("/crop_search/{crop_name}")
@Produces("application/json")
public Response searchCrop(@PathParam("crop_name") String crop_name) {
/*
* Displays information for a user
*/
String msg ="";
try {
DBCollection collection = db.getCollection("crop_details");
BasicDBObject sq = new BasicDBObject();
sq.put("crop_name",java.util.regex.Pattern.compile(crop_name));
DBCursor cursor = collection.find(sq);
if(cursor.hasNext() == false)
{
msg = "null";
return Response.status(200).entity(msg).build();
}
while (cursor.hasNext()) {
msg += cursor.next();
}
} catch (MongoException e) {
Response.status(500);
}
return Response.status(200).entity(msg).build();
}
@POST
@Path("create_crop")
@Produces("application/json")
public Response addcrop(
@FormParam("name") String crop_name,
@FormParam("description") String description) {
/*
* Adds a new crop entry to the database.
*/
try {
DBCollection collection = db.getCollection("crop_details");
// check if the entry is not a duplicate
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("crop_name", crop_name);
DBCursor cursor = collection.find(searchQuery);
if (cursor.hasNext()) {
return Response
.status(403)
.entity("entry already exists, choose to update instead")
.build();
} else {
BasicDBObject document = new BasicDBObject();
document.put("crop_name", crop_name);
document.put("crop_description", description);
//document.put("image",image);
collection.insert(document);
return Response.status(200).entity("success").build();
}
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
@POST
@Path("updatecrop")
@Produces("application/json")
public Response updatecrop(
@FormParam("crop_name") String crop_name,
@FormParam("description") String description) {
/*
* This method returns the list of all the crops grown by a
particular
* user
*/
try {
DBCollection collection = db.getCollection("crop_details");
BasicDBObject newDocument = new BasicDBObject().append(
"$set",
new BasicDBObject().append("crop_description",
description));
collection.update(
new BasicDBObject().append("crop_name", crop_name),
newDocument);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
@GET
@Path("deletecrop/{crop_name}")
@Produces("application/json")
public Response deletecrop(@PathParam("crop_name") String crop_name) {
/*
* This method deletes a particular crop entry
*/
try {
DBCollection collection = db.getCollection("crop_details");
BasicDBObject searchquery = new BasicDBObject();
searchquery.put("crop_name", crop_name);
collection.remove(searchquery);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
@GET
@Path("crop_details/all")
@Produces("application/json")
public Response dashboard() {
/*
* This method returns the list of all the crops that are in the
* database
*/
String msg = "[";
try {
DBCollection collection = db.getCollection("crop_details");
DBCursor cursor = collection.find();
if (cursor.hasNext() == false) {
msg = "null";
}
while (cursor.hasNext()) {
msg += cursor.next() + ",";
}
} catch (Exception e) {
}
msg = msg.substring(0, msg.length() - 1);
msg += "]";
return Response.status(200).entity(msg).build();
}
// Geolocation Based API
@GET
@Path("/search/{zipcode}/{distance}")
@Produces("application/json")
public Response search_crop(@PathParam("zipcode") String zipcode, @PathParam("distance") String distance)
{
/*
* Displays all the users which are within the given radius
*/
String URI = "http://api.geonames.org/findNearbyPostalCodesJSON?";
String RESTCall ="";
String res ="";
String result="";
try {
RESTCall = URI + "formatted=true" + "&postalcode=" + zipcode + "&country=US&" + "radius=" + distance + "&username=gardenshift&" +"style=full";
URL url = new URL(RESTCall);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((res = in.readLine()) != null) {
result += res;
}
} catch (IOException e) {
// TODO Auto-generated catch block
Response.status(500);
}
return Response.status(200).entity(result).build();
}
@GET
@Path("/search/{zipcode}/{distance}/{cropname}")
@Produces("application/json")
public Response search_user_Crop(@PathParam("zipcode") String zipcode, @PathParam("distance") String distance, @PathParam("cropname") String cropname) throws Exception
{
/*
* Displays all the users which are within the given radius
*/
String URI = "http://api.geonames.org/findNearbyPostalCodesJSON?";
String RESTCall ="";
String res ="";
String result="";
RESTCall = URI + "formatted=true" + "&postalcode=" + zipcode + "&country=US&" + "radius=" + distance + "&username=gardenshift&" +"style=full";
URL url = new URL(RESTCall);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((res = in.readLine()) != null) {
result += res;
}
ArrayList<String> zip = new ArrayList();
JsonElement json = new JsonParser().parse(result);
JsonObject obj= json.getAsJsonObject();
JsonArray jarray = obj.getAsJsonArray("postalCodes");
for( int i=0; i < obj.getAsJsonArray("postalCodes").size(); i++)
{
JsonObject jobject = jarray.get(i).getAsJsonObject();
String result1 = jobject.get("postalCode").getAsString();
zip.add(result1);
}
String msg = "[";
BasicDBObject keys = new BasicDBObject();
DBCollection collection = db.getCollection("users");
keys.put("username", 1);
keys.put("email", 1);
keys.put("zipcode", 1);
keys.put("user_crops.crop_name", 1);
List<BasicDBObject> searchQuery = new ArrayList<BasicDBObject>();
BasicDBObject filteredZip = new BasicDBObject();
filteredZip.put("zipcode", new BasicDBObject("$in", zip) );
searchQuery.add(new BasicDBObject("user_crops.crop_name",java.util.regex.Pattern.compile(cropname)));
searchQuery.add(filteredZip);
BasicDBObject sQuery = new BasicDBObject();
sQuery.put("$and", searchQuery);
DBCursor cursor = collection.find(sQuery, keys);
if(cursor.hasNext() == false)
{
return Response.status(200).entity("null").build();
}
while (cursor.hasNext()) {
msg = msg + cursor.next() + ",";
}
msg = msg.substring(0, msg.length() - 1);
msg += "]";
return Response.status(200).entity(msg).build();
}
@Path("send_notification")
@POST
public Response send_notification(@FormParam("username") String username,
@FormParam("type") String type, @FormParam("from") String from,
@FormParam("text") String text) {
/*
* sends a notification to the user.
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject sendNotif = new BasicDBObject();
sendNotif.put("username", username);
BasicDBObject document = new BasicDBObject();
document.put("type", type);
document.put("from",from);
document.put("text",text);
document.put("timestamp",System.currentTimeMillis());
BasicDBObject temp = new BasicDBObject();
temp.put("$push", new BasicDBObject("notifications_unread", document));
collection.update(sendNotif, temp, true, true);
return Response.status(200).entity("success").build();
}catch(Exception e){return Response.status(500).entity("failed").build();}
}
@Path("update_notification_to_read/{username}/{timestamp}")
@GET
public Response update_notification(@PathParam("username") String username,
@PathParam("timestamp") Long timestamp
) {
/*
* sends a notification to the user.
*/
try {
BasicDBObject searchQuery = new BasicDBObject();
BasicDBObject keys = new BasicDBObject();
DBCollection collection = db.getCollection("users");
keys.put("notifications_unread", 1);
searchQuery.put("username",username);
DBCursor cursor = collection.find(searchQuery, keys);
while (cursor.hasNext()) {
BasicDBObject result = (BasicDBObject) cursor.next();
int i = result.size();
@SuppressWarnings("unchecked")
ArrayList<BasicDBObject> notifs =
(ArrayList<BasicDBObject>)result.get("notifications_unread"); // * See Note
for(BasicDBObject embedded : notifs){
Long ts = (Long)embedded.get("timestamp");
if(ts.equals(timestamp)){
String from = (String)embedded.get("from");
String type = (String)embedded.get("type");
String text = (String)embedded.get("text");
Mongo mongo1 = new Mongo("127.3.119.1", 27017);
//Mongo mongo1 = new Mongo("localhost",27017);
DB db1 = mongo1.getDB("gardenshift");
db1.authenticate("admin", "redhat".toCharArray());
DBCollection collection1 = db1.getCollection("users");
BasicDBObject updNotif = new BasicDBObject();
updNotif.put("username", username);
BasicDBObject document1 = new BasicDBObject();
document1.put("type", type);
document1.put("from",from);
document1.put("text",text);
document1.put("timestamp",timestamp);
BasicDBObject temp = new BasicDBObject();
temp.put("$push", new BasicDBObject("notifications_read", document1));
collection.update(updNotif, temp, true, true);
// Mongo mongo2 = new Mongo("127.3.119.1", 27017);
// //Mongo mongo2 = new Mongo("localhost",27017);
// DB db2 = mongo1.getDB("gardenshift");
// db2.authenticate("admin", "redhat".toCharArray());
DBCollection collection2 = db.getCollection("users");
BasicDBObject updateNotif = new BasicDBObject();
updateNotif.put("username", username);
BasicDBObject document2 = new BasicDBObject();
document2.put("timestamp", timestamp);
BasicDBObject temp1 = new BasicDBObject();
temp1.put("$pull", new BasicDBObject("notifications_unread", document2));
collection2.update(updateNotif, temp1, true, true);
}
}
}
return Response.status(200).entity("success").build();
}catch(Exception e){return Response.status(500).entity(e).build();}
}
@Path("get_notification_unread/{username}")
@GET
public Response get_notification_unread(@PathParam("username") String username) {
/*
* gives all the unread notifications of a user.
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject getNotif = new BasicDBObject();
getNotif.put("username", username);
BasicDBObject keys = new BasicDBObject();
keys.put("notifications_unread" ,1 );
DBCursor cursor = collection.find( getNotif, keys);
String msg = "";
while (cursor.hasNext()) {
msg += cursor.next() ;
}
return Response.status(200).entity(msg).build();
}catch(Exception e){return Response.status(500).entity("failed").build();}
}
@Path("get_notification_read/{username}")
@GET
public Response get_notification_read(@PathParam("username") String username) {
/*
* gives all the unread notifications of a user.
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject getNotif = new BasicDBObject();
getNotif.put("username", username);
BasicDBObject keys = new BasicDBObject();
keys.put("notifications_read" ,1 );
DBCursor cursor = collection.find( getNotif, keys);
String msg = "";
while (cursor.hasNext()) {
msg += cursor.next() ;
}
return Response.status(200).entity(msg).build();
}catch(Exception e){return Response.status(500).entity("failed").build();}
}
@Path("delete_notification_read/{username}/{timestamp}")
@GET
public Response delete_notification_read(@PathParam("username") String username,@PathParam("timestamp") Long timestamp) {
/*
* deletes a particular read notification of a user.
*/
try {
DBCollection collection2 = db.getCollection("users");
BasicDBObject updateNotif = new BasicDBObject();
updateNotif.put("username", username);
BasicDBObject document2 = new BasicDBObject();
document2.put("timestamp", timestamp);
BasicDBObject temp1 = new BasicDBObject();
temp1.put("$pull", new BasicDBObject("notifications_read", document2));
collection2.update(updateNotif, temp1, true, true);
return Response.status(200).entity("success").build();
}catch(Exception e){return Response.status(500).entity("failed").build();}
}
@Path("delete_notification_unread/{username}/{timestamp}")
@GET
public Response delete_notification_unread(@PathParam("username") String username,@PathParam("timestamp") Long timestamp) {
/*
* deletes a particular unread notification of a user.
*/
try {
DBCollection collection2 = db.getCollection("users");
BasicDBObject updateNotif = new BasicDBObject();
updateNotif.put("username", username);
BasicDBObject document2 = new BasicDBObject();
document2.put("timestamp", timestamp);
BasicDBObject temp1 = new BasicDBObject();
temp1.put("$pull", new BasicDBObject("notifications_unread", document2));
collection2.update(updateNotif, temp1, true, true);
return Response.status(200).entity("success").build();
}catch(Exception e){return Response.status(500).entity("failed").build();}
}
@Path("add_bulletin")
@POST
public Response add_bulletin(@FormParam("username") String username,@FormParam("text") String text) {
/*
* updates the bulletin.
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject sendNotif = new BasicDBObject();
sendNotif.put("username", username);
BasicDBObject document = new BasicDBObject();
document.put("text", text);
BasicDBObject temp = new BasicDBObject();
temp.put("$push", new BasicDBObject("bulletin", document));
collection.update(sendNotif, temp, true, true);
return Response.status(200).entity("success").build();
}catch(Exception e){return Response.status(500).entity("failed").build();}
}
@Path("flush_bulletin/{username}")
@GET
public Response flush_bulletin(@PathParam("username") String username) {
/*
* updates the bulletin.
*/
try {
BasicDBObject searchQuery = new BasicDBObject();
BasicDBObject keys = new BasicDBObject();
DBCollection collection = db.getCollection("users");
keys.put("bulletin", 1);
searchQuery.put("username",username);
DBCursor cursor = collection.find(searchQuery, keys);
while (cursor.hasNext()) {
BasicDBObject result = (BasicDBObject) cursor.next();
int i = result.size();
@SuppressWarnings("unchecked")
ArrayList<BasicDBObject> bulletins =
(ArrayList<BasicDBObject>)result.get("bulletin"); // * See Note
for(BasicDBObject embedded : bulletins){
String text = (String)embedded.get("text");
Mongo mongo1 = new Mongo("127.3.119.1", 27017);
//Mongo mongo1 = new Mongo("localhost",27017);
DB db1 = mongo1.getDB("gardenshift");
db1.authenticate("admin", "redhat".toCharArray());
DBCollection collection1 = db1.getCollection("users");
BasicDBObject updNotif = new BasicDBObject();
updNotif.put("username", username);
BasicDBObject document1 = new BasicDBObject();
document1.put("text",text);
BasicDBObject temp = new BasicDBObject();
temp.put("$push", new BasicDBObject("bulletin_archive", document1));
collection.update(updNotif, temp, true, true);
// Mongo mongo2 = new Mongo("127.3.119.1", 27017);
// //Mongo mongo2 = new Mongo("localhost",27017);
// DB db2 = mongo1.getDB("gardenshift");
// db2.authenticate("admin", "redhat".toCharArray());
DBCollection collection2 = db.getCollection("users");
BasicDBObject updateNotif = new BasicDBObject();
updateNotif.put("username", username);
BasicDBObject document2 = new BasicDBObject();
BasicDBObject temp1 = new BasicDBObject();
temp1.put("$pull", new BasicDBObject("bulletin",document1));
collection2.update(updateNotif, temp1, true, true);
}
}
return Response.status(200).entity("success").build();
}catch(Exception e){return Response.status(500).entity("failed").build();}}
@Path("get_bulletin/{username}")
@GET
public Response get_bulletin(@PathParam("username") String username) {
/*
* gives all the bulletin notifications of a user.
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject getNotif = new BasicDBObject();
getNotif.put("username", username);
BasicDBObject keys = new BasicDBObject();
keys.put("bulletin" ,1 );
DBCursor cursor = collection.find( getNotif, keys);
String msg = "";
while (cursor.hasNext()) {
msg += cursor.next() ;
}
return Response.status(200).entity(msg).build();
}catch(Exception e){return Response.status(500).entity("failed").build();}
}
@Path("get_bulletin_archive/{username}")
@GET
public Response get_bulletin_archive(@PathParam("username") String username) {
/*
* gives all the bulletin archive notifications of a user.
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject getNotif = new BasicDBObject();
getNotif.put("username", username);
BasicDBObject keys = new BasicDBObject();
keys.put("bulletin_archive" ,1 );
DBCursor cursor = collection.find( getNotif, keys);
String msg = "";
while (cursor.hasNext()) {
msg += cursor.next() ;
}
return Response.status(200).entity(msg).build();
}catch(Exception e){return Response.status(500).entity("failed").build();}
}
@Path("get_bulletin_count/{username}")
@GET
public Response get_bulletin_count(@PathParam("username") String username) {
/*
* gives the bulletin notifications count of a user.
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject getNotif = new BasicDBObject();
getNotif.put("username", username);
BasicDBObject keys = new BasicDBObject();
keys.put("bulletin" ,1 );
DBCursor cursor = collection.find( getNotif, keys);
int count=0;
while (cursor.hasNext()) {
count+=1 ;
}
return Response.status(200).entity(count).build();
}catch(Exception e){return Response.status(500).entity("null").build();}
}
@Path("add_friends")
@POST
public Response addfriends(@FormParam("username") String username,
@FormParam("friend_name") String friend_name) {
/*
* Add a new friend request to user's database
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject update = new BasicDBObject();
update.put("username", friend_name);
BasicDBObject document = new BasicDBObject();
document.put("friends_username", username);
document.put("status", "pending");
BasicDBObject temp = new BasicDBObject();
temp.put("$push", new BasicDBObject("friends", document));
collection.update(update, temp, true, true);
BasicDBObject update1 = new BasicDBObject();
update1.put("username", username);
BasicDBObject document1 = new BasicDBObject();
document1.put("friends_username", friend_name);
document1.put("status", "pending");
BasicDBObject temp1 = new BasicDBObject();
temp1.put("$push", new BasicDBObject("friends", document1));
collection.update(update1, temp1, true, true);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
@Path("accept_friends")
@POST
public Response acceptFriends(@FormParam("username") String username,
@FormParam("friend_name") String friend_name) {
/*
* Accepts invitation of a friend and updates the user's database to
* reflect the change in the friends
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject update = new BasicDBObject();
update.put("username", username);
BasicDBObject document = new BasicDBObject();
document.put("friends_username", friend_name);
BasicDBObject temp = new BasicDBObject();
temp.put("$pull", new BasicDBObject("friends", document));
collection.update(update, temp, true, true);
BasicDBObject update1 = new BasicDBObject();
update1.put("username", username);
BasicDBObject document1 = new BasicDBObject();
document1.put("friends_username", friend_name);
document1.put("status", "accepted");
BasicDBObject temp1 = new BasicDBObject();
temp1.put("$push", new BasicDBObject("friends", document1));
collection.update(update1, temp1, true, true);
BasicDBObject update2 = new BasicDBObject();
update2.put("username", friend_name);
BasicDBObject document2 = new BasicDBObject();
document2.put("friends_username", username);
document2.put("status", "accepted");
BasicDBObject temp2 = new BasicDBObject();
temp2.put("$push", new BasicDBObject("friends", document2));
collection.update(update2, temp2, true, true);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
@Path("add_feedback")
@POST
public Response addFeedback(@FormParam("from") String from, @FormParam("to") String to,
@FormParam("status_txt") String status_txt )
{
/*
* Add a new status to user's database
*/
try {
DBCollection collection = db.getCollection("users");
BasicDBObject update = new BasicDBObject();
update.put("username", to);
BasicDBObject document = new BasicDBObject();
document.put("text", status_txt);
document.put("from", from);
BasicDBObject temp = new BasicDBObject();
temp.put("$push", new BasicDBObject("feedback", document));
collection.update(update, temp, true, true);
return Response.status(200).entity("success").build();
} catch (Exception e) {
return Response.status(503).entity("failed").build();
}
}
}
| false | true | public Response adduser(@FormParam("username") String userID,
@FormParam("password") String password,
@FormParam("email") String emailAdd) {
/*
* Adds a new username to the database.
*/
Boolean userExists = false; // See if username already exists
Boolean emailExists = false; // See if email already exists
Boolean validEmail = false; // See if valid email address
Boolean validUsername = false; // See if valid email address
String user, email; // Stores username and email retrieved from mongoDB
// for verification
String msg = ""; // Error message
try {
// userClass newUser = new userClass();
validEmail = isValidEmailAddress(emailAdd);
if (userID.length() < 6) {
msg = "Username should not be less than 6 characters";
return Response.status(200).entity(msg).build();
}
if (validEmail) {
DBCollection collection = db.getCollection("users");
BasicDBObject document = new BasicDBObject();
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
user = obj.getString("username");
email = obj.getString("email");
if (user.equals(userID)) {
userExists = true;
msg = "failure-user already exists";
}
if (email.equals(emailAdd)) {
emailExists = true;
msg = "failure-email already exists";
}
}
// If username or email is unique, create a new user
if (userExists == false && emailExists == false) {
msg = "Success-user created";
document.put("username", userID);
document.put("password",
encryptPassword(password, "SHA-1", "UTF-8"));
document.put("creation_date", new Date().toString());
document.put("email", emailAdd);
document.put("name", "");
document.put("picture", "http://www.worldbiofuelsmarkets.com/EF/Images/blank_profile_pic.jpg");
document.put("zipcode", ""); // HTML5 Geolocation API can
// also be used
BasicDBObject feedback = new BasicDBObject();
feedback.put("from", "");
feedback.put("text", "");
document.put("feedback", feedback);
document.put("notifications_read", new ArrayList());
document.put("notifications_unread", new ArrayList());
document.put("bulletin", new ArrayList());
document.put("bulletin_archive", new ArrayList());
BasicDBObject friends = new BasicDBObject();
friends.put("friends_username", "");
friends.put("status", "");
friends.put("friends", friends);
// BasicDBObject user_crops = new BasicDBObject();
// user_crops.put("crop_name", "");
// user_crops.put("crop_expected_quantity", "");
// user_crops.put("crop_harvest_date", "");
// user_crops.put("crop_harvested", "");
// user_crops.put("pictures", "");
// user_crops.put("videos", "");
// user_crops.put("comments", "");
// document.put("user_crops", user_crops);
document.put("user_crops", new ArrayList());
collection.insert(document);
}
}
else {
msg = "Invalid Email Address";
return Response.status(200).entity(msg).build();
}
} catch (UnknownHostException e) {
Response.status(500);
} catch (MongoException e) {
Response.status(500);
} catch (Exception e) {
// TODO Auto-generated catch block
Response.status(500);
}
return Response.status(200).entity(msg).build();
}
| public Response adduser(@FormParam("username") String userID,
@FormParam("password") String password,
@FormParam("email") String emailAdd) {
/*
* Adds a new username to the database.
*/
Boolean userExists = false; // See if username already exists
Boolean emailExists = false; // See if email already exists
Boolean validEmail = false; // See if valid email address
Boolean validUsername = false; // See if valid email address
String user, email; // Stores username and email retrieved from mongoDB
// for verification
String msg = ""; // Error message
try {
// userClass newUser = new userClass();
validEmail = isValidEmailAddress(emailAdd);
if (userID.length() < 6) {
msg = "Username should not be less than 6 characters";
return Response.status(200).entity(msg).build();
}
if (validEmail) {
DBCollection collection = db.getCollection("users");
BasicDBObject document = new BasicDBObject();
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
user = obj.getString("username");
email = obj.getString("email");
if (user.equals(userID)) {
userExists = true;
msg = "failure-user already exists";
}
if (email.equals(emailAdd)) {
emailExists = true;
msg = "failure-email already exists";
}
}
// If username or email is unique, create a new user
if (userExists == false && emailExists == false) {
msg = "Success-user created";
document.put("username", userID);
document.put("password",
encryptPassword(password, "SHA-1", "UTF-8"));
document.put("creation_date", new Date().toString());
document.put("email", emailAdd);
document.put("name", "");
document.put("status", new ArrayList());
document.put("picture", "http://www.worldbiofuelsmarkets.com/EF/Images/blank_profile_pic.jpg");
document.put("zipcode", ""); // HTML5 Geolocation API can
// also be used
BasicDBObject feedback = new BasicDBObject();
feedback.put("from", "");
feedback.put("text", "");
document.put("feedback", feedback);
document.put("notifications_read", new ArrayList());
document.put("notifications_unread", new ArrayList());
document.put("bulletin", new ArrayList());
document.put("bulletin_archive", new ArrayList());
BasicDBObject friends = new BasicDBObject();
friends.put("friends_username", "");
friends.put("status", "");
document.put("friends", friends);
// BasicDBObject user_crops = new BasicDBObject();
// user_crops.put("crop_name", "");
// user_crops.put("crop_expected_quantity", "");
// user_crops.put("crop_harvest_date", "");
// user_crops.put("crop_harvested", "");
// user_crops.put("pictures", "");
// user_crops.put("videos", "");
// user_crops.put("comments", "");
// document.put("user_crops", user_crops);
document.put("user_crops", new ArrayList());
collection.insert(document);
}
}
else {
msg = "Invalid Email Address";
return Response.status(200).entity(msg).build();
}
} catch (UnknownHostException e) {
Response.status(500);
} catch (MongoException e) {
Response.status(500);
} catch (Exception e) {
// TODO Auto-generated catch block
Response.status(500);
}
return Response.status(200).entity(msg).build();
}
|
diff --git a/src/net/czlee/debatekeeper/DebateFormatBuilderFromXml.java b/src/net/czlee/debatekeeper/DebateFormatBuilderFromXml.java
index 3d686b5..8b20534 100644
--- a/src/net/czlee/debatekeeper/DebateFormatBuilderFromXml.java
+++ b/src/net/czlee/debatekeeper/DebateFormatBuilderFromXml.java
@@ -1,756 +1,758 @@
/*
* Copyright (C) 2012 Chuan-Zheng Lee
*
* This file is part of the Debatekeeper app, which is licensed under the
* GNU General Public Licence version 3 (GPLv3). You can redistribute
* and/or modify it under the terms of the GPLv3, and you must not use
* this file except in compliance with the GPLv3.
*
* This app 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 Licence for more details.
*
* You should have received a copy of the GNU General Public Licence
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.czlee.debatekeeper;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import net.czlee.debatekeeper.DebateFormatBuilder.DebateFormatBuilderException;
import net.czlee.debatekeeper.SpeechFormat.CountDirection;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import android.content.Context;
import android.util.Log;
import android.util.Xml;
import android.util.Xml.Encoding;
/**
* DebateFormatBuilderFromXml uses the information in an XML file to build a {@link DebateFormat}.
*
* @author Chuan-Zheng Lee
* @since 2012-06-15
*/
public class DebateFormatBuilderFromXml {
private final Context mContext;
private final DebateFormatBuilder mDfb;
private final ArrayList<String> mErrorLog = new ArrayList<String>();
private String mSchemaVersion = null;
private final String DEBATING_TIMER_URI;
private static final String MAXIMUM_SCHEMA_VERSION = "1.0";
public DebateFormatBuilderFromXml(Context context) {
mContext = context;
mDfb = new DebateFormatBuilder(context);
DEBATING_TIMER_URI = context.getString(R.string.XmlUri);
}
//******************************************************************************************
// Private classes
//******************************************************************************************
private class DebateFormatXmlContentHandler implements ContentHandler {
// endElement should erase these (i.e. set them to null) so that they're only not null
// when we're inside one of these elements. NOTE however that they may be null even when
// we are inside one of these elements, if the element in question had an error. (We will
// still be between the relevant tags; there just won't be an active resource/
// speech format). That is:
// m*Ref is NOT null implies we are in * context
// but m*Ref is null does NOT imply we are NOT in * context
// and we are NOT in * context does NOT imply m*Ref is null
private String mCurrentSpeechFormatFirstPeriod = null;
private String mCurrentSpeechFormatRef = null;
private String mCurrentResourceRef = null;
private DebateFormatXmlSecondLevelContext mCurrentSecondLevelContext
= DebateFormatXmlSecondLevelContext.NONE;
private boolean mIsInRootContext = false;
@Override public void characters(char[] ch, int start, int length) throws SAXException {}
@Override public void endDocument() throws SAXException {}
@Override public void endPrefixMapping(String prefix) throws SAXException {}
@Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
@Override public void processingInstruction(String target, String data) throws SAXException {}
@Override public void setDocumentLocator(Locator locator) {}
@Override public void skippedEntity(String name) throws SAXException {}
@Override public void startDocument() throws SAXException {}
@Override public void startPrefixMapping(String prefix, String uri) throws SAXException {}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (!uri.equals(DEBATING_TIMER_URI))
return;
/**
* <debateformat name="something" schemaversion="1.0">
* End the root context.
*/
if (areEqual(localName, R.string.XmlElemNameRoot)) {
mIsInRootContext = false;
/** <resource ref="string">
* End the context.
*/
} else if (areEqual(localName, R.string.XmlElemNameResource)) {
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.NONE;
mCurrentResourceRef = null;
/** <speechtype ref="string" length="5:00" firstperiod="string" countdir="up">
* Set the first period, then end the context.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeechFormat)) {
try {
mDfb.setFirstPeriod(mCurrentSpeechFormatRef, mCurrentSpeechFormatFirstPeriod);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
try {
// If there isn't already a finish bell in this, add one and log the error.
if (!mDfb.hasFinishBellInSpeechFormat(mCurrentSpeechFormatRef)) {
logXmlError(R.string.XmlErrorSpeechFormatNoFinishBell, mCurrentSpeechFormatRef);
mDfb.addBellInfoToSpeechFormatAtFinish(mCurrentSpeechFormatRef, new BellInfo(0, 2), null);
}
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.NONE;
mCurrentSpeechFormatFirstPeriod = null;
mCurrentSpeechFormatRef = null;
/** <speeches>
* End the speeches context.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeechesList)) {
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.NONE;
}
/** <bell time="1:00" number="1" nextperiod="#stay" sound="#default" pauseonbell="true">
* Do nothing
*/
/** <period ref="something" desc="Human readable" bgcolor="#77ffcc00">
* Do nothing
*/
/** <include resource="reference">
* Do nothing
*/
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if (!uri.equals(DEBATING_TIMER_URI))
return;
/**
* <debateformat name="something" schemaversion="1.0">
*/
if (areEqual(localName, R.string.XmlElemNameRoot)) {
String name = getValue(atts, R.string.XmlAttrNameRootName);
if (name == null) {
logXmlError(R.string.XmlErrorRootNoName);
return;
}
mSchemaVersion = getValue(atts, R.string.XmlAttrNameRootSchemaVersion);
if (mSchemaVersion == null) {
logXmlError(R.string.XmlErrorRootNoSchemaVersion);
} else {
try {
if (!isSchemaSupported())
logXmlError(R.string.XmlErrorRootNewSchemaVersion, mSchemaVersion, MAXIMUM_SCHEMA_VERSION);
} catch (IllegalArgumentException e) {
logXmlError(R.string.XmlErrorRootInvalidSchemaVersion, mSchemaVersion);
}
}
mDfb.setDebateFormatName(name);
mIsInRootContext = true;
return;
}
// For everything else, we must be inside the root element.
// If we're not, refuse to do anything.
if (!mIsInRootContext) {
logXmlError(R.string.XmlErrorSomethingOutsideRoot);
return;
}
/** <resource ref="string">
* Create a reference with the reference as specified in 'ref'.
* Must not be inside a resource or speech format.
* 'ref' is mandatory.
*/
if (areEqual(localName, R.string.XmlElemNameResource)) {
// 1. Get the reference string.
String reference = getValue(atts, R.string.XmlAttrNameCommonRef);
if (reference == null) {
logXmlError(R.string.XmlErrorResourceNoRef);
return;
}
// 2. Check we're not inside any contexts.
// If we are, ignore and reset all contexts.
if (!assertNotInsideAnySecondLevelContextAndResetOtherwise()) {
logXmlError(R.string.XmlErrorResourceInsideContext, reference,
getCurrentSecondLevelContext().toString());
return;
}
// 3. Start a new resource
try {
mDfb.addNewResource(reference);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
return;
}
// If we succeeded in adding the resource, take note of this reference string for
// all this resource's sub-elements. (Don't do this if there was an error, so that
// sub-elements can be ignored.)
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.RESOURCE;
mCurrentResourceRef = reference;
/** <speechtype ref="string" length="5:00" firstperiod="string" countdir="up">
* Create a speech format.
* 'ref' and 'length' are mandatory.
* 'firstperiod' and 'countdir' are optional.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeechFormat)) {
// 1. Get the reference string. Mandatory; exit on error.
String reference = getValue(atts, R.string.XmlAttrNameCommonRef);
if (reference == null) {
logXmlError(R.string.XmlErrorSpeechFormatNoRef);
return;
}
// 2. Check we're not inside any contexts.
// If we are, ignore and reset all contexts.
if (!assertNotInsideAnySecondLevelContextAndResetOtherwise()) {
logXmlError(R.string.XmlErrorSpeechFormatInsideContext, reference,
getCurrentSecondLevelContext().toString());
return;
}
// 3. Get the length string, then convert it to seconds. Mandatory; exit on error.
// Take note of it, in case bells use "finish" as their bell time.
String lengthStr = getValue(atts, R.string.XmlAttrNameSpeechFormatLength);
long length = 0;
if (lengthStr == null) {
logXmlError(R.string.XmlErrorSpeechFormatNoLength, reference);
return;
}
try {
length = timeStr2Secs(lengthStr);
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorSpeechFormatInvalidLength, reference, lengthStr);
return;
}
// 4. Add the speech format.
try {
mDfb.addNewSpeechFormat(reference, length);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
return;
}
// 5. If we got this far, take note of this reference string for all this speech
// format's sub-elements. (Don't do this if there was an error, so that
// sub-elements can be ignored.)
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.SPEECH_FORMAT;
mCurrentSpeechFormatRef = reference;
// Now do the optional attributes...
// 6. Get the count direction, and set it if it's present
String countdir = getValue(atts, R.string.XmlAttrNameSpeechFormatCountDir);
if (countdir != null) {
try {
if (areEqualIgnoringCase(countdir,
R.string.XmlAttrValueSpeechFormatCountDirUp)) {
mDfb.setCountDirection(reference, CountDirection.COUNT_UP);
} else if (areEqualIgnoringCase(countdir,
R.string.XmlAttrValueSpeechFormatCountDirDown)) {
mDfb.setCountDirection(reference, CountDirection.COUNT_DOWN);
} else if (areEqualIgnoringCase(countdir,
R.string.XmlAttrValueSpeechFormatCountDirUser)) {
mDfb.setCountDirection(reference, CountDirection.COUNT_USER);
+ } else {
+ logXmlError(R.string.XmlErrorSpeechFormatInvalidCountDir, reference, countdir);
}
} catch (DebateFormatBuilderException e) {
logXmlError(R.string.XmlErrorSpeechFormatUnexpectedlyNotFound, reference);
}
}
// 7. Get the first period, and take note for later.
// We'll deal with it as we exit this element, because the period is defined
// inside the element.
mCurrentSpeechFormatFirstPeriod =
getValue(atts, R.string.XmlAttrNameSpeechFormatFirstPeriod);
/** <bell time="1:00" number="1" nextperiod="#stay" sound="#default" pauseonbell="true">
* Create a BellInfo.
* This must be inside a resource or speech format.
* 'time' is mandatory.
* All other attributes are optional.
*/
} else if (areEqual(localName, R.string.XmlElemNameBell)) {
// 1. Get the bell time. Mandatory; exit on error.
String timeStr = getValue(atts, R.string.XmlAttrNameBellTime);;
long time = 0;
boolean atFinish = false;
if (timeStr == null) {
logXmlError(R.string.XmlErrorBellNoTime, getCurrentContextAndReferenceStr());
return;
} else if (areEqualIgnoringCase(timeStr, R.string.XmlAttrValueBellTimeFinish)) {
time = 0; // will be overwritten addBellInfoToSpeechFormatAtFinish().
atFinish = true;
} else {
try {
time = timeStr2Secs(timeStr);
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorBellInvalidTime, getCurrentContextAndReferenceStr(), timeStr);
return;
}
}
// 2. Get the number of times to play, or default to 1.
String numberStr = getValue(atts, R.string.XmlAttrNameBellNumber);
int number = 1;
if (numberStr != null) {
try {
number = Integer.parseInt(numberStr);
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorBellInvalidNumber, getCurrentContextAndReferenceStr(), timeStr);
}
}
// 3. We now have enough information to create the bell.
BellInfo bi = new BellInfo(time, number);
// 4. Get the next period reference, or default to null
// "#stay" means null (i.e. leave unchanged)
String periodInfoRef = getValue(atts, R.string.XmlAttrNameBellNextPeriod);
if (periodInfoRef != null)
if (areEqualIgnoringCase(periodInfoRef, R.string.XmlAttrValueCommonStay))
periodInfoRef = null;
// 5. Get the sound to play, or default to the default
String bellSound = getValue(atts, R.string.XmlAttrNameBellSound);
if (bellSound != null) {
if (areEqualIgnoringCase(bellSound, R.string.XmlAttrValueCommonStay))
bellSound = null;
else if (areEqualIgnoringCase(bellSound, R.string.XmlAttrValueBellNextPeriodSilent))
bi.setSound(0);
else if (areEqualIgnoringCase(bellSound, R.string.XmlAttrValueCommonDefault));
// Do nothing
else
logXmlError(R.string.XmlErrorBellInvalidSound, getCurrentContextAndReferenceStr(), bellSound);
}
// 6. Determine whether to pause on this bell
String pauseOnBellStr = getValue(atts, R.string.XmlAttrNameBellPauseOnBell);
if (pauseOnBellStr != null) {
if (areEqualIgnoringCase(pauseOnBellStr, R.string.XmlAttrValueCommonTrue))
bi.setPauseOnBell(true);
else if (areEqualIgnoringCase(pauseOnBellStr, R.string.XmlAttrValueCommonFalse))
bi.setPauseOnBell(false);
else
logXmlError(R.string.XmlErrorBellInvalidPauseOnBell, getCurrentContextAndReferenceStr(), pauseOnBellStr);
}
// Finally, add the bell, but first check that the period info exists (and nullify
// if it doesn't, so that the bell still gets added)
try {
switch (getCurrentSecondLevelContext()) {
case RESOURCE:
if (mCurrentResourceRef == null) break;
if (periodInfoRef != null && !mDfb.hasPeriodInfoInResource(mCurrentResourceRef, periodInfoRef)) {
logXmlError(R.string.XmlErrorResourcePeriodInfoNotFound, periodInfoRef, mCurrentResourceRef);
periodInfoRef = null;
}
mDfb.addBellInfoToResource(mCurrentResourceRef, bi, periodInfoRef);
break;
case SPEECH_FORMAT:
if (mCurrentSpeechFormatRef == null) break;
if (periodInfoRef != null && !mDfb.hasPeriodInfoInSpeechFormat(mCurrentSpeechFormatRef, periodInfoRef)) {
logXmlError(R.string.XmlErrorSpeechFormatPeriodInfoNotFound, periodInfoRef, mCurrentSpeechFormatRef);
periodInfoRef = null;
}
if (atFinish)
mDfb.addBellInfoToSpeechFormatAtFinish(mCurrentSpeechFormatRef, bi, periodInfoRef);
else
mDfb.addBellInfoToSpeechFormat(mCurrentSpeechFormatRef, bi, periodInfoRef);
break;
default:
logXmlError(R.string.XmlErrorBellOutsideContext);
}
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
/** <period ref="something" desc="Human readable" bgcolor="#77ffcc00">
* Create a PeriodInfo.
* This must be inside a resource or speech format.
* 'ref' is mandatory.
* 'desc' and 'bgcolor' are optional.
*/
} else if (areEqual(localName, R.string.XmlElemNamePeriod)){
// 1. Get the reference. Mandatory; exit on error.
String reference = getValue(atts, R.string.XmlAttrNameCommonRef);
if (reference == null) {
logXmlError(R.string.XmlErrorPeriodNoRef, getCurrentContextAndReferenceStr());
return;
}
// 2. Get the description (implicitly default to null)
String description = getValue(atts, R.string.XmlAttrNamePeriodDesc);
if (description != null) {
if (areEqualIgnoringCase(description, R.string.XmlAttrValueCommonStay))
description = null;
}
// 3. Get the background colour (implicitly default to null)
String bgcolorStr = getValue(atts, R.string.XmlAttrNamePeriodBgcolor);
Integer backgroundColor = null;
if (bgcolorStr != null) {
if (areEqualIgnoringCase(bgcolorStr, R.string.XmlAttrValueCommonStay))
backgroundColor = null;
else if (bgcolorStr.startsWith("#")) {
try {
// We need to do it via BigInteger in order for large unsigned 32-bit
// integers to be parsed as unsigned integers.
backgroundColor = new BigInteger(bgcolorStr.substring(1), 16).intValue();
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorPeriodInvalidColor, reference, bgcolorStr);
}
} else {
logXmlError(R.string.XmlErrorPeriodInvalidColor, reference, bgcolorStr);
}
}
// 4. We now have enough information to make the PeriodInfo
PeriodInfo pi = new PeriodInfo(description, backgroundColor);
// Finally, add the period
try {
switch (getCurrentSecondLevelContext()) {
case RESOURCE:
if (mCurrentResourceRef != null)
mDfb.addPeriodInfoToResource(mCurrentResourceRef, reference, pi);
break;
case SPEECH_FORMAT:
if (mCurrentSpeechFormatRef != null)
mDfb.addPeriodInfoToSpeechFormat(mCurrentSpeechFormatRef, reference, pi);
break;
default:
logXmlError(R.string.XmlErrorPeriodOutsideContext, reference);
}
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
/** <include resource="reference">
* Include a resource in a speech format.
* This must be in a speech format.
* 'resource' is mandatory.
*/
} else if (areEqual(localName, R.string.XmlElemNameInclude)) {
// 1. Get the resource reference. Mandatory; exit on error.
String resourceRef = getValue(atts, R.string.XmlAttrNameIncludeResource);
if (resourceRef == null) {
logXmlError(R.string.XmlErrorIncludeNoResource, getCurrentContextAndReferenceStr());
return;
}
// 2. Check we're inside a speech format
if (getCurrentSecondLevelContext() != DebateFormatXmlSecondLevelContext.SPEECH_FORMAT) {
logXmlError(R.string.XmlErrorIncludeOutsideSpeechFormat, resourceRef);
return;
}
// 3. Include the resource
try {
if (mCurrentSpeechFormatRef != null)
mDfb.includeResource(mCurrentSpeechFormatRef, resourceRef);
} catch (DebateFormatBuilderException e){
logXmlError(e);
}
/** <speeches>
* Start the speeches context.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeechesList)) {
if (!assertNotInsideAnySecondLevelContextAndResetOtherwise()) {
logXmlError(R.string.XmlErrorSpeechesListInsideContext,
getCurrentSecondLevelContext().toString());
return;
}
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.SPEECHES_LIST;
/**
* <speech name="1st Affirmative" type="formatname">
* Add a speech.
* This must be inside the speeches context.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeech)) {
// 1. Get the speech name.
String name = getValue(atts, R.string.XmlAttrNameSpeechName);
if (name == null) {
logXmlError(R.string.XmlErrorSpeechNoName);
return;
}
// 2. Get the speech format.
String format = getValue(atts, R.string.XmlAttrNameSpeechFormat);
if (format == null) {
logXmlError(R.string.XmlErrorSpeechNoFormat, name);
return;
}
// 3. We must be inside the speeches list.
if (getCurrentSecondLevelContext() != DebateFormatXmlSecondLevelContext.SPEECHES_LIST) {
logXmlError(R.string.XmlErrorSpeechOutsideSpeechesList, name);
return;
}
// Finally, add the speech.
try {
mDfb.addSpeech(name, format);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
}
}
// ******** Private methods ********
private String getCurrentContextAndReferenceStr() {
if (mCurrentResourceRef != null) {
return String.format("%s '%s'", getString(R.string.XmlElemNameResource), mCurrentResourceRef);
} else if (mCurrentSpeechFormatRef != null) {
return String.format("%s '%s'", getString(R.string.XmlElemNameSpeechFormat), mCurrentSpeechFormatRef);
} else {
return "unknown context";
}
}
private boolean areEqual(String string, int resid) {
return string.equals(getString(resid));
}
private boolean areEqualIgnoringCase(String string, int resid) {
return string.equalsIgnoreCase(getString(resid));
}
private String getString(int resid) {
return mContext.getString(resid);
}
private String getValue(Attributes atts, int localNameResid) {
return atts.getValue(DEBATING_TIMER_URI, getString(localNameResid));
}
/**
* Checks we're not currently inside a context.
* If we are, reset all contexts and return false.
* @return true if the assertion passes, false if it fails
*/
private boolean assertNotInsideAnySecondLevelContextAndResetOtherwise() {
if (getCurrentSecondLevelContext() != DebateFormatXmlSecondLevelContext.NONE) {
mCurrentResourceRef = null;
mCurrentSpeechFormatRef = null;
mCurrentSpeechFormatFirstPeriod = null;
return false;
}
return true;
}
private DebateFormatXmlSecondLevelContext getCurrentSecondLevelContext() {
return mCurrentSecondLevelContext;
}
}
//******************************************************************************************
// Public methods
//******************************************************************************************
/**
* Builds a debate from a given input stream, which must be an XML file.
* @param is an {@link InputStream} to an XML file
* @return the {@link DebateFormat}
* @throws IOException if there was an IO error with the <code>InputStream</code>
* @throws SAXException if thrown by the XML parser
* @throws IllegalStateException if there were no speeches in this format
*/
public DebateFormat buildDebateFromXml(InputStream is)
throws IOException, SAXException, IllegalStateException {
Xml.parse(is, Encoding.UTF_8, new DebateFormatXmlContentHandler());
return mDfb.getDebateFormat();
}
public void logXmlErrorStyled(int xmlerrorspeechformatnofinishbell,
String mCurrentSpeechFormatRef) {
// TODO Auto-generated method stub
}
/**
* @return true if there are errors in the error log
*/
public boolean hasErrors() {
return mErrorLog.size() > 0;
}
/**
* @return <code>true</code> if the schema version is supported.
* <code>false</code> if there is no schema version, this includes if this builder hasn't parsed
* an XML file yet.
*/
public boolean isSchemaSupported() throws IllegalArgumentException {
if (mSchemaVersion == null)
return false;
return (compareSchemaVersions(mSchemaVersion, MAXIMUM_SCHEMA_VERSION) <= 0);
}
/**
* @return The schema version, could be <code>null</code>
*/
public String getSchemaVersion() {
return mSchemaVersion;
}
/**
* @return An <i>ArrayList</i> of <code>String</code>s, each item being an error found by
* the XML parser
*/
public ArrayList<String> getErrorLog() {
return mErrorLog;
}
//******************************************************************************************
// Private methods
//******************************************************************************************
/**
* Converts a String in the format 00:00 to a long, being the number of seconds
* @param s the String
* @return the total number of seconds (minutes + seconds * 60)
* @throws NumberFormatException
*/
private static long timeStr2Secs(String s) throws NumberFormatException {
long seconds = 0;
String parts[] = s.split(":", 2);
switch (parts.length){
case 2:
long minutes = Long.parseLong(parts[0]);
seconds += minutes * 60;
seconds += Long.parseLong(parts[1]);
break;
case 1:
seconds = Long.parseLong(parts[0]);
break;
default:
throw new NumberFormatException();
}
return seconds;
}
/**
* @param a
* @param b
* @return 1 if a > b, 0 if a == b, 1 if a < b
*/
private static int compareSchemaVersions(String a, String b) throws IllegalArgumentException {
int[] a_int = versionToIntArray(a);
int[] b_int = versionToIntArray(b);
int min_length = (a_int.length > b_int.length) ? b_int.length : a_int.length;
for (int i = 0; i < min_length; i++) {
if (a_int[i] > b_int[i]) return 1;
if (a_int[i] < b_int[i]) return -1;
}
return 0;
}
/**
* @param version
* @return an integer array
*/
private static int[] versionToIntArray(String version) throws IllegalArgumentException {
int[] result = new int[2];
String[] parts = version.split("\\.", 2);
if (parts.length != 2)
throw new IllegalArgumentException("version must be in the form 'a.b' where a and b are numbers");
for (int i = 0; i < 2; i++) {
try {
result[i] = Integer.parseInt(parts[i]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("version must be in the form 'a.b' where a and b are numbers");
}
}
return result;
}
private void addToErrorLog(String message) {
String bullet = "� ";
String line = bullet.concat(message);
mErrorLog.add(line);
}
/**
* Logs an XML-related error from an exception.
* @param e the Exception
*/
private void logXmlError(Exception e) {
addToErrorLog(e.getMessage());
Log.e("logXmlError", e.getMessage());
}
/**
* Logs an XML-related error from a string resource.
* @param resId the resource ID of the string resource
*/
private void logXmlError(int resId) {
addToErrorLog(mContext.getString(resId));
Log.e("logXmlError", mContext.getString(resId));
}
/**
* Logs an XML-related error from a string resource and formats according to
* <code>String.format</code>
* @param resId the resource ID of the string resource
* @param formatArgs arguments to pass to <code>String.format</code>
*/
private void logXmlError(int resId, Object... formatArgs) {
addToErrorLog(mContext.getString(resId, formatArgs));
Log.e("logXmlError", mContext.getString(resId, formatArgs));
}
}
| true | true | public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if (!uri.equals(DEBATING_TIMER_URI))
return;
/**
* <debateformat name="something" schemaversion="1.0">
*/
if (areEqual(localName, R.string.XmlElemNameRoot)) {
String name = getValue(atts, R.string.XmlAttrNameRootName);
if (name == null) {
logXmlError(R.string.XmlErrorRootNoName);
return;
}
mSchemaVersion = getValue(atts, R.string.XmlAttrNameRootSchemaVersion);
if (mSchemaVersion == null) {
logXmlError(R.string.XmlErrorRootNoSchemaVersion);
} else {
try {
if (!isSchemaSupported())
logXmlError(R.string.XmlErrorRootNewSchemaVersion, mSchemaVersion, MAXIMUM_SCHEMA_VERSION);
} catch (IllegalArgumentException e) {
logXmlError(R.string.XmlErrorRootInvalidSchemaVersion, mSchemaVersion);
}
}
mDfb.setDebateFormatName(name);
mIsInRootContext = true;
return;
}
// For everything else, we must be inside the root element.
// If we're not, refuse to do anything.
if (!mIsInRootContext) {
logXmlError(R.string.XmlErrorSomethingOutsideRoot);
return;
}
/** <resource ref="string">
* Create a reference with the reference as specified in 'ref'.
* Must not be inside a resource or speech format.
* 'ref' is mandatory.
*/
if (areEqual(localName, R.string.XmlElemNameResource)) {
// 1. Get the reference string.
String reference = getValue(atts, R.string.XmlAttrNameCommonRef);
if (reference == null) {
logXmlError(R.string.XmlErrorResourceNoRef);
return;
}
// 2. Check we're not inside any contexts.
// If we are, ignore and reset all contexts.
if (!assertNotInsideAnySecondLevelContextAndResetOtherwise()) {
logXmlError(R.string.XmlErrorResourceInsideContext, reference,
getCurrentSecondLevelContext().toString());
return;
}
// 3. Start a new resource
try {
mDfb.addNewResource(reference);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
return;
}
// If we succeeded in adding the resource, take note of this reference string for
// all this resource's sub-elements. (Don't do this if there was an error, so that
// sub-elements can be ignored.)
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.RESOURCE;
mCurrentResourceRef = reference;
/** <speechtype ref="string" length="5:00" firstperiod="string" countdir="up">
* Create a speech format.
* 'ref' and 'length' are mandatory.
* 'firstperiod' and 'countdir' are optional.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeechFormat)) {
// 1. Get the reference string. Mandatory; exit on error.
String reference = getValue(atts, R.string.XmlAttrNameCommonRef);
if (reference == null) {
logXmlError(R.string.XmlErrorSpeechFormatNoRef);
return;
}
// 2. Check we're not inside any contexts.
// If we are, ignore and reset all contexts.
if (!assertNotInsideAnySecondLevelContextAndResetOtherwise()) {
logXmlError(R.string.XmlErrorSpeechFormatInsideContext, reference,
getCurrentSecondLevelContext().toString());
return;
}
// 3. Get the length string, then convert it to seconds. Mandatory; exit on error.
// Take note of it, in case bells use "finish" as their bell time.
String lengthStr = getValue(atts, R.string.XmlAttrNameSpeechFormatLength);
long length = 0;
if (lengthStr == null) {
logXmlError(R.string.XmlErrorSpeechFormatNoLength, reference);
return;
}
try {
length = timeStr2Secs(lengthStr);
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorSpeechFormatInvalidLength, reference, lengthStr);
return;
}
// 4. Add the speech format.
try {
mDfb.addNewSpeechFormat(reference, length);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
return;
}
// 5. If we got this far, take note of this reference string for all this speech
// format's sub-elements. (Don't do this if there was an error, so that
// sub-elements can be ignored.)
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.SPEECH_FORMAT;
mCurrentSpeechFormatRef = reference;
// Now do the optional attributes...
// 6. Get the count direction, and set it if it's present
String countdir = getValue(atts, R.string.XmlAttrNameSpeechFormatCountDir);
if (countdir != null) {
try {
if (areEqualIgnoringCase(countdir,
R.string.XmlAttrValueSpeechFormatCountDirUp)) {
mDfb.setCountDirection(reference, CountDirection.COUNT_UP);
} else if (areEqualIgnoringCase(countdir,
R.string.XmlAttrValueSpeechFormatCountDirDown)) {
mDfb.setCountDirection(reference, CountDirection.COUNT_DOWN);
} else if (areEqualIgnoringCase(countdir,
R.string.XmlAttrValueSpeechFormatCountDirUser)) {
mDfb.setCountDirection(reference, CountDirection.COUNT_USER);
}
} catch (DebateFormatBuilderException e) {
logXmlError(R.string.XmlErrorSpeechFormatUnexpectedlyNotFound, reference);
}
}
// 7. Get the first period, and take note for later.
// We'll deal with it as we exit this element, because the period is defined
// inside the element.
mCurrentSpeechFormatFirstPeriod =
getValue(atts, R.string.XmlAttrNameSpeechFormatFirstPeriod);
/** <bell time="1:00" number="1" nextperiod="#stay" sound="#default" pauseonbell="true">
* Create a BellInfo.
* This must be inside a resource or speech format.
* 'time' is mandatory.
* All other attributes are optional.
*/
} else if (areEqual(localName, R.string.XmlElemNameBell)) {
// 1. Get the bell time. Mandatory; exit on error.
String timeStr = getValue(atts, R.string.XmlAttrNameBellTime);;
long time = 0;
boolean atFinish = false;
if (timeStr == null) {
logXmlError(R.string.XmlErrorBellNoTime, getCurrentContextAndReferenceStr());
return;
} else if (areEqualIgnoringCase(timeStr, R.string.XmlAttrValueBellTimeFinish)) {
time = 0; // will be overwritten addBellInfoToSpeechFormatAtFinish().
atFinish = true;
} else {
try {
time = timeStr2Secs(timeStr);
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorBellInvalidTime, getCurrentContextAndReferenceStr(), timeStr);
return;
}
}
// 2. Get the number of times to play, or default to 1.
String numberStr = getValue(atts, R.string.XmlAttrNameBellNumber);
int number = 1;
if (numberStr != null) {
try {
number = Integer.parseInt(numberStr);
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorBellInvalidNumber, getCurrentContextAndReferenceStr(), timeStr);
}
}
// 3. We now have enough information to create the bell.
BellInfo bi = new BellInfo(time, number);
// 4. Get the next period reference, or default to null
// "#stay" means null (i.e. leave unchanged)
String periodInfoRef = getValue(atts, R.string.XmlAttrNameBellNextPeriod);
if (periodInfoRef != null)
if (areEqualIgnoringCase(periodInfoRef, R.string.XmlAttrValueCommonStay))
periodInfoRef = null;
// 5. Get the sound to play, or default to the default
String bellSound = getValue(atts, R.string.XmlAttrNameBellSound);
if (bellSound != null) {
if (areEqualIgnoringCase(bellSound, R.string.XmlAttrValueCommonStay))
bellSound = null;
else if (areEqualIgnoringCase(bellSound, R.string.XmlAttrValueBellNextPeriodSilent))
bi.setSound(0);
else if (areEqualIgnoringCase(bellSound, R.string.XmlAttrValueCommonDefault));
// Do nothing
else
logXmlError(R.string.XmlErrorBellInvalidSound, getCurrentContextAndReferenceStr(), bellSound);
}
// 6. Determine whether to pause on this bell
String pauseOnBellStr = getValue(atts, R.string.XmlAttrNameBellPauseOnBell);
if (pauseOnBellStr != null) {
if (areEqualIgnoringCase(pauseOnBellStr, R.string.XmlAttrValueCommonTrue))
bi.setPauseOnBell(true);
else if (areEqualIgnoringCase(pauseOnBellStr, R.string.XmlAttrValueCommonFalse))
bi.setPauseOnBell(false);
else
logXmlError(R.string.XmlErrorBellInvalidPauseOnBell, getCurrentContextAndReferenceStr(), pauseOnBellStr);
}
// Finally, add the bell, but first check that the period info exists (and nullify
// if it doesn't, so that the bell still gets added)
try {
switch (getCurrentSecondLevelContext()) {
case RESOURCE:
if (mCurrentResourceRef == null) break;
if (periodInfoRef != null && !mDfb.hasPeriodInfoInResource(mCurrentResourceRef, periodInfoRef)) {
logXmlError(R.string.XmlErrorResourcePeriodInfoNotFound, periodInfoRef, mCurrentResourceRef);
periodInfoRef = null;
}
mDfb.addBellInfoToResource(mCurrentResourceRef, bi, periodInfoRef);
break;
case SPEECH_FORMAT:
if (mCurrentSpeechFormatRef == null) break;
if (periodInfoRef != null && !mDfb.hasPeriodInfoInSpeechFormat(mCurrentSpeechFormatRef, periodInfoRef)) {
logXmlError(R.string.XmlErrorSpeechFormatPeriodInfoNotFound, periodInfoRef, mCurrentSpeechFormatRef);
periodInfoRef = null;
}
if (atFinish)
mDfb.addBellInfoToSpeechFormatAtFinish(mCurrentSpeechFormatRef, bi, periodInfoRef);
else
mDfb.addBellInfoToSpeechFormat(mCurrentSpeechFormatRef, bi, periodInfoRef);
break;
default:
logXmlError(R.string.XmlErrorBellOutsideContext);
}
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
/** <period ref="something" desc="Human readable" bgcolor="#77ffcc00">
* Create a PeriodInfo.
* This must be inside a resource or speech format.
* 'ref' is mandatory.
* 'desc' and 'bgcolor' are optional.
*/
} else if (areEqual(localName, R.string.XmlElemNamePeriod)){
// 1. Get the reference. Mandatory; exit on error.
String reference = getValue(atts, R.string.XmlAttrNameCommonRef);
if (reference == null) {
logXmlError(R.string.XmlErrorPeriodNoRef, getCurrentContextAndReferenceStr());
return;
}
// 2. Get the description (implicitly default to null)
String description = getValue(atts, R.string.XmlAttrNamePeriodDesc);
if (description != null) {
if (areEqualIgnoringCase(description, R.string.XmlAttrValueCommonStay))
description = null;
}
// 3. Get the background colour (implicitly default to null)
String bgcolorStr = getValue(atts, R.string.XmlAttrNamePeriodBgcolor);
Integer backgroundColor = null;
if (bgcolorStr != null) {
if (areEqualIgnoringCase(bgcolorStr, R.string.XmlAttrValueCommonStay))
backgroundColor = null;
else if (bgcolorStr.startsWith("#")) {
try {
// We need to do it via BigInteger in order for large unsigned 32-bit
// integers to be parsed as unsigned integers.
backgroundColor = new BigInteger(bgcolorStr.substring(1), 16).intValue();
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorPeriodInvalidColor, reference, bgcolorStr);
}
} else {
logXmlError(R.string.XmlErrorPeriodInvalidColor, reference, bgcolorStr);
}
}
// 4. We now have enough information to make the PeriodInfo
PeriodInfo pi = new PeriodInfo(description, backgroundColor);
// Finally, add the period
try {
switch (getCurrentSecondLevelContext()) {
case RESOURCE:
if (mCurrentResourceRef != null)
mDfb.addPeriodInfoToResource(mCurrentResourceRef, reference, pi);
break;
case SPEECH_FORMAT:
if (mCurrentSpeechFormatRef != null)
mDfb.addPeriodInfoToSpeechFormat(mCurrentSpeechFormatRef, reference, pi);
break;
default:
logXmlError(R.string.XmlErrorPeriodOutsideContext, reference);
}
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
/** <include resource="reference">
* Include a resource in a speech format.
* This must be in a speech format.
* 'resource' is mandatory.
*/
} else if (areEqual(localName, R.string.XmlElemNameInclude)) {
// 1. Get the resource reference. Mandatory; exit on error.
String resourceRef = getValue(atts, R.string.XmlAttrNameIncludeResource);
if (resourceRef == null) {
logXmlError(R.string.XmlErrorIncludeNoResource, getCurrentContextAndReferenceStr());
return;
}
// 2. Check we're inside a speech format
if (getCurrentSecondLevelContext() != DebateFormatXmlSecondLevelContext.SPEECH_FORMAT) {
logXmlError(R.string.XmlErrorIncludeOutsideSpeechFormat, resourceRef);
return;
}
// 3. Include the resource
try {
if (mCurrentSpeechFormatRef != null)
mDfb.includeResource(mCurrentSpeechFormatRef, resourceRef);
} catch (DebateFormatBuilderException e){
logXmlError(e);
}
/** <speeches>
* Start the speeches context.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeechesList)) {
if (!assertNotInsideAnySecondLevelContextAndResetOtherwise()) {
logXmlError(R.string.XmlErrorSpeechesListInsideContext,
getCurrentSecondLevelContext().toString());
return;
}
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.SPEECHES_LIST;
/**
* <speech name="1st Affirmative" type="formatname">
* Add a speech.
* This must be inside the speeches context.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeech)) {
// 1. Get the speech name.
String name = getValue(atts, R.string.XmlAttrNameSpeechName);
if (name == null) {
logXmlError(R.string.XmlErrorSpeechNoName);
return;
}
// 2. Get the speech format.
String format = getValue(atts, R.string.XmlAttrNameSpeechFormat);
if (format == null) {
logXmlError(R.string.XmlErrorSpeechNoFormat, name);
return;
}
// 3. We must be inside the speeches list.
if (getCurrentSecondLevelContext() != DebateFormatXmlSecondLevelContext.SPEECHES_LIST) {
logXmlError(R.string.XmlErrorSpeechOutsideSpeechesList, name);
return;
}
// Finally, add the speech.
try {
mDfb.addSpeech(name, format);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
}
}
| public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if (!uri.equals(DEBATING_TIMER_URI))
return;
/**
* <debateformat name="something" schemaversion="1.0">
*/
if (areEqual(localName, R.string.XmlElemNameRoot)) {
String name = getValue(atts, R.string.XmlAttrNameRootName);
if (name == null) {
logXmlError(R.string.XmlErrorRootNoName);
return;
}
mSchemaVersion = getValue(atts, R.string.XmlAttrNameRootSchemaVersion);
if (mSchemaVersion == null) {
logXmlError(R.string.XmlErrorRootNoSchemaVersion);
} else {
try {
if (!isSchemaSupported())
logXmlError(R.string.XmlErrorRootNewSchemaVersion, mSchemaVersion, MAXIMUM_SCHEMA_VERSION);
} catch (IllegalArgumentException e) {
logXmlError(R.string.XmlErrorRootInvalidSchemaVersion, mSchemaVersion);
}
}
mDfb.setDebateFormatName(name);
mIsInRootContext = true;
return;
}
// For everything else, we must be inside the root element.
// If we're not, refuse to do anything.
if (!mIsInRootContext) {
logXmlError(R.string.XmlErrorSomethingOutsideRoot);
return;
}
/** <resource ref="string">
* Create a reference with the reference as specified in 'ref'.
* Must not be inside a resource or speech format.
* 'ref' is mandatory.
*/
if (areEqual(localName, R.string.XmlElemNameResource)) {
// 1. Get the reference string.
String reference = getValue(atts, R.string.XmlAttrNameCommonRef);
if (reference == null) {
logXmlError(R.string.XmlErrorResourceNoRef);
return;
}
// 2. Check we're not inside any contexts.
// If we are, ignore and reset all contexts.
if (!assertNotInsideAnySecondLevelContextAndResetOtherwise()) {
logXmlError(R.string.XmlErrorResourceInsideContext, reference,
getCurrentSecondLevelContext().toString());
return;
}
// 3. Start a new resource
try {
mDfb.addNewResource(reference);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
return;
}
// If we succeeded in adding the resource, take note of this reference string for
// all this resource's sub-elements. (Don't do this if there was an error, so that
// sub-elements can be ignored.)
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.RESOURCE;
mCurrentResourceRef = reference;
/** <speechtype ref="string" length="5:00" firstperiod="string" countdir="up">
* Create a speech format.
* 'ref' and 'length' are mandatory.
* 'firstperiod' and 'countdir' are optional.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeechFormat)) {
// 1. Get the reference string. Mandatory; exit on error.
String reference = getValue(atts, R.string.XmlAttrNameCommonRef);
if (reference == null) {
logXmlError(R.string.XmlErrorSpeechFormatNoRef);
return;
}
// 2. Check we're not inside any contexts.
// If we are, ignore and reset all contexts.
if (!assertNotInsideAnySecondLevelContextAndResetOtherwise()) {
logXmlError(R.string.XmlErrorSpeechFormatInsideContext, reference,
getCurrentSecondLevelContext().toString());
return;
}
// 3. Get the length string, then convert it to seconds. Mandatory; exit on error.
// Take note of it, in case bells use "finish" as their bell time.
String lengthStr = getValue(atts, R.string.XmlAttrNameSpeechFormatLength);
long length = 0;
if (lengthStr == null) {
logXmlError(R.string.XmlErrorSpeechFormatNoLength, reference);
return;
}
try {
length = timeStr2Secs(lengthStr);
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorSpeechFormatInvalidLength, reference, lengthStr);
return;
}
// 4. Add the speech format.
try {
mDfb.addNewSpeechFormat(reference, length);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
return;
}
// 5. If we got this far, take note of this reference string for all this speech
// format's sub-elements. (Don't do this if there was an error, so that
// sub-elements can be ignored.)
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.SPEECH_FORMAT;
mCurrentSpeechFormatRef = reference;
// Now do the optional attributes...
// 6. Get the count direction, and set it if it's present
String countdir = getValue(atts, R.string.XmlAttrNameSpeechFormatCountDir);
if (countdir != null) {
try {
if (areEqualIgnoringCase(countdir,
R.string.XmlAttrValueSpeechFormatCountDirUp)) {
mDfb.setCountDirection(reference, CountDirection.COUNT_UP);
} else if (areEqualIgnoringCase(countdir,
R.string.XmlAttrValueSpeechFormatCountDirDown)) {
mDfb.setCountDirection(reference, CountDirection.COUNT_DOWN);
} else if (areEqualIgnoringCase(countdir,
R.string.XmlAttrValueSpeechFormatCountDirUser)) {
mDfb.setCountDirection(reference, CountDirection.COUNT_USER);
} else {
logXmlError(R.string.XmlErrorSpeechFormatInvalidCountDir, reference, countdir);
}
} catch (DebateFormatBuilderException e) {
logXmlError(R.string.XmlErrorSpeechFormatUnexpectedlyNotFound, reference);
}
}
// 7. Get the first period, and take note for later.
// We'll deal with it as we exit this element, because the period is defined
// inside the element.
mCurrentSpeechFormatFirstPeriod =
getValue(atts, R.string.XmlAttrNameSpeechFormatFirstPeriod);
/** <bell time="1:00" number="1" nextperiod="#stay" sound="#default" pauseonbell="true">
* Create a BellInfo.
* This must be inside a resource or speech format.
* 'time' is mandatory.
* All other attributes are optional.
*/
} else if (areEqual(localName, R.string.XmlElemNameBell)) {
// 1. Get the bell time. Mandatory; exit on error.
String timeStr = getValue(atts, R.string.XmlAttrNameBellTime);;
long time = 0;
boolean atFinish = false;
if (timeStr == null) {
logXmlError(R.string.XmlErrorBellNoTime, getCurrentContextAndReferenceStr());
return;
} else if (areEqualIgnoringCase(timeStr, R.string.XmlAttrValueBellTimeFinish)) {
time = 0; // will be overwritten addBellInfoToSpeechFormatAtFinish().
atFinish = true;
} else {
try {
time = timeStr2Secs(timeStr);
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorBellInvalidTime, getCurrentContextAndReferenceStr(), timeStr);
return;
}
}
// 2. Get the number of times to play, or default to 1.
String numberStr = getValue(atts, R.string.XmlAttrNameBellNumber);
int number = 1;
if (numberStr != null) {
try {
number = Integer.parseInt(numberStr);
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorBellInvalidNumber, getCurrentContextAndReferenceStr(), timeStr);
}
}
// 3. We now have enough information to create the bell.
BellInfo bi = new BellInfo(time, number);
// 4. Get the next period reference, or default to null
// "#stay" means null (i.e. leave unchanged)
String periodInfoRef = getValue(atts, R.string.XmlAttrNameBellNextPeriod);
if (periodInfoRef != null)
if (areEqualIgnoringCase(periodInfoRef, R.string.XmlAttrValueCommonStay))
periodInfoRef = null;
// 5. Get the sound to play, or default to the default
String bellSound = getValue(atts, R.string.XmlAttrNameBellSound);
if (bellSound != null) {
if (areEqualIgnoringCase(bellSound, R.string.XmlAttrValueCommonStay))
bellSound = null;
else if (areEqualIgnoringCase(bellSound, R.string.XmlAttrValueBellNextPeriodSilent))
bi.setSound(0);
else if (areEqualIgnoringCase(bellSound, R.string.XmlAttrValueCommonDefault));
// Do nothing
else
logXmlError(R.string.XmlErrorBellInvalidSound, getCurrentContextAndReferenceStr(), bellSound);
}
// 6. Determine whether to pause on this bell
String pauseOnBellStr = getValue(atts, R.string.XmlAttrNameBellPauseOnBell);
if (pauseOnBellStr != null) {
if (areEqualIgnoringCase(pauseOnBellStr, R.string.XmlAttrValueCommonTrue))
bi.setPauseOnBell(true);
else if (areEqualIgnoringCase(pauseOnBellStr, R.string.XmlAttrValueCommonFalse))
bi.setPauseOnBell(false);
else
logXmlError(R.string.XmlErrorBellInvalidPauseOnBell, getCurrentContextAndReferenceStr(), pauseOnBellStr);
}
// Finally, add the bell, but first check that the period info exists (and nullify
// if it doesn't, so that the bell still gets added)
try {
switch (getCurrentSecondLevelContext()) {
case RESOURCE:
if (mCurrentResourceRef == null) break;
if (periodInfoRef != null && !mDfb.hasPeriodInfoInResource(mCurrentResourceRef, periodInfoRef)) {
logXmlError(R.string.XmlErrorResourcePeriodInfoNotFound, periodInfoRef, mCurrentResourceRef);
periodInfoRef = null;
}
mDfb.addBellInfoToResource(mCurrentResourceRef, bi, periodInfoRef);
break;
case SPEECH_FORMAT:
if (mCurrentSpeechFormatRef == null) break;
if (periodInfoRef != null && !mDfb.hasPeriodInfoInSpeechFormat(mCurrentSpeechFormatRef, periodInfoRef)) {
logXmlError(R.string.XmlErrorSpeechFormatPeriodInfoNotFound, periodInfoRef, mCurrentSpeechFormatRef);
periodInfoRef = null;
}
if (atFinish)
mDfb.addBellInfoToSpeechFormatAtFinish(mCurrentSpeechFormatRef, bi, periodInfoRef);
else
mDfb.addBellInfoToSpeechFormat(mCurrentSpeechFormatRef, bi, periodInfoRef);
break;
default:
logXmlError(R.string.XmlErrorBellOutsideContext);
}
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
/** <period ref="something" desc="Human readable" bgcolor="#77ffcc00">
* Create a PeriodInfo.
* This must be inside a resource or speech format.
* 'ref' is mandatory.
* 'desc' and 'bgcolor' are optional.
*/
} else if (areEqual(localName, R.string.XmlElemNamePeriod)){
// 1. Get the reference. Mandatory; exit on error.
String reference = getValue(atts, R.string.XmlAttrNameCommonRef);
if (reference == null) {
logXmlError(R.string.XmlErrorPeriodNoRef, getCurrentContextAndReferenceStr());
return;
}
// 2. Get the description (implicitly default to null)
String description = getValue(atts, R.string.XmlAttrNamePeriodDesc);
if (description != null) {
if (areEqualIgnoringCase(description, R.string.XmlAttrValueCommonStay))
description = null;
}
// 3. Get the background colour (implicitly default to null)
String bgcolorStr = getValue(atts, R.string.XmlAttrNamePeriodBgcolor);
Integer backgroundColor = null;
if (bgcolorStr != null) {
if (areEqualIgnoringCase(bgcolorStr, R.string.XmlAttrValueCommonStay))
backgroundColor = null;
else if (bgcolorStr.startsWith("#")) {
try {
// We need to do it via BigInteger in order for large unsigned 32-bit
// integers to be parsed as unsigned integers.
backgroundColor = new BigInteger(bgcolorStr.substring(1), 16).intValue();
} catch (NumberFormatException e) {
logXmlError(R.string.XmlErrorPeriodInvalidColor, reference, bgcolorStr);
}
} else {
logXmlError(R.string.XmlErrorPeriodInvalidColor, reference, bgcolorStr);
}
}
// 4. We now have enough information to make the PeriodInfo
PeriodInfo pi = new PeriodInfo(description, backgroundColor);
// Finally, add the period
try {
switch (getCurrentSecondLevelContext()) {
case RESOURCE:
if (mCurrentResourceRef != null)
mDfb.addPeriodInfoToResource(mCurrentResourceRef, reference, pi);
break;
case SPEECH_FORMAT:
if (mCurrentSpeechFormatRef != null)
mDfb.addPeriodInfoToSpeechFormat(mCurrentSpeechFormatRef, reference, pi);
break;
default:
logXmlError(R.string.XmlErrorPeriodOutsideContext, reference);
}
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
/** <include resource="reference">
* Include a resource in a speech format.
* This must be in a speech format.
* 'resource' is mandatory.
*/
} else if (areEqual(localName, R.string.XmlElemNameInclude)) {
// 1. Get the resource reference. Mandatory; exit on error.
String resourceRef = getValue(atts, R.string.XmlAttrNameIncludeResource);
if (resourceRef == null) {
logXmlError(R.string.XmlErrorIncludeNoResource, getCurrentContextAndReferenceStr());
return;
}
// 2. Check we're inside a speech format
if (getCurrentSecondLevelContext() != DebateFormatXmlSecondLevelContext.SPEECH_FORMAT) {
logXmlError(R.string.XmlErrorIncludeOutsideSpeechFormat, resourceRef);
return;
}
// 3. Include the resource
try {
if (mCurrentSpeechFormatRef != null)
mDfb.includeResource(mCurrentSpeechFormatRef, resourceRef);
} catch (DebateFormatBuilderException e){
logXmlError(e);
}
/** <speeches>
* Start the speeches context.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeechesList)) {
if (!assertNotInsideAnySecondLevelContextAndResetOtherwise()) {
logXmlError(R.string.XmlErrorSpeechesListInsideContext,
getCurrentSecondLevelContext().toString());
return;
}
mCurrentSecondLevelContext = DebateFormatXmlSecondLevelContext.SPEECHES_LIST;
/**
* <speech name="1st Affirmative" type="formatname">
* Add a speech.
* This must be inside the speeches context.
*/
} else if (areEqual(localName, R.string.XmlElemNameSpeech)) {
// 1. Get the speech name.
String name = getValue(atts, R.string.XmlAttrNameSpeechName);
if (name == null) {
logXmlError(R.string.XmlErrorSpeechNoName);
return;
}
// 2. Get the speech format.
String format = getValue(atts, R.string.XmlAttrNameSpeechFormat);
if (format == null) {
logXmlError(R.string.XmlErrorSpeechNoFormat, name);
return;
}
// 3. We must be inside the speeches list.
if (getCurrentSecondLevelContext() != DebateFormatXmlSecondLevelContext.SPEECHES_LIST) {
logXmlError(R.string.XmlErrorSpeechOutsideSpeechesList, name);
return;
}
// Finally, add the speech.
try {
mDfb.addSpeech(name, format);
} catch (DebateFormatBuilderException e) {
logXmlError(e);
}
}
}
|
diff --git a/mbt/src/org/tigris/mbt/GUI/App.java b/mbt/src/org/tigris/mbt/GUI/App.java
index 2f17ddd..fc56135 100644
--- a/mbt/src/org/tigris/mbt/GUI/App.java
+++ b/mbt/src/org/tigris/mbt/GUI/App.java
@@ -1,687 +1,687 @@
package org.tigris.mbt.GUI;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.ws.Endpoint;
import org.apache.commons.collections15.Transformer;
import org.apache.log4j.Logger;
import org.tigris.mbt.ModelBasedTesting;
import org.tigris.mbt.SoapServices;
import org.tigris.mbt.Util;
import org.tigris.mbt.events.AppEvent;
import org.tigris.mbt.events.MbtEvent;
import org.tigris.mbt.graph.Edge;
import org.tigris.mbt.graph.Graph;
import org.tigris.mbt.graph.Vertex;
import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.FRLayout;
import edu.uci.ics.jung.algorithms.layout.ISOMLayout;
import edu.uci.ics.jung.algorithms.layout.KKLayout;
import edu.uci.ics.jung.algorithms.layout.SpringLayout;
import edu.uci.ics.jung.algorithms.layout.SpringLayout2;
import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.visualization.Layer;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.layout.LayoutTransition;
import edu.uci.ics.jung.visualization.picking.ShapePickSupport;
import edu.uci.ics.jung.visualization.renderers.Renderer;
import edu.uci.ics.jung.visualization.util.Animator;
public class App extends JFrame implements ActionListener, MbtEvent {
/**
*
*/
private static final long serialVersionUID = -8605452811238545133L;
private JSplitPane splitPaneMessages;
private JSplitPane splitPaneGraph;
private JPanel panelStatistics;
private JPanel panelVariables;
private JPanel panelGraph;
private JTextArea statisticsTextArea;
private JTextArea variablesTextArea;
private JLabel latestStateLabel;
private JFileChooser fileChooser = new JFileChooser(System
.getProperty("user.dir"));
private VisualizationViewer<Vertex, Edge> vv;
private Layout<Vertex, Edge> layout;
private File xmlFile;
private ExecuteMBT executeMBT = null;
public File getXmlFile() {
return xmlFile;
}
public void setXmlFile(File xmlFile) {
this.xmlFile = xmlFile;
}
static private Logger log;
private static Endpoint endpoint = null;
private SoapServices soapService = null;
private JButton loadButton;
private JButton reloadButton;
private JButton runButton;
private JButton pauseButton;
private JButton nextButton;
private JCheckBox soapButton;
private JCheckBox centerOnVertexButton;
public Status status = new Status();
protected String newline = "\n";
static final private String LOAD = "load";
static final private String RELOAD = "reload";
static final private String RUN = "run";
static final private String PAUSE = "pause";
static final private String NEXT = "next";
static final private String SOAP = "soap";
static final private String CENTERONVERTEX = "centerOnVertex";
static private AppEvent appEvent = null;
static private ChangeEvent changeEvent = null;
@SuppressWarnings("unchecked")
private static Class<? extends Layout>[] getCombos()
{
List<Class<? extends Layout>> layouts = new ArrayList<Class<? extends Layout>>();
layouts.add(StaticLayout.class);
layouts.add(KKLayout.class);
layouts.add(FRLayout.class);
layouts.add(CircleLayout.class);
layouts.add(SpringLayout.class);
layouts.add(SpringLayout2.class);
layouts.add(ISOMLayout.class);
return layouts.toArray(new Class[0]);
}
public static void SetAppEventNotifier( AppEvent event )
{
log.debug( "AppEvent is set using: " + event );
appEvent = event;
changeEvent = new ChangeEvent(event);
}
private void runSoap()
{
if ( endpoint != null )
{
endpoint = null;
}
String wsURL = "http://0.0.0.0:" + Util.readWSPort() + "/mbt-services";
soapService = new SoapServices( xmlFile.getAbsolutePath() );
endpoint = Endpoint.publish( wsURL, soapService );
try {
log.info( "Now running as a SOAP server. For the WSDL file, see: " + wsURL.replace( "0.0.0.0", InetAddress.getLocalHost().getHostName() ) + "?WSDL" );
} catch (UnknownHostException e) {
log.info( "Now running as a SOAP server. For the WSDL file, see: " + wsURL + "?WSDL" );
log.error( e.getMessage() );
}
}
public void getNextEvent() {
if ( centerOnVertexButton.isSelected() )
centerOnVertex();
else {
updateUI();
getVv().stateChanged(changeEvent);
}
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
log.debug( "Got action: " + cmd );
// Handle each button.
if (LOAD.equals(cmd)) {
load();
} else if (RELOAD.equals(cmd)) { // second button clicked
reload();
} else if (RUN.equals(cmd)) { // third button clicked
run();
} else if (PAUSE.equals(cmd)) { // third button clicked
pause();
} else if (NEXT.equals(cmd)) { // third button clicked
next();
} else if (SOAP.equals(cmd)) { // soap checkbox clicked
if ( xmlFile != null && xmlFile.canRead() )
reload();
} else if (CENTERONVERTEX.equals(cmd)) { // ceneter on vertex checkbox clicked
if ( centerOnVertexButton.isSelected() )
centerOnVertex();
}
}
public void load() {
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"XML files", "xml");
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showOpenDialog(getContentPane());
if (returnVal == JFileChooser.APPROVE_OPTION) {
xmlFile = fileChooser.getSelectedFile();
log.debug( "Got file: " + xmlFile.getAbsolutePath() );
loadModel();
if ( appEvent != null )
appEvent.getLoadEvent();
}
}
private void outPut() {
statisticsTextArea.setText( ModelBasedTesting.getInstance().getStatisticsString() );
variablesTextArea.setText( ModelBasedTesting.getInstance().getStatisticsString());
String str = "Last edge: "
+ (ModelBasedTesting.getInstance().getMachine().getLastEdge() == null ? ""
: (String) ModelBasedTesting.getInstance().getMachine().getLastEdge()
.getLabelKey())
+ " Current state: "
+ ModelBasedTesting.getInstance().getMachine().getCurrentState().getLabelKey();
latestStateLabel.setText( str );
str = ModelBasedTesting.getInstance().getMachine().getCurrentDataString();
str = str.replaceAll(";", newline);
variablesTextArea.setText( str );
}
private void setButtons() {
if ( status.isPaused() ) {
loadButton.setEnabled(true);
reloadButton.setEnabled(true);
runButton.setEnabled(true);
pauseButton.setEnabled(false);
nextButton.setEnabled(true);
soapButton.setEnabled(true);
}
else if ( status.isRunning() ) {
loadButton.setEnabled(false);
reloadButton.setEnabled(false);
runButton.setEnabled(false);
pauseButton.setEnabled(true);
nextButton.setEnabled(false);
soapButton.setEnabled(false);
}
else if ( status.isNext() ) {
loadButton.setEnabled(false);
reloadButton.setEnabled(false);
runButton.setEnabled(false);
pauseButton.setEnabled(false);
nextButton.setEnabled(false);
soapButton.setEnabled(false);
}
}
@SuppressWarnings("synthetic-access")
private void loadModel() {
if ( executeMBT != null ) {
executeMBT.cancel(true);
executeMBT = null;
}
status.setPaused();
setButtons();
if ( soapButton.isSelected() )
runSoap();
else
{
log.debug( "Loading model" );
ModelBasedTesting.getInstance().setUseGUI();
Util.loadMbtFromXml( xmlFile.getAbsolutePath() );
setTitle( "Model-Based Testing - " + xmlFile.getName() );
if ( centerOnVertexButton.isSelected() )
centerOnVertex();
}
(executeMBT = new ExecuteMBT()).execute();
}
public void run() {
status.setRunning();
setButtons();
}
private class ExecuteMBT extends SwingWorker<Void, Void> {
protected Void doInBackground() {
ModelBasedTesting.getInstance().executePath();
return null;
}
protected void done() {
super.done();
App.getInstance().pause();
}
}
public void pause() {
status.setPaused();
setButtons();
}
public void next() {
if ( ModelBasedTesting.getInstance().hasNextStep() == false )
return;
if ( status.isNext() ) {
return;
}
setButtons();
status.setNext();
setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) );
ModelBasedTesting.getInstance().getNextStep();
setCursor( Cursor.getDefaultCursor() );
status.setPaused();
setButtons();
if ( centerOnVertexButton.isSelected() )
centerOnVertex();
}
public void centerOnVertex() {
Vertex v = ModelBasedTesting.getInstance().getCurrentVertex();
if ( v != null ) {
Point2D target = getVv().getGraphLayout().transform( v );
Point2D current = vv.getRenderContext()
.getMultiLayerTransformer().inverseTransform(
vv.getCenter());
double dx = current.getX() - target.getX();
double dy = current.getY() - target.getY();
vv.getRenderContext().getMultiLayerTransformer()
.getTransformer(Layer.LAYOUT).translate(dx, dy);
}
}
public void updateUI() {
log.debug( "Updating the UI" );
outPut();
}
public void reload() {
loadModel();
}
public void setLayout(Layout<Vertex, Edge> layout) {
this.layout = layout;
Transformer<Vertex,Point2D> vertexLocation = new Transformer<Vertex,Point2D>(){
public Point2D transform(Vertex v) {
return v.getLocation();
}
};
this.layout.setInitializer(vertexLocation);
}
public VisualizationViewer<Vertex, Edge> getVv() {
return vv;
}
public void updateLayout() {
if ( ModelBasedTesting.getInstance().getGraph() != null ) {
setLayout( new StaticLayout<Vertex, Edge>( ModelBasedTesting.getInstance().getGraph() ) );
getVv().setGraphLayout( layout );
updateUI();
}
}
public class MyEdgePaintFunction implements Transformer<Edge,Paint> {
public Paint transform(Edge e) {
if ( ModelBasedTesting.getInstance().getMachine().getLastEdge() != null &&
ModelBasedTesting.getInstance().getMachine().getLastEdge().equals(e))
return Color.RED;
else if (e.getVisitedKey() > 0)
return Color.LIGHT_GRAY;
else
return Color.BLUE;
}
}
public class MyEdgeStrokeFunction implements Transformer<Edge,Stroke> {
protected final Stroke UNVISITED = new BasicStroke(3);
protected final Stroke VISITED = new BasicStroke(1);
protected final Stroke CURRENT = new BasicStroke(3);
public Stroke transform(Edge e) {
if ( ModelBasedTesting.getInstance().getMachine().getLastEdge() != null &&
ModelBasedTesting.getInstance().getMachine().getLastEdge().equals(e))
return CURRENT;
else if (e.getVisitedKey() > 0)
return VISITED;
else
return UNVISITED;
}
}
public class MyVertexPaintFunction implements Transformer<Vertex,Paint> {
public Paint transform(Vertex v) {
if ( ModelBasedTesting.getInstance().getMachine().isCurrentState(v))
return Color.RED;
else if (v.getVisitedKey() > 0 )
return Color.LIGHT_GRAY;
else
return Color.BLUE;
}
}
public class MyVertexFillPaintFunction implements Transformer<Vertex,Paint> {
public Paint transform( Vertex v ) {
if ( ModelBasedTesting.getInstance().getMachine().isCurrentState(v))
return Color.RED;
else if ( v.getVisitedKey() > 0 )
return Color.LIGHT_GRAY;
else
return v.getFillColor();
}
}
private VisualizationViewer<Vertex, Edge> getGraphViewer() {
if ( ModelBasedTesting.getInstance().getGraph() == null )
layout = new StaticLayout<Vertex, Edge>(new Graph() );
else
layout = new StaticLayout<Vertex, Edge>( ModelBasedTesting.getInstance().getGraph() );
vv = new VisualizationViewer<Vertex, Edge>(layout);
DefaultModalGraphMouse<Vertex, Edge> graphMouse = new DefaultModalGraphMouse<Vertex, Edge>();
vv.setGraphMouse(graphMouse);
vv.setPickSupport( new ShapePickSupport<Vertex, Edge>(vv));
vv.setBackground(Color.WHITE);
vv.getRenderContext().setVertexDrawPaintTransformer(new MyVertexPaintFunction());
vv.getRenderContext().setVertexFillPaintTransformer(new MyVertexFillPaintFunction());
vv.getRenderContext().setEdgeDrawPaintTransformer(new MyEdgePaintFunction());
vv.getRenderContext().setEdgeStrokeTransformer(new MyEdgeStrokeFunction());
vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
Transformer<Vertex,Shape> vertexShape = new Transformer<Vertex,Shape>(){
public Shape transform(Vertex v) {
Shape shape = new Rectangle2D.Float(0,0, v.getWidth(),v.getHeight());
return shape;
}
};
vv.getRenderContext().setVertexShapeTransformer( vertexShape );
Transformer<Vertex,String> vertexStringer = new Transformer<Vertex,String>(){
public String transform(Vertex v) {
return "<html><center>" + v.getFullLabelKey().replaceAll( "\\n", "<p>" ) + "<p>INDEX=" + v.getIndexKey();
}
};
vv.getRenderContext().setVertexLabelTransformer(vertexStringer);
Transformer<Edge,String> edgeStringer = new Transformer<Edge,String>(){
public String transform(Edge e) {
return "<html><center>" + e.getFullLabelKey().replaceAll( "\\n", "<p>" ) + "<p>INDEX=" + e.getIndexKey();
}
};
vv.getRenderContext().setEdgeLabelTransformer(edgeStringer);
return vv;
}
public void createPanelStatistics() {
panelStatistics = new JPanel();
panelStatistics.setLayout(new BorderLayout());
statisticsTextArea = new JTextArea();
statisticsTextArea.setPreferredSize(new Dimension(300,100));
panelStatistics.add(statisticsTextArea, BorderLayout.CENTER);
}
public void createPanelVariables() {
panelVariables = new JPanel();
panelVariables.setLayout(new BorderLayout());
variablesTextArea = new JTextArea();
variablesTextArea.setPreferredSize(new Dimension(100,100));
panelVariables.add(variablesTextArea, BorderLayout.CENTER);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand, String toolTipText, String altText, boolean enabled) {
// Look for the image.
String imgLocation = "resources/icons/" + imageName + ".png";
URL imageURL = App.class.getResource(imgLocation);
// Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
button.setEnabled(enabled);
if (imageURL != null) { // image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { // no image found
button.setText(altText);
log.error("Resource not found: " + imgLocation);
}
return button;
}
protected JCheckBox makeNavigationCheckBoxButton(String imageName,
String actionCommand, String toolTipText, String altText) {
// Create and initialize the button.
JCheckBox button = new JCheckBox();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
button.setText(altText);
return button;
}
private static final class LayoutChooser implements ActionListener
{
private final JComboBox jcb;
private final VisualizationViewer<Vertex,Edge> vv;
private LayoutChooser(JComboBox jcb, VisualizationViewer<Vertex,Edge> vv)
{
super();
this.jcb = jcb;
this.vv = vv;
}
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent arg0)
{
Graph graph = null;
if ( ModelBasedTesting.getInstance().getGraph() == null )
graph = new Graph();
else
graph = ModelBasedTesting.getInstance().getGraph();
Object[] constructorArgs =
{ graph };
Class<? extends Layout<Vertex,Edge>> layoutC =
(Class<? extends Layout<Vertex,Edge>>) jcb.getSelectedItem();
try
{
Constructor<? extends Layout<Vertex, Edge>> constructor = layoutC
.getConstructor(new Class[] {edu.uci.ics.jung.graph.Graph.class});
Object o = constructor.newInstance(constructorArgs);
Layout<Vertex,Edge> l = (Layout<Vertex,Edge>) o;
l.setInitializer(vv.getGraphLayout());
l.setSize(vv.getSize());
LayoutTransition<Vertex,Edge> lt =
new LayoutTransition<Vertex,Edge>(vv, vv.getGraphLayout(), l);
Animator animator = new Animator(lt);
animator.start();
vv.getRenderContext().getMultiLayerTransformer().setToIdentity();
vv.repaint();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
@SuppressWarnings({ "unchecked", "serial", "synthetic-access" })
public void addButtons(JToolBar toolBar) {
loadButton = makeNavigationButton("open", LOAD,
"Load a model (graphml file)",
"Load", true);
toolBar.add(loadButton);
reloadButton = makeNavigationButton("reload", RELOAD,
"Reload already loaded Model",
"Reload", false);
toolBar.add(reloadButton);
runButton = makeNavigationButton("run", RUN,
"Starts the execution",
"Run", false);
toolBar.add(runButton);
pauseButton = makeNavigationButton("pause", PAUSE,
"Pauses the execution",
"Pause", false);
toolBar.add(pauseButton);
nextButton = makeNavigationButton("next", NEXT,
"Walk a step in the model",
"Next", false);
toolBar.add(nextButton);
soapButton = makeNavigationCheckBoxButton("soap", SOAP,
"Run MBT in SOAP(Web Services) mode",
"Soap");
toolBar.add(soapButton);
centerOnVertexButton = makeNavigationCheckBoxButton("centerOnVertex", CENTERONVERTEX,
- "Center the layouu on the current vertex",
- "Center on current state");
+ "Center the layout on the current vertex",
+ "Center on current vertex");
toolBar.add(centerOnVertexButton);
Class[] combos = getCombos();
final JComboBox jcb = new JComboBox(combos);
// use a renderer to shorten the layout name presentation
jcb.setRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String valueString = value.toString();
valueString = valueString.substring(valueString.lastIndexOf('.')+1);
return super.getListCellRendererComponent(list, valueString, index, isSelected,
cellHasFocus);
}
});
jcb.addActionListener(new LayoutChooser(jcb, getVv()));
jcb.setSelectedItem(StaticLayout.class);
toolBar.add( jcb );
}
public void createPanelGraph() {
panelGraph = new JPanel();
panelGraph.setLayout(new BorderLayout());
latestStateLabel = new JLabel(" ");
panelGraph.add(latestStateLabel, BorderLayout.NORTH);
panelGraph.add(getGraphViewer(), BorderLayout.CENTER);
}
public void init() {
setTitle("Model-Based Testing");
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
// Create the panels
createPanelStatistics();
createPanelVariables();
createPanelGraph();
// Create a splitter panes
splitPaneGraph = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
topPanel.add(splitPaneGraph, BorderLayout.CENTER);
splitPaneGraph.setTopComponent(panelGraph);
splitPaneMessages = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPaneGraph.setBottomComponent(splitPaneMessages);
splitPaneMessages.setLeftComponent(panelStatistics);
splitPaneMessages.setRightComponent(panelVariables);
JToolBar toolBar = new JToolBar("Toolbar");
add(toolBar, BorderLayout.PAGE_START);
addButtons(toolBar);
}
// Private constructor prevents instantiation from other classes
private App() {
log = Util.setupLogger( App.class );
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationByPlatform(true);
setVisible(true);
}
/**
* AppHolder is loaded on the first execution of App.getInstance()
* or the first access to AppHolder.INSTANCE, not before.
*/
@SuppressWarnings("synthetic-access")
private static class AppHolder {
private static final App INSTANCE = new App();
}
@SuppressWarnings("synthetic-access")
public static App getInstance() {
return AppHolder.INSTANCE;
}
public static void main(String args[]) {
getInstance();
ModelBasedTesting.getInstance().setUseGUI();
}
}
| true | true | public void addButtons(JToolBar toolBar) {
loadButton = makeNavigationButton("open", LOAD,
"Load a model (graphml file)",
"Load", true);
toolBar.add(loadButton);
reloadButton = makeNavigationButton("reload", RELOAD,
"Reload already loaded Model",
"Reload", false);
toolBar.add(reloadButton);
runButton = makeNavigationButton("run", RUN,
"Starts the execution",
"Run", false);
toolBar.add(runButton);
pauseButton = makeNavigationButton("pause", PAUSE,
"Pauses the execution",
"Pause", false);
toolBar.add(pauseButton);
nextButton = makeNavigationButton("next", NEXT,
"Walk a step in the model",
"Next", false);
toolBar.add(nextButton);
soapButton = makeNavigationCheckBoxButton("soap", SOAP,
"Run MBT in SOAP(Web Services) mode",
"Soap");
toolBar.add(soapButton);
centerOnVertexButton = makeNavigationCheckBoxButton("centerOnVertex", CENTERONVERTEX,
"Center the layouu on the current vertex",
"Center on current state");
toolBar.add(centerOnVertexButton);
Class[] combos = getCombos();
final JComboBox jcb = new JComboBox(combos);
// use a renderer to shorten the layout name presentation
jcb.setRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String valueString = value.toString();
valueString = valueString.substring(valueString.lastIndexOf('.')+1);
return super.getListCellRendererComponent(list, valueString, index, isSelected,
cellHasFocus);
}
});
jcb.addActionListener(new LayoutChooser(jcb, getVv()));
jcb.setSelectedItem(StaticLayout.class);
toolBar.add( jcb );
}
| public void addButtons(JToolBar toolBar) {
loadButton = makeNavigationButton("open", LOAD,
"Load a model (graphml file)",
"Load", true);
toolBar.add(loadButton);
reloadButton = makeNavigationButton("reload", RELOAD,
"Reload already loaded Model",
"Reload", false);
toolBar.add(reloadButton);
runButton = makeNavigationButton("run", RUN,
"Starts the execution",
"Run", false);
toolBar.add(runButton);
pauseButton = makeNavigationButton("pause", PAUSE,
"Pauses the execution",
"Pause", false);
toolBar.add(pauseButton);
nextButton = makeNavigationButton("next", NEXT,
"Walk a step in the model",
"Next", false);
toolBar.add(nextButton);
soapButton = makeNavigationCheckBoxButton("soap", SOAP,
"Run MBT in SOAP(Web Services) mode",
"Soap");
toolBar.add(soapButton);
centerOnVertexButton = makeNavigationCheckBoxButton("centerOnVertex", CENTERONVERTEX,
"Center the layout on the current vertex",
"Center on current vertex");
toolBar.add(centerOnVertexButton);
Class[] combos = getCombos();
final JComboBox jcb = new JComboBox(combos);
// use a renderer to shorten the layout name presentation
jcb.setRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String valueString = value.toString();
valueString = valueString.substring(valueString.lastIndexOf('.')+1);
return super.getListCellRendererComponent(list, valueString, index, isSelected,
cellHasFocus);
}
});
jcb.addActionListener(new LayoutChooser(jcb, getVv()));
jcb.setSelectedItem(StaticLayout.class);
toolBar.add( jcb );
}
|
diff --git a/libraries/javalib/java/lang/System.java b/libraries/javalib/java/lang/System.java
index eee51db42..7b158a77e 100644
--- a/libraries/javalib/java/lang/System.java
+++ b/libraries/javalib/java/lang/System.java
@@ -1,240 +1,240 @@
/*
* Java core library component.
*
* Copyright (c) 1997, 1998
* Transvirtual Technologies, Inc. All rights reserved.
*
* See the file "license.terms" for information on usage and redistribution
* of this file.
*/
package java.lang;
import gnu.classpath.SystemProperties;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.util.Properties;
import java.util.PropertyPermission;
import kaffe.lang.ThreadStack;
public final class System {
final public static InputStream in;
final public static PrintStream out;
final public static PrintStream err;
// When trying to debug Java code that gets executed early on during
// JVM initialization, eg, before System.err is initialized, debugging
// println() statements don't work. In these cases, the following routines
// are very handy. Simply uncomment the following two lines to enable them.
/****
public static native void debug(String s); // print s to stderr, then \n
public static native void debugE(Throwable t); // print stack trace to stderr
****/
static {
// Initialise the I/O
if (SystemProperties.getProperty("kaffe.embedded", "false").equals("false")) {
in = new BufferedInputStream(new FileInputStream(FileDescriptor.in), 128);
out = new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out), 128), true);
err = new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.err), 128), true);
} else {
in = new BufferedInputStream(new kaffe.io.StdInputStream(), 128);
out = new PrintStream(new BufferedOutputStream(new kaffe.io.StdOutputStream(), 128), true);
err = new PrintStream(new BufferedOutputStream(new kaffe.io.StdErrorStream(), 128), true);
}
}
private System() { }
public static void arraycopy(Object src, int src_position, Object dst, int dst_position, int length) {
if (src == null)
throw new NullPointerException("src == null");
if (dst == null)
throw new NullPointerException("dst == null");
if (length == 0)
return;
final Class source_class = src.getClass();
if (!source_class.isArray())
throw new ArrayStoreException("source is not an array: " + source_class.getName());
final Class destination_class = dst.getClass();
if (!destination_class.isArray())
throw new ArrayStoreException("destination is not an array: " + destination_class.getName());
if (src_position < 0)
throw new ArrayIndexOutOfBoundsException("src_position < 0: " + src_position);
final int src_length = Array.getLength(src);
- if (src_position + length > src_length)
+ if ((long)src_position + (long)length > (long)src_length)
throw new ArrayIndexOutOfBoundsException("src_position + length > src.length: " + src_position + " + " + length + " > " + src_length);
if (dst_position < 0)
throw new ArrayIndexOutOfBoundsException("dst_position < 0: " + dst_position);
final int dst_length = Array.getLength(dst);
- if (dst_position + length > dst_length)
+ if ((long)dst_position + (long)length > (long)dst_length)
throw new ArrayIndexOutOfBoundsException("dst_position + length > dst.length: " + dst_position + " + " + length + " > " + dst_length);
if (length < 0)
throw new ArrayIndexOutOfBoundsException("length < 0: " + length);
arraycopy0(src, src_position, dst, dst_position, length);
}
private static native void arraycopy0(Object src, int src_position, Object dst, int dst_position, int length);
private static void checkPropertiesAccess() {
SecurityManager sm = getSecurityManager();
if (sm != null)
sm.checkPropertiesAccess();
}
private static void checkPropertyAccess(String key) {
SecurityManager sm = getSecurityManager();
if (key.length() == 0)
throw new IllegalArgumentException("key can't be empty");
if (sm != null)
sm.checkPropertyAccess(key);
}
native public static long currentTimeMillis();
public static void exit (int status) {
Runtime.getRuntime().exit(status);
}
public static void gc() {
Runtime.getRuntime().gc();
}
/* taken from GNUClasspath */
public static Properties getProperties()
{
SecurityManager sm = SecurityManager.current; // Be thread-safe.
if (sm != null)
sm.checkPropertiesAccess();
return SystemProperties.getProperties();
}
public static String getProperty(String key)
{
SecurityManager sm = SecurityManager.current; // Be thread-safe.
if (sm != null)
sm.checkPropertyAccess(key);
else if (key.length() == 0)
throw new IllegalArgumentException("key can't be empty");
return SystemProperties.getProperty(key);
}
public static String getProperty(String key, String def)
{
SecurityManager sm = SecurityManager.current; // Be thread-safe.
if (sm != null)
sm.checkPropertyAccess(key);
return SystemProperties.getProperty(key, def);
}
public static SecurityManager getSecurityManager() {
return Runtime.securityManager;
}
/* Adapted from GNU Classpath */
public static String getenv(String name) {
if (name == null)
throw new NullPointerException();
SecurityManager sm = Runtime.securityManager; // Be thread-safe.
if (sm != null)
sm.checkPermission(new RuntimePermission("getenv." + name));
return getenv0(name);
}
native private static String getenv0(String name);
native public static int identityHashCode(Object x);
native private static Properties initProperties(Properties properties);
public static void load(String filename) {
Runtime.getRuntime().load(filename,
ThreadStack.getCallersClassLoader(false));
}
public static void loadLibrary(String libname) {
Runtime.getRuntime().loadLibrary(libname,
ThreadStack.getCallersClassLoader(false));
}
public static String mapLibraryName(String fn) {
return Runtime.getRuntime().mapLibraryName(fn);
}
public static void runFinalization() {
Runtime.getRuntime().runFinalization();
}
public static void runFinalizersOnExit(boolean value) {
Runtime.runFinalizersOnExit(value);
}
private static void exitJavaCleanup() {
Runtime.getRuntime().exitJavaCleanup();
}
public static void setErr(PrintStream err) {
// XXX call security manager for RuntimePermission("SetIO")
setErr0(err);
}
native private static void setErr0(PrintStream err);
public static void setIn(InputStream in) {
// XXX call security manager for RuntimePermission("SetIO")
setIn0(in);
}
native private static void setIn0(InputStream in);
public static void setOut(PrintStream out) {
// XXX call security manager for RuntimePermission("SetIO")
setOut0(out);
}
native private static void setOut0(PrintStream out);
/* taken from GNU Classpath */
public static String setProperty(String key, String value)
{
SecurityManager sm = SecurityManager.current; // Be thread-safe.
if (sm != null)
sm.checkPermission(new PropertyPermission(key, "write"));
return SystemProperties.setProperty(key, value);
}
public static void setProperties(Properties properties)
{
SecurityManager sm = SecurityManager.current; // Be thread-safe.
if (sm != null)
sm.checkPropertiesAccess();
SystemProperties.setProperties(properties);
}
public static void setSecurityManager(SecurityManager s) {
if (Runtime.securityManager != null) {
Runtime.securityManager.checkPermission(
new RuntimePermission("setSecurityManager"));
}
Runtime.securityManager = s;
}
}
| false | true | public static void arraycopy(Object src, int src_position, Object dst, int dst_position, int length) {
if (src == null)
throw new NullPointerException("src == null");
if (dst == null)
throw new NullPointerException("dst == null");
if (length == 0)
return;
final Class source_class = src.getClass();
if (!source_class.isArray())
throw new ArrayStoreException("source is not an array: " + source_class.getName());
final Class destination_class = dst.getClass();
if (!destination_class.isArray())
throw new ArrayStoreException("destination is not an array: " + destination_class.getName());
if (src_position < 0)
throw new ArrayIndexOutOfBoundsException("src_position < 0: " + src_position);
final int src_length = Array.getLength(src);
if (src_position + length > src_length)
throw new ArrayIndexOutOfBoundsException("src_position + length > src.length: " + src_position + " + " + length + " > " + src_length);
if (dst_position < 0)
throw new ArrayIndexOutOfBoundsException("dst_position < 0: " + dst_position);
final int dst_length = Array.getLength(dst);
if (dst_position + length > dst_length)
throw new ArrayIndexOutOfBoundsException("dst_position + length > dst.length: " + dst_position + " + " + length + " > " + dst_length);
if (length < 0)
throw new ArrayIndexOutOfBoundsException("length < 0: " + length);
arraycopy0(src, src_position, dst, dst_position, length);
}
| public static void arraycopy(Object src, int src_position, Object dst, int dst_position, int length) {
if (src == null)
throw new NullPointerException("src == null");
if (dst == null)
throw new NullPointerException("dst == null");
if (length == 0)
return;
final Class source_class = src.getClass();
if (!source_class.isArray())
throw new ArrayStoreException("source is not an array: " + source_class.getName());
final Class destination_class = dst.getClass();
if (!destination_class.isArray())
throw new ArrayStoreException("destination is not an array: " + destination_class.getName());
if (src_position < 0)
throw new ArrayIndexOutOfBoundsException("src_position < 0: " + src_position);
final int src_length = Array.getLength(src);
if ((long)src_position + (long)length > (long)src_length)
throw new ArrayIndexOutOfBoundsException("src_position + length > src.length: " + src_position + " + " + length + " > " + src_length);
if (dst_position < 0)
throw new ArrayIndexOutOfBoundsException("dst_position < 0: " + dst_position);
final int dst_length = Array.getLength(dst);
if ((long)dst_position + (long)length > (long)dst_length)
throw new ArrayIndexOutOfBoundsException("dst_position + length > dst.length: " + dst_position + " + " + length + " > " + dst_length);
if (length < 0)
throw new ArrayIndexOutOfBoundsException("length < 0: " + length);
arraycopy0(src, src_position, dst, dst_position, length);
}
|
diff --git a/common/fr/minecraftforgefrance/ffmtapi/blockhelper/BlockFFMTLeavesBase.java b/common/fr/minecraftforgefrance/ffmtapi/blockhelper/BlockFFMTLeavesBase.java
index 17d4a3e..aa2f9d3 100644
--- a/common/fr/minecraftforgefrance/ffmtapi/blockhelper/BlockFFMTLeavesBase.java
+++ b/common/fr/minecraftforgefrance/ffmtapi/blockhelper/BlockFFMTLeavesBase.java
@@ -1,43 +1,44 @@
package fr.minecraftforgefrance.ffmtapi.blockhelper;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLeaves;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Icon;
import net.minecraft.world.IBlockAccess;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlockFFMTLeavesBase extends BlockLeaves
{
protected Icon fastIcon;
protected BlockFFMTLeavesBase(int id)
{
super(id);
+ this.setLightOpacity(1);
}
public boolean isOpaqueCube()
{
return Block.leaves.isOpaqueCube();
}
@SideOnly(Side.CLIENT)
public boolean shouldSideBeRendered(IBlockAccess blockaccess, int x, int y, int z, int side)
{
return !this.isOpaqueCube() ? true : super.shouldSideBeRendered(blockaccess, x, y, z, side);
}
public Icon getIcon(int side, int metadata)
{
return(isOpaqueCube() ? fastIcon : blockIcon);
}
public void getSubBlocks(int par1, CreativeTabs creativeTabs, List list)
{
list.add(new ItemStack(par1, 1, 0));
}
}
| true | true | protected BlockFFMTLeavesBase(int id)
{
super(id);
}
| protected BlockFFMTLeavesBase(int id)
{
super(id);
this.setLightOpacity(1);
}
|
diff --git a/src/main/java/org/easymetrics/easymetrics/cglib/MetricsProxyProcessor.java b/src/main/java/org/easymetrics/easymetrics/cglib/MetricsProxyProcessor.java
index 602e49a..27e0136 100644
--- a/src/main/java/org/easymetrics/easymetrics/cglib/MetricsProxyProcessor.java
+++ b/src/main/java/org/easymetrics/easymetrics/cglib/MetricsProxyProcessor.java
@@ -1,50 +1,50 @@
package org.easymetrics.easymetrics.cglib;
import java.lang.reflect.Method;
import org.easymetrics.easymetrics.model.Measurable;
import org.easymetrics.easymetrics.model.annotation.ProxyMetrics;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MetricsProxyProcessor implements BeanPostProcessor {
private ProxyInterceptor proxyInterceptor = new MetricsProxyInterceptor();
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Measurable) {
return proxyInterceptor.proxyObject(bean);
}
Class<? extends Object> clazz = bean.getClass();
if (isMetricsProxied(clazz)) {
- return proxyInterceptor.proxyObject(clazz);
+ return proxyInterceptor.proxyObject(bean);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
protected boolean isMetricsProxied(Class<?> clazz) {
Class<?> itr = clazz;
while (!itr.equals(Object.class)) {
for (Method m : itr.getDeclaredMethods()) {
if (m.getAnnotation(ProxyMetrics.class) != null) {
return true;
}
}
itr = itr.getSuperclass();
}
return false;
}
public void setProxyInterceptor(ProxyInterceptor proxyInterceptor) {
this.proxyInterceptor = proxyInterceptor;
}
}
| true | true | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Measurable) {
return proxyInterceptor.proxyObject(bean);
}
Class<? extends Object> clazz = bean.getClass();
if (isMetricsProxied(clazz)) {
return proxyInterceptor.proxyObject(clazz);
}
return bean;
}
| public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Measurable) {
return proxyInterceptor.proxyObject(bean);
}
Class<? extends Object> clazz = bean.getClass();
if (isMetricsProxied(clazz)) {
return proxyInterceptor.proxyObject(bean);
}
return bean;
}
|
diff --git a/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/domain/Task.java b/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/domain/Task.java
index a74d77a..9f32a6b 100644
--- a/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/domain/Task.java
+++ b/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/domain/Task.java
@@ -1,78 +1,79 @@
package at.ac.tuwien.complang.carfactory.domain;
import java.awt.Color;
import java.io.Serializable;
public class Task implements Serializable {
//Static Fields
private static final long serialVersionUID = -818265961255247515L;
//Fields
private MotorType motortype;
private int amount;
private int amountCompleted;
private Color color;
private long id;
public Task(long id) {
this.id = id;
}
public MotorType getMotortype() {
return motortype;
}
public void setMotortype(MotorType motortype) {
this.motortype = motortype;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public long getId() {
return id;
}
public int getAmountCompleted() {
return amountCompleted;
}
public void setAmountCompleted(int amountCompleted) {
this.amountCompleted = amountCompleted;
}
public Object[] getObjectData() {
String colorString;
if(color == null) {
colorString = "NONE";
} else if(color.equals(Color.RED)) {
colorString = "RED";
} else if(color.equals(Color.BLUE)) {
colorString = "BLUE";
} else if(color.equals(Color.GREEN)) {
colorString = "GREEN";
} else {
colorString = String.format("(%d, %d, %d)", color.getRed(), color.getGreen(), color.getBlue());
}
return new Object[] {
+ id,
motortype.getType(),
colorString,
amount,
amountCompleted
};
}
}
| true | true | public Object[] getObjectData() {
String colorString;
if(color == null) {
colorString = "NONE";
} else if(color.equals(Color.RED)) {
colorString = "RED";
} else if(color.equals(Color.BLUE)) {
colorString = "BLUE";
} else if(color.equals(Color.GREEN)) {
colorString = "GREEN";
} else {
colorString = String.format("(%d, %d, %d)", color.getRed(), color.getGreen(), color.getBlue());
}
return new Object[] {
motortype.getType(),
colorString,
amount,
amountCompleted
};
}
| public Object[] getObjectData() {
String colorString;
if(color == null) {
colorString = "NONE";
} else if(color.equals(Color.RED)) {
colorString = "RED";
} else if(color.equals(Color.BLUE)) {
colorString = "BLUE";
} else if(color.equals(Color.GREEN)) {
colorString = "GREEN";
} else {
colorString = String.format("(%d, %d, %d)", color.getRed(), color.getGreen(), color.getBlue());
}
return new Object[] {
id,
motortype.getType(),
colorString,
amount,
amountCompleted
};
}
|
diff --git a/src/org/aider/pmsi2sql/pmsi2sqlcreate.java b/src/org/aider/pmsi2sql/pmsi2sqlcreate.java
index 4f383cf..316a5e5 100644
--- a/src/org/aider/pmsi2sql/pmsi2sqlcreate.java
+++ b/src/org/aider/pmsi2sql/pmsi2sqlcreate.java
@@ -1,88 +1,92 @@
package org.aider.pmsi2sql;
import java.io.StringReader;
import java.sql.Connection;
import org.aider.pmsi2sql.linetypes.PmsiInsertion;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
/**
* Classe principale du programme pmsi2sqlcreate qui permet de cr�er les
* tables pour utiliser l'application pmsi2sql
* @author delabre
*
*/
public class pmsi2sqlcreate {
/**
* Fonction principale du programme pmsi2sqlcreate
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// D�finition des arguments fournis au programme
Pmsi2SqlBaseOptions options = new Pmsi2SqlBaseOptions();
CmdLineParser parser = new CmdLineParser(options);
// Tentative de lecture de la ligne de commande
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
// Au moins un argument requis est manquant
// Si on a appel� l'aide ou le num�ro de version, il est normal qu'un argument manque,
// Sinon on affiche le message indiquant les arguments possibles ainsi que l'argument
// manquant
if(!options.isHelp() && !options.isVersion()) {
parser.setUsageWidth(80);
parser.printUsage(System.out);
System.out.println(e.getMessage());
// Sortie de la fonction principale du programme
return;
}
}
// La ligne de commande a bien �t� lue, ou bien mal mais parceque l'argument 'help' ou
// 'version' a �t� indiqu�
if(options.isHelp()){
// L'affichage de l'aide a �t� demand�e
parser.setUsageWidth(80);
parser.printUsage(System.out);
+ // Sortie du programme
+ return;
} else if (options.isVersion()){
// L'affichage de la version a �t� demand�
parser.setUsageWidth(80);
System.out.println("Version : test");
+ // sortie du programme
+ return;
}
// Connexion � la base de donn�es selon les arguments de la ligne de commande
Connection myConn = options.getNewSqlConnection();
// Cr�ation de la table qui trace les tentatives d'insertion de fichiers pmsi
PmsiInsertion myInsertionTable = new PmsiInsertion("");
myConn.createStatement().execute(myInsertionTable.getSQLTable());
myConn.createStatement().execute(myInsertionTable.getSQLIndex());
myConn.createStatement().execute(myInsertionTable.getSQLFK());
myConn.commit();
// Cr�ation des tables permettant de stocker les RSS
PmsiRSSReader r = new PmsiRSSReader(new StringReader(""), options.getNewSqlConnection());
r.createTables();
r.createIndexes();
r.createKF();
r.commit();
// Cr�ation des tables permettant de stocker les RSF
PmsiRSFReader f = new PmsiRSFReader(new StringReader(""), options.getNewSqlConnection());
f.createTables();
f.createIndexes();
f.createKF();
f.commit();
//Fermeture de la connexion � la base de donn�es
myConn.close();
// Affichage de la r�ussite du programme
System.out.println("pmsi2sqlcreate successfully finished!");
}
}
| false | true | public static void main(String[] args) throws Exception {
// D�finition des arguments fournis au programme
Pmsi2SqlBaseOptions options = new Pmsi2SqlBaseOptions();
CmdLineParser parser = new CmdLineParser(options);
// Tentative de lecture de la ligne de commande
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
// Au moins un argument requis est manquant
// Si on a appel� l'aide ou le num�ro de version, il est normal qu'un argument manque,
// Sinon on affiche le message indiquant les arguments possibles ainsi que l'argument
// manquant
if(!options.isHelp() && !options.isVersion()) {
parser.setUsageWidth(80);
parser.printUsage(System.out);
System.out.println(e.getMessage());
// Sortie de la fonction principale du programme
return;
}
}
// La ligne de commande a bien �t� lue, ou bien mal mais parceque l'argument 'help' ou
// 'version' a �t� indiqu�
if(options.isHelp()){
// L'affichage de l'aide a �t� demand�e
parser.setUsageWidth(80);
parser.printUsage(System.out);
} else if (options.isVersion()){
// L'affichage de la version a �t� demand�
parser.setUsageWidth(80);
System.out.println("Version : test");
}
// Connexion � la base de donn�es selon les arguments de la ligne de commande
Connection myConn = options.getNewSqlConnection();
// Cr�ation de la table qui trace les tentatives d'insertion de fichiers pmsi
PmsiInsertion myInsertionTable = new PmsiInsertion("");
myConn.createStatement().execute(myInsertionTable.getSQLTable());
myConn.createStatement().execute(myInsertionTable.getSQLIndex());
myConn.createStatement().execute(myInsertionTable.getSQLFK());
myConn.commit();
// Cr�ation des tables permettant de stocker les RSS
PmsiRSSReader r = new PmsiRSSReader(new StringReader(""), options.getNewSqlConnection());
r.createTables();
r.createIndexes();
r.createKF();
r.commit();
// Cr�ation des tables permettant de stocker les RSF
PmsiRSFReader f = new PmsiRSFReader(new StringReader(""), options.getNewSqlConnection());
f.createTables();
f.createIndexes();
f.createKF();
f.commit();
//Fermeture de la connexion � la base de donn�es
myConn.close();
// Affichage de la r�ussite du programme
System.out.println("pmsi2sqlcreate successfully finished!");
}
| public static void main(String[] args) throws Exception {
// D�finition des arguments fournis au programme
Pmsi2SqlBaseOptions options = new Pmsi2SqlBaseOptions();
CmdLineParser parser = new CmdLineParser(options);
// Tentative de lecture de la ligne de commande
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
// Au moins un argument requis est manquant
// Si on a appel� l'aide ou le num�ro de version, il est normal qu'un argument manque,
// Sinon on affiche le message indiquant les arguments possibles ainsi que l'argument
// manquant
if(!options.isHelp() && !options.isVersion()) {
parser.setUsageWidth(80);
parser.printUsage(System.out);
System.out.println(e.getMessage());
// Sortie de la fonction principale du programme
return;
}
}
// La ligne de commande a bien �t� lue, ou bien mal mais parceque l'argument 'help' ou
// 'version' a �t� indiqu�
if(options.isHelp()){
// L'affichage de l'aide a �t� demand�e
parser.setUsageWidth(80);
parser.printUsage(System.out);
// Sortie du programme
return;
} else if (options.isVersion()){
// L'affichage de la version a �t� demand�
parser.setUsageWidth(80);
System.out.println("Version : test");
// sortie du programme
return;
}
// Connexion � la base de donn�es selon les arguments de la ligne de commande
Connection myConn = options.getNewSqlConnection();
// Cr�ation de la table qui trace les tentatives d'insertion de fichiers pmsi
PmsiInsertion myInsertionTable = new PmsiInsertion("");
myConn.createStatement().execute(myInsertionTable.getSQLTable());
myConn.createStatement().execute(myInsertionTable.getSQLIndex());
myConn.createStatement().execute(myInsertionTable.getSQLFK());
myConn.commit();
// Cr�ation des tables permettant de stocker les RSS
PmsiRSSReader r = new PmsiRSSReader(new StringReader(""), options.getNewSqlConnection());
r.createTables();
r.createIndexes();
r.createKF();
r.commit();
// Cr�ation des tables permettant de stocker les RSF
PmsiRSFReader f = new PmsiRSFReader(new StringReader(""), options.getNewSqlConnection());
f.createTables();
f.createIndexes();
f.createKF();
f.commit();
//Fermeture de la connexion � la base de donn�es
myConn.close();
// Affichage de la r�ussite du programme
System.out.println("pmsi2sqlcreate successfully finished!");
}
|
diff --git a/src/main/java/br/com/expense/parser/TransactionParserEngine.java b/src/main/java/br/com/expense/parser/TransactionParserEngine.java
index 3ac627a..9d3a4c5 100644
--- a/src/main/java/br/com/expense/parser/TransactionParserEngine.java
+++ b/src/main/java/br/com/expense/parser/TransactionParserEngine.java
@@ -1,80 +1,80 @@
package br.com.expense.parser;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import br.com.expense.config.Configuration;
import br.com.expense.model.Transaction;
import br.com.expense.parser.rules.CategoryRulesEngine;
import br.com.expense.util.FileUtil;
public class TransactionParserEngine {
private String[] transactionFiles;
private List<TransactionParser> transactionParsers;
private CategoryRulesEngine rulesEngine;
private Configuration configuration;
public TransactionParserEngine(Configuration configuration, List<TransactionParser> transactionParsers, CategoryRulesEngine categoryRulesEngine) {
this.transactionParsers = transactionParsers;
this.configuration = configuration;
this.rulesEngine = categoryRulesEngine;
}
public List<Transaction> getTransactions(File basePath) {
List<Transaction> transactions = new ArrayList<Transaction>();
this. transactionFiles = filterFiles(basePath, configuration);
for (String fileName : transactionFiles) {
String fileContent = FileUtil.loadFile(basePath, fileName);
boolean contentAlreadyParsed = false;
for (TransactionParser parser : transactionParsers) {
if (parser.accept(fileContent)) {
- System.out.println(">> File " + fileName + " accepted by " + parser.getName());
+ System.out.println(" >> File " + fileName + " accepted by " + parser.getName());
if (contentAlreadyParsed) {
throw new IllegalArgumentException("More then 1 parser for content:\r\n" + fileContent);
}
contentAlreadyParsed = true;
transactions.addAll(getParsedTransactions(fileContent, parser));
}
}
}
Collections.sort(transactions);
return transactions;
}
private List<Transaction> getParsedTransactions(String fileContent, TransactionParser parser) {
List<Transaction> parserTransactions = parser.parse(fileContent);
for (Transaction transaction : parserTransactions) {
transaction.setCategory(rulesEngine.getCategoryFor(transaction.getDescription()));
}
return parserTransactions;
}
private static String[] filterFiles(File baseDir, Configuration config) {
return baseDir.list(new TransactionFileFilter(config.getTransactionExtension()));
}
private static class TransactionFileFilter implements FilenameFilter {
private String extension;
public TransactionFileFilter(String extension) {
this.extension = extension;
}
@Override
public boolean accept(File dir, String name) {
boolean accept = name.endsWith(extension);
if (accept) {
System.out.println(">> Filtering " + name);
}
return accept;
}
}
}
| true | true | public List<Transaction> getTransactions(File basePath) {
List<Transaction> transactions = new ArrayList<Transaction>();
this. transactionFiles = filterFiles(basePath, configuration);
for (String fileName : transactionFiles) {
String fileContent = FileUtil.loadFile(basePath, fileName);
boolean contentAlreadyParsed = false;
for (TransactionParser parser : transactionParsers) {
if (parser.accept(fileContent)) {
System.out.println(">> File " + fileName + " accepted by " + parser.getName());
if (contentAlreadyParsed) {
throw new IllegalArgumentException("More then 1 parser for content:\r\n" + fileContent);
}
contentAlreadyParsed = true;
transactions.addAll(getParsedTransactions(fileContent, parser));
}
}
}
Collections.sort(transactions);
return transactions;
}
| public List<Transaction> getTransactions(File basePath) {
List<Transaction> transactions = new ArrayList<Transaction>();
this. transactionFiles = filterFiles(basePath, configuration);
for (String fileName : transactionFiles) {
String fileContent = FileUtil.loadFile(basePath, fileName);
boolean contentAlreadyParsed = false;
for (TransactionParser parser : transactionParsers) {
if (parser.accept(fileContent)) {
System.out.println(" >> File " + fileName + " accepted by " + parser.getName());
if (contentAlreadyParsed) {
throw new IllegalArgumentException("More then 1 parser for content:\r\n" + fileContent);
}
contentAlreadyParsed = true;
transactions.addAll(getParsedTransactions(fileContent, parser));
}
}
}
Collections.sort(transactions);
return transactions;
}
|
diff --git a/smart-load-test/smart-load-test-engine-impl/src/main/java/com/smartitengineering/loadtest/engine/impl/LoadTestEngineImpl.java b/smart-load-test/smart-load-test-engine-impl/src/main/java/com/smartitengineering/loadtest/engine/impl/LoadTestEngineImpl.java
index 96b1ff6..913dac2 100644
--- a/smart-load-test/smart-load-test-engine-impl/src/main/java/com/smartitengineering/loadtest/engine/impl/LoadTestEngineImpl.java
+++ b/smart-load-test/smart-load-test-engine-impl/src/main/java/com/smartitengineering/loadtest/engine/impl/LoadTestEngineImpl.java
@@ -1,382 +1,380 @@
/**
* This module represents an engine IMPL for the load testing framework
* Copyright (C) 2008 Imran M Yousuf ([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 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.smartitengineering.loadtest.engine.impl;
import com.smartitengineering.loadtest.engine.TestCase;
import com.smartitengineering.loadtest.engine.UnitTestInstance;
import com.smartitengineering.loadtest.engine.events.BatchEvent;
import com.smartitengineering.loadtest.engine.events.TestCaseBatchListener;
import com.smartitengineering.loadtest.engine.events.TestCaseStateChangeListener;
import com.smartitengineering.loadtest.engine.events.TestCaseStateChangedEvent;
import com.smartitengineering.loadtest.engine.events.TestCaseTransitionListener;
import com.smartitengineering.loadtest.engine.management.TestCaseBatchCreator;
import com.smartitengineering.loadtest.engine.management.TestCaseBatchCreator.Batch;
import com.smartitengineering.loadtest.engine.result.KeyedInformation;
import com.smartitengineering.loadtest.engine.result.TestCaseInstanceResult;
import com.smartitengineering.loadtest.engine.result.TestCaseResult;
import com.smartitengineering.loadtest.engine.result.TestProperty;
import com.smartitengineering.loadtest.engine.result.TestResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* Default implementation of the LoadTestEngine
*
*/
public class LoadTestEngineImpl
extends AbstractLoadTestEngineImpl {
protected EngineBatchListener engineBatchListener;
private Map<TestCaseBatchCreator, UnitTestInstance> creators;
private Map<UnitTestInstance, UnitTestInstanceRecord> instances;
private Map<TestCase, UnitTestInstanceRecord> caseRecords;
private Semaphore semaphore;
private EngineJobFinishedDetector finishedDetector;
private ExecutorService executorService;
private TestCaseTransitionListener transitionListener;
private TestCaseStateChangeListener caseStateChangeListener;
private TestResult result;
@Override
protected void initializeBeforeCreatedState() {
setTestInstances(new HashSet<UnitTestInstance>());
creators = new HashMap<TestCaseBatchCreator, UnitTestInstance>();
instances = new HashMap<UnitTestInstance, UnitTestInstanceRecord>();
}
public void init(String testName,
Set<UnitTestInstance> testInstances,
Properties initProperties)
throws IllegalArgumentException,
IllegalStateException {
if (getState().getStateStep() != State.CREATED.getStateStep()) {
throw new IllegalStateException();
}
if (testName == null || testName.length() <= 0) {
throw new IllegalArgumentException();
}
if (testInstances == null || testInstances.isEmpty()) {
throw new IllegalArgumentException();
}
if (initProperties != null && !initProperties.isEmpty()) {
if (initProperties.containsKey(PROPS_PERMIT_KEY)) {
try {
setPermits(Integer.parseInt(initProperties.getProperty(
PROPS_PERMIT_KEY)));
}
catch (Exception ex) {
ex.printStackTrace();
setPermits(-1);
}
}
}
engineBatchListener = new EngineBatchListener();
semaphore = new Semaphore(getPermits());
setTestName(testName);
getTestInstances().addAll(testInstances);
- for (UnitTestInstance instance : getTestInstances()) {
- try {
- TestCaseBatchCreator creator = getTestCaseBatchCreatorInstance();
- creator.init(instance);
- creator.addBatchCreatorListener(engineBatchListener);
- creators.put(creator, instance);
- }
- catch (Exception ex) {
- ex.printStackTrace();
- }
- }
transitionListener = new TestCaseStateTransitionMonitor();
addTestCaseTransitionListener(transitionListener);
caseStateChangeListener = new TestCaseStateListenerImpl();
caseRecords = new HashMap<TestCase, UnitTestInstanceRecord>();
finishedDetector = new EngineJobFinishedDetector();
executorService = Executors.newSingleThreadExecutor();
result = new TestResult();
result.setTestName(testName);
HashSet<TestCaseResult> resultSet = new HashSet<TestCaseResult>();
result.setTestCaseRunResults(resultSet);
for (UnitTestInstance instance : testInstances) {
+ try {
+ TestCaseBatchCreator creator = getTestCaseBatchCreatorInstance();
+ creator.init(instance);
+ creator.addBatchCreatorListener(engineBatchListener);
+ creators.put(creator, instance);
+ }
+ catch (Exception ex) {
+ ex.printStackTrace();
+ }
TestCaseResult caseResult = new TestCaseResult();
caseResult.setName(instance.getName());
caseResult.setInstanceFactoryClassName(instance.
getInstanceFactoryClassName());
final Properties testProperties = instance.getProperties();
- Set<TestProperty> testPropertys = new HashSet<TestProperty>(
+ Set<TestProperty> testPropertySet = new HashSet<TestProperty>(
testProperties.size());
final Iterator<Object> keySetIterator = testProperties.keySet().
iterator();
while (keySetIterator.hasNext()) {
TestProperty property = new TestProperty();
final String key = keySetIterator.next().toString();
property.setKey(key);
property.setValue(testProperties.getProperty(key));
- testPropertys.add(property);
+ testPropertySet.add(property);
}
- caseResult.setTestProperties(testPropertys);
+ caseResult.setTestProperties(testPropertySet);
caseResult.setTestCaseInstanceResults(
new HashSet<TestCaseInstanceResult>());
UnitTestInstanceRecord record = new UnitTestInstanceRecord(
caseResult);
instances.put(instance, record);
}
setState(State.INITIALIZED);
}
public void start()
throws IllegalStateException {
if (getState().getStateStep() != State.INITIALIZED.getStateStep()) {
throw new IllegalStateException();
}
getTestCaseThreadManager().startManager();
for (Map.Entry<TestCaseBatchCreator, UnitTestInstance> creator : creators.
entrySet()) {
creator.getKey().start();
}
setState(State.STARTED);
result.setStartDateTime(getStartTime());
}
public TestResult getTestResult()
throws IllegalStateException {
if (getState().getStateStep() < State.FINISHED.getStateStep()) {
throw new IllegalStateException();
}
if (result.isValid()) {
return result;
}
else {
throw new IllegalStateException("Test result in invalid state");
}
}
@Override
protected void rollBackToCreatedState() {
getTestInstances().clear();
setTestName(null);
semaphore = null;
engineBatchListener = null;
finishedDetector = null;
}
protected class EngineBatchListener
implements TestCaseBatchListener {
public void batchAvailable(BatchEvent event) {
boolean acquired = false;
try {
semaphore.acquire();
acquired = true;
Batch batch;
Map.Entry<ThreadGroup, Map<Thread, TestCase>> batchThreads;
batch = event.getBatch();
if (batch != null) {
batchThreads = batch.getBatch();
for (Map.Entry<Thread, TestCase> thread : batchThreads.
getValue().entrySet()) {
if (thread.getKey() != null && thread.getValue() != null) {
thread.getKey().start();
thread.getValue().addTestCaseStateChangeListener(
caseStateChangeListener);
getTestCaseThreadManager().manageThread(thread.
getKey(),
thread.getValue());
final TestCaseBatchCreator batchCreator =
batch.getBatchCreator();
if (batchCreator != null) {
final UnitTestInstance testInstance =
creators.get(batchCreator);
if (testInstance != null) {
final UnitTestInstanceRecord instanceRecord =
instances.get(testInstance);
if (instanceRecord != null) {
instanceRecord.incrementCount();
caseRecords.put(thread.getValue(),
instanceRecord);
}
}
}
}
}
batch.setBatchStarted();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (acquired) {
semaphore.release();
acquired = false;
}
}
}
public void batchCreationEnded(BatchEvent event) {
if (event.getBatch() != null &&
event.getBatch().getBatchCreator() != null) {
UnitTestInstance testInstance = creators.get(event.getBatch().
getBatchCreator());
if (testInstance != null) {
UnitTestInstanceRecord record = instances.get(testInstance);
record.setIntanceFinished();
executorService.submit(finishedDetector);
}
}
}
}
protected class TestCaseStateTransitionMonitor
implements TestCaseTransitionListener {
public void testCaseInitialized(TestCaseStateChangedEvent event) {
}
public void testCaseStarted(TestCaseStateChangedEvent event) {
}
public void testCaseFinished(TestCaseStateChangedEvent event) {
testCaseIsDone(event);
}
public void testCaseStopped(TestCaseStateChangedEvent event) {
testCaseIsDone(event);
}
private void testCaseIsDone(TestCaseStateChangedEvent event) {
UnitTestInstanceRecord record =
caseRecords.remove(event.getSource());
if (record != null) {
TestCase testCase = event.getSource();
TestCaseInstanceResult instanceResult = new TestCaseInstanceResult();
instanceResult.setStartTime(testCase.getStartTimeOfTest());
instanceResult.setEndTime(testCase.getEndTimeOfTest());
instanceResult.setEndTestCaseState(testCase.getState());
instanceResult.setInstanceNumber(record.getTestCaseCount());
Map<String, String> extraInfo = testCase.getTestCaseResultExtraInfo();
if(extraInfo != null) {
Set<Map.Entry<String, String>> entries = extraInfo.entrySet();
Set<KeyedInformation> otherInfo = new HashSet<KeyedInformation>(entries.size());
for (Map.Entry<String, String> extraInfoEntry : entries) {
KeyedInformation information = new KeyedInformation();
information.setKey(extraInfoEntry.getKey());
information.setValue(extraInfoEntry.getValue());
otherInfo.add(information);
}
instanceResult.setOtherInfomations(otherInfo);
}
record.getTestCaseResult().getTestCaseInstanceResults().add(
instanceResult);
record.decrementCount();
if (record.hasUnitTestInstanceFinished()) {
executorService.submit(finishedDetector);
}
}
}
}
protected class TestCaseStateListenerImpl
implements TestCaseStateChangeListener {
public void stateChanged(TestCaseStateChangedEvent stateChangeEvent) {
fireTestCaseStateTransitionEvent(stateChangeEvent);
}
}
protected class UnitTestInstanceRecord {
private int testCaseCount;
private TestCaseResult testCaseResult;
private boolean instanceFinished;
public UnitTestInstanceRecord(TestCaseResult result) {
if (result == null) {
throw new IllegalArgumentException();
}
testCaseCount = 0;
testCaseResult = result;
instanceFinished = true;
}
public synchronized void incrementCount() {
testCaseCount++;
}
public synchronized void decrementCount() {
testCaseCount--;
}
public int getTestCaseCount() {
return testCaseCount;
}
public boolean isInstanceFinished() {
return instanceFinished;
}
public synchronized void setIntanceFinished() {
instanceFinished = true;
}
public TestCaseResult getTestCaseResult() {
return testCaseResult;
}
public boolean hasUnitTestInstanceFinished() {
return isInstanceFinished() && getTestCaseCount() <= 0;
}
}
protected class EngineJobFinishedDetector
implements Runnable {
public void run() {
ArrayList<UnitTestInstance> toBeDeletedInstances =
new ArrayList<UnitTestInstance>();
for (Map.Entry<UnitTestInstance, UnitTestInstanceRecord> instanceRecord : instances.
entrySet()) {
if (instanceRecord.getValue() != null && instanceRecord.getValue().
hasUnitTestInstanceFinished()) {
toBeDeletedInstances.add(instanceRecord.getKey());
}
}
synchronized (instances) {
for (UnitTestInstance instance : toBeDeletedInstances) {
instances.remove(instance);
}
}
if (instances.isEmpty()) {
setState(State.FINISHED);
result.setEndDateTime(getEndTime());
}
}
}
}
| false | true | public void init(String testName,
Set<UnitTestInstance> testInstances,
Properties initProperties)
throws IllegalArgumentException,
IllegalStateException {
if (getState().getStateStep() != State.CREATED.getStateStep()) {
throw new IllegalStateException();
}
if (testName == null || testName.length() <= 0) {
throw new IllegalArgumentException();
}
if (testInstances == null || testInstances.isEmpty()) {
throw new IllegalArgumentException();
}
if (initProperties != null && !initProperties.isEmpty()) {
if (initProperties.containsKey(PROPS_PERMIT_KEY)) {
try {
setPermits(Integer.parseInt(initProperties.getProperty(
PROPS_PERMIT_KEY)));
}
catch (Exception ex) {
ex.printStackTrace();
setPermits(-1);
}
}
}
engineBatchListener = new EngineBatchListener();
semaphore = new Semaphore(getPermits());
setTestName(testName);
getTestInstances().addAll(testInstances);
for (UnitTestInstance instance : getTestInstances()) {
try {
TestCaseBatchCreator creator = getTestCaseBatchCreatorInstance();
creator.init(instance);
creator.addBatchCreatorListener(engineBatchListener);
creators.put(creator, instance);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
transitionListener = new TestCaseStateTransitionMonitor();
addTestCaseTransitionListener(transitionListener);
caseStateChangeListener = new TestCaseStateListenerImpl();
caseRecords = new HashMap<TestCase, UnitTestInstanceRecord>();
finishedDetector = new EngineJobFinishedDetector();
executorService = Executors.newSingleThreadExecutor();
result = new TestResult();
result.setTestName(testName);
HashSet<TestCaseResult> resultSet = new HashSet<TestCaseResult>();
result.setTestCaseRunResults(resultSet);
for (UnitTestInstance instance : testInstances) {
TestCaseResult caseResult = new TestCaseResult();
caseResult.setName(instance.getName());
caseResult.setInstanceFactoryClassName(instance.
getInstanceFactoryClassName());
final Properties testProperties = instance.getProperties();
Set<TestProperty> testPropertys = new HashSet<TestProperty>(
testProperties.size());
final Iterator<Object> keySetIterator = testProperties.keySet().
iterator();
while (keySetIterator.hasNext()) {
TestProperty property = new TestProperty();
final String key = keySetIterator.next().toString();
property.setKey(key);
property.setValue(testProperties.getProperty(key));
testPropertys.add(property);
}
caseResult.setTestProperties(testPropertys);
caseResult.setTestCaseInstanceResults(
new HashSet<TestCaseInstanceResult>());
UnitTestInstanceRecord record = new UnitTestInstanceRecord(
caseResult);
instances.put(instance, record);
}
setState(State.INITIALIZED);
}
| public void init(String testName,
Set<UnitTestInstance> testInstances,
Properties initProperties)
throws IllegalArgumentException,
IllegalStateException {
if (getState().getStateStep() != State.CREATED.getStateStep()) {
throw new IllegalStateException();
}
if (testName == null || testName.length() <= 0) {
throw new IllegalArgumentException();
}
if (testInstances == null || testInstances.isEmpty()) {
throw new IllegalArgumentException();
}
if (initProperties != null && !initProperties.isEmpty()) {
if (initProperties.containsKey(PROPS_PERMIT_KEY)) {
try {
setPermits(Integer.parseInt(initProperties.getProperty(
PROPS_PERMIT_KEY)));
}
catch (Exception ex) {
ex.printStackTrace();
setPermits(-1);
}
}
}
engineBatchListener = new EngineBatchListener();
semaphore = new Semaphore(getPermits());
setTestName(testName);
getTestInstances().addAll(testInstances);
transitionListener = new TestCaseStateTransitionMonitor();
addTestCaseTransitionListener(transitionListener);
caseStateChangeListener = new TestCaseStateListenerImpl();
caseRecords = new HashMap<TestCase, UnitTestInstanceRecord>();
finishedDetector = new EngineJobFinishedDetector();
executorService = Executors.newSingleThreadExecutor();
result = new TestResult();
result.setTestName(testName);
HashSet<TestCaseResult> resultSet = new HashSet<TestCaseResult>();
result.setTestCaseRunResults(resultSet);
for (UnitTestInstance instance : testInstances) {
try {
TestCaseBatchCreator creator = getTestCaseBatchCreatorInstance();
creator.init(instance);
creator.addBatchCreatorListener(engineBatchListener);
creators.put(creator, instance);
}
catch (Exception ex) {
ex.printStackTrace();
}
TestCaseResult caseResult = new TestCaseResult();
caseResult.setName(instance.getName());
caseResult.setInstanceFactoryClassName(instance.
getInstanceFactoryClassName());
final Properties testProperties = instance.getProperties();
Set<TestProperty> testPropertySet = new HashSet<TestProperty>(
testProperties.size());
final Iterator<Object> keySetIterator = testProperties.keySet().
iterator();
while (keySetIterator.hasNext()) {
TestProperty property = new TestProperty();
final String key = keySetIterator.next().toString();
property.setKey(key);
property.setValue(testProperties.getProperty(key));
testPropertySet.add(property);
}
caseResult.setTestProperties(testPropertySet);
caseResult.setTestCaseInstanceResults(
new HashSet<TestCaseInstanceResult>());
UnitTestInstanceRecord record = new UnitTestInstanceRecord(
caseResult);
instances.put(instance, record);
}
setState(State.INITIALIZED);
}
|
diff --git a/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java b/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
index dd495c11..046a4cff 100644
--- a/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
+++ b/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
@@ -1,333 +1,349 @@
/*
* Copyright 2010 The myBatis Team
*
* 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.mybatis.spring;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* {@link org.springframework.beans.factory.FactoryBean} that creates an MyBatis
* {@link org.apache.ibatis.session.SqlSessionFactory}. This is the usual way to set up a shared
* MyBatis SqlSessionFactory in a Spring application context; the SqlSessionFactory can then be
* passed to MyBatis-based DAOs via dependency injection.
*
* Either {@link org.springframework.jdbc.datasource.DataSourceTransactionManager} or
* {@link org.springframework.transaction.jta.JtaTransactionManager} can be used for transaction
* demarcation in combination with a SqlSessionFactory. JTA should be used for transactions
* which span multiple databases or when container managed transactions (CMT) are being used.
*
* Allows for specifying a DataSource at the SqlSessionFactory level. This is preferable to per-DAO
* DataSource references, as it allows for lazy loading and avoids repeated DataSource references in
* every DAO.
*
* @see #setConfigLocation
* @see #setDataSource
* @see org.mybatis.spring.SqlSessionTemplate#setSqlSessionFactory
* @see org.mybatis.spring.SqlSessionTemplate#setDataSource
* @version $Id$
*/
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean {
protected final Log logger = LogFactory.getLog(getClass());
private Resource configLocation;
private Resource[] mapperLocations;
private DataSource dataSource;
private Class<? extends TransactionFactory> transactionFactoryClass = SpringManagedTransactionFactory.class;
private Properties transactionFactoryProperties;
private Properties configurationProperties;
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private SqlSessionFactory sqlSessionFactory;
private String environment = SqlSessionFactoryBean.class.getSimpleName();
public SqlSessionFactoryBean() {}
/**
* Set the location of the MyBatis SqlSessionFactory config file. A typical value is
* "WEB-INF/mybatis-configuration.xml".
*/
public void setConfigLocation(Resource configLocation) {
this.configLocation = configLocation;
}
/**
* Set locations of MyBatis mapper files that are going to be merged into the SqlSessionFactory
* configuration at runtime.
*
* This is an alternative to specifying "<sqlmapper>" entries in an MyBatis config file.
* This property being based on Spring's resource abstraction also allows for specifying
* resource patterns here: e.g. "/sqlmap/*-mapper.xml".
*/
public void setMapperLocations(Resource[] mapperLocations) {
this.mapperLocations = mapperLocations;
}
/**
* Set optional properties to be passed into the SqlSession configuration, as alternative to a
* <code><properties></code> tag in the configuration xml file. This will be used to
* resolve placeholders in the config file.
*
* @see org.apache.ibatis.session.Configuration#getVariables
*/
public void setConfigurationProperties(Properties sqlSessionFactoryProperties) {
this.configurationProperties = sqlSessionFactoryProperties;
}
/**
* Set the JDBC DataSource that this instance should manage transactions for. The DataSource
* should match the one used by the SqlSessionFactory: for example, you could specify the same
* JNDI DataSource for both.
*
* A transactional JDBC Connection for this DataSource will be provided to application code
* accessing this DataSource directly via DataSourceUtils or DataSourceTransactionManager.
*
* The DataSource specified here should be the target DataSource to manage transactions for, not
* a TransactionAwareDataSourceProxy. Only data access code may work with
* TransactionAwareDataSourceProxy, while the transaction manager needs to work on the
* underlying target DataSource. If there's nevertheless a TransactionAwareDataSourceProxy
* passed in, it will be unwrapped to extract its target DataSource.
*
* @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
* @see org.springframework.jdbc.datasource.DataSourceUtils
* @see org.springframework.jdbc.datasource.DataSourceTransactionManager
*/
public void setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
// If we got a TransactionAwareDataSourceProxy, we need to perform
// transactions for its underlying target DataSource, else data
// access code won't see properly exposed transactions (i.e.
// transactions for the target DataSource).
this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
} else {
this.dataSource = dataSource;
}
}
/**
* Sets the SqlSessionFactoryBuilder to use when creating the SqlSessionFactory.
*
* This is mainly meant for testing so that mock SqlSessionFactory classes can be injected. By
* default, SqlSessionFactoryBuilder creates <code>DefaultSqlSessionFactory<code> instances.
*
* @see org.apache.ibatis.session.SqlSessionFactoryBuilder
*/
public void setSqlSessionFactoryBuilder(SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
}
/**
* Set the MyBatis TransactionFactory class to use. Default is
* <code>SpringManagedTransactionFactory</code>.
*
* The default SpringManagedTransactionFactory should be appropriate for all cases: be it Spring
* transaction management, EJB CMT or plain JTA. If there is no active transaction, SqlSession
* operations will execute SQL statements non-transactionally.
*
* <b>It is strongly recommended to use the default TransactionFactory.</b> If not used, any
* attempt at getting an SqlSession through Spring's MyBatis framework will throw an exception if
* a transaction is active.
*
* @see #setDataSource
* @see #setTransactionFactoryProperties(java.util.Properties)
* @see org.apache.ibatis.transaction.TransactionFactory
* @see org.mybatis.spring.transaction.SpringManagedTransactionFactory
* @see org.apache.ibatis.transaction.Transaction
* @see org.mybatis.spring.SqlSessionUtils#getSqlSession(SqlSessionFactory,
* DataSource, org.apache.ibatis.session.ExecutorType)
* @param <TF> the MyBatis TransactionFactory type
* @param transactionFactoryClass the MyBatis TransactionFactory class to use
*/
public <TF extends TransactionFactory> void setTransactionFactoryClass(Class<TF> transactionFactoryClass) {
this.transactionFactoryClass = transactionFactoryClass;
}
/**
* Set properties to be passed to the TransactionFactory instance used by this
* SqlSessionFactory.
*
* The default SpringManagedTransactionFactory does not have any user configurable properties.
*
* @see org.apache.ibatis.transaction.TransactionFactory#setProperties(java.util.Properties)
* @see org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory
* @see org.apache.ibatis.transaction.managed.ManagedTransactionFactory
*/
public void setTransactionFactoryProperties(Properties transactionFactoryProperties) {
this.transactionFactoryProperties = transactionFactoryProperties;
}
/**
* <b>NOTE:</b> This class <em>overrides</em> any Environment you have set in the MyBatis config
* file. This is used only as a placeholder name. The default value is
* <code>SqlSessionFactoryBean.class.getSimpleName()</code>.
*
* @param environment the environment name
*/
public void setEnvironment(String environment) {
this.environment = environment;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(dataSource, "Property 'dataSource' is required");
Assert.notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
Assert.notNull(transactionFactoryClass, "Property 'transactionFactoryClass' is required");
sqlSessionFactory = buildSqlSessionFactory();
}
/**
* Build a SqlSessionFactory instance.
*
* The default implementation uses the standard MyBatis {@link XMLConfigBuilder} API to build a
* SqlSessionFactory instance based on an Reader.
*
* @see org.apache.ibatis.builder.xml.XMLConfigBuilder#parse()
*
* @return SqlSessionFactory
*
* @throws IOException if loading the config file failed
* @throws IllegalAccessException
* @throws InstantiationException
*/
protected SqlSessionFactory buildSqlSessionFactory() throws IOException, IllegalAccessException,
InstantiationException {
XMLConfigBuilder xmlConfigBuilder;
Configuration configuration;
if (configLocation != null) {
+ Reader reader = null;
try {
- Reader reader = new InputStreamReader(configLocation.getInputStream());
+ reader = new InputStreamReader(configLocation.getInputStream());
// Null environment causes the configuration to use the default.
// This will be overwritten below regardless.
xmlConfigBuilder = new XMLConfigBuilder(reader, null, configurationProperties);
configuration = xmlConfigBuilder.parse();
} catch (IOException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex);
+ } finally {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException ignored) {
+ }
+ }
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + configLocation + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
TransactionFactory transactionFactory = this.transactionFactoryClass.newInstance(); // expose IllegalAccessException, InstantiationException
transactionFactory.setProperties(transactionFactoryProperties);
Environment environment = new Environment(this.environment, transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(mapperLocations)) {
Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
+ Reader reader = null;
for (Resource mapperLocation : mapperLocations) {
if (mapperLocation == null) {
continue;
}
// MyBatis holds a Map using "resource" name as a key.
// If a mapper file is loaded, it searches for a mapper interface type.
// If the type is found then it tries to load the mapper file again looking for this:
//
// String xmlResource = type.getName().replace('.', '/') + ".xml";
//
// So if a mapper interface exists, resource cannot be an absolute path.
// Otherwise MyBatis will throw an exception because
// it will load both a mapper interface and the mapper xml file,
// and throw an exception telling that a mapperStatement cannot be loaded twice.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ClassPathResource.class.cast(mapperLocation).getPath();
} else {
// this won't work if there is also a mapper interface in classpath
path = mapperLocation.getURI().getPath();
}
try {
- Reader reader = new InputStreamReader(mapperLocation.getInputStream());
+ reader = new InputStreamReader(mapperLocation.getInputStream());
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(reader, configuration, path, sqlFragments);
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
+ } finally {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException ignored) {
+ }
+ }
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper files specified in the config xml were loaded");
}
return sqlSessionFactoryBuilder.build(configuration);
}
public SqlSessionFactory getObject() throws Exception {
if (sqlSessionFactory == null) {
afterPropertiesSet();
}
return sqlSessionFactory;
}
public Class<? extends SqlSessionFactory> getObjectType() {
return sqlSessionFactory == null ? SqlSessionFactory.class : sqlSessionFactory.getClass();
}
public boolean isSingleton() {
return true;
}
}
| false | true | protected SqlSessionFactory buildSqlSessionFactory() throws IOException, IllegalAccessException,
InstantiationException {
XMLConfigBuilder xmlConfigBuilder;
Configuration configuration;
if (configLocation != null) {
try {
Reader reader = new InputStreamReader(configLocation.getInputStream());
// Null environment causes the configuration to use the default.
// This will be overwritten below regardless.
xmlConfigBuilder = new XMLConfigBuilder(reader, null, configurationProperties);
configuration = xmlConfigBuilder.parse();
} catch (IOException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex);
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + configLocation + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
TransactionFactory transactionFactory = this.transactionFactoryClass.newInstance(); // expose IllegalAccessException, InstantiationException
transactionFactory.setProperties(transactionFactoryProperties);
Environment environment = new Environment(this.environment, transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(mapperLocations)) {
Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
for (Resource mapperLocation : mapperLocations) {
if (mapperLocation == null) {
continue;
}
// MyBatis holds a Map using "resource" name as a key.
// If a mapper file is loaded, it searches for a mapper interface type.
// If the type is found then it tries to load the mapper file again looking for this:
//
// String xmlResource = type.getName().replace('.', '/') + ".xml";
//
// So if a mapper interface exists, resource cannot be an absolute path.
// Otherwise MyBatis will throw an exception because
// it will load both a mapper interface and the mapper xml file,
// and throw an exception telling that a mapperStatement cannot be loaded twice.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ClassPathResource.class.cast(mapperLocation).getPath();
} else {
// this won't work if there is also a mapper interface in classpath
path = mapperLocation.getURI().getPath();
}
try {
Reader reader = new InputStreamReader(mapperLocation.getInputStream());
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(reader, configuration, path, sqlFragments);
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper files specified in the config xml were loaded");
}
return sqlSessionFactoryBuilder.build(configuration);
}
| protected SqlSessionFactory buildSqlSessionFactory() throws IOException, IllegalAccessException,
InstantiationException {
XMLConfigBuilder xmlConfigBuilder;
Configuration configuration;
if (configLocation != null) {
Reader reader = null;
try {
reader = new InputStreamReader(configLocation.getInputStream());
// Null environment causes the configuration to use the default.
// This will be overwritten below regardless.
xmlConfigBuilder = new XMLConfigBuilder(reader, null, configurationProperties);
configuration = xmlConfigBuilder.parse();
} catch (IOException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + configLocation + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
TransactionFactory transactionFactory = this.transactionFactoryClass.newInstance(); // expose IllegalAccessException, InstantiationException
transactionFactory.setProperties(transactionFactoryProperties);
Environment environment = new Environment(this.environment, transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(mapperLocations)) {
Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
Reader reader = null;
for (Resource mapperLocation : mapperLocations) {
if (mapperLocation == null) {
continue;
}
// MyBatis holds a Map using "resource" name as a key.
// If a mapper file is loaded, it searches for a mapper interface type.
// If the type is found then it tries to load the mapper file again looking for this:
//
// String xmlResource = type.getName().replace('.', '/') + ".xml";
//
// So if a mapper interface exists, resource cannot be an absolute path.
// Otherwise MyBatis will throw an exception because
// it will load both a mapper interface and the mapper xml file,
// and throw an exception telling that a mapperStatement cannot be loaded twice.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ClassPathResource.class.cast(mapperLocation).getPath();
} else {
// this won't work if there is also a mapper interface in classpath
path = mapperLocation.getURI().getPath();
}
try {
reader = new InputStreamReader(mapperLocation.getInputStream());
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(reader, configuration, path, sqlFragments);
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper files specified in the config xml were loaded");
}
return sqlSessionFactoryBuilder.build(configuration);
}
|
diff --git a/do_jdbc/src/java/data_objects/drivers/AbstractDriverDefinition.java b/do_jdbc/src/java/data_objects/drivers/AbstractDriverDefinition.java
index a3516791..1d2b6b67 100644
--- a/do_jdbc/src/java/data_objects/drivers/AbstractDriverDefinition.java
+++ b/do_jdbc/src/java/data_objects/drivers/AbstractDriverDefinition.java
@@ -1,582 +1,586 @@
package data_objects.drivers;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.jruby.Ruby;
import org.jruby.RubyBigDecimal;
import org.jruby.RubyBignum;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyNumeric;
import org.jruby.RubyObjectAdapter;
import org.jruby.RubyProc;
import org.jruby.RubyString;
import org.jruby.RubyTime;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import data_objects.RubyType;
/**
*
* @author alexbcoles
*/
public abstract class AbstractDriverDefinition implements DriverDefinition {
protected static final RubyObjectAdapter api = JavaEmbedUtils
.newObjectAdapter();
private final String scheme;
private final String jdbcScheme;
private final String moduleName;
protected AbstractDriverDefinition(String scheme, String moduleName) {
this(scheme, scheme, moduleName);
}
protected AbstractDriverDefinition(String scheme, String jdbcScheme,
String moduleName) {
this.scheme = scheme;
this.jdbcScheme = jdbcScheme;
this.moduleName = moduleName;
}
public String getModuleName() {
return this.moduleName;
}
public String getErrorName() {
return this.moduleName + "Error";
}
@SuppressWarnings("unchecked")
public final URI parseConnectionURI(IRubyObject connection_uri)
throws URISyntaxException, UnsupportedEncodingException {
URI uri;
if ("DataObjects::URI".equals(connection_uri.getType().getName())) {
String query = null;
StringBuffer userInfo = new StringBuffer();
verifyScheme(stringOrNull(api.callMethod(connection_uri, "scheme")));
String user = stringOrNull(api.callMethod(connection_uri, "user"));
String password = stringOrNull(api.callMethod(connection_uri,
"password"));
String host = stringOrNull(api.callMethod(connection_uri, "host"));
int port = intOrMinusOne(api.callMethod(connection_uri, "port"));
String path = stringOrNull(api.callMethod(connection_uri, "path"));
IRubyObject query_values = api.callMethod(connection_uri, "query");
String fragment = stringOrNull(api.callMethod(connection_uri,
"fragment"));
if (user != null && !"".equals(user)) {
userInfo.append(user);
if (password != null && !"".equals(password)) {
userInfo.append(":").append(password);
}
}
if (query_values.isNil()) {
query = null;
} else if (query_values instanceof RubyHash) {
query = mapToQueryString(query_values.convertToHash());
} else {
query = api.callMethod(query_values, "to_s").asJavaString();
}
if (host != null && !"".equals(host)) {
// a client/server database (e.g. MySQL, PostgreSQL, MS
// SQLServer)
uri = new URI(this.jdbcScheme, userInfo.toString(), host, port,
path, query, fragment);
} else {
// an embedded / file-based database (e.g. SQLite3, Derby
// (embedded mode), HSQLDB - use opaque uri
uri = new java.net.URI(this.jdbcScheme, path, fragment);
}
} else {
// If connection_uri comes in as a string, we just pass it
// through
uri = new URI(connection_uri.asJavaString());
}
return uri;
}
protected void verifyScheme(String scheme) {
if (!this.scheme.equals(scheme)) {
throw new RuntimeException("scheme mismatch, expected: "
+ this.scheme + " but got: " + scheme);
}
}
public String sanitizePreparedStatementText(String psText) {
return psText;
}
/**
* Convert a map of key/values to a URI query string
*
* @param map
* @return
* @throws java.io.UnsupportedEncodingException
*/
private String mapToQueryString(Map<Object, Object> map)
throws UnsupportedEncodingException {
Iterator it = map.entrySet().iterator();
StringBuffer querySb = new StringBuffer();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
String key = (pairs.getKey() != null) ? pairs.getKey().toString()
: "";
String value = (pairs.getValue() != null) ? pairs.getValue()
.toString() : "";
querySb.append(java.net.URLEncoder.encode(key, "UTF-8"))
.append("=");
querySb.append(java.net.URLEncoder.encode(value, "UTF-8"));
}
return querySb.toString();
}
public RaiseException newDriverError(Ruby runtime, String message) {
RubyClass driverError = runtime.getClass(getErrorName());
return new RaiseException(runtime, driverError, message, true);
}
public RaiseException newDriverError(Ruby runtime, SQLException exception) {
return newDriverError(runtime, exception, null);
}
public RaiseException newDriverError(Ruby runtime, SQLException exception,
java.sql.Statement statement) {
RubyClass driverError = runtime.getClass(getErrorName());
int code = exception.getErrorCode();
StringBuffer sb = new StringBuffer("(");
// Append the Vendor Code, if there is one
// TODO: parse vendor exception codes
// TODO: replace 'vendor' with vendor name
if (code > 0)
sb.append("vendor_errno=").append(code).append(", ");
sb.append("sql_state=").append(exception.getSQLState()).append(") ");
sb.append(exception.getLocalizedMessage());
// TODO: delegate to the DriverDefinition for this
if (statement != null)
sb.append("\nQuery: ").append(statement.toString());
return new RaiseException(runtime, driverError, sb.toString(), true);
}
public RubyObjectAdapter getObjectAdapter() {
return api;
}
public final IRubyObject getTypecastResultSetValue(Ruby runtime,
ResultSet rs, int col, RubyType type) throws SQLException,
IOException {
// TODO assert to needs to be turned on with the java call
// better throw something
assert (type != null); // this method does not expect a null Ruby Type
if (rs == null) {// || rs.wasNull()) {
return runtime.getNil();
}
return doGetTypecastResultSetValue(runtime, rs, col, type);
}
protected IRubyObject doGetTypecastResultSetValue(Ruby runtime,
ResultSet rs, int col, RubyType type) throws SQLException,
IOException {
switch (type) {
case FIXNUM:
case INTEGER:
case BIGNUM:
// TODO: attempt to make this more granular, depending on the
// size of the number (?)
long lng = rs.getLong(col);
return RubyNumeric.int2fix(runtime, lng);
case FLOAT:
- return new RubyFloat(runtime, rs.getBigDecimal(col).doubleValue());
+ java.math.BigDecimal bdf = rs.getBigDecimal(col);
+ if (bdf == null) {
+ return runtime.getNil();
+ }
+ return new RubyFloat(runtime, bdf.doubleValue());
case BIG_DECIMAL:
return new RubyBigDecimal(runtime, rs.getBigDecimal(col));
case DATE:
java.sql.Date date = rs.getDate(col);
if (date == null) {
return runtime.getNil();
}
return prepareRubyDateFromSqlDate(runtime, new DateTime(date));
case DATE_TIME:
java.sql.Timestamp dt = null;
// DateTimes with all-zero components throw a SQLException with
// SQLState S1009 in MySQL Connector/J 3.1+
// See
// http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html
try {
dt = rs.getTimestamp(col);
} catch (SQLException sqle) {
}
if (dt == null) {
return runtime.getNil();
}
return prepareRubyDateTimeFromSqlTimestamp(runtime,
new DateTime(dt));
case TIME:
switch (rs.getMetaData().getColumnType(col)) {
case Types.TIME:
java.sql.Time tm = rs.getTime(col);
if (tm == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm));
case Types.TIMESTAMP:
java.sql.Time ts = rs.getTime(col);
if (ts == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlTime(runtime, new DateTime(ts));
case Types.DATE:
java.sql.Date da = rs.getDate(col);
if (da == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlDate(runtime, da);
default:
String str = rs.getString(col);
if (str == null) {
return runtime.getNil();
}
RubyString return_str = RubyString.newUnicodeString(runtime,
str);
return_str.setTaint(true);
return return_str;
}
case TRUE_CLASS:
boolean bool = rs.getBoolean(col);
return runtime.newBoolean(bool);
case BYTE_ARRAY:
InputStream binaryStream = rs.getBinaryStream(col);
ByteList bytes = new ByteList(2048);
try {
byte[] buf = new byte[2048];
for (int n = binaryStream.read(buf); n != -1; n = binaryStream
.read(buf)) {
bytes.append(buf, 0, n);
}
} finally {
binaryStream.close();
}
return api.callMethod(runtime.fastGetModule("Extlib").fastGetClass(
"ByteArray"), "new", runtime.newString(bytes));
case CLASS:
String classNameStr = rs.getString(col);
if (classNameStr == null) {
return runtime.getNil();
}
RubyString class_name_str = RubyString.newUnicodeString(runtime, rs
.getString(col));
class_name_str.setTaint(true);
return api.callMethod(runtime.getObject(), "full_const_get",
class_name_str);
case OBJECT:
InputStream asciiStream = rs.getAsciiStream(col);
IRubyObject obj = runtime.getNil();
try {
UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream,
RubyProc.NEVER);
obj = ums.unmarshalObject();
} catch (IOException ioe) {
// TODO: log this
}
return obj;
case NIL:
return runtime.getNil();
case STRING:
default:
String str = rs.getString(col);
if (str == null) {
return runtime.getNil();
}
RubyString return_str = RubyString.newUnicodeString(runtime, str);
return_str.setTaint(true);
return return_str;
}
}
// TODO SimpleDateFormat is not threadsafe better use joda classes
// http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html#synchronization
// http://joda-time.sourceforge.net/api-release/org/joda/time/DateTime.html
// private static final DateFormat FORMAT = new SimpleDateFormat(
// "yyyy-MM-dd HH:mm:ss");
public void setPreparedStatementParam(PreparedStatement ps,
IRubyObject arg, int idx) throws SQLException {
switch (RubyType.getRubyType(arg.getType().getName())) {
case FIXNUM:
ps.setInt(idx, Integer.parseInt(arg.toString()));
break;
case BIGNUM:
ps.setLong(idx, ((RubyBignum) arg).getLongValue());
break;
case FLOAT:
ps.setDouble(idx, RubyNumeric.num2dbl(arg));
break;
case BIG_DECIMAL:
ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue());
break;
case NIL:
ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx));
break;
case TRUE_CLASS:
case FALSE_CLASS:
ps.setBoolean(idx, arg.toString().equals("true"));
break;
case CLASS:
ps.setString(idx, arg.toString());
break;
case BYTE_ARRAY:
ps.setBytes(idx, ((RubyString) arg).getBytes());
break;
// TODO: add support for ps.setBlob();
case DATE:
ps.setDate(idx, java.sql.Date.valueOf(arg.toString()));
break;
case TIME:
DateTime dateTime = ((RubyTime) arg).getDateTime();
GregorianCalendar cal = dateTime.toGregorianCalendar();
Timestamp ts;
if (supportsCalendarsInJDBCPreparedStatement() == true) {
ts = new Timestamp(dateTime.getMillis());
} else {
// XXX ugly workaround for MySQL and Hsqldb
// use the default timeZone the oposite way these jdbc drivers do it
long offset = DateTimeZone.getDefault().getOffset(dateTime.getMillis());
ts = new Timestamp(dateTime.getMillis() - offset);
}
ps.setTimestamp(idx, ts, cal);
break;
case DATE_TIME:
String datetime = arg.toString().replace('T', ' ');
ps.setTimestamp(idx, Timestamp.valueOf(datetime
.replaceFirst("[-+]..:..$", "")));
break;
default:
if (arg.toString().indexOf("-") != -1
&& arg.toString().indexOf(":") != -1) {
// TODO: improve the above string pattern checking
// Handle date patterns in strings
try {
DateTime timestamp = DATE_TIME_FORMAT.parseDateTime(arg
.asJavaString().replace('T', ' '));
ps.setTimestamp(idx, new Timestamp(timestamp.getMillis()));
} catch (IllegalArgumentException ex) {
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
}
} else if (arg.toString().indexOf(":") != -1
&& arg.toString().length() == 8) {
// Handle time patterns in strings
ps.setTime(idx, java.sql.Time.valueOf(arg.asJavaString()));
} else {
Integer jdbcTypeId = null;
try {
jdbcTypeId = ps.getMetaData().getColumnType(idx);
} catch (Exception ex) {
}
if (jdbcTypeId == null) {
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
} else {
// TODO: Here comes conversions like '.execute_reader("2")'
// It definitly needs to be refactored...
try {
if (jdbcTypeId == Types.VARCHAR) {
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
} else if (jdbcTypeId == Types.INTEGER) {
ps.setObject(idx, Integer.valueOf(arg.toString()),
jdbcTypeId);
} else {
// I'm not sure is it correct in 100%
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
}
} catch (NumberFormatException ex) { // i.e
// Integer.valueOf
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
}
}
}
}
}
public abstract boolean supportsJdbcGeneratedKeys();
public abstract boolean supportsJdbcScrollableResultSets();
public boolean supportsConnectionEncodings() {
return false;
}
public boolean supportsConnectionPrepareStatementMethodWithGKFlag() {
return true;
}
public boolean supportsCalendarsInJDBCPreparedStatement(){
return true;
}
public ResultSet getGeneratedKeys(Connection connection) {
return null;
}
public Properties getDefaultConnectionProperties() {
return new Properties();
}
public void setEncodingProperty(Properties props, String encodingName) {
// do nothing
}
public String quoteString(String str) {
StringBuffer quotedValue = new StringBuffer(str.length() + 2);
quotedValue.append("\'");
quotedValue.append(str);
quotedValue.append("\'");
return quotedValue.toString();
}
public String toString(PreparedStatement ps) {
return ps.toString();
}
protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp(
Ruby runtime, DateTime stamp) {
if (stamp.getMillis() == 0) {
return runtime.getNil();
}
int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; // regCalendar.get(Calendar.ZONE_OFFSET)
// /
// 3600000;
RubyClass klazz = runtime.fastGetClass("DateTime");
IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod(
runtime.getCurrentContext(),
"new",
new IRubyObject[] { runtime.newFixnum(zoneOffset),
runtime.newFixnum(24) });
return klazz.callMethod(runtime.getCurrentContext(), "civil",
new IRubyObject[] { runtime.newFixnum(stamp.getYear()),// gregCalendar.get(Calendar.YEAR)),
runtime.newFixnum(stamp.getMonthOfYear()),// month),
runtime.newFixnum(stamp.getDayOfMonth()), // gregCalendar.get(Calendar.DAY_OF_MONTH)),
runtime.newFixnum(stamp.getHourOfDay()), // gregCalendar.get(Calendar.HOUR_OF_DAY)),
runtime.newFixnum(stamp.getMinuteOfHour()), // gregCalendar.get(Calendar.MINUTE)),
runtime.newFixnum(stamp.getSecondOfMinute()), // gregCalendar.get(Calendar.SECOND)),
rbOffset });
}
protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime,
DateTime time) {
if (time.getMillis() + 3600000 == 0) {
return runtime.getNil();
}
RubyTime rbTime = RubyTime.newTime(runtime, time);
rbTime.extend(new IRubyObject[] { runtime.getModule("TimeFormatter") });
return rbTime;
}
protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime,
Date date) {
if (date.getTime() + 3600000 == 0) {
return runtime.getNil();
}
RubyTime rbTime = RubyTime.newTime(runtime, date.getTime());
rbTime.extend(new IRubyObject[] { runtime.getModule("TimeFormatter") });
return rbTime;
}
public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime,
DateTime date) {
if (date.getMillis() == 0) {
return runtime.getNil();
}
// TODO
// gregCalendar.setTime(date.toDate());
// int month = gregCalendar.get(Calendar.MONTH);
// month++; // In Calendar January == 0, etc...
RubyClass klazz = runtime.fastGetClass("Date");
return klazz.callMethod(runtime.getCurrentContext(), "civil",
new IRubyObject[] { runtime.newFixnum(date.getYear()),
runtime.newFixnum(date.getMonthOfYear()),
runtime.newFixnum(date.getDayOfMonth()) });
}
private final static DateTimeFormatter DATE_FORMAT = ISODateTimeFormat
.date();// yyyy-MM-dd
private final static DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat
.forPattern("yyyy-MM-dd HH:mm:ss");
private final static DateTimeFormatter TIMESTAMP_FORMAT = ISODateTimeFormat
.dateTime();
public static DateTime toDate(String date) {
return DATE_FORMAT.parseDateTime(date.replaceFirst("T.*", ""));
}
public static DateTime toTimestamp(String stamp) {
DateTimeFormatter formatter = stamp.contains("T") ? TIMESTAMP_FORMAT
: DATE_FORMAT;// "yyyy-MM-dd'T'HH:mm:ssZ" : "yyyy-MM-dd");
return formatter.parseDateTime(stamp);
}
public static DateTime toTime(String time) {
DateTimeFormatter formatter = time.contains(" ") ? DATE_TIME_FORMAT
: DATE_FORMAT;
return formatter.parseDateTime(time);
}
private static String stringOrNull(IRubyObject obj) {
return (!obj.isNil()) ? obj.asJavaString() : null;
}
private static int intOrMinusOne(IRubyObject obj) {
return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1;
}
// private static Integer integerOrNull(IRubyObject obj) {
// return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null;
// }
}
| true | true | public final IRubyObject getTypecastResultSetValue(Ruby runtime,
ResultSet rs, int col, RubyType type) throws SQLException,
IOException {
// TODO assert to needs to be turned on with the java call
// better throw something
assert (type != null); // this method does not expect a null Ruby Type
if (rs == null) {// || rs.wasNull()) {
return runtime.getNil();
}
return doGetTypecastResultSetValue(runtime, rs, col, type);
}
protected IRubyObject doGetTypecastResultSetValue(Ruby runtime,
ResultSet rs, int col, RubyType type) throws SQLException,
IOException {
switch (type) {
case FIXNUM:
case INTEGER:
case BIGNUM:
// TODO: attempt to make this more granular, depending on the
// size of the number (?)
long lng = rs.getLong(col);
return RubyNumeric.int2fix(runtime, lng);
case FLOAT:
return new RubyFloat(runtime, rs.getBigDecimal(col).doubleValue());
case BIG_DECIMAL:
return new RubyBigDecimal(runtime, rs.getBigDecimal(col));
case DATE:
java.sql.Date date = rs.getDate(col);
if (date == null) {
return runtime.getNil();
}
return prepareRubyDateFromSqlDate(runtime, new DateTime(date));
case DATE_TIME:
java.sql.Timestamp dt = null;
// DateTimes with all-zero components throw a SQLException with
// SQLState S1009 in MySQL Connector/J 3.1+
// See
// http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html
try {
dt = rs.getTimestamp(col);
} catch (SQLException sqle) {
}
if (dt == null) {
return runtime.getNil();
}
return prepareRubyDateTimeFromSqlTimestamp(runtime,
new DateTime(dt));
case TIME:
switch (rs.getMetaData().getColumnType(col)) {
case Types.TIME:
java.sql.Time tm = rs.getTime(col);
if (tm == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm));
case Types.TIMESTAMP:
java.sql.Time ts = rs.getTime(col);
if (ts == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlTime(runtime, new DateTime(ts));
case Types.DATE:
java.sql.Date da = rs.getDate(col);
if (da == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlDate(runtime, da);
default:
String str = rs.getString(col);
if (str == null) {
return runtime.getNil();
}
RubyString return_str = RubyString.newUnicodeString(runtime,
str);
return_str.setTaint(true);
return return_str;
}
case TRUE_CLASS:
boolean bool = rs.getBoolean(col);
return runtime.newBoolean(bool);
case BYTE_ARRAY:
InputStream binaryStream = rs.getBinaryStream(col);
ByteList bytes = new ByteList(2048);
try {
byte[] buf = new byte[2048];
for (int n = binaryStream.read(buf); n != -1; n = binaryStream
.read(buf)) {
bytes.append(buf, 0, n);
}
} finally {
binaryStream.close();
}
return api.callMethod(runtime.fastGetModule("Extlib").fastGetClass(
"ByteArray"), "new", runtime.newString(bytes));
case CLASS:
String classNameStr = rs.getString(col);
if (classNameStr == null) {
return runtime.getNil();
}
RubyString class_name_str = RubyString.newUnicodeString(runtime, rs
.getString(col));
class_name_str.setTaint(true);
return api.callMethod(runtime.getObject(), "full_const_get",
class_name_str);
case OBJECT:
InputStream asciiStream = rs.getAsciiStream(col);
IRubyObject obj = runtime.getNil();
try {
UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream,
RubyProc.NEVER);
obj = ums.unmarshalObject();
} catch (IOException ioe) {
// TODO: log this
}
return obj;
case NIL:
return runtime.getNil();
case STRING:
default:
String str = rs.getString(col);
if (str == null) {
return runtime.getNil();
}
RubyString return_str = RubyString.newUnicodeString(runtime, str);
return_str.setTaint(true);
return return_str;
}
}
// TODO SimpleDateFormat is not threadsafe better use joda classes
// http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html#synchronization
// http://joda-time.sourceforge.net/api-release/org/joda/time/DateTime.html
// private static final DateFormat FORMAT = new SimpleDateFormat(
// "yyyy-MM-dd HH:mm:ss");
public void setPreparedStatementParam(PreparedStatement ps,
IRubyObject arg, int idx) throws SQLException {
switch (RubyType.getRubyType(arg.getType().getName())) {
case FIXNUM:
ps.setInt(idx, Integer.parseInt(arg.toString()));
break;
case BIGNUM:
ps.setLong(idx, ((RubyBignum) arg).getLongValue());
break;
case FLOAT:
ps.setDouble(idx, RubyNumeric.num2dbl(arg));
break;
case BIG_DECIMAL:
ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue());
break;
case NIL:
ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx));
break;
case TRUE_CLASS:
case FALSE_CLASS:
ps.setBoolean(idx, arg.toString().equals("true"));
break;
case CLASS:
ps.setString(idx, arg.toString());
break;
case BYTE_ARRAY:
ps.setBytes(idx, ((RubyString) arg).getBytes());
break;
// TODO: add support for ps.setBlob();
case DATE:
ps.setDate(idx, java.sql.Date.valueOf(arg.toString()));
break;
case TIME:
DateTime dateTime = ((RubyTime) arg).getDateTime();
GregorianCalendar cal = dateTime.toGregorianCalendar();
Timestamp ts;
if (supportsCalendarsInJDBCPreparedStatement() == true) {
ts = new Timestamp(dateTime.getMillis());
} else {
// XXX ugly workaround for MySQL and Hsqldb
// use the default timeZone the oposite way these jdbc drivers do it
long offset = DateTimeZone.getDefault().getOffset(dateTime.getMillis());
ts = new Timestamp(dateTime.getMillis() - offset);
}
ps.setTimestamp(idx, ts, cal);
break;
case DATE_TIME:
String datetime = arg.toString().replace('T', ' ');
ps.setTimestamp(idx, Timestamp.valueOf(datetime
.replaceFirst("[-+]..:..$", "")));
break;
default:
if (arg.toString().indexOf("-") != -1
&& arg.toString().indexOf(":") != -1) {
// TODO: improve the above string pattern checking
// Handle date patterns in strings
try {
DateTime timestamp = DATE_TIME_FORMAT.parseDateTime(arg
.asJavaString().replace('T', ' '));
ps.setTimestamp(idx, new Timestamp(timestamp.getMillis()));
} catch (IllegalArgumentException ex) {
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
}
} else if (arg.toString().indexOf(":") != -1
&& arg.toString().length() == 8) {
// Handle time patterns in strings
ps.setTime(idx, java.sql.Time.valueOf(arg.asJavaString()));
} else {
Integer jdbcTypeId = null;
try {
jdbcTypeId = ps.getMetaData().getColumnType(idx);
} catch (Exception ex) {
}
if (jdbcTypeId == null) {
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
} else {
// TODO: Here comes conversions like '.execute_reader("2")'
// It definitly needs to be refactored...
try {
if (jdbcTypeId == Types.VARCHAR) {
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
} else if (jdbcTypeId == Types.INTEGER) {
ps.setObject(idx, Integer.valueOf(arg.toString()),
jdbcTypeId);
} else {
// I'm not sure is it correct in 100%
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
}
} catch (NumberFormatException ex) { // i.e
// Integer.valueOf
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
}
}
}
}
}
public abstract boolean supportsJdbcGeneratedKeys();
public abstract boolean supportsJdbcScrollableResultSets();
public boolean supportsConnectionEncodings() {
return false;
}
public boolean supportsConnectionPrepareStatementMethodWithGKFlag() {
return true;
}
public boolean supportsCalendarsInJDBCPreparedStatement(){
return true;
}
public ResultSet getGeneratedKeys(Connection connection) {
return null;
}
public Properties getDefaultConnectionProperties() {
return new Properties();
}
public void setEncodingProperty(Properties props, String encodingName) {
// do nothing
}
public String quoteString(String str) {
StringBuffer quotedValue = new StringBuffer(str.length() + 2);
quotedValue.append("\'");
quotedValue.append(str);
quotedValue.append("\'");
return quotedValue.toString();
}
public String toString(PreparedStatement ps) {
return ps.toString();
}
protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp(
Ruby runtime, DateTime stamp) {
if (stamp.getMillis() == 0) {
return runtime.getNil();
}
int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; // regCalendar.get(Calendar.ZONE_OFFSET)
// /
// 3600000;
RubyClass klazz = runtime.fastGetClass("DateTime");
IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod(
runtime.getCurrentContext(),
"new",
new IRubyObject[] { runtime.newFixnum(zoneOffset),
runtime.newFixnum(24) });
return klazz.callMethod(runtime.getCurrentContext(), "civil",
new IRubyObject[] { runtime.newFixnum(stamp.getYear()),// gregCalendar.get(Calendar.YEAR)),
runtime.newFixnum(stamp.getMonthOfYear()),// month),
runtime.newFixnum(stamp.getDayOfMonth()), // gregCalendar.get(Calendar.DAY_OF_MONTH)),
runtime.newFixnum(stamp.getHourOfDay()), // gregCalendar.get(Calendar.HOUR_OF_DAY)),
runtime.newFixnum(stamp.getMinuteOfHour()), // gregCalendar.get(Calendar.MINUTE)),
runtime.newFixnum(stamp.getSecondOfMinute()), // gregCalendar.get(Calendar.SECOND)),
rbOffset });
}
protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime,
DateTime time) {
if (time.getMillis() + 3600000 == 0) {
return runtime.getNil();
}
RubyTime rbTime = RubyTime.newTime(runtime, time);
rbTime.extend(new IRubyObject[] { runtime.getModule("TimeFormatter") });
return rbTime;
}
protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime,
Date date) {
if (date.getTime() + 3600000 == 0) {
return runtime.getNil();
}
RubyTime rbTime = RubyTime.newTime(runtime, date.getTime());
rbTime.extend(new IRubyObject[] { runtime.getModule("TimeFormatter") });
return rbTime;
}
public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime,
DateTime date) {
if (date.getMillis() == 0) {
return runtime.getNil();
}
// TODO
// gregCalendar.setTime(date.toDate());
// int month = gregCalendar.get(Calendar.MONTH);
// month++; // In Calendar January == 0, etc...
RubyClass klazz = runtime.fastGetClass("Date");
return klazz.callMethod(runtime.getCurrentContext(), "civil",
new IRubyObject[] { runtime.newFixnum(date.getYear()),
runtime.newFixnum(date.getMonthOfYear()),
runtime.newFixnum(date.getDayOfMonth()) });
}
private final static DateTimeFormatter DATE_FORMAT = ISODateTimeFormat
.date();// yyyy-MM-dd
private final static DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat
.forPattern("yyyy-MM-dd HH:mm:ss");
private final static DateTimeFormatter TIMESTAMP_FORMAT = ISODateTimeFormat
.dateTime();
public static DateTime toDate(String date) {
return DATE_FORMAT.parseDateTime(date.replaceFirst("T.*", ""));
}
public static DateTime toTimestamp(String stamp) {
DateTimeFormatter formatter = stamp.contains("T") ? TIMESTAMP_FORMAT
: DATE_FORMAT;// "yyyy-MM-dd'T'HH:mm:ssZ" : "yyyy-MM-dd");
return formatter.parseDateTime(stamp);
}
public static DateTime toTime(String time) {
DateTimeFormatter formatter = time.contains(" ") ? DATE_TIME_FORMAT
: DATE_FORMAT;
return formatter.parseDateTime(time);
}
private static String stringOrNull(IRubyObject obj) {
return (!obj.isNil()) ? obj.asJavaString() : null;
}
private static int intOrMinusOne(IRubyObject obj) {
return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1;
}
// private static Integer integerOrNull(IRubyObject obj) {
// return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null;
// }
}
| public final IRubyObject getTypecastResultSetValue(Ruby runtime,
ResultSet rs, int col, RubyType type) throws SQLException,
IOException {
// TODO assert to needs to be turned on with the java call
// better throw something
assert (type != null); // this method does not expect a null Ruby Type
if (rs == null) {// || rs.wasNull()) {
return runtime.getNil();
}
return doGetTypecastResultSetValue(runtime, rs, col, type);
}
protected IRubyObject doGetTypecastResultSetValue(Ruby runtime,
ResultSet rs, int col, RubyType type) throws SQLException,
IOException {
switch (type) {
case FIXNUM:
case INTEGER:
case BIGNUM:
// TODO: attempt to make this more granular, depending on the
// size of the number (?)
long lng = rs.getLong(col);
return RubyNumeric.int2fix(runtime, lng);
case FLOAT:
java.math.BigDecimal bdf = rs.getBigDecimal(col);
if (bdf == null) {
return runtime.getNil();
}
return new RubyFloat(runtime, bdf.doubleValue());
case BIG_DECIMAL:
return new RubyBigDecimal(runtime, rs.getBigDecimal(col));
case DATE:
java.sql.Date date = rs.getDate(col);
if (date == null) {
return runtime.getNil();
}
return prepareRubyDateFromSqlDate(runtime, new DateTime(date));
case DATE_TIME:
java.sql.Timestamp dt = null;
// DateTimes with all-zero components throw a SQLException with
// SQLState S1009 in MySQL Connector/J 3.1+
// See
// http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html
try {
dt = rs.getTimestamp(col);
} catch (SQLException sqle) {
}
if (dt == null) {
return runtime.getNil();
}
return prepareRubyDateTimeFromSqlTimestamp(runtime,
new DateTime(dt));
case TIME:
switch (rs.getMetaData().getColumnType(col)) {
case Types.TIME:
java.sql.Time tm = rs.getTime(col);
if (tm == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm));
case Types.TIMESTAMP:
java.sql.Time ts = rs.getTime(col);
if (ts == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlTime(runtime, new DateTime(ts));
case Types.DATE:
java.sql.Date da = rs.getDate(col);
if (da == null) {
return runtime.getNil();
}
return prepareRubyTimeFromSqlDate(runtime, da);
default:
String str = rs.getString(col);
if (str == null) {
return runtime.getNil();
}
RubyString return_str = RubyString.newUnicodeString(runtime,
str);
return_str.setTaint(true);
return return_str;
}
case TRUE_CLASS:
boolean bool = rs.getBoolean(col);
return runtime.newBoolean(bool);
case BYTE_ARRAY:
InputStream binaryStream = rs.getBinaryStream(col);
ByteList bytes = new ByteList(2048);
try {
byte[] buf = new byte[2048];
for (int n = binaryStream.read(buf); n != -1; n = binaryStream
.read(buf)) {
bytes.append(buf, 0, n);
}
} finally {
binaryStream.close();
}
return api.callMethod(runtime.fastGetModule("Extlib").fastGetClass(
"ByteArray"), "new", runtime.newString(bytes));
case CLASS:
String classNameStr = rs.getString(col);
if (classNameStr == null) {
return runtime.getNil();
}
RubyString class_name_str = RubyString.newUnicodeString(runtime, rs
.getString(col));
class_name_str.setTaint(true);
return api.callMethod(runtime.getObject(), "full_const_get",
class_name_str);
case OBJECT:
InputStream asciiStream = rs.getAsciiStream(col);
IRubyObject obj = runtime.getNil();
try {
UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream,
RubyProc.NEVER);
obj = ums.unmarshalObject();
} catch (IOException ioe) {
// TODO: log this
}
return obj;
case NIL:
return runtime.getNil();
case STRING:
default:
String str = rs.getString(col);
if (str == null) {
return runtime.getNil();
}
RubyString return_str = RubyString.newUnicodeString(runtime, str);
return_str.setTaint(true);
return return_str;
}
}
// TODO SimpleDateFormat is not threadsafe better use joda classes
// http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html#synchronization
// http://joda-time.sourceforge.net/api-release/org/joda/time/DateTime.html
// private static final DateFormat FORMAT = new SimpleDateFormat(
// "yyyy-MM-dd HH:mm:ss");
public void setPreparedStatementParam(PreparedStatement ps,
IRubyObject arg, int idx) throws SQLException {
switch (RubyType.getRubyType(arg.getType().getName())) {
case FIXNUM:
ps.setInt(idx, Integer.parseInt(arg.toString()));
break;
case BIGNUM:
ps.setLong(idx, ((RubyBignum) arg).getLongValue());
break;
case FLOAT:
ps.setDouble(idx, RubyNumeric.num2dbl(arg));
break;
case BIG_DECIMAL:
ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue());
break;
case NIL:
ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx));
break;
case TRUE_CLASS:
case FALSE_CLASS:
ps.setBoolean(idx, arg.toString().equals("true"));
break;
case CLASS:
ps.setString(idx, arg.toString());
break;
case BYTE_ARRAY:
ps.setBytes(idx, ((RubyString) arg).getBytes());
break;
// TODO: add support for ps.setBlob();
case DATE:
ps.setDate(idx, java.sql.Date.valueOf(arg.toString()));
break;
case TIME:
DateTime dateTime = ((RubyTime) arg).getDateTime();
GregorianCalendar cal = dateTime.toGregorianCalendar();
Timestamp ts;
if (supportsCalendarsInJDBCPreparedStatement() == true) {
ts = new Timestamp(dateTime.getMillis());
} else {
// XXX ugly workaround for MySQL and Hsqldb
// use the default timeZone the oposite way these jdbc drivers do it
long offset = DateTimeZone.getDefault().getOffset(dateTime.getMillis());
ts = new Timestamp(dateTime.getMillis() - offset);
}
ps.setTimestamp(idx, ts, cal);
break;
case DATE_TIME:
String datetime = arg.toString().replace('T', ' ');
ps.setTimestamp(idx, Timestamp.valueOf(datetime
.replaceFirst("[-+]..:..$", "")));
break;
default:
if (arg.toString().indexOf("-") != -1
&& arg.toString().indexOf(":") != -1) {
// TODO: improve the above string pattern checking
// Handle date patterns in strings
try {
DateTime timestamp = DATE_TIME_FORMAT.parseDateTime(arg
.asJavaString().replace('T', ' '));
ps.setTimestamp(idx, new Timestamp(timestamp.getMillis()));
} catch (IllegalArgumentException ex) {
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
}
} else if (arg.toString().indexOf(":") != -1
&& arg.toString().length() == 8) {
// Handle time patterns in strings
ps.setTime(idx, java.sql.Time.valueOf(arg.asJavaString()));
} else {
Integer jdbcTypeId = null;
try {
jdbcTypeId = ps.getMetaData().getColumnType(idx);
} catch (Exception ex) {
}
if (jdbcTypeId == null) {
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
} else {
// TODO: Here comes conversions like '.execute_reader("2")'
// It definitly needs to be refactored...
try {
if (jdbcTypeId == Types.VARCHAR) {
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
} else if (jdbcTypeId == Types.INTEGER) {
ps.setObject(idx, Integer.valueOf(arg.toString()),
jdbcTypeId);
} else {
// I'm not sure is it correct in 100%
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
}
} catch (NumberFormatException ex) { // i.e
// Integer.valueOf
ps.setString(idx, api.convertToRubyString(arg)
.getUnicodeValue());
}
}
}
}
}
public abstract boolean supportsJdbcGeneratedKeys();
public abstract boolean supportsJdbcScrollableResultSets();
public boolean supportsConnectionEncodings() {
return false;
}
public boolean supportsConnectionPrepareStatementMethodWithGKFlag() {
return true;
}
public boolean supportsCalendarsInJDBCPreparedStatement(){
return true;
}
public ResultSet getGeneratedKeys(Connection connection) {
return null;
}
public Properties getDefaultConnectionProperties() {
return new Properties();
}
public void setEncodingProperty(Properties props, String encodingName) {
// do nothing
}
public String quoteString(String str) {
StringBuffer quotedValue = new StringBuffer(str.length() + 2);
quotedValue.append("\'");
quotedValue.append(str);
quotedValue.append("\'");
return quotedValue.toString();
}
public String toString(PreparedStatement ps) {
return ps.toString();
}
protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp(
Ruby runtime, DateTime stamp) {
if (stamp.getMillis() == 0) {
return runtime.getNil();
}
int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; // regCalendar.get(Calendar.ZONE_OFFSET)
// /
// 3600000;
RubyClass klazz = runtime.fastGetClass("DateTime");
IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod(
runtime.getCurrentContext(),
"new",
new IRubyObject[] { runtime.newFixnum(zoneOffset),
runtime.newFixnum(24) });
return klazz.callMethod(runtime.getCurrentContext(), "civil",
new IRubyObject[] { runtime.newFixnum(stamp.getYear()),// gregCalendar.get(Calendar.YEAR)),
runtime.newFixnum(stamp.getMonthOfYear()),// month),
runtime.newFixnum(stamp.getDayOfMonth()), // gregCalendar.get(Calendar.DAY_OF_MONTH)),
runtime.newFixnum(stamp.getHourOfDay()), // gregCalendar.get(Calendar.HOUR_OF_DAY)),
runtime.newFixnum(stamp.getMinuteOfHour()), // gregCalendar.get(Calendar.MINUTE)),
runtime.newFixnum(stamp.getSecondOfMinute()), // gregCalendar.get(Calendar.SECOND)),
rbOffset });
}
protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime,
DateTime time) {
if (time.getMillis() + 3600000 == 0) {
return runtime.getNil();
}
RubyTime rbTime = RubyTime.newTime(runtime, time);
rbTime.extend(new IRubyObject[] { runtime.getModule("TimeFormatter") });
return rbTime;
}
protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime,
Date date) {
if (date.getTime() + 3600000 == 0) {
return runtime.getNil();
}
RubyTime rbTime = RubyTime.newTime(runtime, date.getTime());
rbTime.extend(new IRubyObject[] { runtime.getModule("TimeFormatter") });
return rbTime;
}
public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime,
DateTime date) {
if (date.getMillis() == 0) {
return runtime.getNil();
}
// TODO
// gregCalendar.setTime(date.toDate());
// int month = gregCalendar.get(Calendar.MONTH);
// month++; // In Calendar January == 0, etc...
RubyClass klazz = runtime.fastGetClass("Date");
return klazz.callMethod(runtime.getCurrentContext(), "civil",
new IRubyObject[] { runtime.newFixnum(date.getYear()),
runtime.newFixnum(date.getMonthOfYear()),
runtime.newFixnum(date.getDayOfMonth()) });
}
private final static DateTimeFormatter DATE_FORMAT = ISODateTimeFormat
.date();// yyyy-MM-dd
private final static DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat
.forPattern("yyyy-MM-dd HH:mm:ss");
private final static DateTimeFormatter TIMESTAMP_FORMAT = ISODateTimeFormat
.dateTime();
public static DateTime toDate(String date) {
return DATE_FORMAT.parseDateTime(date.replaceFirst("T.*", ""));
}
public static DateTime toTimestamp(String stamp) {
DateTimeFormatter formatter = stamp.contains("T") ? TIMESTAMP_FORMAT
: DATE_FORMAT;// "yyyy-MM-dd'T'HH:mm:ssZ" : "yyyy-MM-dd");
return formatter.parseDateTime(stamp);
}
public static DateTime toTime(String time) {
DateTimeFormatter formatter = time.contains(" ") ? DATE_TIME_FORMAT
: DATE_FORMAT;
return formatter.parseDateTime(time);
}
private static String stringOrNull(IRubyObject obj) {
return (!obj.isNil()) ? obj.asJavaString() : null;
}
private static int intOrMinusOne(IRubyObject obj) {
return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1;
}
// private static Integer integerOrNull(IRubyObject obj) {
// return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null;
// }
}
|
diff --git a/src/org/pentaho/experimental/chart/plugin/jfreechart/JFreeChartFactoryEngine.java b/src/org/pentaho/experimental/chart/plugin/jfreechart/JFreeChartFactoryEngine.java
index d1fba34..c50cf88 100644
--- a/src/org/pentaho/experimental/chart/plugin/jfreechart/JFreeChartFactoryEngine.java
+++ b/src/org/pentaho/experimental/chart/plugin/jfreechart/JFreeChartFactoryEngine.java
@@ -1,190 +1,190 @@
package org.pentaho.experimental.chart.plugin.jfreechart;
import java.io.Serializable;
import java.text.NumberFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.IntervalBarRenderer;
import org.jfree.chart.renderer.category.LayeredBarRenderer;
import org.jfree.chart.renderer.category.StackedBarRenderer;
import org.jfree.util.SortOrder;
import org.pentaho.experimental.chart.core.ChartDocument;
import org.pentaho.experimental.chart.core.ChartElement;
import org.pentaho.experimental.chart.css.keys.ChartStyleKeys;
import org.pentaho.experimental.chart.css.styles.ChartBarStyle;
import org.pentaho.experimental.chart.data.ChartTableModel;
import org.pentaho.experimental.chart.plugin.api.IOutput;
import org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine;
import org.pentaho.experimental.chart.plugin.jfreechart.utils.CylinderRenderer;
import org.pentaho.experimental.chart.plugin.jfreechart.utils.JFreeChartUtils;
import org.pentaho.reporting.libraries.css.values.CSSValue;
public class JFreeChartFactoryEngine implements ChartFactoryEngine, Serializable {
private static final long serialVersionUID = -1079376910255750394L;
public JFreeChartFactoryEngine(){
}
public ChartFactoryEngine getInstance() {
return this;
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeAreaChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeAreaChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeBarChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeBarChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) throws Exception {
String title = JFreeChartUtils.getTitle(chartDocument);
String valueCategoryLabel = JFreeChartUtils.getValueCategoryLabel(chartDocument);
String valueAxisLabel = JFreeChartUtils.getValueAxisLabel(chartDocument);
PlotOrientation orientation = JFreeChartUtils.getPlotOrientation(chartDocument);
boolean legend = JFreeChartUtils.getShowLegend(chartDocument);
boolean toolTips = JFreeChartUtils.getShowToolTips(chartDocument);
JFreeChart chart = createBarChartSubtype(chartDocument, data, title, valueCategoryLabel, valueAxisLabel, orientation, legend, toolTips);
JFreeChartUtils.setPlotAttributes(chart.getCategoryPlot(), chartDocument, data);
outHandler.setChart(chart);
outHandler.persist();
}
private JFreeChart createBarChartSubtype(ChartDocument chartDocument, ChartTableModel data, String title, String valueCategoryLabel, String valueAxisLabel, PlotOrientation orientation, boolean legend, boolean toolTips) {
boolean stacked = false;
boolean stackedPct = false;
boolean cylinder = false;
boolean interval = false;
boolean layered = false;
boolean stacked100Pct = false;
ChartElement[] elements = chartDocument.getRootElement().findChildrenByName(ChartElement.TAG_NAME_SERIES);
for (ChartElement element : elements) {
CSSValue value = element.getLayoutStyle().getValue(ChartStyleKeys.BAR_STYLE);
stacked = value.equals(ChartBarStyle.STACKED) ? true : stacked;
stackedPct = value.equals(ChartBarStyle.STACK_PERCENT) ? true : stackedPct;
cylinder = value.equals(ChartBarStyle.CYLINDER) ? true : cylinder;
interval = value.equals(ChartBarStyle.INTERVAL) ? true : interval;
layered = value.equals(ChartBarStyle.LAYERED) ? true : layered;
stacked100Pct = value.equals(ChartBarStyle.STACK_100_PERCENT) ? true : stacked100Pct;
}
JFreeChart chart = null;
// Note: We'll handle url generator when we update the plot info
if (stacked || stackedPct || stacked100Pct) {
chart = ChartFactory.createStackedBarChart(title, valueAxisLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
((StackedBarRenderer)chart.getCategoryPlot().getRenderer()).setRenderAsPercentages(stackedPct || stacked100Pct);
if (stacked100Pct) {
NumberAxis rangeAxis = (NumberAxis) chart.getCategoryPlot().getRangeAxis();
rangeAxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
}
} else {
if (cylinder) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
CylinderRenderer renderer = new CylinderRenderer();
chart.getCategoryPlot().setRenderer(renderer);
- } if (layered) {
+ } else if (layered) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
LayeredBarRenderer renderer = new LayeredBarRenderer();
renderer.setDrawBarOutline(false);
chart.getCategoryPlot().setRenderer(renderer);
chart.getCategoryPlot().setRowRenderingOrder(SortOrder.DESCENDING);
} else if (interval) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultIntervalCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
chart.getCategoryPlot().setRenderer(new IntervalBarRenderer());
} else {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
}
}
return chart;
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeBarLineChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeBarLineChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeBubbleChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeBubbleChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeDialChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeDialChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeDifferenceChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeDifferenceChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeLineChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeLineChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeMultiPieChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeMultiPieChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makePieChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makePieChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeScatterPlotChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeScatterPlotChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeStepAreaChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeStepAreaChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeStepChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeStepChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeWaterfallChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeWaterfallChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
}
| true | true | private JFreeChart createBarChartSubtype(ChartDocument chartDocument, ChartTableModel data, String title, String valueCategoryLabel, String valueAxisLabel, PlotOrientation orientation, boolean legend, boolean toolTips) {
boolean stacked = false;
boolean stackedPct = false;
boolean cylinder = false;
boolean interval = false;
boolean layered = false;
boolean stacked100Pct = false;
ChartElement[] elements = chartDocument.getRootElement().findChildrenByName(ChartElement.TAG_NAME_SERIES);
for (ChartElement element : elements) {
CSSValue value = element.getLayoutStyle().getValue(ChartStyleKeys.BAR_STYLE);
stacked = value.equals(ChartBarStyle.STACKED) ? true : stacked;
stackedPct = value.equals(ChartBarStyle.STACK_PERCENT) ? true : stackedPct;
cylinder = value.equals(ChartBarStyle.CYLINDER) ? true : cylinder;
interval = value.equals(ChartBarStyle.INTERVAL) ? true : interval;
layered = value.equals(ChartBarStyle.LAYERED) ? true : layered;
stacked100Pct = value.equals(ChartBarStyle.STACK_100_PERCENT) ? true : stacked100Pct;
}
JFreeChart chart = null;
// Note: We'll handle url generator when we update the plot info
if (stacked || stackedPct || stacked100Pct) {
chart = ChartFactory.createStackedBarChart(title, valueAxisLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
((StackedBarRenderer)chart.getCategoryPlot().getRenderer()).setRenderAsPercentages(stackedPct || stacked100Pct);
if (stacked100Pct) {
NumberAxis rangeAxis = (NumberAxis) chart.getCategoryPlot().getRangeAxis();
rangeAxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
}
} else {
if (cylinder) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
CylinderRenderer renderer = new CylinderRenderer();
chart.getCategoryPlot().setRenderer(renderer);
} if (layered) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
LayeredBarRenderer renderer = new LayeredBarRenderer();
renderer.setDrawBarOutline(false);
chart.getCategoryPlot().setRenderer(renderer);
chart.getCategoryPlot().setRowRenderingOrder(SortOrder.DESCENDING);
} else if (interval) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultIntervalCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
chart.getCategoryPlot().setRenderer(new IntervalBarRenderer());
} else {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
}
}
return chart;
}
| private JFreeChart createBarChartSubtype(ChartDocument chartDocument, ChartTableModel data, String title, String valueCategoryLabel, String valueAxisLabel, PlotOrientation orientation, boolean legend, boolean toolTips) {
boolean stacked = false;
boolean stackedPct = false;
boolean cylinder = false;
boolean interval = false;
boolean layered = false;
boolean stacked100Pct = false;
ChartElement[] elements = chartDocument.getRootElement().findChildrenByName(ChartElement.TAG_NAME_SERIES);
for (ChartElement element : elements) {
CSSValue value = element.getLayoutStyle().getValue(ChartStyleKeys.BAR_STYLE);
stacked = value.equals(ChartBarStyle.STACKED) ? true : stacked;
stackedPct = value.equals(ChartBarStyle.STACK_PERCENT) ? true : stackedPct;
cylinder = value.equals(ChartBarStyle.CYLINDER) ? true : cylinder;
interval = value.equals(ChartBarStyle.INTERVAL) ? true : interval;
layered = value.equals(ChartBarStyle.LAYERED) ? true : layered;
stacked100Pct = value.equals(ChartBarStyle.STACK_100_PERCENT) ? true : stacked100Pct;
}
JFreeChart chart = null;
// Note: We'll handle url generator when we update the plot info
if (stacked || stackedPct || stacked100Pct) {
chart = ChartFactory.createStackedBarChart(title, valueAxisLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
((StackedBarRenderer)chart.getCategoryPlot().getRenderer()).setRenderAsPercentages(stackedPct || stacked100Pct);
if (stacked100Pct) {
NumberAxis rangeAxis = (NumberAxis) chart.getCategoryPlot().getRangeAxis();
rangeAxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
}
} else {
if (cylinder) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
CylinderRenderer renderer = new CylinderRenderer();
chart.getCategoryPlot().setRenderer(renderer);
} else if (layered) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
LayeredBarRenderer renderer = new LayeredBarRenderer();
renderer.setDrawBarOutline(false);
chart.getCategoryPlot().setRenderer(renderer);
chart.getCategoryPlot().setRowRenderingOrder(SortOrder.DESCENDING);
} else if (interval) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultIntervalCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
chart.getCategoryPlot().setRenderer(new IntervalBarRenderer());
} else {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data, chartDocument), orientation, legend, toolTips, false);
}
}
return chart;
}
|
diff --git a/basex-core/src/main/java/org/basex/io/in/TarInputStream.java b/basex-core/src/main/java/org/basex/io/in/TarInputStream.java
index 91d80f8d1..e21c9dca9 100644
--- a/basex-core/src/main/java/org/basex/io/in/TarInputStream.java
+++ b/basex-core/src/main/java/org/basex/io/in/TarInputStream.java
@@ -1,98 +1,98 @@
package org.basex.io.in;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.basex.util.*;
/**
* Input stream filter for reading files in the TAR file format.
*
* @author BaseX Team 2005-14, BSD License
* @author Christian Gruen
*/
public final class TarInputStream extends FilterInputStream {
/** Block size. */
private static final int BLOCK = 512;
/** Single byte buffer. */
private final byte[] buf = new byte[1];
/** Current entry. */
private TarEntry entry;
/** File size. */
private long size;
/**
* Constructor.
* @param is input stream
*/
public TarInputStream(final InputStream is) {
super(is);
}
@Override
public int read() throws IOException {
final int res = read(buf, 0, 1);
return res == -1 ? -1 : (buf[0] & 0xFF);
}
@Override
public int read(final byte[] bytes, final int off, final int len) throws IOException {
int l = len;
if(entry != null) {
final long ln = entry.getSize() - size;
if(ln == 0) return -1;
if(ln < len) l = (int) ln;
}
final int br = super.read(bytes, off, l);
if(br != -1 && entry != null) size += br;
return br;
}
@Override
public boolean markSupported() {
return false;
}
@Override
public synchronized void mark(final int limit) {
Util.notImplemented();
}
@Override
public synchronized void reset() throws IOException {
Util.notImplemented();
}
/**
* Returns the next entry.
* @return entry
* @throws IOException I/O exception
*/
public TarEntry getNextEntry() throws IOException {
// close entry
if(entry != null) {
long ln = entry.getSize() - size + BLOCK - (size & (BLOCK - 1));
- while(ln > 0) ln -= skip(ln);
+ while(ln != BLOCK && ln > 0) ln -= skip(ln);
entry = null;
size = 0;
}
// read header
final byte[] header = new byte[BLOCK];
int tr = 0;
while(tr < BLOCK) {
final int res = read(header, tr, BLOCK - tr);
if(res < 0) break;
tr += res;
}
for(final byte b : header) {
if(b != 0) {
entry = new TarEntry(header);
break;
}
}
return entry;
}
}
| true | true | public TarEntry getNextEntry() throws IOException {
// close entry
if(entry != null) {
long ln = entry.getSize() - size + BLOCK - (size & (BLOCK - 1));
while(ln > 0) ln -= skip(ln);
entry = null;
size = 0;
}
// read header
final byte[] header = new byte[BLOCK];
int tr = 0;
while(tr < BLOCK) {
final int res = read(header, tr, BLOCK - tr);
if(res < 0) break;
tr += res;
}
for(final byte b : header) {
if(b != 0) {
entry = new TarEntry(header);
break;
}
}
return entry;
}
| public TarEntry getNextEntry() throws IOException {
// close entry
if(entry != null) {
long ln = entry.getSize() - size + BLOCK - (size & (BLOCK - 1));
while(ln != BLOCK && ln > 0) ln -= skip(ln);
entry = null;
size = 0;
}
// read header
final byte[] header = new byte[BLOCK];
int tr = 0;
while(tr < BLOCK) {
final int res = read(header, tr, BLOCK - tr);
if(res < 0) break;
tr += res;
}
for(final byte b : header) {
if(b != 0) {
entry = new TarEntry(header);
break;
}
}
return entry;
}
|
diff --git a/tests/com/google/caja/lang/html/HtmlSchemaTest.java b/tests/com/google/caja/lang/html/HtmlSchemaTest.java
index 0aa55e6b..76bccaec 100644
--- a/tests/com/google/caja/lang/html/HtmlSchemaTest.java
+++ b/tests/com/google/caja/lang/html/HtmlSchemaTest.java
@@ -1,112 +1,116 @@
// Copyright (C) 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.caja.lang.html;
import com.google.caja.reporting.MessageQueue;
import com.google.caja.reporting.SimpleMessageQueue;
import com.google.caja.util.Name;
import junit.framework.TestCase;
/**
*
* @author [email protected]
*/
public class HtmlSchemaTest extends TestCase {
MessageQueue mq;
HtmlSchema schema;
@Override
public void setUp() throws Exception {
mq = new SimpleMessageQueue();
schema = HtmlSchema.getDefault(mq);
assertTrue(mq.getMessages().isEmpty());
}
/** blacklist the whitelist. */
public void testSchema() throws Exception {
assertFalse(schema.isElementAllowed(id("script")));
assertFalse(schema.isElementAllowed(id("style")));
assertFalse(schema.isElementAllowed(id("iframe")));
// swapping innerHTML from an XMP or LISTING tag into another tag might
// allow bad things to happen.
assertFalse(schema.isElementAllowed(id("xmp")));
assertFalse(schema.isElementAllowed(id("listing")));
assertFalse(schema.isElementAllowed(id("frame")));
assertFalse(schema.isElementAllowed(id("frameset")));
assertFalse(schema.isElementAllowed(id("body")));
assertFalse(schema.isElementAllowed(id("head")));
assertFalse(schema.isElementAllowed(id("html")));
assertFalse(schema.isElementAllowed(id("title")));
}
public void testAttributeTypes() throws Exception {
assertEquals(HTML.Attribute.Type.STYLE,
schema.lookupAttribute(id("div"), id("style")).getType());
assertEquals(HTML.Attribute.Type.SCRIPT,
schema.lookupAttribute(id("a"), id("onclick")).getType());
assertEquals(HTML.Attribute.Type.URI,
schema.lookupAttribute(id("a"), id("href")).getType());
assertEquals(HTML.Attribute.Type.NONE,
schema.lookupAttribute(id("a"), id("title")).getType());
}
public void testAttributeMimeTypes() throws Exception {
assertEquals(
"image/*",
schema.lookupAttribute(id("img"), id("src")).getMimeTypes());
assertEquals(
"text/javascript",
schema.lookupAttribute(id("script"), id("src")).getMimeTypes());
assertEquals(
null,
schema.lookupAttribute(id("table"), id("cellpadding")).getMimeTypes());
}
public void testAttributeCriteria() throws Exception {
assertFalse(schema.getAttributeCriteria(id("a"), id("target"))
.accept("_top"));
assertTrue(schema.getAttributeCriteria(id("a"), id("target"))
.accept("_blank"));
assertFalse(schema.getAttributeCriteria(id("table"), id("cellpadding"))
.accept("six"));
assertTrue(schema.getAttributeCriteria(id("table"), id("cellpadding"))
.accept("6"));
+ assertTrue(schema.getAttributeCriteria(id("table"), id("width"))
+ .accept("10%"));
+ assertFalse(schema.getAttributeCriteria(id("table"), id("width"))
+ .accept("%"));
assertFalse(schema.getAttributeCriteria(id("script"), id("type"))
.accept("text/vbscript"));
assertTrue(schema.getAttributeCriteria(id("script"), id("type"))
.accept("text/javascript"));
assertTrue(schema.getAttributeCriteria(id("script"), id("type"))
.accept("text/javascript;charset=UTF-8"));
assertTrue(schema.getAttributeCriteria(id("input"), id("type"))
.accept("text"));
assertTrue(schema.getAttributeCriteria(id("input"), id("type"))
.accept("TEXT"));
assertTrue(schema.getAttributeCriteria(id("input"), id("type"))
.accept("button"));
assertFalse(schema.getAttributeCriteria(id("input"), id("type"))
.accept("file"));
assertFalse(schema.getAttributeCriteria(id("input"), id("type"))
.accept("FILE"));
assertFalse(schema.getAttributeCriteria(id("input"), id("type"))
.accept("bogus"));
}
private static Name id(String name) {
return Name.html(name);
}
}
| true | true | public void testAttributeCriteria() throws Exception {
assertFalse(schema.getAttributeCriteria(id("a"), id("target"))
.accept("_top"));
assertTrue(schema.getAttributeCriteria(id("a"), id("target"))
.accept("_blank"));
assertFalse(schema.getAttributeCriteria(id("table"), id("cellpadding"))
.accept("six"));
assertTrue(schema.getAttributeCriteria(id("table"), id("cellpadding"))
.accept("6"));
assertFalse(schema.getAttributeCriteria(id("script"), id("type"))
.accept("text/vbscript"));
assertTrue(schema.getAttributeCriteria(id("script"), id("type"))
.accept("text/javascript"));
assertTrue(schema.getAttributeCriteria(id("script"), id("type"))
.accept("text/javascript;charset=UTF-8"));
assertTrue(schema.getAttributeCriteria(id("input"), id("type"))
.accept("text"));
assertTrue(schema.getAttributeCriteria(id("input"), id("type"))
.accept("TEXT"));
assertTrue(schema.getAttributeCriteria(id("input"), id("type"))
.accept("button"));
assertFalse(schema.getAttributeCriteria(id("input"), id("type"))
.accept("file"));
assertFalse(schema.getAttributeCriteria(id("input"), id("type"))
.accept("FILE"));
assertFalse(schema.getAttributeCriteria(id("input"), id("type"))
.accept("bogus"));
}
| public void testAttributeCriteria() throws Exception {
assertFalse(schema.getAttributeCriteria(id("a"), id("target"))
.accept("_top"));
assertTrue(schema.getAttributeCriteria(id("a"), id("target"))
.accept("_blank"));
assertFalse(schema.getAttributeCriteria(id("table"), id("cellpadding"))
.accept("six"));
assertTrue(schema.getAttributeCriteria(id("table"), id("cellpadding"))
.accept("6"));
assertTrue(schema.getAttributeCriteria(id("table"), id("width"))
.accept("10%"));
assertFalse(schema.getAttributeCriteria(id("table"), id("width"))
.accept("%"));
assertFalse(schema.getAttributeCriteria(id("script"), id("type"))
.accept("text/vbscript"));
assertTrue(schema.getAttributeCriteria(id("script"), id("type"))
.accept("text/javascript"));
assertTrue(schema.getAttributeCriteria(id("script"), id("type"))
.accept("text/javascript;charset=UTF-8"));
assertTrue(schema.getAttributeCriteria(id("input"), id("type"))
.accept("text"));
assertTrue(schema.getAttributeCriteria(id("input"), id("type"))
.accept("TEXT"));
assertTrue(schema.getAttributeCriteria(id("input"), id("type"))
.accept("button"));
assertFalse(schema.getAttributeCriteria(id("input"), id("type"))
.accept("file"));
assertFalse(schema.getAttributeCriteria(id("input"), id("type"))
.accept("FILE"));
assertFalse(schema.getAttributeCriteria(id("input"), id("type"))
.accept("bogus"));
}
|
diff --git a/StatisticsPlugin/src/org/gephi/statistics/plugin/GraphDistance.java b/StatisticsPlugin/src/org/gephi/statistics/plugin/GraphDistance.java
index 539ab4607..e1136f0bf 100644
--- a/StatisticsPlugin/src/org/gephi/statistics/plugin/GraphDistance.java
+++ b/StatisticsPlugin/src/org/gephi/statistics/plugin/GraphDistance.java
@@ -1,391 +1,391 @@
/*
Copyright 2008-2010 Gephi
Authors : Patick J. McSweeney <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Gephi 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.statistics.plugin;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.gephi.statistics.spi.Statistics;
import org.gephi.graph.api.*;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Stack;
import org.gephi.data.attributes.api.AttributeTable;
import org.gephi.data.attributes.api.AttributeColumn;
import org.gephi.data.attributes.api.AttributeModel;
import org.gephi.data.attributes.api.AttributeOrigin;
import org.gephi.data.attributes.api.AttributeRow;
import org.gephi.data.attributes.api.AttributeType;
import org.gephi.utils.TempDirUtils;
import org.gephi.utils.TempDirUtils.TempDir;
import org.gephi.utils.longtask.spi.LongTask;
import org.gephi.utils.progress.Progress;
import org.gephi.utils.progress.ProgressTicket;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
/**
*
* @author pjmcswee
*/
public class GraphDistance implements Statistics, LongTask {
public static final String BETWEENNESS = "betweenesscentrality";
public static final String CLOSENESS = "closnesscentrality";
public static final String ECCENTRICITY = "eccentricity";
/** */
private double[] mBetweenness;
/** */
private double[] mCloseness;
/** */
private double[] mEccentricity;
/** */
private int mDiameter;
private int mRadius;
/** */
private double mAvgDist;
/** */
private int mN;
/** */
private boolean mDirected;
/** */
private ProgressTicket mProgress;
/** */
private boolean mIsCanceled;
private int mShortestPaths;
private boolean mRelativeValues;
public GraphDistance() {
GraphController graphController = Lookup.getDefault().lookup(GraphController.class);
if (graphController != null && graphController.getModel() != null) {
mDirected = graphController.getModel().isDirected();
}
}
public double getPathLength() {
return mAvgDist;
}
/**
*
* @return
*/
public double getDiameter() {
return mDiameter;
}
/**
*
* @param graphModel
*/
public void execute(Graph graph, AttributeModel attributeModel) {
mIsCanceled = false;
AttributeTable nodeTable = attributeModel.getNodeTable();
AttributeColumn eccentricityCol = nodeTable.getColumn(ECCENTRICITY);
AttributeColumn closenessCol = nodeTable.getColumn(CLOSENESS);
AttributeColumn betweenessCol = nodeTable.getColumn(BETWEENNESS);
if (eccentricityCol == null) {
eccentricityCol = nodeTable.addColumn(ECCENTRICITY, "Eccentricity", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0));
}
if (closenessCol == null) {
closenessCol = nodeTable.addColumn(CLOSENESS, "Closeness Centrality", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0));
}
if (betweenessCol == null) {
betweenessCol = nodeTable.addColumn(BETWEENNESS, "Betweenness Centrality", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0));
}
graph.readLock();
mN = graph.getNodeCount();
mBetweenness = new double[mN];
mEccentricity = new double[mN];
mCloseness = new double[mN];
mDiameter = 0;
mAvgDist = 0;
mShortestPaths = 0;
mRadius = Integer.MAX_VALUE;
HashMap<Node, Integer> indicies = new HashMap<Node, Integer>();
int index = 0;
for (Node s : graph.getNodes()) {
indicies.put(s, index);
index++;
}
Progress.start(mProgress, graph.getNodeCount());
int count = 0;
for (Node s : graph.getNodes()) {
Stack<Node> S = new Stack<Node>();
LinkedList<Node>[] P = new LinkedList[mN];
double[] theta = new double[mN];
int[] d = new int[mN];
for (int j = 0; j < mN; j++) {
P[j] = new LinkedList<Node>();
theta[j] = 0;
d[j] = -1;
}
int s_index = indicies.get(s);
theta[s_index] = 1;
d[s_index] = 0;
LinkedList<Node> Q = new LinkedList<Node>();
Q.addLast(s);
while (!Q.isEmpty()) {
Node v = Q.removeFirst();
S.push(v);
int v_index = indicies.get(v);
EdgeIterable edgeIter = null;
if (mDirected) {
edgeIter = ((DirectedGraph) graph).getOutEdges(v);
} else {
edgeIter = graph.getEdges(v);
}
for (Edge edge : edgeIter) {
Node reachable = graph.getOpposite(v, edge);
int r_index = indicies.get(reachable);
if (d[r_index] < 0) {
Q.addLast(reachable);
d[r_index] = d[v_index] + 1;
}
if (d[r_index] == (d[v_index] + 1)) {
theta[r_index] = theta[r_index] + theta[v_index];
P[r_index].addLast(v);
}
}
}
double reachable = 0;
for (int i = 0; i < mN; i++) {
if (d[i] > 0) {
mAvgDist += d[i];
mEccentricity[s_index] = (int) Math.max(mEccentricity[s_index], d[i]);
mCloseness[s_index] += d[i];
mDiameter = Math.max(mDiameter, d[i]);
reachable++;
}
}
mRadius = (int) Math.min(mEccentricity[s_index], mRadius);
if (reachable != 0) {
mCloseness[s_index] /= reachable;
}
mShortestPaths += reachable;
double[] delta = new double[mN];
while (!S.empty()) {
Node w = S.pop();
int w_index = indicies.get(w);
ListIterator<Node> iter1 = P[w_index].listIterator();
while (iter1.hasNext()) {
Node u = iter1.next();
int u_index = indicies.get(u);
delta[u_index] += (theta[u_index] / theta[w_index]) * (1 + delta[w_index]);
}
if (w != s) {
mBetweenness[w_index] += delta[w_index];
}
}
count++;
if (mIsCanceled) {
graph.readUnlockAll();
return;
}
Progress.progress(mProgress, count);
}
mAvgDist /= this.mShortestPaths;//mN * (mN - 1.0f);
for (Node s : graph.getNodes()) {
AttributeRow row = (AttributeRow) s.getNodeData().getAttributes();
int s_index = indicies.get(s);
if (!mDirected) {
mBetweenness[s_index] /= 2;
}
if (this.mRelativeValues) {
mCloseness[s_index] = (mCloseness[s_index] == 0) ? 0 : 1.0 / mCloseness[s_index];
- mBetweenness[s_index] /= ((mN - 1) * (mN - 2)) / 2;
+ mBetweenness[s_index] /= mDirected ? (mN - 1) * (mN - 2) : (mN - 1) * (mN - 2) / 2;
}
row.setValue(eccentricityCol, mEccentricity[s_index]);
row.setValue(closenessCol, mCloseness[s_index]);
row.setValue(betweenessCol, mBetweenness[s_index]);
}
graph.readUnlock();
}
/**
*
* @param graphModel
*/
public void execute(GraphModel graphModel, AttributeModel attributeModel) {
Graph graph = null;
if (mDirected) {
graph = graphModel.getDirectedGraphVisible();
} else {
graph = graphModel.getUndirectedGraphVisible();
}
execute(graph, attributeModel);
}
/**
*
* @param pRelative
*/
public void setRelative(boolean pRelative) {
this.mRelativeValues = pRelative;
}
/**
*
* @param pRelative
*/
public boolean useRelative() {
return this.mRelativeValues;
}
/**
*
* @param pDirected
*/
public void setDirected(boolean pDirected) {
this.mDirected = pDirected;
}
public boolean isDirected() {
return mDirected;
}
/**
*
* @param pVals
* @param pName
* @param pX
* @param pY
* @return
*/
private String createImageFile(TempDir tempDir, double[] pVals, String pName, String pX, String pY) throws IOException {
XYSeries series = new XYSeries(pName);
for (int i = 0; i < mN; i++) {
series.add(i, pVals[i]);
}
XYSeriesCollection dataSet = new XYSeriesCollection();
dataSet.addSeries(series);
JFreeChart chart = ChartFactory.createXYLineChart(
pName,
pX,
pY,
dataSet,
PlotOrientation.VERTICAL,
true,
false,
false);
XYPlot plot = (XYPlot) chart.getPlot();
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
renderer.setSeriesLinesVisible(0, false);
renderer.setSeriesShapesVisible(0, true);
renderer.setSeriesShape(0, new java.awt.geom.Ellipse2D.Double(0, 0, 1, 1));
plot.setBackgroundPaint(java.awt.Color.WHITE);
plot.setDomainGridlinePaint(java.awt.Color.GRAY);
plot.setRangeGridlinePaint(java.awt.Color.GRAY);
plot.setRenderer(renderer);
String imageFile = "";
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
String fileName = pY + ".png";
File file1 = tempDir.createFile(fileName);
imageFile = "<IMG SRC=\"file:" + file1.getAbsolutePath() + "\" " + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\"></IMG>";
ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
return imageFile;
}
/**
*
* @return
*/
public String getReport() {
String htmlIMG1 = "";
String htmlIMG2 = "";
String htmlIMG3 = "";
try {
TempDir tempDir = TempDirUtils.createTempDir();
htmlIMG1 = createImageFile(tempDir, mBetweenness, "Betweenness Centrality", "Nodes", "Betweenness");
htmlIMG2 = createImageFile(tempDir, mCloseness, "Closeness Centrality", "Nodes", "Closeness");
htmlIMG3 = createImageFile(tempDir, mEccentricity, "Eccentricity", "Nodes", "Eccentricity");
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
String report = "<HTML> <BODY> <h1>Graph Distance Report </h1> "
+ "<hr>"
+ "<br>"
+ "<h2> Parameters: </h2>"
+ "Network Interpretation: " + (this.mDirected ? "directed" : "undirected") + "<br>"
+ "<br> <h2> Results: </h2>"
+ "Diameter: " + this.mDiameter + "<br>"
+ "Radius: " + this.mRadius + "<br>"
+ "Average Path length: " + this.mAvgDist + "<br>"
+ "Number of shortest paths: " + this.mShortestPaths + "<br>"
+ htmlIMG1 + "<br>"
+ htmlIMG2 + "<br>"
+ htmlIMG3
+ "</BODY></HTML>";
return report;
}
/**
*
* @return
*/
public boolean cancel() {
mIsCanceled = true;
return true;
}
/**
*
* @param progressTicket
*/
public void setProgressTicket(ProgressTicket progressTicket) {
mProgress = progressTicket;
}
}
| true | true | public void execute(Graph graph, AttributeModel attributeModel) {
mIsCanceled = false;
AttributeTable nodeTable = attributeModel.getNodeTable();
AttributeColumn eccentricityCol = nodeTable.getColumn(ECCENTRICITY);
AttributeColumn closenessCol = nodeTable.getColumn(CLOSENESS);
AttributeColumn betweenessCol = nodeTable.getColumn(BETWEENNESS);
if (eccentricityCol == null) {
eccentricityCol = nodeTable.addColumn(ECCENTRICITY, "Eccentricity", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0));
}
if (closenessCol == null) {
closenessCol = nodeTable.addColumn(CLOSENESS, "Closeness Centrality", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0));
}
if (betweenessCol == null) {
betweenessCol = nodeTable.addColumn(BETWEENNESS, "Betweenness Centrality", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0));
}
graph.readLock();
mN = graph.getNodeCount();
mBetweenness = new double[mN];
mEccentricity = new double[mN];
mCloseness = new double[mN];
mDiameter = 0;
mAvgDist = 0;
mShortestPaths = 0;
mRadius = Integer.MAX_VALUE;
HashMap<Node, Integer> indicies = new HashMap<Node, Integer>();
int index = 0;
for (Node s : graph.getNodes()) {
indicies.put(s, index);
index++;
}
Progress.start(mProgress, graph.getNodeCount());
int count = 0;
for (Node s : graph.getNodes()) {
Stack<Node> S = new Stack<Node>();
LinkedList<Node>[] P = new LinkedList[mN];
double[] theta = new double[mN];
int[] d = new int[mN];
for (int j = 0; j < mN; j++) {
P[j] = new LinkedList<Node>();
theta[j] = 0;
d[j] = -1;
}
int s_index = indicies.get(s);
theta[s_index] = 1;
d[s_index] = 0;
LinkedList<Node> Q = new LinkedList<Node>();
Q.addLast(s);
while (!Q.isEmpty()) {
Node v = Q.removeFirst();
S.push(v);
int v_index = indicies.get(v);
EdgeIterable edgeIter = null;
if (mDirected) {
edgeIter = ((DirectedGraph) graph).getOutEdges(v);
} else {
edgeIter = graph.getEdges(v);
}
for (Edge edge : edgeIter) {
Node reachable = graph.getOpposite(v, edge);
int r_index = indicies.get(reachable);
if (d[r_index] < 0) {
Q.addLast(reachable);
d[r_index] = d[v_index] + 1;
}
if (d[r_index] == (d[v_index] + 1)) {
theta[r_index] = theta[r_index] + theta[v_index];
P[r_index].addLast(v);
}
}
}
double reachable = 0;
for (int i = 0; i < mN; i++) {
if (d[i] > 0) {
mAvgDist += d[i];
mEccentricity[s_index] = (int) Math.max(mEccentricity[s_index], d[i]);
mCloseness[s_index] += d[i];
mDiameter = Math.max(mDiameter, d[i]);
reachable++;
}
}
mRadius = (int) Math.min(mEccentricity[s_index], mRadius);
if (reachable != 0) {
mCloseness[s_index] /= reachable;
}
mShortestPaths += reachable;
double[] delta = new double[mN];
while (!S.empty()) {
Node w = S.pop();
int w_index = indicies.get(w);
ListIterator<Node> iter1 = P[w_index].listIterator();
while (iter1.hasNext()) {
Node u = iter1.next();
int u_index = indicies.get(u);
delta[u_index] += (theta[u_index] / theta[w_index]) * (1 + delta[w_index]);
}
if (w != s) {
mBetweenness[w_index] += delta[w_index];
}
}
count++;
if (mIsCanceled) {
graph.readUnlockAll();
return;
}
Progress.progress(mProgress, count);
}
mAvgDist /= this.mShortestPaths;//mN * (mN - 1.0f);
for (Node s : graph.getNodes()) {
AttributeRow row = (AttributeRow) s.getNodeData().getAttributes();
int s_index = indicies.get(s);
if (!mDirected) {
mBetweenness[s_index] /= 2;
}
if (this.mRelativeValues) {
mCloseness[s_index] = (mCloseness[s_index] == 0) ? 0 : 1.0 / mCloseness[s_index];
mBetweenness[s_index] /= ((mN - 1) * (mN - 2)) / 2;
}
row.setValue(eccentricityCol, mEccentricity[s_index]);
row.setValue(closenessCol, mCloseness[s_index]);
row.setValue(betweenessCol, mBetweenness[s_index]);
}
graph.readUnlock();
}
| public void execute(Graph graph, AttributeModel attributeModel) {
mIsCanceled = false;
AttributeTable nodeTable = attributeModel.getNodeTable();
AttributeColumn eccentricityCol = nodeTable.getColumn(ECCENTRICITY);
AttributeColumn closenessCol = nodeTable.getColumn(CLOSENESS);
AttributeColumn betweenessCol = nodeTable.getColumn(BETWEENNESS);
if (eccentricityCol == null) {
eccentricityCol = nodeTable.addColumn(ECCENTRICITY, "Eccentricity", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0));
}
if (closenessCol == null) {
closenessCol = nodeTable.addColumn(CLOSENESS, "Closeness Centrality", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0));
}
if (betweenessCol == null) {
betweenessCol = nodeTable.addColumn(BETWEENNESS, "Betweenness Centrality", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0));
}
graph.readLock();
mN = graph.getNodeCount();
mBetweenness = new double[mN];
mEccentricity = new double[mN];
mCloseness = new double[mN];
mDiameter = 0;
mAvgDist = 0;
mShortestPaths = 0;
mRadius = Integer.MAX_VALUE;
HashMap<Node, Integer> indicies = new HashMap<Node, Integer>();
int index = 0;
for (Node s : graph.getNodes()) {
indicies.put(s, index);
index++;
}
Progress.start(mProgress, graph.getNodeCount());
int count = 0;
for (Node s : graph.getNodes()) {
Stack<Node> S = new Stack<Node>();
LinkedList<Node>[] P = new LinkedList[mN];
double[] theta = new double[mN];
int[] d = new int[mN];
for (int j = 0; j < mN; j++) {
P[j] = new LinkedList<Node>();
theta[j] = 0;
d[j] = -1;
}
int s_index = indicies.get(s);
theta[s_index] = 1;
d[s_index] = 0;
LinkedList<Node> Q = new LinkedList<Node>();
Q.addLast(s);
while (!Q.isEmpty()) {
Node v = Q.removeFirst();
S.push(v);
int v_index = indicies.get(v);
EdgeIterable edgeIter = null;
if (mDirected) {
edgeIter = ((DirectedGraph) graph).getOutEdges(v);
} else {
edgeIter = graph.getEdges(v);
}
for (Edge edge : edgeIter) {
Node reachable = graph.getOpposite(v, edge);
int r_index = indicies.get(reachable);
if (d[r_index] < 0) {
Q.addLast(reachable);
d[r_index] = d[v_index] + 1;
}
if (d[r_index] == (d[v_index] + 1)) {
theta[r_index] = theta[r_index] + theta[v_index];
P[r_index].addLast(v);
}
}
}
double reachable = 0;
for (int i = 0; i < mN; i++) {
if (d[i] > 0) {
mAvgDist += d[i];
mEccentricity[s_index] = (int) Math.max(mEccentricity[s_index], d[i]);
mCloseness[s_index] += d[i];
mDiameter = Math.max(mDiameter, d[i]);
reachable++;
}
}
mRadius = (int) Math.min(mEccentricity[s_index], mRadius);
if (reachable != 0) {
mCloseness[s_index] /= reachable;
}
mShortestPaths += reachable;
double[] delta = new double[mN];
while (!S.empty()) {
Node w = S.pop();
int w_index = indicies.get(w);
ListIterator<Node> iter1 = P[w_index].listIterator();
while (iter1.hasNext()) {
Node u = iter1.next();
int u_index = indicies.get(u);
delta[u_index] += (theta[u_index] / theta[w_index]) * (1 + delta[w_index]);
}
if (w != s) {
mBetweenness[w_index] += delta[w_index];
}
}
count++;
if (mIsCanceled) {
graph.readUnlockAll();
return;
}
Progress.progress(mProgress, count);
}
mAvgDist /= this.mShortestPaths;//mN * (mN - 1.0f);
for (Node s : graph.getNodes()) {
AttributeRow row = (AttributeRow) s.getNodeData().getAttributes();
int s_index = indicies.get(s);
if (!mDirected) {
mBetweenness[s_index] /= 2;
}
if (this.mRelativeValues) {
mCloseness[s_index] = (mCloseness[s_index] == 0) ? 0 : 1.0 / mCloseness[s_index];
mBetweenness[s_index] /= mDirected ? (mN - 1) * (mN - 2) : (mN - 1) * (mN - 2) / 2;
}
row.setValue(eccentricityCol, mEccentricity[s_index]);
row.setValue(closenessCol, mCloseness[s_index]);
row.setValue(betweenessCol, mBetweenness[s_index]);
}
graph.readUnlock();
}
|
diff --git a/jamwiki/src/main/java/org/jamwiki/parser/ParserInput.java b/jamwiki/src/main/java/org/jamwiki/parser/ParserInput.java
index 8a52f283..cd65579b 100644
--- a/jamwiki/src/main/java/org/jamwiki/parser/ParserInput.java
+++ b/jamwiki/src/main/java/org/jamwiki/parser/ParserInput.java
@@ -1,328 +1,328 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.parser;
import java.util.Hashtable;
import java.util.Locale;
import org.jamwiki.model.Role;
import org.jamwiki.model.WikiUser;
/**
* This class is a utility class used to hold configuration settings for the
* parser.
*/
public class ParserInput {
private boolean allowSectionEdit = true;
private String context = null;
/** Depth is used to prevent infinite nesting of templates and other objects. */
private int depth = 0;
private Locale locale = null;
private TableOfContents tableOfContents = new TableOfContents();
/** Template inclusion tracks whether or not template code is being parsed. A counter is used to deal with nested templates. */
private int templateDepth = 0;
/** Hashtable of generic temporary objects used during parsing. */
private final Hashtable tempParams = new Hashtable();
private String topicName = null;
/** IP address of the current user. */
private String userIpAddress = null;
private String virtualWiki = null;
/** Current WikiUser (if any). */
private WikiUser wikiUser = null;
/**
*
*/
public ParserInput() {
}
/**
* This method will return <code>true</code> if edit links are allowed
* next to each section heading. During preview and in some other
* instances that feature needs to be disabled.
*
* @return Returns <code>true</code> if edit links are allowed next to
* each section heading.
*/
public boolean getAllowSectionEdit() {
return allowSectionEdit;
}
/**
* Set method used to indicate whether or not to allow edit links
* next to each section heading. During preview and in some other
* instances that feature needs to be disabled.
*
* @param allowSectionEdit Set to <code>true</code> if edits links are
* allowed next to each section heading, <code>false</code> otherwise.
*/
public void setAllowSectionEdit(boolean allowSectionEdit) {
this.allowSectionEdit = allowSectionEdit;
}
/**
* Get the servlet context associated with the current parser input
* instance. Servlet context is used when building links.
*
* @return The servlet context associated with the current parser
* input instance.
*/
public String getContext() {
return context;
}
/**
* Set the servlet context associated with the current parser input
* instance. Servlet context is used when building links.
*
* @param context The servlet context associated with the current parser
* input instance.
*/
public void setContext(String context) {
this.context = context;
}
/**
* Since it is possible to call a new parser instance from within another
* parser instance, depth provides a way to determine how many times the
* parser has nested, thus providing a way of avoiding infinite loops.
*
* @return The current nesting level of the parser instance.
*/
public int getDepth() {
return depth;
}
/**
* This method decreases the current parser instance depth and should
* only be called when a parser instance exits. Depth is useful as a
* way of avoiding infinite loops in the parser.
*/
public void decrementDepth() {
this.depth--;
}
/**
* This method increases the current parser instance depth and should
* only be called when a instantiating a new parser instance. Depth is
* useful as a way of avoiding infinite loops in the parser.
*/
public void incrementDepth() {
this.depth++;
}
/**
* Since it is possible to call a new parser instance from within another
* parser instance, depth provides a way to determine how many times the
* parser has nested, thus providing a way of avoiding infinite loops.
*
* @param depth The current nesting level of the parser instance.
*/
public void setDepth(int depth) {
this.depth = depth;
}
/**
* Get the locale associated with the current parser input instance.
* Locale is used primarily when building links or displaying messages.
*
* @return The locale associated with the current parser input instance.
*/
public Locale getLocale() {
return locale;
}
/**
* Set the locale associated with the current parser input instance.
* Locale is used primarily when building links or displaying messages.
*
* @param locale The locale associated with the current parser input
* instance.
*/
public void setLocale(Locale locale) {
this.locale = locale;
}
/**
* Get the table of contents object associated with the current parser
* input instance. The table of contents is used for building an internal
* set of links to headings in the current document.
*
* @return The table of contents object associated with the current parser
* input instance.
*/
public TableOfContents getTableOfContents() {
return this.tableOfContents;
}
/**
* Set the table of contents object associated with the current parser
* input instance. The table of contents is used for building an internal
* set of links to headings in the current document.
*
* @param tableOfContents The table of contents object associated with the
* current parser input instance.
*/
public void setTableOfContents(TableOfContents tableOfContents) {
this.tableOfContents = tableOfContents;
}
/**
* Get the Hashtable of arbitrary temporary parameters associated with
* the current parser input instance. This hashtable provides a method
* for the parser to keep track of arbitrary data during the parsing
* process.
*
* @return The Hashtable of arbitrary temporary parameters associated with
* the current parser input instance.
*/
public Hashtable getTempParams() {
return this.tempParams;
}
/**
* Get the depth level when template code is being parsed.
*
* @return The current number of template inclusions.
*/
public int getTemplateDepth() {
return templateDepth;
}
/**
* This method decreases the current template inclusion depth and should
* only be called when a template finishes processing.
*/
public void decrementTemplateDepth() {
this.templateDepth--;
}
/**
* This method decreases the current template inclusion depth and should
* only be called when a template begins processing.
*/
public void incrementTemplateDepth() {
this.templateDepth++;
}
/**
* Set the depth level when template code is being parsed.
*
* @param templateDepth The current number of template inclusions.
*/
public void setTemplateDepth(int templateDepth) {
this.templateDepth = templateDepth;
}
/**
* Get the topic name for the topic being parsed by this parser input
* instance.
*
* @return The topic name for the topic being parsed by this parser input
* instance.
*/
public String getTopicName() {
return this.topicName;
}
/**
* Set the topic name for the topic being parsed by this parser input
* instance.
*
* @param topicName The topic name for the topic being parsed by this
* parser input instance.
*/
public void setTopicName(String topicName) {
this.topicName = topicName;
}
/**
* Get the user IP address associated with the current parser input
* instance. The user IP address is used primarily when parsing
* signatures.
*
* @return The user IP address associated with the current parser input
* instance.
*/
public String getUserIpAddress() {
return this.userIpAddress;
}
/**
* Set the user IP address associated with the current parser input
* instance. The user IP address is used primarily when parsing
* signatures.
*
* @param userIpAddress The user IP address associated with the current
* parser input instance.
*/
public void setUserIpAddress(String userIpAddress) {
this.userIpAddress = userIpAddress;
}
/**
* Get the virtual wiki name associated with the current parser input
* instance. The virtual wiki name is used primarily when parsing links.
*
* @return The virtual wiki name associated with the current parser input
* instance.
*/
public String getVirtualWiki() {
return this.virtualWiki;
}
/**
* Set the virtual wiki name associated with the current parser input
* instance. The virtual wiki name is used primarily when parsing links.
*
* @param virtualWiki The virtual wiki name associated with the current
* parser input instance.
*/
public void setVirtualWiki(String virtualWiki) {
this.virtualWiki = virtualWiki;
}
/**
* Get the wiki user object associated with the current parser input
* instance. The wiki user object is used primarily when parsing
* signatures.
*
* @return The wiki user object associated with the current parser input
* instance.
*/
public WikiUser getWikiUser() {
return this.wikiUser;
}
/**
* Set the wiki user object associated with the current parser input
* instance. The wiki user object is used primarily when parsing
* signatures.
*
* @param user The wiki user object associated with the current
* parser input instance.
*/
public void setWikiUser(WikiUser user) {
- if (!user.hasRole(Role.ROLE_USER)) {
+ if (user!=null && !user.hasRole(Role.ROLE_USER)) {
// FIXME - setting the user to null may not be necessary, but it is
// consistent with how the code behaved when Utilities.currentUser()
// returned null for non-logged-in users
user = null;
}
this.wikiUser = user;
}
}
| true | true | public void setWikiUser(WikiUser user) {
if (!user.hasRole(Role.ROLE_USER)) {
// FIXME - setting the user to null may not be necessary, but it is
// consistent with how the code behaved when Utilities.currentUser()
// returned null for non-logged-in users
user = null;
}
this.wikiUser = user;
}
| public void setWikiUser(WikiUser user) {
if (user!=null && !user.hasRole(Role.ROLE_USER)) {
// FIXME - setting the user to null may not be necessary, but it is
// consistent with how the code behaved when Utilities.currentUser()
// returned null for non-logged-in users
user = null;
}
this.wikiUser = user;
}
|
diff --git a/src/com/yahoo/platform/yui/compressor/CssCompressor.java b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
index 61216e0..136b45d 100644
--- a/src/com/yahoo/platform/yui/compressor/CssCompressor.java
+++ b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
@@ -1,360 +1,365 @@
/*
* YUI Compressor
* http://developer.yahoo.com/yui/compressor/
* Author: Julien Lecomte - http://www.julienlecomte.net/
* Author: Isaac Schlueter - http://foohack.com/
* Author: Stoyan Stefanov - http://phpied.com/
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed
* by Yahoo! Inc. under the BSD (revised) open source license.
*/
package com.yahoo.platform.yui.compressor;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
public class CssCompressor {
private StringBuffer srcsb = new StringBuffer();
public CssCompressor(Reader in) throws IOException {
// Read the stream...
int c;
while ((c = in.read()) != -1) {
srcsb.append((char) c);
}
}
// Leave data urls alone to increase parse performance.
protected String extractDataUrls(String css, ArrayList preservedTokens) {
int maxIndex = css.length() - 1;
int appendIndex = 0;
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("url\\(\\s*([\"']?)data\\:");
Matcher m = p.matcher(css);
/*
* Since we need to account for non-base64 data urls, we need to handle
* ' and ) being part of the data string. Hence switching to indexOf,
* to determine whether or not we have matching string terminators and
* handling sb appends directly, instead of using matcher.append* methods.
*/
while (m.find()) {
int startIndex = m.start() + 4; // "url(".length()
String terminator = m.group(1); // ', " or empty (not quoted)
if (terminator.length() == 0) {
terminator = ")";
}
boolean foundTerminator = false;
int endIndex = m.end() - 1;
while(foundTerminator == false && endIndex+1 <= maxIndex) {
endIndex = css.indexOf(terminator, endIndex+1);
if ((endIndex > 0) && (css.charAt(endIndex-1) != '\\')) {
foundTerminator = true;
if (!")".equals(terminator)) {
endIndex = css.indexOf(")", endIndex);
}
}
}
// Enough searching, start moving stuff over to the buffer
sb.append(css.substring(appendIndex, m.start()));
if (foundTerminator) {
String token = css.substring(startIndex, endIndex);
token = token.replaceAll("\\s+", "");
preservedTokens.add(token);
String preserver = "url(___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___)";
sb.append(preserver);
appendIndex = endIndex + 1;
} else {
// No end terminator found, re-add the whole match. Should we throw/warn here?
sb.append(css.substring(m.start(), m.end()));
appendIndex = m.end();
}
}
sb.append(css.substring(appendIndex));
return sb.toString();
}
public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
- // Test for AABBCC pattern
- if (m.group(3).equalsIgnoreCase(m.group(4)) &&
+ if (m.group(1).equals("}")) {
+ // Likely an ID selector. Don't touch.
+ // #AABBCC is a valid ID. IDs are case-sensitive.
+ m.appendReplacement(sb, m.group());
+ } else if (m.group(3).equalsIgnoreCase(m.group(4)) &&
m.group(5).equalsIgnoreCase(m.group(6)) &&
m.group(7).equalsIgnoreCase(m.group(8))) {
+ // #AABBCC pattern
m.appendReplacement(sb, (m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
+ // Any other color.
m.appendReplacement(sb, m.group().toLowerCase());
}
}
m.appendTail(sb);
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
}
| false | true | public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
// Test for AABBCC pattern
if (m.group(3).equalsIgnoreCase(m.group(4)) &&
m.group(5).equalsIgnoreCase(m.group(6)) &&
m.group(7).equalsIgnoreCase(m.group(8))) {
m.appendReplacement(sb, (m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
m.appendReplacement(sb, m.group().toLowerCase());
}
}
m.appendTail(sb);
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
| public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
if (m.group(1).equals("}")) {
// Likely an ID selector. Don't touch.
// #AABBCC is a valid ID. IDs are case-sensitive.
m.appendReplacement(sb, m.group());
} else if (m.group(3).equalsIgnoreCase(m.group(4)) &&
m.group(5).equalsIgnoreCase(m.group(6)) &&
m.group(7).equalsIgnoreCase(m.group(8))) {
// #AABBCC pattern
m.appendReplacement(sb, (m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Any other color.
m.appendReplacement(sb, m.group().toLowerCase());
}
}
m.appendTail(sb);
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
|
diff --git a/src/java/main/esg/node/filters/AccessLoggingFilter.java b/src/java/main/esg/node/filters/AccessLoggingFilter.java
index 1e128ef..78956e4 100644
--- a/src/java/main/esg/node/filters/AccessLoggingFilter.java
+++ b/src/java/main/esg/node/filters/AccessLoggingFilter.java
@@ -1,413 +1,420 @@
/***************************************************************************
* *
* Organization: Earth System Grid Federation *
* *
****************************************************************************
* *
* Copyright (c) 2009, Lawrence Livermore National Security, LLC. *
* Produced at the Lawrence Livermore National Laboratory *
* Written by: Gavin M. Bell ([email protected]) *
* LLNL-CODE-420962 *
* *
* All rights reserved. This file is part of the: *
* Earth System Grid Federation (ESGF) Data Node Software Stack *
* *
* For details, see http://esgf.org/ *
* Please also read this link *
* http://esgf.org/LICENSE *
* *
* * 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 disclaimer below. *
* *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the disclaimer (as noted below) *
* in the documentation and/or other materials provided with the *
* distribution. *
* *
* Neither the name of the LLNS/LLNL 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 LAWRENCE *
* LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. *
* *
***************************************************************************/
/**
Description:
The web.xml entry... (NOTE: must appear AFTER all Authorization
Filters because they put additional information in the request that
we need like email address and/or userid)
<!-- Filter for token-based authorization -->
<filter>
<filter-name>AccessLoggingFilter</filter-name>
<filter-class>esg.node.filters.AccessLoggingFilter</filter-class>
<!--
<init-param>
<param-name>db.driver</param-name>
<param-value>org.postgresql.Driver</param-value>
</init-param>
<init-param>
<param-name>db.protocol</param-name>
<param-value>jdbc:postgresql:</param-value>
</init-param>
<init-param>
<param-name>db.host</param-name>
<param-value>localhost</param-value>
</init-param>
<init-param>
<param-name>db.port</param-name>
<param-value>5432</param-value>
</init-param>
<init-param>
<param-name>db.database</param-name>
<param-value>esgcet</param-value>
</init-param>
<init-param>
<param-name>db.user</param-name>
<param-value>dbsuper</param-value>
</init-param>
<init-param>
<param-name>db.password</param-name>
<param-value>***</param-value>
</init-param>
-->
<init-param>
<param-name>service.name</param-name>
<param-value>thredds</param-value>
</init-param>
<init-param>
<param-name>exempt_extensions</param-name>
<param-value>.xml</param-value>
<param-name>extensions</param-name>
<param-value>.nc,.foo,.bar</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>AccessLoggingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
**/
package esg.node.filters;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Map;
import java.util.regex.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.*;
import esg.common.db.DatabaseResource;
import esg.common.util.ESGFProperties;
public class AccessLoggingFilter implements Filter {
final static String AUTHORIZATION_REQUEST_ATTRIBUTE = "eske.model.security.AuthorizationToken"; // legacy value compatible with old TDS filter
private static Log log = LogFactory.getLog(AccessLoggingFilter.class);
FilterConfig filterConfig = null;
AccessLoggingDAO accessLoggingDAO = null;
Properties dbProperties = null;
private Pattern urlPattern = null;
private Pattern exemptUrlPattern = null;
private Pattern mountedPathPattern;
private MountedPathResolver mpResolver = null;
private String serviceName = null;
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Initializing filter: "+this.getClass().getName());
this.filterConfig = filterConfig;
ESGFProperties esgfProperties = null;
try{
esgfProperties = new ESGFProperties();
}catch (java.io.IOException e) { e.printStackTrace(); log.error(e); }
String value = null;
dbProperties = new Properties();
log.debug("FilterConfig is : ["+filterConfig+"]");
log.debug("db.protocol is : ["+filterConfig.getInitParameter("db.protocol")+"]");
dbProperties.put("db.protocol",((null != (value = filterConfig.getInitParameter("db.protocol"))) ? value : esgfProperties.getProperty("db.protocol"))); value = null;
dbProperties.put("db.host",((null != (value = filterConfig.getInitParameter("db.host"))) ? value : esgfProperties.getProperty("db.host"))); value = null;
dbProperties.put("db.port",((null != (value = filterConfig.getInitParameter("db.port"))) ? value : esgfProperties.getProperty("db.port"))); value = null;
dbProperties.put("db.database",((null != (value = filterConfig.getInitParameter("db.database"))) ? value : esgfProperties.getProperty("db.database"))); value = null;
dbProperties.put("db.user",((null != (value = filterConfig.getInitParameter("db.user"))) ? value : esgfProperties.getProperty("db.user"))); value = null;
dbProperties.put("db.password",((null != (value = filterConfig.getInitParameter("db.password"))) ? value : esgfProperties.getDatabasePassword())); value = null;
dbProperties.put("db.driver",((null != (value = filterConfig.getInitParameter("db.driver"))) ? value : esgfProperties.getProperty("db.driver","org.postgresql.Driver"))); value = null;
serviceName = (null != (value = filterConfig.getInitParameter("service.name"))) ? value : "thredds"; value = null;
log.debug("Database parameters: "+dbProperties);
DatabaseResource.init(dbProperties.getProperty("db.driver","org.postgresql.Driver")).setupDataSource(dbProperties);
DatabaseResource.getInstance().showDriverStats();
accessLoggingDAO = new AccessLoggingDAO(DatabaseResource.getInstance().getDataSource());
//------------------------------------------------------------------------
// Extensions that this filter will handle...
//------------------------------------------------------------------------
String extensionsParam = filterConfig.getInitParameter("extensions");
if (extensionsParam == null) { extensionsParam=""; } //defensive program against null for this param
String[] extensions = (".nc,"+extensionsParam.toString()).split(",");
StringBuffer sb = new StringBuffer();
for(int i=0 ; i<extensions.length; i++) {
sb.append(extensions[i].trim());
if(i<extensions.length-1) sb.append("|");
}
System.out.println("Looking for extensions: "+sb.toString());
String regex = "http.*(?:"+sb.toString()+")$";
System.out.println("Regex = "+regex);
urlPattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
//------------------------------------------------------------------------
//------------------------------------------------------------------------
// Extensions that this filter will NOT handle...
//------------------------------------------------------------------------
String exemptExtensionsParam = filterConfig.getInitParameter("exempt_extensions");
if (exemptExtensionsParam == null) { exemptExtensionsParam=""; } //defensive program against null for this param
String[] exemptExtensions = (".xml,"+exemptExtensionsParam.toString()).split(",");
sb = new StringBuffer();
for(int i=0 ; i<exemptExtensions.length; i++) {
sb.append(exemptExtensions[i].trim());
if(i<exemptExtensions.length-1) sb.append("|");
}
System.out.println("Looking for exempt extensions: "+sb.toString());
regex = "http.*(?:"+sb.toString()+")$";
System.out.println("Exempt Regex = "+regex);
exemptUrlPattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
//------------------------------------------------------------------------
log.trace(accessLoggingDAO.toString());
String svc_prefix = esgfProperties.getProperty("node.download.svc.prefix","thredds/fileServer");
String mountedPathRegex = "http[s]?://([^:/]*)(:(?:[0-9]*))?/"+svc_prefix+"(.*$)";
mountedPathPattern = Pattern.compile(mountedPathRegex,Pattern.CASE_INSENSITIVE);
mpResolver = new MountedPathResolver((new esg.common.util.ESGIni()).getMounts());
}
public void destroy() {
this.filterConfig = null;
this.dbProperties.clear();
this.accessLoggingDAO = null;
//Shutting down this resource under the assuption that no one
//else is using this resource but us
DatabaseResource.getInstance().shutdownResource();
}
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(filterConfig == null) return;
int id = -1;
//Record identifying tuple
String userID = null;
String email = null;
String url = null;
String fileID = null;
String remoteAddress = null;
String userAgent = null;
long dateFetched = 0L;
long batchUpdateTime = 0L;
//(note: serviceName defined in global scope)
//firewall off any errors so that nothing stops the show...
try {
log.warn("accessLogging DAO -> "+accessLoggingDAO);
if(accessLoggingDAO != null) {
//This filter should only appy to specific requests
//in particular requests for data files (*.nc)
HttpServletRequest req = (HttpServletRequest)request;
url = req.getRequestURL().toString().trim();
System.out.println("Requested URL: "+url);
- Matcher exemptMatcher = exemptUrlPattern.matcher(url);
- Matcher m = urlPattern.matcher(url);
+ Matcher exemptFilesMatcher = exemptUrlPattern.matcher(url);
+ Matcher forThreddsFileServiceMatcher = mountedPathPattern.matcher(url);
+ Matcher allowedFilesMatcher = urlPattern.matcher(url);
- if(exemptMatcher.matches()) {
+ if(exemptFilesMatcher.matches()) {
System.out.println("I am not logging this, punting!!!! on "+url);
chain.doFilter(request, response);
return;
}
+ System.out.println("+");
+ if (!forThreddsFileServiceMatcher.find()) {
+ System.out.println("url not for thredds' fileService, punting!!!! on "+url);
+ chain.doFilter(request, response);
+ return;
+ }
System.out.println("+");
- if(m.matches()) {
+ if(allowedFilesMatcher.matches()) {
// only proceed if the request has been authorized
final Boolean requestIsAuthorized = (Boolean)request.getAttribute(AUTHORIZATION_REQUEST_ATTRIBUTE);
log.debug("AUTHORIZATION_REQUEST_ATTRIBUTE="+requestIsAuthorized);
if (requestIsAuthorized==null || requestIsAuthorized==false) {
System.out.println("UnAuthorized Request for: "+req.getRequestURL().toString().trim());
chain.doFilter(request, response);
return;
}
System.out.println("Executing filter on: "+url);
//------------------------------------------------------------------------------------------
//For Token authentication there is a Validation Map present with user and email information
//------------------------------------------------------------------------------------------
Map<String,String> validationMap = (Map<String,String>)req.getAttribute("validationMap");
if(validationMap != null) {
userID = validationMap.get("user");
email = validationMap.get("email");
//Want to make sure that any snooping filters
//behind this one does not have access to this
//information (posted by the
//authorizationTokenValidationFilter, which should
//immediately preceed this one). This is in
//effort to limit information exposure the
//best we can.
req.removeAttribute("validationMap");
}else{
log.warn("Validation Map is ["+validationMap+"] - (not a token based request)");
}
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
//For TokenLESS authentication the userid information is in a parameter called "esg.openid"
//------------------------------------------------------------------------------------------
if (userID == null || userID.isEmpty()) {
userID = ((req.getAttribute("esg.openid") == null) ? "<no-id>" : req.getAttribute("esg.openid").toString());
if(userID == null || userID.isEmpty()) { log.warn("This request is apparently not a \"tokenless\" request either - no openid attribute!!!!!"); }
log.warn("AccessLoggingFilter - Tokenless: UserID = ["+userID+"]");
}
//------------------------------------------------------------------------------------------
fileID = "0A";
remoteAddress = req.getRemoteAddr();
userAgent = (String)req.getAttribute("userAgent");
dateFetched = System.currentTimeMillis()/1000;
batchUpdateTime = dateFetched; //For the life of my I am not sure why this is there, something from the gridftp metrics collection. -gmb
id = accessLoggingDAO.logIngressInfo(userID,email,url,fileID,remoteAddress,userAgent,serviceName,batchUpdateTime,dateFetched);
System.out.println("myID: ["+id+"] = accessLoggingDAO.logIngressInfo(userID: ["+userID+"], email, url: ["+url+"], fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched)");
}else {
log.warn("No match against: "+url);
}
}else{
log.error("DAO is null :["+accessLoggingDAO+"]");
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid State Of ESG Access Logging Filter: DAO=["+accessLoggingDAO+"]");
}
}catch(Throwable t) {
log.error(t);
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter");
}
try{
ByteCountListener byteCountListener = new ByteCountListener() {
int myID = -1;
long duration = -1;
long startTime = -1;
long dataSize = -1;
long byteCount = -1;
boolean success = false;
public void setRecordID(int id) { this.myID = id; }
public void setStartTime(long startTime) { this.startTime = startTime; }
public void setDataSizeBytes(long dataSize) { this.dataSize = dataSize; }
//This callback method should get called by the ByteCountingResponseStream when it is *closed*
public void setByteCount(long xferSize) {
byteCount=xferSize;
System.out.println("**** setByteCount("+xferSize+")");
if((AccessLoggingFilter.this.accessLoggingDAO != null) && (myID > 0)) {
if (dataSize == xferSize) { success = true; }
duration = System.currentTimeMillis() - startTime;
System.out.println("AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID: ["+myID+"], success: ["+success+"], duration: ["+duration+"]ms, dataSize ["+dataSize+"], xferSize: ["+xferSize+"] );");
AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID, success, duration, dataSize, xferSize);
}
}
public long getByteCount() { return byteCount; }
};
byteCountListener.setRecordID(id);
byteCountListener.setDataSizeBytes(resolveUrlToFile(url).length());
byteCountListener.setStartTime(System.currentTimeMillis());
AccessLoggingResponseWrapper accessLoggingResponseWrapper = new AccessLoggingResponseWrapper((HttpServletResponse)response, byteCountListener);
chain.doFilter(request, accessLoggingResponseWrapper);
}catch(Throwable t) {
log.error(t);
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter* (may not be resolvable url) "+t.getMessage());
}
}
//Here we resolve the URL passed in to where the bits reside on the filesystem.
private File resolveUrlToFile(String url) {
//Strip url down to just the path...
System.out.println("AccessLoggingFilter.resolveUrlToFile("+url+")");
Matcher m = mountedPathPattern.matcher(url);
if (!m.find()) {
System.out.println("url not of resolvable form (returning null)");
return null;
}
String path = m.group(3); //the path AFTER the service prefix
System.out.println(" --> stripping url ["+url+"] to path ["+path+"]");
File resolvedFile = null;
try{
resolvedFile = new File(mpResolver.resolve(path));
if ((resolvedFile != null) && resolvedFile.exists()) {
return resolvedFile;
}else{
log.warn("Unable to resolve file to existing filesystem location");
}
}catch(Exception e) { log.error(e); }
return resolvedFile;
}
}
| false | true | public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(filterConfig == null) return;
int id = -1;
//Record identifying tuple
String userID = null;
String email = null;
String url = null;
String fileID = null;
String remoteAddress = null;
String userAgent = null;
long dateFetched = 0L;
long batchUpdateTime = 0L;
//(note: serviceName defined in global scope)
//firewall off any errors so that nothing stops the show...
try {
log.warn("accessLogging DAO -> "+accessLoggingDAO);
if(accessLoggingDAO != null) {
//This filter should only appy to specific requests
//in particular requests for data files (*.nc)
HttpServletRequest req = (HttpServletRequest)request;
url = req.getRequestURL().toString().trim();
System.out.println("Requested URL: "+url);
Matcher exemptMatcher = exemptUrlPattern.matcher(url);
Matcher m = urlPattern.matcher(url);
if(exemptMatcher.matches()) {
System.out.println("I am not logging this, punting!!!! on "+url);
chain.doFilter(request, response);
return;
}
System.out.println("+");
if(m.matches()) {
// only proceed if the request has been authorized
final Boolean requestIsAuthorized = (Boolean)request.getAttribute(AUTHORIZATION_REQUEST_ATTRIBUTE);
log.debug("AUTHORIZATION_REQUEST_ATTRIBUTE="+requestIsAuthorized);
if (requestIsAuthorized==null || requestIsAuthorized==false) {
System.out.println("UnAuthorized Request for: "+req.getRequestURL().toString().trim());
chain.doFilter(request, response);
return;
}
System.out.println("Executing filter on: "+url);
//------------------------------------------------------------------------------------------
//For Token authentication there is a Validation Map present with user and email information
//------------------------------------------------------------------------------------------
Map<String,String> validationMap = (Map<String,String>)req.getAttribute("validationMap");
if(validationMap != null) {
userID = validationMap.get("user");
email = validationMap.get("email");
//Want to make sure that any snooping filters
//behind this one does not have access to this
//information (posted by the
//authorizationTokenValidationFilter, which should
//immediately preceed this one). This is in
//effort to limit information exposure the
//best we can.
req.removeAttribute("validationMap");
}else{
log.warn("Validation Map is ["+validationMap+"] - (not a token based request)");
}
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
//For TokenLESS authentication the userid information is in a parameter called "esg.openid"
//------------------------------------------------------------------------------------------
if (userID == null || userID.isEmpty()) {
userID = ((req.getAttribute("esg.openid") == null) ? "<no-id>" : req.getAttribute("esg.openid").toString());
if(userID == null || userID.isEmpty()) { log.warn("This request is apparently not a \"tokenless\" request either - no openid attribute!!!!!"); }
log.warn("AccessLoggingFilter - Tokenless: UserID = ["+userID+"]");
}
//------------------------------------------------------------------------------------------
fileID = "0A";
remoteAddress = req.getRemoteAddr();
userAgent = (String)req.getAttribute("userAgent");
dateFetched = System.currentTimeMillis()/1000;
batchUpdateTime = dateFetched; //For the life of my I am not sure why this is there, something from the gridftp metrics collection. -gmb
id = accessLoggingDAO.logIngressInfo(userID,email,url,fileID,remoteAddress,userAgent,serviceName,batchUpdateTime,dateFetched);
System.out.println("myID: ["+id+"] = accessLoggingDAO.logIngressInfo(userID: ["+userID+"], email, url: ["+url+"], fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched)");
}else {
log.warn("No match against: "+url);
}
}else{
log.error("DAO is null :["+accessLoggingDAO+"]");
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid State Of ESG Access Logging Filter: DAO=["+accessLoggingDAO+"]");
}
}catch(Throwable t) {
log.error(t);
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter");
}
try{
ByteCountListener byteCountListener = new ByteCountListener() {
int myID = -1;
long duration = -1;
long startTime = -1;
long dataSize = -1;
long byteCount = -1;
boolean success = false;
public void setRecordID(int id) { this.myID = id; }
public void setStartTime(long startTime) { this.startTime = startTime; }
public void setDataSizeBytes(long dataSize) { this.dataSize = dataSize; }
//This callback method should get called by the ByteCountingResponseStream when it is *closed*
public void setByteCount(long xferSize) {
byteCount=xferSize;
System.out.println("**** setByteCount("+xferSize+")");
if((AccessLoggingFilter.this.accessLoggingDAO != null) && (myID > 0)) {
if (dataSize == xferSize) { success = true; }
duration = System.currentTimeMillis() - startTime;
System.out.println("AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID: ["+myID+"], success: ["+success+"], duration: ["+duration+"]ms, dataSize ["+dataSize+"], xferSize: ["+xferSize+"] );");
AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID, success, duration, dataSize, xferSize);
}
}
public long getByteCount() { return byteCount; }
};
byteCountListener.setRecordID(id);
byteCountListener.setDataSizeBytes(resolveUrlToFile(url).length());
byteCountListener.setStartTime(System.currentTimeMillis());
AccessLoggingResponseWrapper accessLoggingResponseWrapper = new AccessLoggingResponseWrapper((HttpServletResponse)response, byteCountListener);
chain.doFilter(request, accessLoggingResponseWrapper);
}catch(Throwable t) {
log.error(t);
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter* (may not be resolvable url) "+t.getMessage());
}
}
| public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(filterConfig == null) return;
int id = -1;
//Record identifying tuple
String userID = null;
String email = null;
String url = null;
String fileID = null;
String remoteAddress = null;
String userAgent = null;
long dateFetched = 0L;
long batchUpdateTime = 0L;
//(note: serviceName defined in global scope)
//firewall off any errors so that nothing stops the show...
try {
log.warn("accessLogging DAO -> "+accessLoggingDAO);
if(accessLoggingDAO != null) {
//This filter should only appy to specific requests
//in particular requests for data files (*.nc)
HttpServletRequest req = (HttpServletRequest)request;
url = req.getRequestURL().toString().trim();
System.out.println("Requested URL: "+url);
Matcher exemptFilesMatcher = exemptUrlPattern.matcher(url);
Matcher forThreddsFileServiceMatcher = mountedPathPattern.matcher(url);
Matcher allowedFilesMatcher = urlPattern.matcher(url);
if(exemptFilesMatcher.matches()) {
System.out.println("I am not logging this, punting!!!! on "+url);
chain.doFilter(request, response);
return;
}
System.out.println("+");
if (!forThreddsFileServiceMatcher.find()) {
System.out.println("url not for thredds' fileService, punting!!!! on "+url);
chain.doFilter(request, response);
return;
}
System.out.println("+");
if(allowedFilesMatcher.matches()) {
// only proceed if the request has been authorized
final Boolean requestIsAuthorized = (Boolean)request.getAttribute(AUTHORIZATION_REQUEST_ATTRIBUTE);
log.debug("AUTHORIZATION_REQUEST_ATTRIBUTE="+requestIsAuthorized);
if (requestIsAuthorized==null || requestIsAuthorized==false) {
System.out.println("UnAuthorized Request for: "+req.getRequestURL().toString().trim());
chain.doFilter(request, response);
return;
}
System.out.println("Executing filter on: "+url);
//------------------------------------------------------------------------------------------
//For Token authentication there is a Validation Map present with user and email information
//------------------------------------------------------------------------------------------
Map<String,String> validationMap = (Map<String,String>)req.getAttribute("validationMap");
if(validationMap != null) {
userID = validationMap.get("user");
email = validationMap.get("email");
//Want to make sure that any snooping filters
//behind this one does not have access to this
//information (posted by the
//authorizationTokenValidationFilter, which should
//immediately preceed this one). This is in
//effort to limit information exposure the
//best we can.
req.removeAttribute("validationMap");
}else{
log.warn("Validation Map is ["+validationMap+"] - (not a token based request)");
}
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
//For TokenLESS authentication the userid information is in a parameter called "esg.openid"
//------------------------------------------------------------------------------------------
if (userID == null || userID.isEmpty()) {
userID = ((req.getAttribute("esg.openid") == null) ? "<no-id>" : req.getAttribute("esg.openid").toString());
if(userID == null || userID.isEmpty()) { log.warn("This request is apparently not a \"tokenless\" request either - no openid attribute!!!!!"); }
log.warn("AccessLoggingFilter - Tokenless: UserID = ["+userID+"]");
}
//------------------------------------------------------------------------------------------
fileID = "0A";
remoteAddress = req.getRemoteAddr();
userAgent = (String)req.getAttribute("userAgent");
dateFetched = System.currentTimeMillis()/1000;
batchUpdateTime = dateFetched; //For the life of my I am not sure why this is there, something from the gridftp metrics collection. -gmb
id = accessLoggingDAO.logIngressInfo(userID,email,url,fileID,remoteAddress,userAgent,serviceName,batchUpdateTime,dateFetched);
System.out.println("myID: ["+id+"] = accessLoggingDAO.logIngressInfo(userID: ["+userID+"], email, url: ["+url+"], fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched)");
}else {
log.warn("No match against: "+url);
}
}else{
log.error("DAO is null :["+accessLoggingDAO+"]");
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid State Of ESG Access Logging Filter: DAO=["+accessLoggingDAO+"]");
}
}catch(Throwable t) {
log.error(t);
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter");
}
try{
ByteCountListener byteCountListener = new ByteCountListener() {
int myID = -1;
long duration = -1;
long startTime = -1;
long dataSize = -1;
long byteCount = -1;
boolean success = false;
public void setRecordID(int id) { this.myID = id; }
public void setStartTime(long startTime) { this.startTime = startTime; }
public void setDataSizeBytes(long dataSize) { this.dataSize = dataSize; }
//This callback method should get called by the ByteCountingResponseStream when it is *closed*
public void setByteCount(long xferSize) {
byteCount=xferSize;
System.out.println("**** setByteCount("+xferSize+")");
if((AccessLoggingFilter.this.accessLoggingDAO != null) && (myID > 0)) {
if (dataSize == xferSize) { success = true; }
duration = System.currentTimeMillis() - startTime;
System.out.println("AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID: ["+myID+"], success: ["+success+"], duration: ["+duration+"]ms, dataSize ["+dataSize+"], xferSize: ["+xferSize+"] );");
AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID, success, duration, dataSize, xferSize);
}
}
public long getByteCount() { return byteCount; }
};
byteCountListener.setRecordID(id);
byteCountListener.setDataSizeBytes(resolveUrlToFile(url).length());
byteCountListener.setStartTime(System.currentTimeMillis());
AccessLoggingResponseWrapper accessLoggingResponseWrapper = new AccessLoggingResponseWrapper((HttpServletResponse)response, byteCountListener);
chain.doFilter(request, accessLoggingResponseWrapper);
}catch(Throwable t) {
log.error(t);
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter* (may not be resolvable url) "+t.getMessage());
}
}
|
diff --git a/src/com/android/nfc/NfcService.java b/src/com/android/nfc/NfcService.java
index e3ecb03..bf18f42 100755
--- a/src/com/android/nfc/NfcService.java
+++ b/src/com/android/nfc/NfcService.java
@@ -1,2323 +1,2325 @@
/*
* 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.nfc;
import com.android.internal.nfc.LlcpServiceSocket;
import com.android.internal.nfc.LlcpSocket;
import com.android.nfc.mytag.MyTagClient;
import com.android.nfc.mytag.MyTagServer;
import android.app.Application;
import android.app.StatusBarManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.ErrorCodes;
import android.nfc.FormatException;
import android.nfc.ILlcpConnectionlessSocket;
import android.nfc.ILlcpServiceSocket;
import android.nfc.ILlcpSocket;
import android.nfc.INfcAdapter;
import android.nfc.INfcTag;
import android.nfc.IP2pInitiator;
import android.nfc.IP2pTarget;
import android.nfc.LlcpPacket;
import android.nfc.NdefMessage;
import android.nfc.NdefTag;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
public class NfcService extends Application {
static {
System.loadLibrary("nfc_jni");
}
public static final String SERVICE_NAME = "nfc";
private static final String TAG = "NfcService";
private static final String NFC_PERM = android.Manifest.permission.NFC;
private static final String NFC_PERM_ERROR = "NFC permission required";
private static final String ADMIN_PERM = android.Manifest.permission.WRITE_SECURE_SETTINGS;
private static final String ADMIN_PERM_ERROR = "WRITE_SECURE_SETTINGS permission required";
private static final String PREF = "NfcServicePrefs";
private static final String PREF_NFC_ON = "nfc_on";
private static final boolean NFC_ON_DEFAULT = true;
private static final String PREF_SECURE_ELEMENT_ON = "secure_element_on";
private static final boolean SECURE_ELEMENT_ON_DEFAULT = false;
private static final String PREF_SECURE_ELEMENT_ID = "secure_element_id";
private static final int SECURE_ELEMENT_ID_DEFAULT = 0;
private static final String PREF_LLCP_LTO = "llcp_lto";
private static final int LLCP_LTO_DEFAULT = 150;
private static final int LLCP_LTO_MAX = 255;
/** Maximum Information Unit */
private static final String PREF_LLCP_MIU = "llcp_miu";
private static final int LLCP_MIU_DEFAULT = 128;
private static final int LLCP_MIU_MAX = 2176;
/** Well Known Service List */
private static final String PREF_LLCP_WKS = "llcp_wks";
private static final int LLCP_WKS_DEFAULT = 1;
private static final int LLCP_WKS_MAX = 15;
private static final String PREF_LLCP_OPT = "llcp_opt";
private static final int LLCP_OPT_DEFAULT = 0;
private static final int LLCP_OPT_MAX = 3;
private static final String PREF_DISCOVERY_A = "discovery_a";
private static final boolean DISCOVERY_A_DEFAULT = true;
private static final String PREF_DISCOVERY_B = "discovery_b";
private static final boolean DISCOVERY_B_DEFAULT = true;
private static final String PREF_DISCOVERY_F = "discovery_f";
private static final boolean DISCOVERY_F_DEFAULT = true;
private static final String PREF_DISCOVERY_15693 = "discovery_15693";
private static final boolean DISCOVERY_15693_DEFAULT = true;
private static final String PREF_DISCOVERY_NFCIP = "discovery_nfcip";
private static final boolean DISCOVERY_NFCIP_DEFAULT = true;
/** NFC Reader Discovery mode for enableDiscovery() */
private static final int DISCOVERY_MODE_READER = 0;
/** Card Emulation Discovery mode for enableDiscovery() */
private static final int DISCOVERY_MODE_CARD_EMULATION = 2;
private static final int LLCP_SERVICE_SOCKET_TYPE = 0;
private static final int LLCP_SOCKET_TYPE = 1;
private static final int LLCP_CONNECTIONLESS_SOCKET_TYPE = 2;
private static final int LLCP_SOCKET_NB_MAX = 5; // Maximum number of socket managed
private static final int LLCP_RW_MAX_VALUE = 15; // Receive Window
private static final int PROPERTY_LLCP_LTO = 0;
private static final String PROPERTY_LLCP_LTO_VALUE = "llcp.lto";
private static final int PROPERTY_LLCP_MIU = 1;
private static final String PROPERTY_LLCP_MIU_VALUE = "llcp.miu";
private static final int PROPERTY_LLCP_WKS = 2;
private static final String PROPERTY_LLCP_WKS_VALUE = "llcp.wks";
private static final int PROPERTY_LLCP_OPT = 3;
private static final String PROPERTY_LLCP_OPT_VALUE = "llcp.opt";
private static final int PROPERTY_NFC_DISCOVERY_A = 4;
private static final String PROPERTY_NFC_DISCOVERY_A_VALUE = "discovery.iso14443A";
private static final int PROPERTY_NFC_DISCOVERY_B = 5;
private static final String PROPERTY_NFC_DISCOVERY_B_VALUE = "discovery.iso14443B";
private static final int PROPERTY_NFC_DISCOVERY_F = 6;
private static final String PROPERTY_NFC_DISCOVERY_F_VALUE = "discovery.felica";
private static final int PROPERTY_NFC_DISCOVERY_15693 = 7;
private static final String PROPERTY_NFC_DISCOVERY_15693_VALUE = "discovery.iso15693";
private static final int PROPERTY_NFC_DISCOVERY_NFCIP = 8;
private static final String PROPERTY_NFC_DISCOVERY_NFCIP_VALUE = "discovery.nfcip";
static final int MSG_NDEF_TAG = 0;
static final int MSG_CARD_EMULATION = 1;
static final int MSG_LLCP_LINK_ACTIVATION = 2;
static final int MSG_LLCP_LINK_DEACTIVATED = 3;
static final int MSG_TARGET_DESELECTED = 4;
static final int MSG_SHOW_MY_TAG_ICON = 5;
static final int MSG_HIDE_MY_TAG_ICON = 6;
static final int MSG_MOCK_NDEF_TAG = 7;
// TODO: none of these appear to be synchronized but are
// read/written from different threads (notably Binder threads)...
private final LinkedList<RegisteredSocket> mRegisteredSocketList = new LinkedList<RegisteredSocket>();
private int mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
private int mGeneratedSocketHandle = 0;
private int mNbSocketCreated = 0;
private volatile boolean mIsNfcEnabled = false;
private int mSelectedSeId = 0;
private boolean mNfcSecureElementState;
private boolean mOpenPending = false;
// fields below are used in multiple threads and protected by synchronized(this)
private final HashMap<Integer, Object> mObjectMap = new HashMap<Integer, Object>();
private final HashMap<Integer, Object> mSocketMap = new HashMap<Integer, Object>();
private int mTimeout = 0;
private boolean mBootComplete = false;
private boolean mScreenOn;
// fields below are final after onCreate()
private Context mContext;
private NativeNfcManager mManager;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;
private MyTagServer mMyTagServer;
private MyTagClient mMyTagClient;
private static NfcService sService;
public static NfcService getInstance() {
return sService;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting NFC service");
sService = this;
mContext = this;
mManager = new NativeNfcManager(mContext, this);
mManager.initializeNativeStructure();
mMyTagServer = new MyTagServer();
mMyTagClient = new MyTagClient(this);
// mMyTagServer.start();
mPrefs = mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE);
mPrefsEditor = mPrefs.edit();
mIsNfcEnabled = false; // real preference read later
mScreenOn = true; // assume screen is on during boot
ServiceManager.addService(SERVICE_NAME, mNfcAdapter);
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
filter.addAction(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
mContext.registerReceiver(mReceiver, filter);
Thread t = new Thread() {
@Override
public void run() {
boolean nfc_on = mPrefs.getBoolean(PREF_NFC_ON, NFC_ON_DEFAULT);
if (nfc_on) {
_enable(false);
}
}
};
t.start();
}
@Override
public void onTerminate() {
super.onTerminate();
// NFC application is persistent, it should not be destroyed by framework
Log.wtf(TAG, "NFC service is under attack!");
}
private final INfcAdapter.Stub mNfcAdapter = new INfcAdapter.Stub() {
/** Protected by "this" */
// TODO read this from permanent storage at boot time
NdefMessage mLocalMessage = null;
public boolean enable() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
boolean isSuccess = false;
boolean previouslyEnabled = isEnabled();
if (!previouslyEnabled) {
reset();
isSuccess = _enable(previouslyEnabled);
}
return isSuccess;
}
public boolean disable() throws RemoteException {
boolean isSuccess = false;
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
boolean previouslyEnabled = isEnabled();
Log.d(TAG, "Disabling NFC. previous=" + previouslyEnabled);
if (previouslyEnabled) {
isSuccess = mManager.deinitialize();
Log.d(TAG, "NFC success of deinitialize = " + isSuccess);
if (isSuccess) {
mIsNfcEnabled = false;
}
}
updateNfcOnSetting(previouslyEnabled);
return isSuccess;
}
public int createLlcpConnectionlessSocket(int sap) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* Check SAP is not already used */
/* Check nb socket created */
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
/* Store the socket handle */
int sockeHandle = mGeneratedSocketHandle;
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
NativeLlcpConnectionlessSocket socket;
socket = mManager.doCreateLlcpConnectionlessSocket(sap);
if (socket != null) {
synchronized(NfcService.this) {
/* Update the number of socket created */
mNbSocketCreated++;
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
}
return sockeHandle;
} else {
/*
* socket creation error - update the socket handle
* generation
*/
mGeneratedSocketHandle -= 1;
/* Get Error Status */
int errorStatus = mManager.doGetLastError();
switch (errorStatus) {
case ErrorCodes.ERROR_BUFFER_TO_SMALL:
return ErrorCodes.ERROR_BUFFER_TO_SMALL;
case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
default:
return ErrorCodes.ERROR_SOCKET_CREATION;
}
}
} else {
/* Check SAP is not already used */
if (!CheckSocketSap(sap)) {
return ErrorCodes.ERROR_SAP_USED;
}
NativeLlcpConnectionlessSocket socket = new NativeLlcpConnectionlessSocket(sap);
synchronized(NfcService.this) {
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
/* Update the number of socket created */
mNbSocketCreated++;
}
/* Create new registered socket */
RegisteredSocket registeredSocket = new RegisteredSocket(
LLCP_CONNECTIONLESS_SOCKET_TYPE, sockeHandle, sap);
/* Put this socket into a list of registered socket */
mRegisteredSocketList.add(registeredSocket);
}
/* update socket handle generation */
mGeneratedSocketHandle++;
return sockeHandle;
} else {
/* No socket available */
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
public int createLlcpServiceSocket(int sap, String sn, int miu, int rw, int linearBufferLength)
throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
int sockeHandle = mGeneratedSocketHandle;
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
NativeLlcpServiceSocket socket;
socket = mManager.doCreateLlcpServiceSocket(sap, sn, miu, rw, linearBufferLength);
if (socket != null) {
synchronized(NfcService.this) {
/* Update the number of socket created */
mNbSocketCreated++;
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
}
} else {
/* socket creation error - update the socket handle counter */
mGeneratedSocketHandle -= 1;
/* Get Error Status */
int errorStatus = mManager.doGetLastError();
switch (errorStatus) {
case ErrorCodes.ERROR_BUFFER_TO_SMALL:
return ErrorCodes.ERROR_BUFFER_TO_SMALL;
case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
default:
return ErrorCodes.ERROR_SOCKET_CREATION;
}
}
} else {
/* Check SAP is not already used */
if (!CheckSocketSap(sap)) {
return ErrorCodes.ERROR_SAP_USED;
}
/* Service Name */
if (!CheckSocketServiceName(sn)) {
return ErrorCodes.ERROR_SERVICE_NAME_USED;
}
/* Check socket options */
if (!CheckSocketOptions(miu, rw, linearBufferLength)) {
return ErrorCodes.ERROR_SOCKET_OPTIONS;
}
NativeLlcpServiceSocket socket = new NativeLlcpServiceSocket(sn);
synchronized(NfcService.this) {
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
/* Update the number of socket created */
mNbSocketCreated++;
}
/* Create new registered socket */
RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SERVICE_SOCKET_TYPE,
sockeHandle, sap, sn, miu, rw, linearBufferLength);
/* Put this socket into a list of registered socket */
mRegisteredSocketList.add(registeredSocket);
}
/* update socket handle generation */
mGeneratedSocketHandle += 1;
Log.d(TAG, "Llcp Service Socket Handle =" + sockeHandle);
return sockeHandle;
} else {
/* No socket available */
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
public int createLlcpSocket(int sap, int miu, int rw, int linearBufferLength)
throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
int sockeHandle = mGeneratedSocketHandle;
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
NativeLlcpSocket socket;
socket = mManager.doCreateLlcpSocket(sap, miu, rw, linearBufferLength);
if (socket != null) {
synchronized(NfcService.this) {
/* Update the number of socket created */
mNbSocketCreated++;
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
}
} else {
/*
* socket creation error - update the socket handle
* generation
*/
mGeneratedSocketHandle -= 1;
/* Get Error Status */
int errorStatus = mManager.doGetLastError();
switch (errorStatus) {
case ErrorCodes.ERROR_BUFFER_TO_SMALL:
return ErrorCodes.ERROR_BUFFER_TO_SMALL;
case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
default:
return ErrorCodes.ERROR_SOCKET_CREATION;
}
}
} else {
/* Check SAP is not already used */
if (!CheckSocketSap(sap)) {
return ErrorCodes.ERROR_SAP_USED;
}
/* Check Socket options */
if (!CheckSocketOptions(miu, rw, linearBufferLength)) {
return ErrorCodes.ERROR_SOCKET_OPTIONS;
}
NativeLlcpSocket socket = new NativeLlcpSocket(sap, miu, rw);
synchronized(NfcService.this) {
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
/* Update the number of socket created */
mNbSocketCreated++;
}
/* Create new registered socket */
RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SOCKET_TYPE,
sockeHandle, sap, miu, rw, linearBufferLength);
/* Put this socket into a list of registered socket */
mRegisteredSocketList.add(registeredSocket);
}
/* update socket handle generation */
mGeneratedSocketHandle++;
return sockeHandle;
} else {
/* No socket available */
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
public int deselectSecureElement() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mSelectedSeId == 0) {
return ErrorCodes.ERROR_NO_SE_CONNECTED;
}
mManager.doDeselectSecureElement(mSelectedSeId);
mNfcSecureElementState = false;
mSelectedSeId = 0;
/* store preference */
mPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, false);
mPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, 0);
mPrefsEditor.apply();
return ErrorCodes.SUCCESS;
}
public ILlcpConnectionlessSocket getLlcpConnectionlessInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mLlcpConnectionlessSocketService;
}
public ILlcpSocket getLlcpInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mLlcpSocket;
}
public ILlcpServiceSocket getLlcpServiceInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mLlcpServerSocketService;
}
public INfcTag getNfcTagInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mNfcTagService;
}
public synchronized int getOpenTimeout() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mTimeout;
}
public IP2pInitiator getP2pInitiatorInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mP2pInitiatorService;
}
public IP2pTarget getP2pTargetInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mP2pTargetService;
}
public String getProperties(String param) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
if (param == null) {
return null;
}
if (param.equals(PROPERTY_LLCP_LTO_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_LTO, LLCP_LTO_DEFAULT));
} else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_MIU, LLCP_MIU_DEFAULT));
} else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_WKS, LLCP_WKS_DEFAULT));
} else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_OPT, LLCP_OPT_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_A, DISCOVERY_A_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_B, DISCOVERY_B_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_F, DISCOVERY_F_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_NFCIP, DISCOVERY_NFCIP_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_15693, DISCOVERY_15693_DEFAULT));
} else {
return "Unknown property";
}
}
public int[] getSecureElementList() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
int[] list = null;
if (mIsNfcEnabled == true) {
list = mManager.doGetSecureElementList();
}
return list;
}
public int getSelectedSecureElement() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
return mSelectedSeId;
}
public boolean isEnabled() throws RemoteException {
return mIsNfcEnabled;
}
public void openTagConnection(Tag tag) throws RemoteException {
// TODO: Remove obsolete code
}
public int selectSecureElement(int seId) throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mSelectedSeId == seId) {
return ErrorCodes.ERROR_SE_ALREADY_SELECTED;
}
if (mSelectedSeId != 0) {
return ErrorCodes.ERROR_SE_CONNECTED;
}
mSelectedSeId = seId;
mManager.doSelectSecureElement(mSelectedSeId);
/* store */
mPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, true);
mPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, mSelectedSeId);
mPrefsEditor.apply();
mNfcSecureElementState = true;
return ErrorCodes.SUCCESS;
}
public synchronized void setOpenTimeout(int timeout) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
mTimeout = timeout;
}
public int setProperties(String param, String value) throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
if (isEnabled()) {
return ErrorCodes.ERROR_NFC_ON;
}
int val;
/* Check params validity */
if (param == null || value == null) {
return ErrorCodes.ERROR_INVALID_PARAM;
}
if (param.equals(PROPERTY_LLCP_LTO_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if (val > LLCP_LTO_MAX)
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_LTO, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_LTO, val);
} else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if ((val < LLCP_MIU_DEFAULT) || (val > LLCP_MIU_MAX))
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_MIU, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_MIU, val);
} else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if (val > LLCP_WKS_MAX)
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_WKS, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_WKS, val);
} else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if (val > LLCP_OPT_MAX)
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_OPT, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_OPT, val);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_A, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_B, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_F, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_15693, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_NFCIP, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP, b ? 1 : 0);
} else {
return ErrorCodes.ERROR_INVALID_PARAM;
}
return ErrorCodes.SUCCESS;
}
@Override
public NdefMessage localGet() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
synchronized (this) {
return mLocalMessage;
}
}
@Override
public void localSet(NdefMessage message) throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
synchronized (this) {
mLocalMessage = message;
// Send a message to the UI thread to show or hide the icon so the requests are
// serialized and the icon can't get out of sync with reality.
if (message != null) {
sendMessage(MSG_SHOW_MY_TAG_ICON, null);
} else {
sendMessage(MSG_HIDE_MY_TAG_ICON, null);
}
}
}
};
private final ILlcpSocket mLlcpSocket = new ILlcpSocket.Stub() {
private final int CONNECT_FLAG = 0x01;
private final int CLOSE_FLAG = 0x02;
private final int RECV_FLAG = 0x04;
private final int SEND_FLAG = 0x08;
private int concurrencyFlags;
private Object sync;
public int close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
isSuccess = socket.doClose();
if (isSuccess) {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Remove registered socket from the list */
RemoveRegisteredSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
return ErrorCodes.SUCCESS;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
public int connect(int nativeHandle, int sap) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doConnect(sap, socket.getConnectTimeout());
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
public int connectByName(int nativeHandle, String sn) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doConnectBy(sn, socket.getConnectTimeout());
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
public int getConnectTimeout(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getConnectTimeout();
} else {
return 0;
}
}
public int getLocalSap(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getSap();
} else {
return 0;
}
}
public int getLocalSocketMiu(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getMiu();
} else {
return 0;
}
}
public int getLocalSocketRw(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getRw();
} else {
return 0;
}
}
public int getRemoteSocketMiu(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
if (socket.doGetRemoteSocketMiu() != 0) {
return socket.doGetRemoteSocketMiu();
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
}
public int getRemoteSocketRw(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
if (socket.doGetRemoteSocketRw() != 0) {
return socket.doGetRemoteSocketRw();
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
}
public int receive(int nativeHandle, byte[] receiveBuffer) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
int receiveLength = 0;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
receiveLength = socket.doReceive(receiveBuffer);
if (receiveLength != 0) {
return receiveLength;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
public int send(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doSend(data);
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
public void setConnectTimeout(int nativeHandle, int timeout) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
socket.setConnectTimeout(timeout);
}
}
};
private final ILlcpServiceSocket mLlcpServerSocketService = new ILlcpServiceSocket.Stub() {
public int accept(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpServiceSocket socket = null;
NativeLlcpSocket clientSocket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
/* find the socket in the hmap */
socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
if (socket != null) {
clientSocket = socket.doAccept(socket.getAcceptTimeout(), socket.getMiu(),
socket.getRw(), socket.getLinearBufferLength());
if (clientSocket != null) {
/* Add the socket into the socket map */
synchronized(this) {
mSocketMap.put(clientSocket.getHandle(), clientSocket);
mNbSocketCreated++;
}
return clientSocket.getHandle();
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
public void close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpServiceSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return;
}
/* find the socket in the hmap */
socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
if (socket != null) {
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
isSuccess = socket.doClose();
if (isSuccess) {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
}
} else {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Remove registered socket from the list */
RemoveRegisteredSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
}
}
}
public int getAcceptTimeout(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpServiceSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getAcceptTimeout();
} else {
return 0;
}
}
public void setAcceptTimeout(int nativeHandle, int timeout) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpServiceSocket socket = null;
/* find the socket in the hmap */
socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
if (socket != null) {
socket.setAcceptTimeout(timeout);
}
}
};
private final ILlcpConnectionlessSocket mLlcpConnectionlessSocketService = new ILlcpConnectionlessSocket.Stub() {
public void close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
isSuccess = socket.doClose();
if (isSuccess) {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
}
} else {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Remove registered socket from the list */
RemoveRegisteredSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
}
}
}
public int getSap(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getSap();
} else {
return 0;
}
}
public LlcpPacket receiveFrom(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
LlcpPacket packet;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
packet = socket.doReceiveFrom(socket.getLinkMiu());
if (packet != null) {
return packet;
}
return null;
} else {
return null;
}
}
public int sendTo(int nativeHandle, LlcpPacket packet) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doSendTo(packet.getRemoteSap(), packet.getDataBuffer());
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
};
private final INfcTag mNfcTagService = new INfcTag.Stub() {
public int close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
/* Remove the device from the hmap */
unregisterObject(nativeHandle);
tag.asyncDisconnect();
return ErrorCodes.SUCCESS;
}
/* Restart polling loop for notification */
maybeEnableDiscovery();
mOpenPending = false;
return ErrorCodes.ERROR_DISCONNECT;
}
public int connect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_DISCONNECT;
}
// TODO: register the tag as being locked rather than really connect
return ErrorCodes.SUCCESS;
}
public String getType(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
String type;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
type = tag.getType();
return type;
}
return null;
}
public byte[] getUid(int nativeHandle) throws RemoteException {
NativeNfcTag tag = null;
byte[] uid;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
uid = tag.getUid();
return uid;
}
return null;
}
public boolean isPresent(int nativeHandle) throws RemoteException {
NativeNfcTag tag = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return false;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag == null) {
return false;
}
return tag.presenceCheck();
}
public boolean isNdef(int nativeHandle) throws RemoteException {
NativeNfcTag tag = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return isSuccess;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
isSuccess = tag.checkNdef();
}
return isSuccess;
}
public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
byte[] response;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
response = tag.transceive(data);
return response;
}
return null;
}
public NdefMessage read(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
byte[] buf = tag.read();
if (buf == null)
return null;
/* Create an NdefMessage */
try {
return new NdefMessage(buf);
} catch (FormatException e) {
return null;
}
}
return null;
}
public int write(int nativeHandle, NdefMessage msg) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_IO;
}
if (tag.write(msg.toByteArray())) {
return ErrorCodes.SUCCESS;
}
else {
return ErrorCodes.ERROR_IO;
}
}
public int getLastError(int nativeHandle) throws RemoteException {
// TODO Auto-generated method stub
return 0;
}
public int getModeHint(int nativeHandle) throws RemoteException {
// TODO Auto-generated method stub
return 0;
}
public int makeReadOnly(int nativeHandle) throws RemoteException {
// TODO Auto-generated method stub
return 0;
}
};
private final IP2pInitiator mP2pInitiatorService = new IP2pInitiator.Stub() {
public byte[] getGeneralBytes(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.getGeneralBytes();
if (buff == null)
return null;
return buff;
}
return null;
}
public int getMode(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
return device.getMode();
}
return ErrorCodes.ERROR_INVALID_PARAM;
}
public byte[] receive(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.doReceive();
if (buff == null)
return null;
return buff;
}
/* Restart polling loop for notification */
maybeEnableDiscovery();
mOpenPending = false;
return null;
}
public boolean send(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return isSuccess;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
isSuccess = device.doSend(data);
}
return isSuccess;
}
};
private final IP2pTarget mP2pTargetService = new IP2pTarget.Stub() {
public int connect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
if (device.doConnect()) {
return ErrorCodes.SUCCESS;
}
}
return ErrorCodes.ERROR_CONNECT;
}
public boolean disconnect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return isSuccess;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
if (isSuccess = device.doDisconnect()) {
mOpenPending = false;
/* remove the device from the hmap */
unregisterObject(nativeHandle);
/* Restart polling loop for notification */
maybeEnableDiscovery();
}
}
return isSuccess;
}
public byte[] getGeneralBytes(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.getGeneralBytes();
if (buff == null)
return null;
return buff;
}
return null;
}
public int getMode(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
return device.getMode();
}
return ErrorCodes.ERROR_INVALID_PARAM;
}
public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.doTransceive(data);
if (buff == null)
return null;
return buff;
}
return null;
}
};
private boolean _enable(boolean oldEnabledState) {
boolean isSuccess = mManager.initialize();
if (isSuccess) {
applyProperties();
/* Check Secure Element setting */
mNfcSecureElementState = mPrefs.getBoolean(PREF_SECURE_ELEMENT_ON,
SECURE_ELEMENT_ON_DEFAULT);
if (mNfcSecureElementState) {
int secureElementId = mPrefs.getInt(PREF_SECURE_ELEMENT_ID,
SECURE_ELEMENT_ID_DEFAULT);
int[] Se_list = mManager.doGetSecureElementList();
if (Se_list != null) {
for (int i = 0; i < Se_list.length; i++) {
if (Se_list[i] == secureElementId) {
mManager.doSelectSecureElement(Se_list[i]);
mSelectedSeId = Se_list[i];
break;
}
}
}
}
mIsNfcEnabled = true;
/* Start polling loop */
maybeEnableDiscovery();
} else {
mIsNfcEnabled = false;
}
updateNfcOnSetting(oldEnabledState);
return isSuccess;
}
/** Enable active tag discovery if screen is on and NFC is enabled */
private synchronized void maybeEnableDiscovery() {
if (mScreenOn && mIsNfcEnabled) {
mManager.enableDiscovery(DISCOVERY_MODE_READER);
// mMyTagServer.start();
}
}
/** Disable active tag discovery if necessary */
private synchronized void maybeDisableDiscovery() {
if (mIsNfcEnabled) {
mManager.disableDiscovery();
// mMyTagServer.stop();
}
}
private void applyProperties() {
mManager.doSetProperties(PROPERTY_LLCP_LTO, mPrefs.getInt(PREF_LLCP_LTO, LLCP_LTO_DEFAULT));
mManager.doSetProperties(PROPERTY_LLCP_MIU, mPrefs.getInt(PREF_LLCP_MIU, LLCP_MIU_DEFAULT));
mManager.doSetProperties(PROPERTY_LLCP_WKS, mPrefs.getInt(PREF_LLCP_WKS, LLCP_WKS_DEFAULT));
mManager.doSetProperties(PROPERTY_LLCP_OPT, mPrefs.getInt(PREF_LLCP_OPT, LLCP_OPT_DEFAULT));
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A,
mPrefs.getBoolean(PREF_DISCOVERY_A, DISCOVERY_A_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B,
mPrefs.getBoolean(PREF_DISCOVERY_B, DISCOVERY_B_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F,
mPrefs.getBoolean(PREF_DISCOVERY_F, DISCOVERY_F_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693,
mPrefs.getBoolean(PREF_DISCOVERY_15693, DISCOVERY_15693_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP,
mPrefs.getBoolean(PREF_DISCOVERY_NFCIP, DISCOVERY_NFCIP_DEFAULT) ? 1 : 0);
}
private void updateNfcOnSetting(boolean oldEnabledState) {
int state;
mPrefsEditor.putBoolean(PREF_NFC_ON, mIsNfcEnabled);
mPrefsEditor.apply();
synchronized(this) {
if (mBootComplete && oldEnabledState != mIsNfcEnabled) {
Intent intent = new Intent(NfcAdapter.ACTION_ADAPTER_STATE_CHANGE);
intent.putExtra(NfcAdapter.EXTRA_NEW_BOOLEAN_STATE, mIsNfcEnabled);
mContext.sendBroadcast(intent);
}
}
}
// Reset all internals
private synchronized void reset() {
// TODO: none of these appear to be synchronized but are
// read/written from different threads (notably Binder threads)...
// Clear tables
mObjectMap.clear();
mSocketMap.clear();
mRegisteredSocketList.clear();
// Reset variables
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
mNbSocketCreated = 0;
mIsNfcEnabled = false;
mSelectedSeId = 0;
mTimeout = 0;
mOpenPending = false;
}
private synchronized Object findObject(int key) {
Object device = null;
device = mObjectMap.get(key);
if (device == null) {
Log.w(TAG, "Handle not found !");
}
return device;
}
synchronized void registerTagObject(NativeNfcTag nativeTag) {
mObjectMap.put(nativeTag.getHandle(), nativeTag);
}
synchronized void unregisterObject(int handle) {
mObjectMap.remove(handle);
}
private synchronized Object findSocket(int key) {
Object socket = null;
socket = mSocketMap.get(key);
return socket;
}
private void RemoveSocket(int key) {
mSocketMap.remove(key);
}
private boolean CheckSocketSap(int sap) {
/* List of sockets registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
if (sap == registeredSocket.mSap) {
/* SAP already used */
return false;
}
}
return true;
}
private boolean CheckSocketOptions(int miu, int rw, int linearBufferlength) {
if (rw > LLCP_RW_MAX_VALUE || miu < LLCP_MIU_DEFAULT || linearBufferlength < miu) {
return false;
}
return true;
}
private boolean CheckSocketServiceName(String sn) {
/* List of sockets registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
if (sn.equals(registeredSocket.mServiceName)) {
/* Service Name already used */
return false;
}
}
return true;
}
private void RemoveRegisteredSocket(int nativeHandle) {
/* check if sockets are registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
if (registeredSocket.mHandle == nativeHandle) {
/* remove the registered socket from the list */
it.remove();
Log.d(TAG, "socket removed");
}
}
}
/*
* RegisteredSocket class to store the creation request of socket until the
* LLCP link in not activated
*/
private class RegisteredSocket {
private final int mType;
private final int mHandle;
private final int mSap;
private int mMiu;
private int mRw;
private String mServiceName;
private int mlinearBufferLength;
RegisteredSocket(int type, int handle, int sap, String sn, int miu, int rw,
int linearBufferLength) {
mType = type;
mHandle = handle;
mSap = sap;
mServiceName = sn;
mRw = rw;
mMiu = miu;
mlinearBufferLength = linearBufferLength;
}
RegisteredSocket(int type, int handle, int sap, int miu, int rw, int linearBufferLength) {
mType = type;
mHandle = handle;
mSap = sap;
mRw = rw;
mMiu = miu;
mlinearBufferLength = linearBufferLength;
}
RegisteredSocket(int type, int handle, int sap) {
mType = type;
mHandle = handle;
mSap = sap;
}
}
/** For use by code in this process */
public LlcpSocket createLlcpSocket(int sap, int miu, int rw, int linearBufferLength) {
try {
int handle = mNfcAdapter.createLlcpSocket(sap, miu, rw, linearBufferLength);
return new LlcpSocket(mLlcpSocket, handle);
} catch (RemoteException e) {
// This will never happen since the code is calling into it's own process
throw new IllegalStateException("unable to talk to myself", e);
}
}
/** For use by code in this process */
public LlcpServiceSocket createLlcpServiceSocket(int sap, String sn, int miu, int rw,
int linearBufferLength) {
try {
int handle = mNfcAdapter.createLlcpServiceSocket(sap, sn, miu, rw, linearBufferLength);
return new LlcpServiceSocket(mLlcpServerSocketService, mLlcpSocket, handle);
} catch (RemoteException e) {
// This will never happen since the code is calling into it's own process
throw new IllegalStateException("unable to talk to myself", e);
}
}
private void activateLlcpLink() {
/* check if sockets are registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
Log.d(TAG, "Nb socket resgistered = " + mRegisteredSocketList.size());
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
switch (registeredSocket.mType) {
case LLCP_SERVICE_SOCKET_TYPE:
Log.d(TAG, "Registered Llcp Service Socket");
NativeLlcpServiceSocket serviceSocket;
serviceSocket = mManager.doCreateLlcpServiceSocket(
registeredSocket.mSap, registeredSocket.mServiceName,
registeredSocket.mMiu, registeredSocket.mRw,
registeredSocket.mlinearBufferLength);
if (serviceSocket != null) {
/* Add the socket into the socket map */
synchronized(NfcService.this) {
mSocketMap.put(registeredSocket.mHandle, serviceSocket);
}
} else {
/* socket creation error - update the socket
* handle counter */
mGeneratedSocketHandle -= 1;
}
break;
case LLCP_SOCKET_TYPE:
Log.d(TAG, "Registered Llcp Socket");
NativeLlcpSocket clientSocket;
clientSocket = mManager.doCreateLlcpSocket(registeredSocket.mSap,
registeredSocket.mMiu, registeredSocket.mRw,
registeredSocket.mlinearBufferLength);
if (clientSocket != null) {
/* Add the socket into the socket map */
synchronized(NfcService.this) {
mSocketMap.put(registeredSocket.mHandle, clientSocket);
}
} else {
/* socket creation error - update the socket
* handle counter */
mGeneratedSocketHandle -= 1;
}
break;
case LLCP_CONNECTIONLESS_SOCKET_TYPE:
Log.d(TAG, "Registered Llcp Connectionless Socket");
NativeLlcpConnectionlessSocket connectionlessSocket;
connectionlessSocket = mManager.doCreateLlcpConnectionlessSocket(
registeredSocket.mSap);
if (connectionlessSocket != null) {
/* Add the socket into the socket map */
synchronized(NfcService.this) {
mSocketMap.put(registeredSocket.mHandle, connectionlessSocket);
}
} else {
/* socket creation error - update the socket
* handle counter */
mGeneratedSocketHandle -= 1;
}
break;
}
}
/* Remove all registered socket from the list */
mRegisteredSocketList.clear();
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_ACTIVATED);
Log.d(TAG, "Broadcasting LLCP activation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
}
public void sendMockNdefTag(NdefMessage msg) {
NdefTag tag = NdefTag.createMockNdefTag(new byte[] { 0x00 },
new String[] { Tag.TARGET_OTHER },
null, null, new String[] { NdefTag.TARGET_OTHER },
new NdefMessage[][] { new NdefMessage[] { msg } });
sendMessage(MSG_MOCK_NDEF_TAG, tag);
}
void sendMessage(int what, Object obj) {
Message msg = mHandler.obtainMessage();
msg.what = what;
msg.obj = obj;
mHandler.sendMessage(msg);
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF_TAG: {
NdefTag tag = (NdefTag) msg.obj;
Intent intent = buildNdefTagIntent(tag);
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for mock tag");
}
}
case MSG_NDEF_TAG:
Log.d(TAG, "Tag detected, notifying applications");
NativeNfcTag nativeTag = (NativeNfcTag) msg.obj;
if (nativeTag.connect()) {
if (nativeTag.checkNdef()) {
byte[] buff = nativeTag.read();
if (buff != null) {
NdefMessage[] msgNdef = new NdefMessage[1];
try {
msgNdef[0] = new NdefMessage(buff);
NdefTag tag = new NdefTag(nativeTag.getUid(),
TagTarget.internalTypeToRawTargets(nativeTag.getType()),
null, null, nativeTag.getHandle(),
TagTarget.internalTypeToNdefTargets(nativeTag.getType()),
new NdefMessage[][] {msgNdef});
Intent intent = buildNdefTagIntent(tag);
Log.d(TAG, "NDEF tag found, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
+ registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.asyncDisconnect();
}
} catch (FormatException e) {
Log.w(TAG, "Unable to create NDEF message object (tag empty or not well formated)");
nativeTag.asyncDisconnect();
}
} else {
Log.w(TAG, "Unable to read NDEF message (tag empty or not well formated)");
nativeTag.asyncDisconnect();
}
} else {
Intent intent = new Intent();
Tag tag = new Tag(nativeTag.getUid(), false,
TagTarget.internalTypeToRawTargets(nativeTag.getType()),
null, null, nativeTag.getHandle());
intent.setAction(NfcAdapter.ACTION_TAG_DISCOVERED);
intent.putExtra(NfcAdapter.EXTRA_TAG, tag);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d(TAG, "Non-NDEF tag found, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
+ registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.asyncDisconnect();
}
}
} else {
Log.w(TAG, "Failed to connect to tag");
nativeTag.asyncDisconnect();
}
break;
case MSG_CARD_EMULATION:
Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast ordered */
Intent TransactionIntent = new Intent();
TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED);
TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid);
Log.d(TAG, "Broadcasting Card Emulation event");
mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM);
break;
case MSG_LLCP_LINK_ACTIVATION:
NativeP2pDevice device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (device.doConnect()) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
Log.d(TAG, "Initiator Activate LLCP OK");
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent
.setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION);
LlcpLinkIntent.putExtra(
mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA,
NfcAdapter.LLCP_LINK_STATE_ACTIVATED);
Log.d(TAG, "Broadcasting internal LLCP activation");
mContext.sendBroadcast(LlcpLinkIntent);
}
} else {
device.doDisconnect();
}
}
} else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
Log.d(TAG, "Target Activate LLCP OK");
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent
.setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION);
LlcpLinkIntent.putExtra(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA,
NfcAdapter.LLCP_LINK_STATE_ACTIVATED);
Log.d(TAG, "Broadcasting internal LLCP activation");
mContext.sendBroadcast(LlcpLinkIntent);
}
}
}
break;
case MSG_LLCP_LINK_DEACTIVATED:
/* Broadcast Intent Link LLCP activated */
Log.d(TAG, "LLCP Link Deactivated message");
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
Log.d(TAG, "Broadcasting LLCP deactivation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
Log.d(TAG, "Target Deselected");
Intent TargetDeselectedIntent = new Intent();
TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION);
Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM);
break;
case MSG_SHOW_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0);
break;
}
case MSG_HIDE_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.removeIcon("nfc");
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
private Intent buildNdefTagIntent(NdefTag tag) {
Intent intent = new Intent();
intent.setAction(NfcAdapter.ACTION_NDEF_TAG_DISCOVERED);
intent.putExtra(NfcAdapter.EXTRA_TAG, tag);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
};
private class EnableDisableDiscoveryTask extends AsyncTask<Boolean, Void, Void> {
protected Void doInBackground(Boolean... enable) {
if (enable != null && enable.length > 0 && enable[0]) {
maybeEnableDiscovery();
} else {
maybeDisableDiscovery();
}
return null;
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED)) {
Log.d(TAG, "LLCP_LINK_STATE_CHANGED");
mLlcpLinkState = intent.getIntExtra(
NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_DEACTIVATED) {
/* restart polling loop */
maybeEnableDiscovery();
} else if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
activateLlcpLink();
}
} else if (intent.getAction().equals(
NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION)) {
Log.d(TAG, "INERNAL_TARGET_DESELECTED_ACTION");
mOpenPending = false;
/* Restart polling loop for notification */
maybeEnableDiscovery();
} else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.i(TAG, "Boot complete");
synchronized(this) {
mBootComplete = true;
// now its safe to send the NFC state
Intent sendIntent = new Intent(NfcAdapter.ACTION_ADAPTER_STATE_CHANGE);
sendIntent.putExtra(NfcAdapter.EXTRA_NEW_BOOLEAN_STATE, mIsNfcEnabled);
mContext.sendBroadcast(sendIntent);
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
synchronized (NfcService.this) {
mScreenOn = true;
}
// Perform discovery enable in thread to protect against ANR when the
// NFC stack wedges. This is *not* the correct way to fix this issue -
// configuration of the local NFC adapter should be very quick and should
// be safe on the main thread, and the NFC stack should not wedge.
new EnableDisableDiscoveryTask().execute(new Boolean(true));
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
synchronized (NfcService.this) {
mScreenOn = false;
}
// Perform discovery disable in thread to protect against ANR when the
// NFC stack wedges. This is *not* the correct way to fix this issue -
// configuration of the local NFC adapter should be very quick and should
// be safe on the main thread, and the NFC stack should not wedge.
new EnableDisableDiscoveryTask().execute(new Boolean(false));
}
}
};
}
| false | true | public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF_TAG: {
NdefTag tag = (NdefTag) msg.obj;
Intent intent = buildNdefTagIntent(tag);
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for mock tag");
}
}
case MSG_NDEF_TAG:
Log.d(TAG, "Tag detected, notifying applications");
NativeNfcTag nativeTag = (NativeNfcTag) msg.obj;
if (nativeTag.connect()) {
if (nativeTag.checkNdef()) {
byte[] buff = nativeTag.read();
if (buff != null) {
NdefMessage[] msgNdef = new NdefMessage[1];
try {
msgNdef[0] = new NdefMessage(buff);
NdefTag tag = new NdefTag(nativeTag.getUid(),
TagTarget.internalTypeToRawTargets(nativeTag.getType()),
null, null, nativeTag.getHandle(),
TagTarget.internalTypeToNdefTargets(nativeTag.getType()),
new NdefMessage[][] {msgNdef});
Intent intent = buildNdefTagIntent(tag);
Log.d(TAG, "NDEF tag found, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.asyncDisconnect();
}
} catch (FormatException e) {
Log.w(TAG, "Unable to create NDEF message object (tag empty or not well formated)");
nativeTag.asyncDisconnect();
}
} else {
Log.w(TAG, "Unable to read NDEF message (tag empty or not well formated)");
nativeTag.asyncDisconnect();
}
} else {
Intent intent = new Intent();
Tag tag = new Tag(nativeTag.getUid(), false,
TagTarget.internalTypeToRawTargets(nativeTag.getType()),
null, null, nativeTag.getHandle());
intent.setAction(NfcAdapter.ACTION_TAG_DISCOVERED);
intent.putExtra(NfcAdapter.EXTRA_TAG, tag);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d(TAG, "Non-NDEF tag found, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.asyncDisconnect();
}
}
} else {
Log.w(TAG, "Failed to connect to tag");
nativeTag.asyncDisconnect();
}
break;
case MSG_CARD_EMULATION:
Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast ordered */
Intent TransactionIntent = new Intent();
TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED);
TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid);
Log.d(TAG, "Broadcasting Card Emulation event");
mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM);
break;
case MSG_LLCP_LINK_ACTIVATION:
NativeP2pDevice device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (device.doConnect()) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
Log.d(TAG, "Initiator Activate LLCP OK");
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent
.setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION);
LlcpLinkIntent.putExtra(
mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA,
NfcAdapter.LLCP_LINK_STATE_ACTIVATED);
Log.d(TAG, "Broadcasting internal LLCP activation");
mContext.sendBroadcast(LlcpLinkIntent);
}
} else {
device.doDisconnect();
}
}
} else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
Log.d(TAG, "Target Activate LLCP OK");
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent
.setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION);
LlcpLinkIntent.putExtra(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA,
NfcAdapter.LLCP_LINK_STATE_ACTIVATED);
Log.d(TAG, "Broadcasting internal LLCP activation");
mContext.sendBroadcast(LlcpLinkIntent);
}
}
}
break;
case MSG_LLCP_LINK_DEACTIVATED:
/* Broadcast Intent Link LLCP activated */
Log.d(TAG, "LLCP Link Deactivated message");
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
Log.d(TAG, "Broadcasting LLCP deactivation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
Log.d(TAG, "Target Deselected");
Intent TargetDeselectedIntent = new Intent();
TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION);
Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM);
break;
case MSG_SHOW_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0);
break;
}
case MSG_HIDE_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.removeIcon("nfc");
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
| public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF_TAG: {
NdefTag tag = (NdefTag) msg.obj;
Intent intent = buildNdefTagIntent(tag);
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for mock tag");
}
}
case MSG_NDEF_TAG:
Log.d(TAG, "Tag detected, notifying applications");
NativeNfcTag nativeTag = (NativeNfcTag) msg.obj;
if (nativeTag.connect()) {
if (nativeTag.checkNdef()) {
byte[] buff = nativeTag.read();
if (buff != null) {
NdefMessage[] msgNdef = new NdefMessage[1];
try {
msgNdef[0] = new NdefMessage(buff);
NdefTag tag = new NdefTag(nativeTag.getUid(),
TagTarget.internalTypeToRawTargets(nativeTag.getType()),
null, null, nativeTag.getHandle(),
TagTarget.internalTypeToNdefTargets(nativeTag.getType()),
new NdefMessage[][] {msgNdef});
Intent intent = buildNdefTagIntent(tag);
Log.d(TAG, "NDEF tag found, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.asyncDisconnect();
}
} catch (FormatException e) {
Log.w(TAG, "Unable to create NDEF message object (tag empty or not well formated)");
nativeTag.asyncDisconnect();
}
} else {
Log.w(TAG, "Unable to read NDEF message (tag empty or not well formated)");
nativeTag.asyncDisconnect();
}
} else {
Intent intent = new Intent();
Tag tag = new Tag(nativeTag.getUid(), false,
TagTarget.internalTypeToRawTargets(nativeTag.getType()),
null, null, nativeTag.getHandle());
intent.setAction(NfcAdapter.ACTION_TAG_DISCOVERED);
intent.putExtra(NfcAdapter.EXTRA_TAG, tag);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d(TAG, "Non-NDEF tag found, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.asyncDisconnect();
}
}
} else {
Log.w(TAG, "Failed to connect to tag");
nativeTag.asyncDisconnect();
}
break;
case MSG_CARD_EMULATION:
Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast ordered */
Intent TransactionIntent = new Intent();
TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED);
TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid);
Log.d(TAG, "Broadcasting Card Emulation event");
mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM);
break;
case MSG_LLCP_LINK_ACTIVATION:
NativeP2pDevice device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (device.doConnect()) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
Log.d(TAG, "Initiator Activate LLCP OK");
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent
.setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION);
LlcpLinkIntent.putExtra(
mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA,
NfcAdapter.LLCP_LINK_STATE_ACTIVATED);
Log.d(TAG, "Broadcasting internal LLCP activation");
mContext.sendBroadcast(LlcpLinkIntent);
}
} else {
device.doDisconnect();
}
}
} else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
Log.d(TAG, "Target Activate LLCP OK");
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent
.setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION);
LlcpLinkIntent.putExtra(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA,
NfcAdapter.LLCP_LINK_STATE_ACTIVATED);
Log.d(TAG, "Broadcasting internal LLCP activation");
mContext.sendBroadcast(LlcpLinkIntent);
}
}
}
break;
case MSG_LLCP_LINK_DEACTIVATED:
/* Broadcast Intent Link LLCP activated */
Log.d(TAG, "LLCP Link Deactivated message");
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
Log.d(TAG, "Broadcasting LLCP deactivation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
Log.d(TAG, "Target Deselected");
Intent TargetDeselectedIntent = new Intent();
TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION);
Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM);
break;
case MSG_SHOW_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0);
break;
}
case MSG_HIDE_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.removeIcon("nfc");
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
|
diff --git a/src/com/android/gallery3d/filtershow/filters/ImageFilterRS.java b/src/com/android/gallery3d/filtershow/filters/ImageFilterRS.java
index 56e848aa7..cff071142 100644
--- a/src/com/android/gallery3d/filtershow/filters/ImageFilterRS.java
+++ b/src/com/android/gallery3d/filtershow/filters/ImageFilterRS.java
@@ -1,203 +1,200 @@
/*
* 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.gallery3d.filtershow.filters;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v8.renderscript.*;
import android.util.Log;
import android.content.res.Resources;
import com.android.gallery3d.R;
import com.android.gallery3d.filtershow.cache.CachingPipeline;
public abstract class ImageFilterRS extends ImageFilter {
private static final String LOGTAG = "ImageFilterRS";
private boolean DEBUG = false;
private static volatile RenderScript sRS = null;
private static volatile Resources sResources = null;
private volatile boolean mResourcesLoaded = false;
// This must be used inside block synchronized on ImageFilterRS class object
protected abstract void createFilter(android.content.res.Resources res,
float scaleFactor, int quality);
// This must be used inside block synchronized on ImageFilterRS class object
protected abstract void runFilter();
// This must be used inside block synchronized on ImageFilterRS class object
protected void update(Bitmap bitmap) {
getOutPixelsAllocation().copyTo(bitmap);
}
protected Allocation getInPixelsAllocation() {
CachingPipeline pipeline = getEnvironment().getCachingPipeline();
return pipeline.getInPixelsAllocation();
}
protected Allocation getOutPixelsAllocation() {
CachingPipeline pipeline = getEnvironment().getCachingPipeline();
return pipeline.getOutPixelsAllocation();
}
@Override
public Bitmap apply(Bitmap bitmap, float scaleFactor, int quality) {
if (bitmap == null || bitmap.getWidth() == 0 || bitmap.getHeight() == 0) {
return bitmap;
}
try {
synchronized(ImageFilterRS.class) {
if (sRS == null) {
Log.w(LOGTAG, "Cannot apply before calling createRenderScriptContext");
return bitmap;
}
CachingPipeline pipeline = getEnvironment().getCachingPipeline();
if (DEBUG) {
Log.v(LOGTAG, "apply filter " + getName() + " in pipeline " + pipeline.getName());
}
- boolean needsUpdate = pipeline.prepareRenderscriptAllocations(bitmap);
- if (needsUpdate || !isResourcesLoaded()) {
- // the allocations changed size
- freeResources();
- createFilter(sResources, scaleFactor, quality);
- setResourcesLoaded(true);
- }
+ pipeline.prepareRenderscriptAllocations(bitmap);
+ createFilter(sResources, scaleFactor, quality);
+ setResourcesLoaded(true);
runFilter();
update(bitmap);
+ freeResources();
if (DEBUG) {
Log.v(LOGTAG, "DONE apply filter " + getName() + " in pipeline " + pipeline.getName());
}
}
} catch (android.renderscript.RSIllegalArgumentException e) {
Log.e(LOGTAG, "Illegal argument? " + e);
} catch (android.renderscript.RSRuntimeException e) {
Log.e(LOGTAG, "RS runtime exception ? " + e);
} catch (java.lang.OutOfMemoryError e) {
// Many of the renderscript filters allocated large (>16Mb resources) in order to apply.
System.gc();
displayLowMemoryToast();
Log.e(LOGTAG, "not enough memory for filter " + getName(), e);
}
return bitmap;
}
public static synchronized RenderScript getRenderScriptContext() {
return sRS;
}
public static synchronized void createRenderscriptContext(Activity context) {
if( sRS != null) {
Log.w(LOGTAG, "A prior RS context exists when calling setRenderScriptContext");
destroyRenderScriptContext();
}
sRS = RenderScript.create(context);
sResources = context.getResources();
}
public static synchronized void destroyRenderScriptContext() {
sRS.destroy();
sRS = null;
sResources = null;
}
private static synchronized Allocation convertBitmap(Bitmap bitmap) {
return Allocation.createFromBitmap(sRS, bitmap,
Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
}
private static synchronized Allocation convertRGBAtoA(Bitmap bitmap) {
Type.Builder tb_a8 = new Type.Builder(sRS, Element.A_8(sRS));
ScriptC_grey greyConvert = new ScriptC_grey(sRS,
sRS.getApplicationContext().getResources(), R.raw.grey);
Allocation bitmapTemp = convertBitmap(bitmap);
if (bitmapTemp.getType().getElement().isCompatible(Element.A_8(sRS))) {
return bitmapTemp;
}
tb_a8.setX(bitmapTemp.getType().getX());
tb_a8.setY(bitmapTemp.getType().getY());
Allocation bitmapAlloc = Allocation.createTyped(sRS, tb_a8.create());
greyConvert.forEach_RGBAtoA(bitmapTemp, bitmapAlloc);
return bitmapAlloc;
}
public Allocation loadScaledResourceAlpha(int resource, int inSampleSize) {
Resources res = null;
synchronized(ImageFilterRS.class) {
res = sRS.getApplicationContext().getResources();
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ALPHA_8;
options.inSampleSize = inSampleSize;
Bitmap bitmap = BitmapFactory.decodeResource(
res,
resource, options);
Allocation ret = convertRGBAtoA(bitmap);
bitmap.recycle();
return ret;
}
public Allocation loadResourceAlpha(int resource) {
return loadScaledResourceAlpha(resource, 1);
}
public Allocation loadResource(int resource) {
Resources res = null;
synchronized(ImageFilterRS.class) {
res = sRS.getApplicationContext().getResources();
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeResource(
res,
resource, options);
Allocation ret = convertBitmap(bitmap);
bitmap.recycle();
return ret;
}
private boolean isResourcesLoaded() {
return mResourcesLoaded;
}
private void setResourcesLoaded(boolean resourcesLoaded) {
mResourcesLoaded = resourcesLoaded;
}
/**
* Bitmaps and RS Allocations should be cleared here
*/
abstract protected void resetAllocations();
/**
* RS Script objects (and all other RS objects) should be cleared here
*/
abstract protected void resetScripts();
public void freeResources() {
if (!isResourcesLoaded()) {
return;
}
synchronized(ImageFilterRS.class) {
resetAllocations();
setResourcesLoaded(false);
}
}
}
| false | true | public Bitmap apply(Bitmap bitmap, float scaleFactor, int quality) {
if (bitmap == null || bitmap.getWidth() == 0 || bitmap.getHeight() == 0) {
return bitmap;
}
try {
synchronized(ImageFilterRS.class) {
if (sRS == null) {
Log.w(LOGTAG, "Cannot apply before calling createRenderScriptContext");
return bitmap;
}
CachingPipeline pipeline = getEnvironment().getCachingPipeline();
if (DEBUG) {
Log.v(LOGTAG, "apply filter " + getName() + " in pipeline " + pipeline.getName());
}
boolean needsUpdate = pipeline.prepareRenderscriptAllocations(bitmap);
if (needsUpdate || !isResourcesLoaded()) {
// the allocations changed size
freeResources();
createFilter(sResources, scaleFactor, quality);
setResourcesLoaded(true);
}
runFilter();
update(bitmap);
if (DEBUG) {
Log.v(LOGTAG, "DONE apply filter " + getName() + " in pipeline " + pipeline.getName());
}
}
} catch (android.renderscript.RSIllegalArgumentException e) {
Log.e(LOGTAG, "Illegal argument? " + e);
} catch (android.renderscript.RSRuntimeException e) {
Log.e(LOGTAG, "RS runtime exception ? " + e);
} catch (java.lang.OutOfMemoryError e) {
// Many of the renderscript filters allocated large (>16Mb resources) in order to apply.
System.gc();
displayLowMemoryToast();
Log.e(LOGTAG, "not enough memory for filter " + getName(), e);
}
return bitmap;
}
| public Bitmap apply(Bitmap bitmap, float scaleFactor, int quality) {
if (bitmap == null || bitmap.getWidth() == 0 || bitmap.getHeight() == 0) {
return bitmap;
}
try {
synchronized(ImageFilterRS.class) {
if (sRS == null) {
Log.w(LOGTAG, "Cannot apply before calling createRenderScriptContext");
return bitmap;
}
CachingPipeline pipeline = getEnvironment().getCachingPipeline();
if (DEBUG) {
Log.v(LOGTAG, "apply filter " + getName() + " in pipeline " + pipeline.getName());
}
pipeline.prepareRenderscriptAllocations(bitmap);
createFilter(sResources, scaleFactor, quality);
setResourcesLoaded(true);
runFilter();
update(bitmap);
freeResources();
if (DEBUG) {
Log.v(LOGTAG, "DONE apply filter " + getName() + " in pipeline " + pipeline.getName());
}
}
} catch (android.renderscript.RSIllegalArgumentException e) {
Log.e(LOGTAG, "Illegal argument? " + e);
} catch (android.renderscript.RSRuntimeException e) {
Log.e(LOGTAG, "RS runtime exception ? " + e);
} catch (java.lang.OutOfMemoryError e) {
// Many of the renderscript filters allocated large (>16Mb resources) in order to apply.
System.gc();
displayLowMemoryToast();
Log.e(LOGTAG, "not enough memory for filter " + getName(), e);
}
return bitmap;
}
|
diff --git a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richCollapsibleSubTable/TestCollapsibleSubTableFacets.java b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richCollapsibleSubTable/TestCollapsibleSubTableFacets.java
index 3aa1079d..6e8328dd 100644
--- a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richCollapsibleSubTable/TestCollapsibleSubTableFacets.java
+++ b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/richCollapsibleSubTable/TestCollapsibleSubTableFacets.java
@@ -1,96 +1,94 @@
/*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt 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.richfaces.tests.metamer.ftest.richCollapsibleSubTable;
import static org.jboss.test.selenium.utils.URLUtils.buildUrl;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.net.URL;
import org.testng.annotations.Test;
/**
* @author <a href="mailto:[email protected]">Lukas Fryc</a>
* @version $Revision$
*/
public class TestCollapsibleSubTableFacets extends AbstractCollapsibleSubTableTest {
private static final String SAMPLE_STRING = "Abc123!@#ĚščСам";
private static final String EMPTY_STRING = "";
@Override
public URL getTestUrl() {
return buildUrl(contextPath, "faces/components/richCollapsibleSubTable/facets.xhtml");
}
@Test
public void testNoDataFacet() {
assertTrue(subtable.hasVisibleRows());
attributes.setShowData(false);
assertFalse(subtable.hasVisibleRows());
assertTrue(subtable.isNoData());
- assertEquals(selenium.getText(subtable.getNoData()), EMPTY_STRING);
facets.setNoData(SAMPLE_STRING);
attributes.setShowData(true);
assertTrue(subtable.hasVisibleRows());
attributes.setShowData(false);
assertFalse(subtable.hasVisibleRows());
assertTrue(subtable.isNoData());
- assertEquals(selenium.getText(subtable.getNoData()), SAMPLE_STRING);
}
@Test
public void testHeaderInstantChange() {
facets.setHeader(SAMPLE_STRING);
assertEquals(selenium.getText(subtable.getHeader()), SAMPLE_STRING);
facets.setHeader(EMPTY_STRING);
if (selenium.isElementPresent(subtable.getHeader())) {
assertEquals(selenium.getText(subtable.getHeader()), EMPTY_STRING);
}
facets.setHeader(SAMPLE_STRING);
assertEquals(selenium.getText(subtable.getHeader()), SAMPLE_STRING);
}
@Test
public void testFooterInstantChange() {
facets.setFooter(SAMPLE_STRING);
assertEquals(selenium.getText(subtable.getFooter()), SAMPLE_STRING);
facets.setFooter(EMPTY_STRING);
if (selenium.isElementPresent(subtable.getFooter())) {
assertEquals(selenium.getText(subtable.getFooter()), EMPTY_STRING);
}
facets.setFooter(SAMPLE_STRING);
assertEquals(selenium.getText(subtable.getFooter()), SAMPLE_STRING);
}
}
| false | true | public void testNoDataFacet() {
assertTrue(subtable.hasVisibleRows());
attributes.setShowData(false);
assertFalse(subtable.hasVisibleRows());
assertTrue(subtable.isNoData());
assertEquals(selenium.getText(subtable.getNoData()), EMPTY_STRING);
facets.setNoData(SAMPLE_STRING);
attributes.setShowData(true);
assertTrue(subtable.hasVisibleRows());
attributes.setShowData(false);
assertFalse(subtable.hasVisibleRows());
assertTrue(subtable.isNoData());
assertEquals(selenium.getText(subtable.getNoData()), SAMPLE_STRING);
}
| public void testNoDataFacet() {
assertTrue(subtable.hasVisibleRows());
attributes.setShowData(false);
assertFalse(subtable.hasVisibleRows());
assertTrue(subtable.isNoData());
facets.setNoData(SAMPLE_STRING);
attributes.setShowData(true);
assertTrue(subtable.hasVisibleRows());
attributes.setShowData(false);
assertFalse(subtable.hasVisibleRows());
assertTrue(subtable.isNoData());
}
|
diff --git a/software/examples/java/ExampleCallback.java b/software/examples/java/ExampleCallback.java
index 47b4ed8..0130920 100644
--- a/software/examples/java/ExampleCallback.java
+++ b/software/examples/java/ExampleCallback.java
@@ -1,55 +1,58 @@
import com.tinkerforge.BrickStepper;
import com.tinkerforge.IPConnection;
import java.util.Random;
public class ExampleCallback {
private static final String host = "localhost";
private static final int port = 4223;
private static final String UID = "9yEBJVAgcoj"; // Change to your UID
// Declare stepper static, so the listener can use it. In a real program you probably
// want to make a real listener class (not the anonym inner class) and pass the stepper
// reference to it. But we want to keep the examples as short es possible.
static BrickStepper stepper;
// Note: To make the example code cleaner we do not handle exceptions. Exceptions you
// might normally want to catch are described in the documentation
public static void main(String args[]) throws Exception {
IPConnection ipcon = new IPConnection(); // Create IP connection
stepper = new BrickStepper(UID, ipcon); // Create device object
ipcon.connect(host, port); // Connect to brickd
// Don't use device before ipcon is connected
// Add and implement position reached listener
// (called if position set by setSteps or setTargetPosition is reached)
stepper.addListener(new BrickStepper.PositionReachedListener() {
Random random = new Random();
public void positionReached(int position) {
int steps = 0;
if(random.nextInt(2) == 1) {
steps = random.nextInt(4001) + 1000; // steps (forward)
} else {
steps = random.nextInt(5001) - 6000; // steps (backward)
}
int vel = random.nextInt(1801) + 200; // steps/s
int acc = random.nextInt(901) + 100; // steps/s^2
int dec = random.nextInt(901) + 100; // steps/s^2
System.out.println("Configuration (vel, acc, dec): (" +
vel + ", " + acc + ", " + dec + ")");
- stepper.setSpeedRamping(acc, dec);
- stepper.setMaxVelocity(vel);
- stepper.setSteps(steps);
+ try {
+ stepper.setSpeedRamping(acc, dec);
+ stepper.setMaxVelocity(vel);
+ stepper.setSteps(steps);
+ } catch(IPConnection.TimeoutException e) {
+ }
}
});
stepper.enable();
stepper.setSteps(1); // Drive one step forward to get things going
System.console().readLine("Press key to exit\n");
}
}
| true | true | public static void main(String args[]) throws Exception {
IPConnection ipcon = new IPConnection(); // Create IP connection
stepper = new BrickStepper(UID, ipcon); // Create device object
ipcon.connect(host, port); // Connect to brickd
// Don't use device before ipcon is connected
// Add and implement position reached listener
// (called if position set by setSteps or setTargetPosition is reached)
stepper.addListener(new BrickStepper.PositionReachedListener() {
Random random = new Random();
public void positionReached(int position) {
int steps = 0;
if(random.nextInt(2) == 1) {
steps = random.nextInt(4001) + 1000; // steps (forward)
} else {
steps = random.nextInt(5001) - 6000; // steps (backward)
}
int vel = random.nextInt(1801) + 200; // steps/s
int acc = random.nextInt(901) + 100; // steps/s^2
int dec = random.nextInt(901) + 100; // steps/s^2
System.out.println("Configuration (vel, acc, dec): (" +
vel + ", " + acc + ", " + dec + ")");
stepper.setSpeedRamping(acc, dec);
stepper.setMaxVelocity(vel);
stepper.setSteps(steps);
}
});
stepper.enable();
stepper.setSteps(1); // Drive one step forward to get things going
System.console().readLine("Press key to exit\n");
}
| public static void main(String args[]) throws Exception {
IPConnection ipcon = new IPConnection(); // Create IP connection
stepper = new BrickStepper(UID, ipcon); // Create device object
ipcon.connect(host, port); // Connect to brickd
// Don't use device before ipcon is connected
// Add and implement position reached listener
// (called if position set by setSteps or setTargetPosition is reached)
stepper.addListener(new BrickStepper.PositionReachedListener() {
Random random = new Random();
public void positionReached(int position) {
int steps = 0;
if(random.nextInt(2) == 1) {
steps = random.nextInt(4001) + 1000; // steps (forward)
} else {
steps = random.nextInt(5001) - 6000; // steps (backward)
}
int vel = random.nextInt(1801) + 200; // steps/s
int acc = random.nextInt(901) + 100; // steps/s^2
int dec = random.nextInt(901) + 100; // steps/s^2
System.out.println("Configuration (vel, acc, dec): (" +
vel + ", " + acc + ", " + dec + ")");
try {
stepper.setSpeedRamping(acc, dec);
stepper.setMaxVelocity(vel);
stepper.setSteps(steps);
} catch(IPConnection.TimeoutException e) {
}
}
});
stepper.enable();
stepper.setSteps(1); // Drive one step forward to get things going
System.console().readLine("Press key to exit\n");
}
|
diff --git a/src/test/java/jscover/instrument/InstrumenterTest.java b/src/test/java/jscover/instrument/InstrumenterTest.java
index c5a3649d..b36f6f2b 100644
--- a/src/test/java/jscover/instrument/InstrumenterTest.java
+++ b/src/test/java/jscover/instrument/InstrumenterTest.java
@@ -1,453 +1,454 @@
/**
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
*/
package jscover.instrument;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Token;
import org.mozilla.javascript.ast.Assignment;
import org.mozilla.javascript.ast.AstNode;
import org.mozilla.javascript.ast.ExpressionStatement;
import org.mozilla.javascript.ast.Name;
import org.mozilla.javascript.ast.NumberLiteral;
@RunWith(JUnit4.class)
public class InstrumenterTest {
private static CompilerEnvirons compilerEnv = new CompilerEnvirons();
static {
// compilerEnv.setAllowMemberExprAsFunctionName(true);
compilerEnv.setLanguageVersion(Context.VERSION_1_8);
compilerEnv.setStrictMode(false);
}
private SourceProcessor instrumenter = new SourceProcessor(compilerEnv, "test.js", null, false);
@Test
public void shouldPatchRhinoBug684131() {
assertEquals("^=", AstNode.operatorToString(92));
}
@Test
public void shouldPatchRhinoBugVoid() {
assertEquals("void", AstNode.operatorToString(126));
}
@Test
public void shouldBuildSimpleStatement() {
Name left = new Name(0,"x");
NumberLiteral right = new NumberLiteral(0,"50");
Assignment assignment = new Assignment(left, right);
assignment.setOperator(Token.ASSIGN);
ExpressionStatement newChild = new ExpressionStatement(assignment);
String expectedSource = "x = 50;\n";
assertEquals(expectedSource, newChild.toSource());
}
@Test
public void shouldInstrumentStatements() {
String source = "var x,y;\nx = 1;\ny = x * 1;";
String instrumentedSource = instrumenter.instrumentSource(source);
String expectedSource = "_$jscoverage['test.js'][1]++;\nvar x, y;\n_$jscoverage['test.js'][2]++;\nx = 1;\n_$jscoverage['test.js'][3]++;\ny = x * 1;\n";
assertEquals(expectedSource, instrumentedSource);
}
@Test
public void shouldInstrumentStatementFunctionAssignment() {
String source = "this.someFn()\n ._renderItem = function() {};";
String instrumentedSource = instrumenter.instrumentSource(source);
String expectedSource = "_$jscoverage['test.js'][1]++;\nthis.someFn()._renderItem = function() {\n};\n";
assertEquals(expectedSource, instrumentedSource);
}
@Test
public void shouldInstrumentFunctionDeclarationAndAssignment() {
- String source = "var x, fn = function() {\n" +
+ String source = "var x,\n" +
+ " fn = function() {\n" +
" ;\n" +
" };";
String instrumentedSource = instrumenter.instrumentSource(source);
String expectedSource = "_$jscoverage['test.js'][1]++;\n" +
"var x, fn = function() {\n" +
- " _$jscoverage['test.js'][2]++;\n" +
+ " _$jscoverage['test.js'][3]++;\n" +
" ;\n" +
"};\n";
assertEquals(expectedSource, instrumentedSource);
}
@Test
public void shouldInstrumentIfWithBraces() {
String source = "if (x > 10)\n{\n x++;\n}";
String instrumentedSource = instrumenter.instrumentSource(source);
String expectedSource = "_$jscoverage['test.js'][1]++;\nif (x > 10) {\n _$jscoverage['test.js'][3]++;\n x++;\n}\n";
assertEquals(expectedSource, instrumentedSource);
}
@Test
public void shouldInstrumentIfWithoutBraces() {
String source = "if (x > 10)\n x++;";
String instrumentedSource = instrumenter.instrumentSource(source);
String expectedSource = "_$jscoverage['test.js'][1]++;\nif (x > 10) {\n _$jscoverage['test.js'][2]++;\n x++;\n}\n";
assertEquals(expectedSource, instrumentedSource);
}
@Test
public void shouldInstrumentElseWithBraces() {
String source = "if (x > 10)\n{\n x++;\n} else {\n x--;\n}";
String instrumentedSource = instrumenter.instrumentSource(source);
String expectedSource = "_$jscoverage['test.js'][1]++;\nif (x > 10) {\n _$jscoverage['test.js'][3]++;\n x++;\n} else {\n _$jscoverage['test.js'][5]++;\n x--;\n}\n";
assertEquals(expectedSource, instrumentedSource);
}
@Test
public void shouldNotInstrumentSameLineTwice() {
String source = "var x,y;\nx = 1;y = x * 1;";
String instrumentedSource = instrumenter.instrumentSource(source);
String expectedSource = "_$jscoverage['test.js'][1]++;\nvar x, y;\n_$jscoverage['test.js'][2]++;\nx = 1;\ny = x * 1;\n";
assertEquals(expectedSource, instrumentedSource);
}
}
| false | true | public void shouldInstrumentFunctionDeclarationAndAssignment() {
String source = "var x, fn = function() {\n" +
" ;\n" +
" };";
String instrumentedSource = instrumenter.instrumentSource(source);
String expectedSource = "_$jscoverage['test.js'][1]++;\n" +
"var x, fn = function() {\n" +
" _$jscoverage['test.js'][2]++;\n" +
" ;\n" +
"};\n";
assertEquals(expectedSource, instrumentedSource);
}
| public void shouldInstrumentFunctionDeclarationAndAssignment() {
String source = "var x,\n" +
" fn = function() {\n" +
" ;\n" +
" };";
String instrumentedSource = instrumenter.instrumentSource(source);
String expectedSource = "_$jscoverage['test.js'][1]++;\n" +
"var x, fn = function() {\n" +
" _$jscoverage['test.js'][3]++;\n" +
" ;\n" +
"};\n";
assertEquals(expectedSource, instrumentedSource);
}
|
diff --git a/src/net/sf/hajdbc/local/LocalStateManager.java b/src/net/sf/hajdbc/local/LocalStateManager.java
index b878260c..b4f38b88 100644
--- a/src/net/sf/hajdbc/local/LocalStateManager.java
+++ b/src/net/sf/hajdbc/local/LocalStateManager.java
@@ -1,118 +1,121 @@
/*
* HA-JDBC: High-Availability JDBC
* Copyright (c) 2004-2007 Paul Ferraro
*
* This library 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 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*/
package net.sf.hajdbc.local;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import net.sf.hajdbc.Database;
import net.sf.hajdbc.DatabaseCluster;
import net.sf.hajdbc.StateManager;
import net.sf.hajdbc.Messages;
/**
* @author Paul Ferraro
*/
public class LocalStateManager implements StateManager
{
private static final String STATE_DELIMITER = ",";
private static Preferences preferences = Preferences.userNodeForPackage(LocalStateManager.class);
private DatabaseCluster<?> databaseCluster;
public LocalStateManager(DatabaseCluster<?> databaseCluster)
{
this.databaseCluster = databaseCluster;
}
/**
* @see net.sf.hajdbc.StateManager#getInitialState()
*/
public Set<String> getInitialState()
{
String state = preferences.get(this.databaseCluster.getId(), null);
if (state == null) return null;
if (state.length() == 0) return Collections.emptySet();
return new TreeSet<String>(Arrays.asList(state.split(STATE_DELIMITER)));
}
/**
* @see net.sf.hajdbc.StateManager#add(java.lang.String)
*/
public void add(String databaseId)
{
this.storeState();
}
/**
* @see net.sf.hajdbc.StateManager#remove(java.lang.String)
*/
public void remove(String databaseId)
{
this.storeState();
}
private void storeState()
{
StringBuilder builder = new StringBuilder();
for (Database<?> database: this.databaseCluster.getBalancer().all())
{
builder.append(database.getId()).append(STATE_DELIMITER);
}
- builder.deleteCharAt(builder.length() - 1);
+ if (builder.length() > 0)
+ {
+ builder.deleteCharAt(builder.length() - 1);
+ }
preferences.put(this.databaseCluster.getId(), builder.toString());
try
{
preferences.flush();
}
catch (BackingStoreException e)
{
throw new RuntimeException(Messages.getMessage(Messages.CLUSTER_STATE_STORE_FAILED, this.databaseCluster), e);
}
}
/**
* @see net.sf.hajdbc.StateManager#start()
*/
public void start() throws Exception
{
preferences.sync();
}
/**
* @see net.sf.hajdbc.StateManager#stop()
*/
public void stop()
{
}
}
| true | true | private void storeState()
{
StringBuilder builder = new StringBuilder();
for (Database<?> database: this.databaseCluster.getBalancer().all())
{
builder.append(database.getId()).append(STATE_DELIMITER);
}
builder.deleteCharAt(builder.length() - 1);
preferences.put(this.databaseCluster.getId(), builder.toString());
try
{
preferences.flush();
}
catch (BackingStoreException e)
{
throw new RuntimeException(Messages.getMessage(Messages.CLUSTER_STATE_STORE_FAILED, this.databaseCluster), e);
}
}
| private void storeState()
{
StringBuilder builder = new StringBuilder();
for (Database<?> database: this.databaseCluster.getBalancer().all())
{
builder.append(database.getId()).append(STATE_DELIMITER);
}
if (builder.length() > 0)
{
builder.deleteCharAt(builder.length() - 1);
}
preferences.put(this.databaseCluster.getId(), builder.toString());
try
{
preferences.flush();
}
catch (BackingStoreException e)
{
throw new RuntimeException(Messages.getMessage(Messages.CLUSTER_STATE_STORE_FAILED, this.databaseCluster), e);
}
}
|
diff --git a/main/src/main/java/com/bloatit/web/linkable/softwares/SoftwarePage.java b/main/src/main/java/com/bloatit/web/linkable/softwares/SoftwarePage.java
index 1af94b94f..f78398247 100644
--- a/main/src/main/java/com/bloatit/web/linkable/softwares/SoftwarePage.java
+++ b/main/src/main/java/com/bloatit/web/linkable/softwares/SoftwarePage.java
@@ -1,119 +1,119 @@
/*
* Copyright (C) 2010 BloatIt. This file is part of BloatIt. BloatIt is free software: you
* can redistribute it and/or modify it under the terms of the GNU Affero General Public
* License as published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version. BloatIt 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 Affero General Public
* License for more details. You should have received a copy of the GNU Affero General
* Public License along with BloatIt. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bloatit.web.linkable.softwares;
import static com.bloatit.framework.webprocessor.context.Context.tr;
import java.util.Locale;
import com.bloatit.framework.exceptions.highlevel.ShallNotPassException;
import com.bloatit.framework.exceptions.lowlevel.RedirectException;
import com.bloatit.framework.exceptions.lowlevel.UnauthorizedOperationException;
import com.bloatit.framework.webprocessor.PageNotFoundException;
import com.bloatit.framework.webprocessor.annotations.ParamConstraint;
import com.bloatit.framework.webprocessor.annotations.ParamContainer;
import com.bloatit.framework.webprocessor.annotations.RequestParam;
import com.bloatit.framework.webprocessor.annotations.tr;
import com.bloatit.framework.webprocessor.components.HtmlImage;
import com.bloatit.framework.webprocessor.components.HtmlParagraph;
import com.bloatit.framework.webprocessor.components.HtmlTitle;
import com.bloatit.framework.webprocessor.components.meta.HtmlElement;
import com.bloatit.framework.webprocessor.components.renderer.HtmlRawTextRenderer;
import com.bloatit.framework.webprocessor.context.Context;
import com.bloatit.model.FileMetadata;
import com.bloatit.model.Software;
import com.bloatit.model.Translation;
import com.bloatit.web.pages.master.Breadcrumb;
import com.bloatit.web.pages.master.MasterPage;
import com.bloatit.web.pages.master.sidebar.TwoColumnLayout;
import com.bloatit.web.url.FileResourceUrl;
import com.bloatit.web.url.SoftwarePageUrl;
@ParamContainer("software")
public final class SoftwarePage extends MasterPage {
@ParamConstraint(optionalErrorMsg = @tr("You have to specify a software number."))
@RequestParam(name = "id", conversionErrorMsg = @tr("I cannot find the software number: ''%value''."))
private final Software software;
private final SoftwarePageUrl url;
public SoftwarePage(final SoftwarePageUrl url) {
super(url);
this.url = url;
this.software = url.getSoftware();
}
@Override
protected HtmlElement createBodyContent() throws RedirectException {
- if (!url.getMessages().hasMessage()) {
+ if (url.getMessages().hasMessage()) {
throw new PageNotFoundException();
}
final TwoColumnLayout layout = new TwoColumnLayout(true, url);
try {
HtmlTitle softwareName;
softwareName = new HtmlTitle(software.getName(), 1);
layout.addLeft(softwareName);
final FileMetadata image = software.getImage();
if (image != null) {
layout.addLeft(new HtmlImage(new FileResourceUrl(image), image.getShortDescription(), "float_right"));
}
final Locale defaultLocale = Context.getLocalizator().getLocale();
final Translation translatedDescription = software.getDescription().getTranslationOrDefault(defaultLocale);
final HtmlParagraph shortDescription = new HtmlParagraph(new HtmlRawTextRenderer(translatedDescription.getTitle()));
final HtmlParagraph description = new HtmlParagraph(new HtmlRawTextRenderer(translatedDescription.getText()));
layout.addLeft(shortDescription);
layout.addLeft(description);
} catch (final UnauthorizedOperationException e) {
session.notifyError("An error prevented us from displaying software information. Please notify us.");
throw new ShallNotPassException("User cannot access software information", e);
}
return layout;
}
@Override
protected String createPageTitle() {
try {
return tr("Software - ") + software.getName();
} catch (final UnauthorizedOperationException e) {
session.notifyError("An error prevented us from displaying software name. Please notify us.");
throw new ShallNotPassException("User cannot access software name", e);
}
}
@Override
public boolean isStable() {
return true;
}
@Override
protected Breadcrumb createBreadcrumb() {
return SoftwarePage.generateBreadcrumb(software);
}
public static Breadcrumb generateBreadcrumb(final Software software) {
final Breadcrumb breadcrumb = SoftwareListPage.generateBreadcrumb();
try {
breadcrumb.pushLink(new SoftwarePageUrl(software).getHtmlLink(software.getName()));
} catch (final UnauthorizedOperationException e) {
Context.getSession().notifyError("An error prevented us from displaying software name. Please notify us.");
throw new ShallNotPassException("User cannot access software name", e);
}
return breadcrumb;
}
}
| true | true | protected HtmlElement createBodyContent() throws RedirectException {
if (!url.getMessages().hasMessage()) {
throw new PageNotFoundException();
}
final TwoColumnLayout layout = new TwoColumnLayout(true, url);
try {
HtmlTitle softwareName;
softwareName = new HtmlTitle(software.getName(), 1);
layout.addLeft(softwareName);
final FileMetadata image = software.getImage();
if (image != null) {
layout.addLeft(new HtmlImage(new FileResourceUrl(image), image.getShortDescription(), "float_right"));
}
final Locale defaultLocale = Context.getLocalizator().getLocale();
final Translation translatedDescription = software.getDescription().getTranslationOrDefault(defaultLocale);
final HtmlParagraph shortDescription = new HtmlParagraph(new HtmlRawTextRenderer(translatedDescription.getTitle()));
final HtmlParagraph description = new HtmlParagraph(new HtmlRawTextRenderer(translatedDescription.getText()));
layout.addLeft(shortDescription);
layout.addLeft(description);
} catch (final UnauthorizedOperationException e) {
session.notifyError("An error prevented us from displaying software information. Please notify us.");
throw new ShallNotPassException("User cannot access software information", e);
}
return layout;
}
| protected HtmlElement createBodyContent() throws RedirectException {
if (url.getMessages().hasMessage()) {
throw new PageNotFoundException();
}
final TwoColumnLayout layout = new TwoColumnLayout(true, url);
try {
HtmlTitle softwareName;
softwareName = new HtmlTitle(software.getName(), 1);
layout.addLeft(softwareName);
final FileMetadata image = software.getImage();
if (image != null) {
layout.addLeft(new HtmlImage(new FileResourceUrl(image), image.getShortDescription(), "float_right"));
}
final Locale defaultLocale = Context.getLocalizator().getLocale();
final Translation translatedDescription = software.getDescription().getTranslationOrDefault(defaultLocale);
final HtmlParagraph shortDescription = new HtmlParagraph(new HtmlRawTextRenderer(translatedDescription.getTitle()));
final HtmlParagraph description = new HtmlParagraph(new HtmlRawTextRenderer(translatedDescription.getText()));
layout.addLeft(shortDescription);
layout.addLeft(description);
} catch (final UnauthorizedOperationException e) {
session.notifyError("An error prevented us from displaying software information. Please notify us.");
throw new ShallNotPassException("User cannot access software information", e);
}
return layout;
}
|
diff --git a/src/crypto/Main.java b/src/crypto/Main.java
index 89a2612..78da9de 100644
--- a/src/crypto/Main.java
+++ b/src/crypto/Main.java
@@ -1,23 +1,23 @@
package crypto;
/**
*
* Instantiate {@link Window}
*
* @author Florent LACROIX & Laetitia GAIGNIER
* @version 1.0
*
* @see Window
*
*/
public class Main {
/**
*
* Instantiate a {@link Window}
*
*/
- public static void main() {
+ public static void main(String args[]) {
Window window = new Window();
}
}
| true | true | public static void main() {
Window window = new Window();
}
| public static void main(String args[]) {
Window window = new Window();
}
|
diff --git a/src/org/ita/neutrino/junit3parser/BatteryParser.java b/src/org/ita/neutrino/junit3parser/BatteryParser.java
index 5f3895f..2aa48b8 100644
--- a/src/org/ita/neutrino/junit3parser/BatteryParser.java
+++ b/src/org/ita/neutrino/junit3parser/BatteryParser.java
@@ -1,25 +1,25 @@
package org.ita.neutrino.junit3parser;
import org.ita.neutrino.codeparser.Method;
/**
* Responsável por localizar as Suites de testes e seus respectivos métodos.
*
* @author Rafael Monico
*
*/
class BatteryParser extends org.ita.neutrino.junitgenericparser.BatteryParser {
protected TestMethodKind getTestMethodKind(Method method) {
if (method.getName().equals("setup")) {
return TestMethodKind.BEFORE_METHOD;
- } else if (method.getName().equals("tearDown")) {
+ } else if (method.getName().equals("teardown")) {
return TestMethodKind.AFTER_METHOD;
} else if (method.getName().startsWith("test")) {
return TestMethodKind.TEST_METHOD;
} else {
return TestMethodKind.NOT_TEST_METHOD;
}
}
}
| true | true | protected TestMethodKind getTestMethodKind(Method method) {
if (method.getName().equals("setup")) {
return TestMethodKind.BEFORE_METHOD;
} else if (method.getName().equals("tearDown")) {
return TestMethodKind.AFTER_METHOD;
} else if (method.getName().startsWith("test")) {
return TestMethodKind.TEST_METHOD;
} else {
return TestMethodKind.NOT_TEST_METHOD;
}
}
| protected TestMethodKind getTestMethodKind(Method method) {
if (method.getName().equals("setup")) {
return TestMethodKind.BEFORE_METHOD;
} else if (method.getName().equals("teardown")) {
return TestMethodKind.AFTER_METHOD;
} else if (method.getName().startsWith("test")) {
return TestMethodKind.TEST_METHOD;
} else {
return TestMethodKind.NOT_TEST_METHOD;
}
}
|
diff --git a/JPL/ch07/ex02/Literal.java b/JPL/ch07/ex02/Literal.java
index de779ad..4295646 100644
--- a/JPL/ch07/ex02/Literal.java
+++ b/JPL/ch07/ex02/Literal.java
@@ -1,96 +1,96 @@
package ch07.ex02;
public class Literal {
public static boolean mBoolean = true;
public static char mChar = 'A';
public static byte mMaxByte = Byte.MAX_VALUE;
public static byte mMinByte = Byte.MIN_VALUE;
public static short mMaxShort = Short.MAX_VALUE;
public static short mMinShort = Short.MIN_VALUE;
public static int mMaxInt = Integer.MAX_VALUE;
public static int mMinInt = Integer.MIN_VALUE;
public static long mMaxLong = Long.MAX_VALUE;
public static long mMinLong = Long.MIN_VALUE;
public static float mMaxFloat = Float.MAX_VALUE;
public static float mMinFloat = Float.MIN_VALUE;
public static double mMaxDouble = Double.MAX_VALUE;
public static double mMinDouble = Double.MIN_VALUE;
public static void main(String[]args) {
// �f�t�H���g�l�̏o��
System.out.println(mBoolean);
System.out.println(mChar);
System.out.println("MaxByte: " + mMaxByte);
System.out.println("MinByte: " + mMinByte);
System.out.println("MaxShort: " + mMaxShort);
System.out.println("MinShort: " + mMinShort);
System.out.println("MaxInt: " + mMaxInt);
System.out.println("MinInt: " + mMinInt);
System.out.println("MaxLong: " + mMaxLong);
System.out.println("MinLong: " + mMinLong);
System.out.println("MaxFloat: " + mMaxFloat);
System.out.println("MinFloat: " + mMinFloat);
System.out.println("MaxDouble: " + mMaxDouble);
System.out.println("MinDouble: " + mMinDouble);
// Int�^�ɕϊ����o��
int aInt = 0;
System.out.println(aInt = (int)mMaxByte);
System.out.println(aInt = (int)mMinByte);
System.out.println(aInt = (int)mMaxShort);
System.out.println(aInt = (int)mMinShort);
System.out.println(aInt = (int)mMaxInt);
System.out.println(aInt = (int)mMinInt);
System.out.println(aInt = (int)mMaxLong); //NG -1
System.out.println(aInt = (int)mMinLong); //NG 0
System.out.println(aInt = (int)mMaxFloat); //NG 2147483647
System.out.println(aInt = (int)mMinFloat); //NG 0
System.out.println(aInt = (int)mMaxDouble); //NG 2147483647
System.out.println(aInt = (int)mMinDouble); //NG 0
// Long�^�ɕϊ����o��
long aLong = 0;
System.out.println(aLong = (long)mMaxByte);
System.out.println(aLong = (long)mMinByte);
System.out.println(aLong = (long)mMaxShort);
System.out.println(aLong = (long)mMinShort);
System.out.println(aLong = (long)mMaxInt);
System.out.println(aLong = (long)mMinInt);
System.out.println(aLong = (long)mMaxLong);
System.out.println(aLong = (long)mMinLong);
System.out.println(aLong = (long)mMaxFloat); //NG 9223372036854775807
System.out.println(aLong = (long)mMinFloat); //NG 0
System.out.println(aLong = (long)mMaxDouble); //NG 9223372036854775807
System.out.println(aLong = (long)mMinDouble); //NG 0
// Float�^�ɕϊ����o��
float aFloat = 0;
System.out.println(aFloat = (float)mMaxByte);
System.out.println(aFloat = (float)mMinByte);
System.out.println(aFloat = (float)mMaxShort);
System.out.println(aFloat = (float)mMinShort);
System.out.println(aFloat = (float)mMaxInt);
System.out.println(aFloat = (float)mMinInt);
System.out.println(aFloat = (float)mMaxLong);
System.out.println(aFloat = (float)mMinLong);
System.out.println(aFloat = (float)mMaxFloat);
System.out.println(aFloat = (float)mMinFloat);
System.out.println(aFloat = (float)mMaxDouble); //NG Infinity
System.out.println(aFloat = (float)mMinDouble); //NG 0.0
// Double�^�ɕϊ����o��
double aDouble = 0;
System.out.println(aDouble = (double)mMaxByte);
System.out.println(aDouble = (double)mMinByte);
System.out.println(aDouble = (double)mMaxShort);
System.out.println(aDouble = (double)mMinShort);
System.out.println(aDouble = (double)mMaxInt);
System.out.println(aDouble = (double)mMinInt);
System.out.println(aDouble = (double)mMaxLong);
System.out.println(aDouble = (double)mMinLong);
System.out.println(aDouble = (double)mMaxFloat);
System.out.println(aDouble = (double)mMinFloat);
- System.out.println(aDouble = (double)mMaxDouble); //NG Infinity
- System.out.println(aDouble = (double)mMinDouble); //NG 0.0
+ System.out.println(aDouble = (double)mMaxDouble);
+ System.out.println(aDouble = (double)mMinDouble);
}
}
| true | true | public static void main(String[]args) {
// �f�t�H���g�l�̏o��
System.out.println(mBoolean);
System.out.println(mChar);
System.out.println("MaxByte: " + mMaxByte);
System.out.println("MinByte: " + mMinByte);
System.out.println("MaxShort: " + mMaxShort);
System.out.println("MinShort: " + mMinShort);
System.out.println("MaxInt: " + mMaxInt);
System.out.println("MinInt: " + mMinInt);
System.out.println("MaxLong: " + mMaxLong);
System.out.println("MinLong: " + mMinLong);
System.out.println("MaxFloat: " + mMaxFloat);
System.out.println("MinFloat: " + mMinFloat);
System.out.println("MaxDouble: " + mMaxDouble);
System.out.println("MinDouble: " + mMinDouble);
// Int�^�ɕϊ����o��
int aInt = 0;
System.out.println(aInt = (int)mMaxByte);
System.out.println(aInt = (int)mMinByte);
System.out.println(aInt = (int)mMaxShort);
System.out.println(aInt = (int)mMinShort);
System.out.println(aInt = (int)mMaxInt);
System.out.println(aInt = (int)mMinInt);
System.out.println(aInt = (int)mMaxLong); //NG -1
System.out.println(aInt = (int)mMinLong); //NG 0
System.out.println(aInt = (int)mMaxFloat); //NG 2147483647
System.out.println(aInt = (int)mMinFloat); //NG 0
System.out.println(aInt = (int)mMaxDouble); //NG 2147483647
System.out.println(aInt = (int)mMinDouble); //NG 0
// Long�^�ɕϊ����o��
long aLong = 0;
System.out.println(aLong = (long)mMaxByte);
System.out.println(aLong = (long)mMinByte);
System.out.println(aLong = (long)mMaxShort);
System.out.println(aLong = (long)mMinShort);
System.out.println(aLong = (long)mMaxInt);
System.out.println(aLong = (long)mMinInt);
System.out.println(aLong = (long)mMaxLong);
System.out.println(aLong = (long)mMinLong);
System.out.println(aLong = (long)mMaxFloat); //NG 9223372036854775807
System.out.println(aLong = (long)mMinFloat); //NG 0
System.out.println(aLong = (long)mMaxDouble); //NG 9223372036854775807
System.out.println(aLong = (long)mMinDouble); //NG 0
// Float�^�ɕϊ����o��
float aFloat = 0;
System.out.println(aFloat = (float)mMaxByte);
System.out.println(aFloat = (float)mMinByte);
System.out.println(aFloat = (float)mMaxShort);
System.out.println(aFloat = (float)mMinShort);
System.out.println(aFloat = (float)mMaxInt);
System.out.println(aFloat = (float)mMinInt);
System.out.println(aFloat = (float)mMaxLong);
System.out.println(aFloat = (float)mMinLong);
System.out.println(aFloat = (float)mMaxFloat);
System.out.println(aFloat = (float)mMinFloat);
System.out.println(aFloat = (float)mMaxDouble); //NG Infinity
System.out.println(aFloat = (float)mMinDouble); //NG 0.0
// Double�^�ɕϊ����o��
double aDouble = 0;
System.out.println(aDouble = (double)mMaxByte);
System.out.println(aDouble = (double)mMinByte);
System.out.println(aDouble = (double)mMaxShort);
System.out.println(aDouble = (double)mMinShort);
System.out.println(aDouble = (double)mMaxInt);
System.out.println(aDouble = (double)mMinInt);
System.out.println(aDouble = (double)mMaxLong);
System.out.println(aDouble = (double)mMinLong);
System.out.println(aDouble = (double)mMaxFloat);
System.out.println(aDouble = (double)mMinFloat);
System.out.println(aDouble = (double)mMaxDouble); //NG Infinity
System.out.println(aDouble = (double)mMinDouble); //NG 0.0
}
| public static void main(String[]args) {
// �f�t�H���g�l�̏o��
System.out.println(mBoolean);
System.out.println(mChar);
System.out.println("MaxByte: " + mMaxByte);
System.out.println("MinByte: " + mMinByte);
System.out.println("MaxShort: " + mMaxShort);
System.out.println("MinShort: " + mMinShort);
System.out.println("MaxInt: " + mMaxInt);
System.out.println("MinInt: " + mMinInt);
System.out.println("MaxLong: " + mMaxLong);
System.out.println("MinLong: " + mMinLong);
System.out.println("MaxFloat: " + mMaxFloat);
System.out.println("MinFloat: " + mMinFloat);
System.out.println("MaxDouble: " + mMaxDouble);
System.out.println("MinDouble: " + mMinDouble);
// Int�^�ɕϊ����o��
int aInt = 0;
System.out.println(aInt = (int)mMaxByte);
System.out.println(aInt = (int)mMinByte);
System.out.println(aInt = (int)mMaxShort);
System.out.println(aInt = (int)mMinShort);
System.out.println(aInt = (int)mMaxInt);
System.out.println(aInt = (int)mMinInt);
System.out.println(aInt = (int)mMaxLong); //NG -1
System.out.println(aInt = (int)mMinLong); //NG 0
System.out.println(aInt = (int)mMaxFloat); //NG 2147483647
System.out.println(aInt = (int)mMinFloat); //NG 0
System.out.println(aInt = (int)mMaxDouble); //NG 2147483647
System.out.println(aInt = (int)mMinDouble); //NG 0
// Long�^�ɕϊ����o��
long aLong = 0;
System.out.println(aLong = (long)mMaxByte);
System.out.println(aLong = (long)mMinByte);
System.out.println(aLong = (long)mMaxShort);
System.out.println(aLong = (long)mMinShort);
System.out.println(aLong = (long)mMaxInt);
System.out.println(aLong = (long)mMinInt);
System.out.println(aLong = (long)mMaxLong);
System.out.println(aLong = (long)mMinLong);
System.out.println(aLong = (long)mMaxFloat); //NG 9223372036854775807
System.out.println(aLong = (long)mMinFloat); //NG 0
System.out.println(aLong = (long)mMaxDouble); //NG 9223372036854775807
System.out.println(aLong = (long)mMinDouble); //NG 0
// Float�^�ɕϊ����o��
float aFloat = 0;
System.out.println(aFloat = (float)mMaxByte);
System.out.println(aFloat = (float)mMinByte);
System.out.println(aFloat = (float)mMaxShort);
System.out.println(aFloat = (float)mMinShort);
System.out.println(aFloat = (float)mMaxInt);
System.out.println(aFloat = (float)mMinInt);
System.out.println(aFloat = (float)mMaxLong);
System.out.println(aFloat = (float)mMinLong);
System.out.println(aFloat = (float)mMaxFloat);
System.out.println(aFloat = (float)mMinFloat);
System.out.println(aFloat = (float)mMaxDouble); //NG Infinity
System.out.println(aFloat = (float)mMinDouble); //NG 0.0
// Double�^�ɕϊ����o��
double aDouble = 0;
System.out.println(aDouble = (double)mMaxByte);
System.out.println(aDouble = (double)mMinByte);
System.out.println(aDouble = (double)mMaxShort);
System.out.println(aDouble = (double)mMinShort);
System.out.println(aDouble = (double)mMaxInt);
System.out.println(aDouble = (double)mMinInt);
System.out.println(aDouble = (double)mMaxLong);
System.out.println(aDouble = (double)mMinLong);
System.out.println(aDouble = (double)mMaxFloat);
System.out.println(aDouble = (double)mMinFloat);
System.out.println(aDouble = (double)mMaxDouble);
System.out.println(aDouble = (double)mMinDouble);
}
|
diff --git a/StarVisuals/src/com/starlon/starvisuals/StarVisualsRenderer.java b/StarVisuals/src/com/starlon/starvisuals/StarVisualsRenderer.java
index aa078b29..6b25c231 100644
--- a/StarVisuals/src/com/starlon/starvisuals/StarVisualsRenderer.java
+++ b/StarVisuals/src/com/starlon/starvisuals/StarVisualsRenderer.java
@@ -1,381 +1,381 @@
package com.starlon.starvisuals;
import android.content.Context;
import android.util.Log;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Matrix;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLUtils;
import android.opengl.GLES20;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import java.util.Timer;
import java.util.TimerTask;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class StarVisualsRenderer implements Renderer {
private Visual vis;
private int mSurfaceWidth;
private int mSurfaceHeight;
private Stats mStats;
private StarVisuals mActivity;
private NativeHelper mNativeHelper;
public Particles mParticles;
private boolean mInited = false;
public StarVisualsRenderer(Context context) {
vis = new Visual((StarVisuals)context, this);
mStats = new Stats();
mStats.statsInit();
mActivity = (StarVisuals)context;
mInited = true;
mParticles = new Particles(context);
}
public void destroy()
{
if(!mInited) return;
vis.destroy();
vis = null;
mStats = null;
mActivity = null;
}
@Override
public void onDrawFrame(GL10 gl10) {
mStats.startFrame();
vis.performFrame(gl10, mSurfaceWidth, mSurfaceHeight);
mStats.endFrame();
}
@Override
public void onSurfaceChanged(GL10 gl10, int width, int height) {
vis.initialize(gl10, width, height);
mParticles.onSurfaceChanged(gl10, width, height);
mSurfaceWidth = width;
mSurfaceHeight = height;
}
@Override
public void onSurfaceCreated(GL10 gl10, EGLConfig eglconfig) {
final int delay = 0;
final int period = 300;
final Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mActivity.warn(mStats.getText(), true);
}
};
timer.scheduleAtFixedRate(task, delay, period);
mParticles.onSurfaceCreated(gl10, eglconfig);
}
}
final class Visual {
private int mTextureWidth;
private int mTextureHeight;
private ByteBuffer mPixelBuffer;
private static final int bytesPerPixel = 4;
private int mTextureId = -1;
private int[] textureCrop = new int[4];
private boolean glInited = false;
private NativeHelper mNativeHelper;
private StarVisuals mActivity;
private StarVisualsRenderer mRenderer;
private Bitmap mBitmap;
private Paint mPaint;
private Canvas mCanvas;
private GL10 mGL10 = null;
private FloatBuffer mVertexBuffer; // buffer holding the vertices
private float vertices[] = {
-1.0f, -1.0f, 0.0f, // V1 - bottom left
-1.0f, 1.0f, 0.0f, // V2 - top left
1.0f, -1.0f, 0.0f, // V3 - bottom right
1.0f, 1.0f, 0.0f // V4 - top right
};
private FloatBuffer mTextureBuffer; // buffer holding the texture coordinates
private float texture[] = {
// Mapping coordinates for the vertices
0.0f, 1.0f, // top left (V2)
0.0f, 0.0f, // bottom left (V1)
1.0f, 1.0f, // top right (V4)
1.0f, 0.0f // bottom right (V3)
};
public Visual(StarVisuals activity, StarVisualsRenderer renderer) {
mActivity = activity;
mRenderer = renderer;
// a float has 4 bytes so we allocate for each coordinate 4 bytes
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(vertices.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
// allocates the memory from the byte buffer
mVertexBuffer = byteBuffer.asFloatBuffer();
// fill the mVertexBuffer with the vertices
mVertexBuffer.put(vertices);
// set the cursor position to the beginning of the buffer
mVertexBuffer.position(0);
byteBuffer = ByteBuffer.allocateDirect(texture.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
mTextureBuffer = byteBuffer.asFloatBuffer();
mTextureBuffer.put(texture);
mTextureBuffer.position(0);
mNativeHelper.initApp(mTextureWidth, mTextureHeight);
mActivity.setPlugins(true);
}
public void initialize(GL10 gl, int surfaceWidth, int surfaceHeight) {
mGL10 = gl;
mTextureWidth = 128;
mTextureHeight = 128;
textureCrop[0] = 0;
textureCrop[1] = 0;
textureCrop[2] = mTextureWidth;
textureCrop[3] = mTextureHeight;
mCanvas = new Canvas();
mBitmap = Bitmap.createBitmap(mTextureWidth, mTextureHeight, Bitmap.Config.ARGB_8888);
mCanvas.setBitmap(mBitmap);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(10);
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.ITALIC));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(1);
mPaint.setColor(Color.WHITE);
mPaint.setTextAlign(Paint.Align.CENTER);
// init the pixel buffer
mPixelBuffer = ByteBuffer.allocate(mTextureWidth * mTextureHeight * bytesPerPixel);
// init the GL settings
if (glInited) {
resetGl();
}
initGl(surfaceWidth, surfaceHeight);
// init the GL texture
initGlTexture();
}
public void resetGl() {
if(!glInited || mGL10 == null) return;
glInited = false;
mGL10.glMatrixMode(GL10.GL_PROJECTION);
mGL10.glPopMatrix();
mGL10.glMatrixMode(GL10.GL_TEXTURE);
mGL10.glPopMatrix();
mGL10.glMatrixMode(GL10.GL_MODELVIEW);
mGL10.glPopMatrix();
}
public void destroy()
{
if(!glInited) return;
resetGl();
mBitmap.recycle();
mBitmap = null;
mPixelBuffer = null;
mPaint = null;
mCanvas = null;
mVertexBuffer = null;
mTextureBuffer = null;
releaseTexture();
glInited = false;
mGL10 = null; // This needs to be last.
}
public void initGl(int surfaceWidth, int surfaceHeight) {
if(glInited || mGL10 == null) return;
mGL10.glViewport(0, 0, surfaceWidth, surfaceHeight);
mGL10.glShadeModel(GL10.GL_FLAT);
mGL10.glFrontFace(GL10.GL_CCW);
mGL10.glEnable(GL10.GL_TEXTURE_2D);
mGL10.glMatrixMode(GL10.GL_PROJECTION);
mGL10.glLoadIdentity();
mGL10.glPushMatrix();
mGL10.glMatrixMode(GL10.GL_MODELVIEW);
mGL10.glLoadIdentity();
mGL10.glOrthof(-1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f);
mGL10.glPushMatrix();
glInited = true;
}
public void updatePixels()
{
// Fill the bitmap with black.
if(false)
{
mBitmap = mActivity.getVisualObject().run();
mCanvas.setBitmap(mBitmap);
}
else
{
mBitmap.eraseColor(Color.BLACK);
mNativeHelper.renderBitmap(mBitmap, mActivity.getDoSwap());
}
// If StarVisuals has text to display, then use a canvas and paint brush to display it.
String text = mActivity.getDisplayText();
if(text != null)
{
// Give the bitmap a canvas so we can draw on it.
float canvasWidth = mCanvas.getWidth();
float textWidth = mPaint.measureText(text);
float startPositionX = (canvasWidth - textWidth / 2) / 2;
mCanvas.drawText(text, startPositionX, mTextureWidth-12, mPaint);
}
// Copy bitmap pixels into buffer.
mPixelBuffer.rewind();
mBitmap.copyPixelsToBuffer(mPixelBuffer);
}
private void releaseTexture() {
if(mGL10 == null)
return;
if (mTextureId != -1) {
mGL10.glDeleteTextures(1, new int[] { mTextureId }, 0);
}
}
private void initGlTexture() {
releaseTexture();
int[] textures = new int[1];
mGL10.glGenTextures(1, textures, 0);
mTextureId = textures[0];
// we want to modify this texture so bind it
mGL10.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);
// GL_LINEAR gives us smoothing since the texture is larger than the screen
mGL10.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
mGL10.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_LINEAR);
// repeat the edge pixels if a surface is larger than the texture
mGL10.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
mGL10.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
// now, let's init the texture with pixel values
//updatePixels();
// and init the GL texture with the pixels
mGL10.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA, mTextureWidth, mTextureHeight,
0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, mPixelBuffer);
// at this point, we are OK to further modify the texture
// using glTexSubImage2D
}
public void performFrame(GL10 gl, int surfaceWidth, int surfaceHeight) {
if(mGL10 != gl)
mGL10 = gl;
if(mGL10 == null)
return;
// Draw
updatePixels();
// Clear the surface
mGL10.glClearColorx(0, 0, 0, 0);
mGL10.glClear(GL10.GL_COLOR_BUFFER_BIT);
// Point to our buffers
mGL10.glEnableClientState(GL10.GL_VERTEX_ARRAY);
mGL10.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Set the face rotation
mGL10.glFrontFace(GL10.GL_CW);
// Point to our vertex buffer
mGL10.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
mGL10.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);
// Choose the texture
mGL10.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);
// Update the texture
mGL10.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, 0, 0, mTextureWidth, mTextureHeight,
GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, mPixelBuffer);
// Draw the vertices as triangle strip
mGL10.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
//Disable the client state before leaving
mGL10.glDisableClientState(GL10.GL_VERTEX_ARRAY);
mGL10.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
- mRenderer.mParticles.onDrawFrame(gl);
+ //mRenderer.mParticles.onDrawFrame(gl);
}
}
| true | true | public void performFrame(GL10 gl, int surfaceWidth, int surfaceHeight) {
if(mGL10 != gl)
mGL10 = gl;
if(mGL10 == null)
return;
// Draw
updatePixels();
// Clear the surface
mGL10.glClearColorx(0, 0, 0, 0);
mGL10.glClear(GL10.GL_COLOR_BUFFER_BIT);
// Point to our buffers
mGL10.glEnableClientState(GL10.GL_VERTEX_ARRAY);
mGL10.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Set the face rotation
mGL10.glFrontFace(GL10.GL_CW);
// Point to our vertex buffer
mGL10.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
mGL10.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);
// Choose the texture
mGL10.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);
// Update the texture
mGL10.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, 0, 0, mTextureWidth, mTextureHeight,
GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, mPixelBuffer);
// Draw the vertices as triangle strip
mGL10.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
//Disable the client state before leaving
mGL10.glDisableClientState(GL10.GL_VERTEX_ARRAY);
mGL10.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
mRenderer.mParticles.onDrawFrame(gl);
}
| public void performFrame(GL10 gl, int surfaceWidth, int surfaceHeight) {
if(mGL10 != gl)
mGL10 = gl;
if(mGL10 == null)
return;
// Draw
updatePixels();
// Clear the surface
mGL10.glClearColorx(0, 0, 0, 0);
mGL10.glClear(GL10.GL_COLOR_BUFFER_BIT);
// Point to our buffers
mGL10.glEnableClientState(GL10.GL_VERTEX_ARRAY);
mGL10.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Set the face rotation
mGL10.glFrontFace(GL10.GL_CW);
// Point to our vertex buffer
mGL10.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
mGL10.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);
// Choose the texture
mGL10.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);
// Update the texture
mGL10.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, 0, 0, mTextureWidth, mTextureHeight,
GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, mPixelBuffer);
// Draw the vertices as triangle strip
mGL10.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
//Disable the client state before leaving
mGL10.glDisableClientState(GL10.GL_VERTEX_ARRAY);
mGL10.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
//mRenderer.mParticles.onDrawFrame(gl);
}
|
diff --git a/source/de/anomic/kelondro/kelondroFlexSplitTable.java b/source/de/anomic/kelondro/kelondroFlexSplitTable.java
index 21248172c..0d9a653f1 100644
--- a/source/de/anomic/kelondro/kelondroFlexSplitTable.java
+++ b/source/de/anomic/kelondro/kelondroFlexSplitTable.java
@@ -1,337 +1,338 @@
// kelondroFlexSplitTable.java
// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
// first published 12.10.2006 on http://www.anomic.de
//
// This is a part of YaCy, a peer-to-peer based web search engine
//
// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $
// $LastChangedRevision: 1986 $
// $LastChangedBy: orbiter $
//
// 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 de.anomic.kelondro;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class kelondroFlexSplitTable implements kelondroIndex {
// this is a set of kelondroFlex tables
// the set is divided into FlexTables with different entry date
private HashMap tables;
private kelondroOrder objectOrder;
private kelondroRow rowdef;
private File path;
private String tablename;
private long buffersize;
public kelondroFlexSplitTable(File path, String tablename, long buffersize, long preloadTime, kelondroRow rowdef, kelondroOrder objectOrder) throws IOException {
this.path = path;
this.tablename = tablename;
this.objectOrder = objectOrder;
this.rowdef = rowdef;
// initialized tables map
this.tables = new HashMap();
if (!(path.exists())) path.mkdirs();
String[] dir = path.list();
String date;
// first pass: find tables
HashMap t = new HashMap(); // file/Integer(size) relation
long ram, sum = 0;
for (int i = 0; i < dir.length; i++) {
if ((dir[i].startsWith(tablename)) &&
(dir[i].charAt(tablename.length()) == '.') &&
(dir[i].length() == tablename.length() + 7)) {
ram = kelondroFlexTable.staticRAMIndexNeed(path, dir[i], rowdef);
if (ram > 0) {
t.put(dir[i], new Long(ram));
sum += ram;
}
}
}
// second pass: open tables
Iterator i;
Map.Entry entry;
String f, maxf;
long maxram;
kelondroIndex table;
while (t.size() > 0) {
// find maximum table
maxram = 0;
maxf = null;
i = t.entrySet().iterator();
while (i.hasNext()) {
entry = (Map.Entry) i.next();
f = (String) entry.getKey();
ram = ((Long) entry.getValue()).longValue();
if (ram > maxram) {
maxf = f;
maxram = ram;
}
}
// open next biggest table
t.remove(maxf);
date = maxf.substring(tablename.length() + 1);
- if (maxram <= sum) {
+ if (buffersize >= maxram) {
// this will cause usage of a complete RAM index
table = new kelondroCache(new kelondroFlexTable(path, maxf, maxram, preloadTime, rowdef, objectOrder), maxram / 10, true, false);
- sum -= maxram;
- sum -= maxram / 10;
+ buffersize -= maxram;
+ buffersize -= maxram / 10;
} else {
// this will cause a generation of a file index
- table = new kelondroFlexTable(path, maxf, sum / (t.size() + 1), preloadTime, rowdef, objectOrder);
- sum -= sum / (t.size() + 1);
+ table = new kelondroFlexTable(path, maxf, buffersize / (t.size() + 1), preloadTime, rowdef, objectOrder);
+ buffersize -= buffersize / (t.size() + 1);
}
tables.put(date, table);
}
+ System.out.println("*** remaining buffer RAM (not used): " + buffersize);
}
private static final Calendar thisCalendar = Calendar.getInstance();
public static final String dateSuffix(Date date) {
int month, year;
StringBuffer suffix = new StringBuffer(6);
synchronized (thisCalendar) {
thisCalendar.setTime(date);
month = thisCalendar.get(Calendar.MONTH) + 1;
year = thisCalendar.get(Calendar.YEAR);
}
if ((year < 1970) && (year >= 70)) suffix.append("19").append(Integer.toString(year));
else if (year < 1970) suffix.append("20").append(Integer.toString(year));
else if (year > 3000) return null;
else suffix.append(Integer.toString(year));
if (month < 10) suffix.append("0").append(Integer.toString(month)); else suffix.append(Integer.toString(month));
return new String(suffix);
}
public kelondroOrder order() {
return this.objectOrder;
}
public int primarykey() {
return 0;
}
public synchronized int size() throws IOException {
Iterator i = tables.values().iterator();
int s = 0;
while (i.hasNext()) {
s += ((kelondroIndex) i.next()).size();
}
return s;
}
public synchronized kelondroProfile profile() {
kelondroProfile[] profiles = new kelondroProfile[tables.size()];
Iterator i = tables.values().iterator();
int c = 0;
while (i.hasNext()) profiles[c++] = ((kelondroIndex) i.next()).profile();
return kelondroProfile.consolidate(profiles);
}
public int writeBufferSize() {
Iterator i = tables.values().iterator();
int s = 0;
kelondroIndex ki;
while (i.hasNext()) {
ki = ((kelondroIndex) i.next());
if (ki instanceof kelondroCache) s += ((kelondroCache) ki).writeBufferSize();
}
return s;
}
public void flushSome() {
Iterator i = tables.values().iterator();
kelondroIndex ki;
while (i.hasNext()) {
ki = ((kelondroIndex) i.next());
if (ki instanceof kelondroCache)
try {((kelondroCache) ki).flushSome();} catch (IOException e) {}
}
}
public kelondroRow row() throws IOException {
return this.rowdef;
}
public synchronized kelondroRow.Entry get(byte[] key) throws IOException {
Object[] keeper = keeperOf(key);
if (keeper == null) return null;
return (kelondroRow.Entry) keeper[1];
}
public synchronized kelondroRow.Entry put(kelondroRow.Entry row) throws IOException {
return put(row, new Date()); // entry for current date
}
public synchronized kelondroRow.Entry put(kelondroRow.Entry row, Date entryDate) throws IOException {
assert row.bytes().length <= this.rowdef.objectsize;
Object[] keeper = keeperOf(row.getColBytes(0));
if (keeper != null) return ((kelondroIndex) keeper[0]).put(row);
String suffix = dateSuffix(entryDate);
if (suffix == null) return null;
kelondroIndex table = (kelondroIndex) tables.get(suffix);
if (table == null) {
// make new table
table = new kelondroFlexTable(path, tablename + "." + suffix, buffersize / (tables.size() + 1), -1, rowdef, objectOrder);
tables.put(suffix, table);
}
table.put(row);
return null;
}
public synchronized Object[] keeperOf(byte[] key) throws IOException {
Iterator i = tables.values().iterator();
kelondroIndex table;
kelondroRow.Entry entry;
while (i.hasNext()) {
table = (kelondroIndex) i.next();
entry = table.get(key);
if (entry != null) return new Object[]{table, entry};
}
return null;
}
public synchronized void addUnique(kelondroRow.Entry row) throws IOException {
addUnique(row, new Date());
}
public synchronized void addUnique(kelondroRow.Entry row, Date entryDate) throws IOException {
assert row.bytes().length <= this.rowdef.objectsize;
String suffix = dateSuffix(entryDate);
if (suffix == null) return;
kelondroIndex table = (kelondroIndex) tables.get(suffix);
if (table == null) {
// make new table
table = new kelondroFlexTable(path, tablename + "." + suffix, buffersize / (tables.size() + 1), -1, rowdef, objectOrder);
tables.put(suffix, table);
}
table.addUnique(row, entryDate);
}
public synchronized kelondroRow.Entry remove(byte[] key) throws IOException {
Iterator i = tables.values().iterator();
kelondroIndex table;
kelondroRow.Entry entry;
while (i.hasNext()) {
table = (kelondroIndex) i.next();
entry = table.remove(key);
if (entry != null) return entry;
}
return null;
}
public synchronized kelondroRow.Entry removeOne() throws IOException {
Iterator i = tables.values().iterator();
kelondroIndex table, maxtable = null;
int maxcount = -1;
while (i.hasNext()) {
table = (kelondroIndex) i.next();
if (table.size() > maxcount) {
maxtable = table;
maxcount = table.size();
}
}
if (maxtable == null) {
return null;
} else {
return maxtable.removeOne();
}
}
public synchronized Iterator rows(boolean up, boolean rotating, byte[] firstKey) throws IOException {
return new rowIter();
}
public class rowIter implements Iterator {
Iterator t, tt;
public rowIter() {
t = tables.values().iterator();
tt = null;
}
public boolean hasNext() {
return ((t.hasNext()) || ((tt != null) && (tt.hasNext())));
}
public Object next() {
if (t.hasNext()) {
if ((tt == null) || (!(tt.hasNext()))) {
try {
tt = ((kelondroIndex) t.next()).rows(true, false, null);
} catch (IOException e) {
return null;
}
}
if (tt.hasNext()) {
return tt.next();
} else {
return null;
}
}
return null;
}
public void remove() {
if (tt != null) tt.remove();
}
}
public final int cacheObjectChunkSize() {
// dummy method
return -1;
}
public long[] cacheObjectStatus() {
// dummy method
return null;
}
public final int cacheNodeChunkSize() {
// returns the size that the node cache uses for a single entry
return -1;
}
public final int[] cacheNodeStatus() {
// a collection of different node cache status values
return new int[]{0,0,0,0,0,0,0,0,0,0};
}
public synchronized void close() throws IOException {
Iterator i = tables.values().iterator();
while (i.hasNext()) ((kelondroIndex) i.next()).close();
tables = null;
}
public static void main(String[] args) {
System.out.println(dateSuffix(new Date()));
}
}
| false | true | public kelondroFlexSplitTable(File path, String tablename, long buffersize, long preloadTime, kelondroRow rowdef, kelondroOrder objectOrder) throws IOException {
this.path = path;
this.tablename = tablename;
this.objectOrder = objectOrder;
this.rowdef = rowdef;
// initialized tables map
this.tables = new HashMap();
if (!(path.exists())) path.mkdirs();
String[] dir = path.list();
String date;
// first pass: find tables
HashMap t = new HashMap(); // file/Integer(size) relation
long ram, sum = 0;
for (int i = 0; i < dir.length; i++) {
if ((dir[i].startsWith(tablename)) &&
(dir[i].charAt(tablename.length()) == '.') &&
(dir[i].length() == tablename.length() + 7)) {
ram = kelondroFlexTable.staticRAMIndexNeed(path, dir[i], rowdef);
if (ram > 0) {
t.put(dir[i], new Long(ram));
sum += ram;
}
}
}
// second pass: open tables
Iterator i;
Map.Entry entry;
String f, maxf;
long maxram;
kelondroIndex table;
while (t.size() > 0) {
// find maximum table
maxram = 0;
maxf = null;
i = t.entrySet().iterator();
while (i.hasNext()) {
entry = (Map.Entry) i.next();
f = (String) entry.getKey();
ram = ((Long) entry.getValue()).longValue();
if (ram > maxram) {
maxf = f;
maxram = ram;
}
}
// open next biggest table
t.remove(maxf);
date = maxf.substring(tablename.length() + 1);
if (maxram <= sum) {
// this will cause usage of a complete RAM index
table = new kelondroCache(new kelondroFlexTable(path, maxf, maxram, preloadTime, rowdef, objectOrder), maxram / 10, true, false);
sum -= maxram;
sum -= maxram / 10;
} else {
// this will cause a generation of a file index
table = new kelondroFlexTable(path, maxf, sum / (t.size() + 1), preloadTime, rowdef, objectOrder);
sum -= sum / (t.size() + 1);
}
tables.put(date, table);
}
}
| public kelondroFlexSplitTable(File path, String tablename, long buffersize, long preloadTime, kelondroRow rowdef, kelondroOrder objectOrder) throws IOException {
this.path = path;
this.tablename = tablename;
this.objectOrder = objectOrder;
this.rowdef = rowdef;
// initialized tables map
this.tables = new HashMap();
if (!(path.exists())) path.mkdirs();
String[] dir = path.list();
String date;
// first pass: find tables
HashMap t = new HashMap(); // file/Integer(size) relation
long ram, sum = 0;
for (int i = 0; i < dir.length; i++) {
if ((dir[i].startsWith(tablename)) &&
(dir[i].charAt(tablename.length()) == '.') &&
(dir[i].length() == tablename.length() + 7)) {
ram = kelondroFlexTable.staticRAMIndexNeed(path, dir[i], rowdef);
if (ram > 0) {
t.put(dir[i], new Long(ram));
sum += ram;
}
}
}
// second pass: open tables
Iterator i;
Map.Entry entry;
String f, maxf;
long maxram;
kelondroIndex table;
while (t.size() > 0) {
// find maximum table
maxram = 0;
maxf = null;
i = t.entrySet().iterator();
while (i.hasNext()) {
entry = (Map.Entry) i.next();
f = (String) entry.getKey();
ram = ((Long) entry.getValue()).longValue();
if (ram > maxram) {
maxf = f;
maxram = ram;
}
}
// open next biggest table
t.remove(maxf);
date = maxf.substring(tablename.length() + 1);
if (buffersize >= maxram) {
// this will cause usage of a complete RAM index
table = new kelondroCache(new kelondroFlexTable(path, maxf, maxram, preloadTime, rowdef, objectOrder), maxram / 10, true, false);
buffersize -= maxram;
buffersize -= maxram / 10;
} else {
// this will cause a generation of a file index
table = new kelondroFlexTable(path, maxf, buffersize / (t.size() + 1), preloadTime, rowdef, objectOrder);
buffersize -= buffersize / (t.size() + 1);
}
tables.put(date, table);
}
System.out.println("*** remaining buffer RAM (not used): " + buffersize);
}
|
diff --git a/Cmail-Dao/src/org/cmail/rehabilitacion/dao/FichaIngresoDao.java b/Cmail-Dao/src/org/cmail/rehabilitacion/dao/FichaIngresoDao.java
index 1c6aa60..9b5631e 100644
--- a/Cmail-Dao/src/org/cmail/rehabilitacion/dao/FichaIngresoDao.java
+++ b/Cmail-Dao/src/org/cmail/rehabilitacion/dao/FichaIngresoDao.java
@@ -1,59 +1,61 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.cmail.rehabilitacion.dao;
import org.cmail.rehabilitacion.modelo.sira.FichaIngreso;
import org.hibernate.Transaction;
/**
* Clase de acceso a datos para menejar las fichas de ingreso.
*
* @author Noralma Vera
* @author Doris Viñamagua
* @version 1.0
*/
public class FichaIngresoDao extends GanericDao<FichaIngreso> {
/**
* Constructor por defecto
*/
public FichaIngresoDao() {
super(FichaIngreso.class);
}
/**
* Guarda una ficha de ingreso
*
* @param fichaIngreso la ficha de ingreso a guardar
* @return true si se guardó correctamente
*/
public boolean save(FichaIngreso fichaIngreso) {
boolean b = false;
Transaction tx = null;
log.info("Guardando ficha....");
try {
tx = getSession().beginTransaction();
//merge(instancia);
- log.info("Madre: " + fichaIngreso.getAdolescente().getMadre().getNombres());
+ if (fichaIngreso.getAdolescente().getMadre() != null){
+ log.info("Madre: " + fichaIngreso.getAdolescente().getMadre().getNombres());
+ }
getSession().saveOrUpdate(merge(fichaIngreso.getAdolescente()));
getSession().saveOrUpdate(merge(fichaIngreso));
tx.commit();
b=true;
} catch (Exception e) {
log.error("Error guardar ficha", e);
if(tx !=null) tx.rollback();
b = false;
}
return b;
}
}
| true | true | public boolean save(FichaIngreso fichaIngreso) {
boolean b = false;
Transaction tx = null;
log.info("Guardando ficha....");
try {
tx = getSession().beginTransaction();
//merge(instancia);
log.info("Madre: " + fichaIngreso.getAdolescente().getMadre().getNombres());
getSession().saveOrUpdate(merge(fichaIngreso.getAdolescente()));
getSession().saveOrUpdate(merge(fichaIngreso));
tx.commit();
b=true;
} catch (Exception e) {
log.error("Error guardar ficha", e);
if(tx !=null) tx.rollback();
b = false;
}
return b;
}
| public boolean save(FichaIngreso fichaIngreso) {
boolean b = false;
Transaction tx = null;
log.info("Guardando ficha....");
try {
tx = getSession().beginTransaction();
//merge(instancia);
if (fichaIngreso.getAdolescente().getMadre() != null){
log.info("Madre: " + fichaIngreso.getAdolescente().getMadre().getNombres());
}
getSession().saveOrUpdate(merge(fichaIngreso.getAdolescente()));
getSession().saveOrUpdate(merge(fichaIngreso));
tx.commit();
b=true;
} catch (Exception e) {
log.error("Error guardar ficha", e);
if(tx !=null) tx.rollback();
b = false;
}
return b;
}
|
diff --git a/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/editor/internal/commands/DragAndDropCommand.java b/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/editor/internal/commands/DragAndDropCommand.java
index a9e254bc8..9ae66fcbf 100644
--- a/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/editor/internal/commands/DragAndDropCommand.java
+++ b/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/editor/internal/commands/DragAndDropCommand.java
@@ -1,341 +1,341 @@
/*******************************************************************************
* Copyright (c) 2001, 2006 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.wst.xsd.editor.internal.commands;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.PointList;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.requests.ChangeBoundsRequest;
import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer;
import org.eclipse.wst.xsd.adt.design.editparts.BaseFieldEditPart;
import org.eclipse.wst.xsd.adt.design.editparts.CompartmentEditPart;
import org.eclipse.wst.xsd.adt.design.editparts.ComplexTypeEditPart;
import org.eclipse.wst.xsd.editor.internal.actions.MoveAction;
import org.eclipse.wst.xsd.editor.internal.adapters.XSDBaseAdapter;
import org.eclipse.wst.xsd.editor.internal.design.editparts.ModelGroupDefinitionReferenceEditPart;
import org.eclipse.wst.xsd.editor.internal.design.editparts.ModelGroupEditPart;
import org.eclipse.wst.xsd.editor.internal.design.editparts.TargetConnectionSpacingFigureEditPart;
import org.eclipse.wst.xsd.editor.internal.design.editparts.XSDGroupsForAnnotationEditPart;
import org.eclipse.wst.xsd.editor.internal.design.figures.GenericGroupFigure;
import org.eclipse.wst.xsd.ui.common.commands.BaseCommand;
import org.eclipse.xsd.XSDConcreteComponent;
import org.eclipse.xsd.XSDModelGroup;
public class DragAndDropCommand extends BaseCommand
{
protected EditPartViewer viewer;
protected ChangeBoundsRequest request;
protected BaseFieldEditPart previousChildRefEditPart, nextChildRefEditPart;
public ModelGroupEditPart parentEditPart;
public Point location;
protected MoveAction action;
protected boolean canExecute;
EditPart target;
List modelGroupsList = new ArrayList();
List targetSpacesList = new ArrayList();
public DragAndDropCommand(EditPartViewer viewer, ChangeBoundsRequest request)
{
this.viewer = viewer;
this.request = request;
location = request.getLocation();
target = viewer.findObjectAt(location);
if (viewer instanceof ScrollingGraphicalViewer)
{
ScrollingGraphicalViewer sgv = (ScrollingGraphicalViewer)viewer;
Point p = ((FigureCanvas)sgv.getControl()).getViewport().getViewLocation();
location.y += p.y;
location.x += p.x;
}
List list = request.getEditParts();
if (list.size() > 0 && target instanceof BaseFieldEditPart)
{
BaseFieldEditPart baseFieldEditPart = (BaseFieldEditPart)target;
XSDModelGroup targetModelGroup = null;
modelGroupsList.clear();
targetSpacesList.clear();
calculateModelGroupList();
List modelGroups = new ArrayList(modelGroupsList.size());
for (Iterator i = modelGroupsList.iterator(); i.hasNext(); )
{
ModelGroupEditPart editPart = (ModelGroupEditPart)i.next();
modelGroups.add(editPart.getXSDModelGroup());
}
EditPart compartment = baseFieldEditPart.getParent();
parentEditPart = null;
if (compartment != null)
{
List l = compartment.getChildren();
Rectangle rectangle = new Rectangle(0, 0, 0, 0), previousRectangle = new Rectangle(0,0,0,0);
int index = -1;
BaseFieldEditPart childGraphNodeEditPart = null;
for (Iterator i = l.iterator(); i.hasNext(); )
{
EditPart child = (EditPart)i.next();
if (child instanceof BaseFieldEditPart)
{
index ++;
previousChildRefEditPart = childGraphNodeEditPart;
childGraphNodeEditPart = (BaseFieldEditPart)child;
if (previousChildRefEditPart != null)
{
previousRectangle = previousChildRefEditPart.getFigure().getBounds();
}
rectangle = childGraphNodeEditPart.getFigure().getBounds();
if (location.y < (rectangle.getCenter().y))
{
nextChildRefEditPart = childGraphNodeEditPart;
TargetConnectionSpacingFigureEditPart tSpace = (TargetConnectionSpacingFigureEditPart)targetSpacesList.get(index-1);
if (previousRectangle != null && location.y > (previousRectangle.getBottom().y))
{
tSpace = (TargetConnectionSpacingFigureEditPart)targetSpacesList.get(index);
}
parentEditPart = (ModelGroupEditPart)tSpace.getParent();
targetModelGroup = parentEditPart.getXSDModelGroup();
break;
}
// if (location.y < (rectangle.getCenter().y))
// {
// nextChildRefEditPart = childGraphNodeEditPart;
// TargetConnectionSpacingFigureEditPart previousSpace = null;
// for (Iterator s = targetSpacesList.iterator(); s.hasNext(); )
// {
// TargetConnectionSpacingFigureEditPart tSpace = (TargetConnectionSpacingFigureEditPart) s.next();
// Rectangle tRect = tSpace.getFigure().getBounds();
// if (location.y < (tRect.getCenter().y + tRect.height/2))
// {
// parentEditPart = (ModelGroupEditPart)tSpace.getParent();
// targetModelGroup = parentEditPart.getXSDModelGroup();
// break;
// }
// previousSpace = tSpace;
// }
// if (parentEditPart != null)
// break;
// }
}
else
{
// This is the annotation edit part
}
}
List editPartsList = request.getEditParts();
List concreteComponentList = new ArrayList(editPartsList.size());
for (Iterator i = editPartsList.iterator(); i.hasNext(); )
{
EditPart editPart = (EditPart)i.next();
concreteComponentList.add((XSDConcreteComponent) ((XSDBaseAdapter)editPart.getModel()).getTarget());
}
XSDConcreteComponent previousRefComponent = null, nextRefComponent = null;
if (nextChildRefEditPart != null)
{
if (nextChildRefEditPart.getModel() instanceof XSDBaseAdapter)
{
nextRefComponent = (XSDConcreteComponent)((XSDBaseAdapter)nextChildRefEditPart.getModel()).getTarget();
}
}
if (previousChildRefEditPart != null)
{
if (previousChildRefEditPart.getModel() instanceof XSDBaseAdapter)
{
previousRefComponent = (XSDConcreteComponent)((XSDBaseAdapter)previousChildRefEditPart.getModel()).getTarget();
}
}
- System.out.println(previousRefComponent + "\n " + nextRefComponent);
+// System.out.println(previousRefComponent + "\n " + nextRefComponent);
action = new MoveAction(targetModelGroup, concreteComponentList, previousRefComponent, nextRefComponent);
canExecute = action.canMove();
}
}
}
protected void calculateModelGroupList()
{
EditPart editPart = target;
while (editPart != null)
{
if (editPart instanceof ModelGroupEditPart)
{
ModelGroupEditPart modelGroupEditPart = (ModelGroupEditPart)editPart;
modelGroupsList.addAll(getModelGroupEditParts(modelGroupEditPart));
}
else if (editPart instanceof ComplexTypeEditPart ||
editPart instanceof ModelGroupDefinitionReferenceEditPart)
{
List list = editPart.getChildren();
for (Iterator i = list.iterator(); i.hasNext(); )
{
Object child = i.next();
if (child instanceof CompartmentEditPart)
{
List compartmentList = ((CompartmentEditPart)child).getChildren();
for (Iterator it = compartmentList.iterator(); it.hasNext(); )
{
Object obj = it.next();
if (obj instanceof XSDGroupsForAnnotationEditPart)
{
XSDGroupsForAnnotationEditPart groups = (XSDGroupsForAnnotationEditPart)obj;
List groupList = groups.getChildren();
for (Iterator iter = groupList.iterator(); iter.hasNext(); )
{
Object groupChild = iter.next();
if (groupChild instanceof ModelGroupEditPart)
{
ModelGroupEditPart modelGroupEditPart = (ModelGroupEditPart)groupChild;
modelGroupsList.add(modelGroupEditPart);
modelGroupsList.addAll(getModelGroupEditParts(modelGroupEditPart));
}
}
}
}
}
}
}
editPart = editPart.getParent();
}
}
protected List getModelGroupEditParts(ModelGroupEditPart modelGroupEditPart)
{
List modelGroupList = new ArrayList();
List list = modelGroupEditPart.getChildren();
for (Iterator i = list.iterator(); i.hasNext(); )
{
Object object = i.next();
if (object instanceof TargetConnectionSpacingFigureEditPart)
{
targetSpacesList.add(object);
}
else if (object instanceof ModelGroupDefinitionReferenceEditPart)
{
ModelGroupDefinitionReferenceEditPart groupRef = (ModelGroupDefinitionReferenceEditPart)object;
List groupRefChildren = groupRef.getChildren();
for (Iterator it = groupRefChildren.iterator(); it.hasNext(); )
{
Object o = it.next();
if (o instanceof ModelGroupEditPart)
{
ModelGroupEditPart aGroup = (ModelGroupEditPart)o;
modelGroupList.add(aGroup);
modelGroupList.addAll(getModelGroupEditParts(aGroup));
}
}
}
else if (object instanceof ModelGroupEditPart)
{
ModelGroupEditPart aGroup = (ModelGroupEditPart)object;
modelGroupList.add(aGroup);
modelGroupList.addAll(getModelGroupEditParts(aGroup));
}
}
return modelGroupList;
}
public void execute()
{
if (canExecute)
{
action.run();
}
}
public void redo()
{
}
public void undo()
{
}
public boolean canExecute()
{
return canExecute;
}
public PointList getConnectionPoints(Rectangle draggedFigureBounds)
{
PointList pointList = null;
if (parentEditPart != null && nextChildRefEditPart != null)
{
pointList = getConnectionPoints(parentEditPart, nextChildRefEditPart, draggedFigureBounds);
}
return pointList != null ? pointList : new PointList();
}
// This method supports the preview connection line function related to drag and drop
//
public PointList getConnectionPoints(ModelGroupEditPart parentEditPart, BaseFieldEditPart childRefEditPart, Rectangle draggedFigureBounds)
{
PointList pointList = new PointList();
int[] data = new int[1];
Point a = getConnectionPoint(parentEditPart, childRefEditPart, data);
if (a != null)
{
int draggedFigureBoundsY = draggedFigureBounds.y + draggedFigureBounds.height/2;
pointList.addPoint(a);
if (data[0] == 0) // insert between 2 items
{
int x = a.x + (draggedFigureBounds.x - a.x)/2;
pointList.addPoint(new Point(x, a.y));
pointList.addPoint(new Point(x, draggedFigureBoundsY));
pointList.addPoint(new Point(draggedFigureBounds.x, draggedFigureBoundsY));
}
else // insert at first or last position
{
pointList.addPoint(new Point(a.x, draggedFigureBoundsY));
pointList.addPoint(new Point(draggedFigureBounds.x, draggedFigureBoundsY));
}
}
return pointList;
}
// This method supports the preview connection line function related to drag and drop
//
protected Point getConnectionPoint(ModelGroupEditPart parentEditPart, BaseFieldEditPart childRefEditPart, int[] data)
{
Point point = null;
List childList = parentEditPart.getChildren();
if (parentEditPart.getFigure() instanceof GenericGroupFigure && childList.size() > 0)
{
point = new Point();
Rectangle r = getConnectedEditPartConnectionBounds(parentEditPart);
point.x = r.x + r.width;
point.y = r.y + r.height/2;
}
return point;
}
protected Rectangle getConnectedEditPartConnectionBounds(ModelGroupEditPart editPart)
{
return ((GenericGroupFigure)editPart.getFigure()).getIconFigure().getBounds();
}
}
| true | true | public DragAndDropCommand(EditPartViewer viewer, ChangeBoundsRequest request)
{
this.viewer = viewer;
this.request = request;
location = request.getLocation();
target = viewer.findObjectAt(location);
if (viewer instanceof ScrollingGraphicalViewer)
{
ScrollingGraphicalViewer sgv = (ScrollingGraphicalViewer)viewer;
Point p = ((FigureCanvas)sgv.getControl()).getViewport().getViewLocation();
location.y += p.y;
location.x += p.x;
}
List list = request.getEditParts();
if (list.size() > 0 && target instanceof BaseFieldEditPart)
{
BaseFieldEditPart baseFieldEditPart = (BaseFieldEditPart)target;
XSDModelGroup targetModelGroup = null;
modelGroupsList.clear();
targetSpacesList.clear();
calculateModelGroupList();
List modelGroups = new ArrayList(modelGroupsList.size());
for (Iterator i = modelGroupsList.iterator(); i.hasNext(); )
{
ModelGroupEditPart editPart = (ModelGroupEditPart)i.next();
modelGroups.add(editPart.getXSDModelGroup());
}
EditPart compartment = baseFieldEditPart.getParent();
parentEditPart = null;
if (compartment != null)
{
List l = compartment.getChildren();
Rectangle rectangle = new Rectangle(0, 0, 0, 0), previousRectangle = new Rectangle(0,0,0,0);
int index = -1;
BaseFieldEditPart childGraphNodeEditPart = null;
for (Iterator i = l.iterator(); i.hasNext(); )
{
EditPart child = (EditPart)i.next();
if (child instanceof BaseFieldEditPart)
{
index ++;
previousChildRefEditPart = childGraphNodeEditPart;
childGraphNodeEditPart = (BaseFieldEditPart)child;
if (previousChildRefEditPart != null)
{
previousRectangle = previousChildRefEditPart.getFigure().getBounds();
}
rectangle = childGraphNodeEditPart.getFigure().getBounds();
if (location.y < (rectangle.getCenter().y))
{
nextChildRefEditPart = childGraphNodeEditPart;
TargetConnectionSpacingFigureEditPart tSpace = (TargetConnectionSpacingFigureEditPart)targetSpacesList.get(index-1);
if (previousRectangle != null && location.y > (previousRectangle.getBottom().y))
{
tSpace = (TargetConnectionSpacingFigureEditPart)targetSpacesList.get(index);
}
parentEditPart = (ModelGroupEditPart)tSpace.getParent();
targetModelGroup = parentEditPart.getXSDModelGroup();
break;
}
// if (location.y < (rectangle.getCenter().y))
// {
// nextChildRefEditPart = childGraphNodeEditPart;
// TargetConnectionSpacingFigureEditPart previousSpace = null;
// for (Iterator s = targetSpacesList.iterator(); s.hasNext(); )
// {
// TargetConnectionSpacingFigureEditPart tSpace = (TargetConnectionSpacingFigureEditPart) s.next();
// Rectangle tRect = tSpace.getFigure().getBounds();
// if (location.y < (tRect.getCenter().y + tRect.height/2))
// {
// parentEditPart = (ModelGroupEditPart)tSpace.getParent();
// targetModelGroup = parentEditPart.getXSDModelGroup();
// break;
// }
// previousSpace = tSpace;
// }
// if (parentEditPart != null)
// break;
// }
}
else
{
// This is the annotation edit part
}
}
List editPartsList = request.getEditParts();
List concreteComponentList = new ArrayList(editPartsList.size());
for (Iterator i = editPartsList.iterator(); i.hasNext(); )
{
EditPart editPart = (EditPart)i.next();
concreteComponentList.add((XSDConcreteComponent) ((XSDBaseAdapter)editPart.getModel()).getTarget());
}
XSDConcreteComponent previousRefComponent = null, nextRefComponent = null;
if (nextChildRefEditPart != null)
{
if (nextChildRefEditPart.getModel() instanceof XSDBaseAdapter)
{
nextRefComponent = (XSDConcreteComponent)((XSDBaseAdapter)nextChildRefEditPart.getModel()).getTarget();
}
}
if (previousChildRefEditPart != null)
{
if (previousChildRefEditPart.getModel() instanceof XSDBaseAdapter)
{
previousRefComponent = (XSDConcreteComponent)((XSDBaseAdapter)previousChildRefEditPart.getModel()).getTarget();
}
}
System.out.println(previousRefComponent + "\n " + nextRefComponent);
action = new MoveAction(targetModelGroup, concreteComponentList, previousRefComponent, nextRefComponent);
canExecute = action.canMove();
}
}
}
| public DragAndDropCommand(EditPartViewer viewer, ChangeBoundsRequest request)
{
this.viewer = viewer;
this.request = request;
location = request.getLocation();
target = viewer.findObjectAt(location);
if (viewer instanceof ScrollingGraphicalViewer)
{
ScrollingGraphicalViewer sgv = (ScrollingGraphicalViewer)viewer;
Point p = ((FigureCanvas)sgv.getControl()).getViewport().getViewLocation();
location.y += p.y;
location.x += p.x;
}
List list = request.getEditParts();
if (list.size() > 0 && target instanceof BaseFieldEditPart)
{
BaseFieldEditPart baseFieldEditPart = (BaseFieldEditPart)target;
XSDModelGroup targetModelGroup = null;
modelGroupsList.clear();
targetSpacesList.clear();
calculateModelGroupList();
List modelGroups = new ArrayList(modelGroupsList.size());
for (Iterator i = modelGroupsList.iterator(); i.hasNext(); )
{
ModelGroupEditPart editPart = (ModelGroupEditPart)i.next();
modelGroups.add(editPart.getXSDModelGroup());
}
EditPart compartment = baseFieldEditPart.getParent();
parentEditPart = null;
if (compartment != null)
{
List l = compartment.getChildren();
Rectangle rectangle = new Rectangle(0, 0, 0, 0), previousRectangle = new Rectangle(0,0,0,0);
int index = -1;
BaseFieldEditPart childGraphNodeEditPart = null;
for (Iterator i = l.iterator(); i.hasNext(); )
{
EditPart child = (EditPart)i.next();
if (child instanceof BaseFieldEditPart)
{
index ++;
previousChildRefEditPart = childGraphNodeEditPart;
childGraphNodeEditPart = (BaseFieldEditPart)child;
if (previousChildRefEditPart != null)
{
previousRectangle = previousChildRefEditPart.getFigure().getBounds();
}
rectangle = childGraphNodeEditPart.getFigure().getBounds();
if (location.y < (rectangle.getCenter().y))
{
nextChildRefEditPart = childGraphNodeEditPart;
TargetConnectionSpacingFigureEditPart tSpace = (TargetConnectionSpacingFigureEditPart)targetSpacesList.get(index-1);
if (previousRectangle != null && location.y > (previousRectangle.getBottom().y))
{
tSpace = (TargetConnectionSpacingFigureEditPart)targetSpacesList.get(index);
}
parentEditPart = (ModelGroupEditPart)tSpace.getParent();
targetModelGroup = parentEditPart.getXSDModelGroup();
break;
}
// if (location.y < (rectangle.getCenter().y))
// {
// nextChildRefEditPart = childGraphNodeEditPart;
// TargetConnectionSpacingFigureEditPart previousSpace = null;
// for (Iterator s = targetSpacesList.iterator(); s.hasNext(); )
// {
// TargetConnectionSpacingFigureEditPart tSpace = (TargetConnectionSpacingFigureEditPart) s.next();
// Rectangle tRect = tSpace.getFigure().getBounds();
// if (location.y < (tRect.getCenter().y + tRect.height/2))
// {
// parentEditPart = (ModelGroupEditPart)tSpace.getParent();
// targetModelGroup = parentEditPart.getXSDModelGroup();
// break;
// }
// previousSpace = tSpace;
// }
// if (parentEditPart != null)
// break;
// }
}
else
{
// This is the annotation edit part
}
}
List editPartsList = request.getEditParts();
List concreteComponentList = new ArrayList(editPartsList.size());
for (Iterator i = editPartsList.iterator(); i.hasNext(); )
{
EditPart editPart = (EditPart)i.next();
concreteComponentList.add((XSDConcreteComponent) ((XSDBaseAdapter)editPart.getModel()).getTarget());
}
XSDConcreteComponent previousRefComponent = null, nextRefComponent = null;
if (nextChildRefEditPart != null)
{
if (nextChildRefEditPart.getModel() instanceof XSDBaseAdapter)
{
nextRefComponent = (XSDConcreteComponent)((XSDBaseAdapter)nextChildRefEditPart.getModel()).getTarget();
}
}
if (previousChildRefEditPart != null)
{
if (previousChildRefEditPart.getModel() instanceof XSDBaseAdapter)
{
previousRefComponent = (XSDConcreteComponent)((XSDBaseAdapter)previousChildRefEditPart.getModel()).getTarget();
}
}
// System.out.println(previousRefComponent + "\n " + nextRefComponent);
action = new MoveAction(targetModelGroup, concreteComponentList, previousRefComponent, nextRefComponent);
canExecute = action.canMove();
}
}
}
|
diff --git a/phone/com/android/internal/policy/impl/PhoneWindowManager.java b/phone/com/android/internal/policy/impl/PhoneWindowManager.java
index 2143f52..2f9faae 100755
--- a/phone/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/phone/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -1,2236 +1,2242 @@
/*
* Copyright (C) 2006 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.internal.policy.impl;
import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.IStatusBar;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.Rect;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.LocalPowerManager;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.Vibrator;
import android.provider.Settings;
import com.android.internal.policy.PolicyManager;
import com.android.internal.telephony.ITelephony;
import android.util.Config;
import android.util.EventLog;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.IWindowManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowOrientationListener;
import android.view.RawInputEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD;
import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
import static android.view.WindowManager.LayoutParams.TYPE_PHONE;
import static android.view.WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
import static android.view.WindowManager.LayoutParams.TYPE_SEARCH_BAR;
import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
import android.view.WindowManagerImpl;
import android.view.WindowManagerPolicy;
import android.view.WindowManagerPolicy.WindowState;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.media.IAudioService;
import android.media.AudioManager;
/**
* WindowManagerPolicy implementation for the Android phone UI. This
* introduces a new method suffix, Lp, for an internal lock of the
* PhoneWindowManager. This is used to protect some internal state, and
* can be acquired with either thw Lw and Li lock held, so has the restrictions
* of both of those when held.
*/
public class PhoneWindowManager implements WindowManagerPolicy {
static final String TAG = "WindowManager";
static final boolean DEBUG = false;
static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
static final boolean DEBUG_LAYOUT = false;
static final boolean SHOW_STARTING_ANIMATIONS = true;
static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
// wallpaper is at the bottom, though the window manager may move it.
static final int WALLPAPER_LAYER = 2;
static final int APPLICATION_LAYER = 2;
static final int PHONE_LAYER = 3;
static final int SEARCH_BAR_LAYER = 4;
static final int STATUS_BAR_PANEL_LAYER = 5;
// toasts and the plugged-in battery thing
static final int TOAST_LAYER = 6;
static final int STATUS_BAR_LAYER = 7;
// SIM errors and unlock. Not sure if this really should be in a high layer.
static final int PRIORITY_PHONE_LAYER = 8;
// like the ANR / app crashed dialogs
static final int SYSTEM_ALERT_LAYER = 9;
// system-level error dialogs
static final int SYSTEM_ERROR_LAYER = 10;
// on-screen keyboards and other such input method user interfaces go here.
static final int INPUT_METHOD_LAYER = 11;
// on-screen keyboards and other such input method user interfaces go here.
static final int INPUT_METHOD_DIALOG_LAYER = 12;
// the keyguard; nothing on top of these can take focus, since they are
// responsible for power management when displayed.
static final int KEYGUARD_LAYER = 13;
static final int KEYGUARD_DIALOG_LAYER = 14;
// things in here CAN NOT take focus, but are shown on top of everything else.
static final int SYSTEM_OVERLAY_LAYER = 15;
static final int APPLICATION_MEDIA_SUBLAYER = -2;
static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
static final int APPLICATION_PANEL_SUBLAYER = 1;
static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
static final float SLIDE_TOUCH_EVENT_SIZE_LIMIT = 0.6f;
// Debugging: set this to have the system act like there is no hard keyboard.
static final boolean KEYBOARD_ALWAYS_HIDDEN = false;
static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
final Object mLock = new Object();
Context mContext;
IWindowManager mWindowManager;
LocalPowerManager mPowerManager;
Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
// Vibrator pattern for haptic feedback of a long press.
long[] mLongPressVibePattern;
// Vibrator pattern for haptic feedback of virtual key press.
long[] mVirtualKeyVibePattern;
// Vibrator pattern for haptic feedback during boot when safe mode is disabled.
long[] mSafeModeDisabledVibePattern;
// Vibrator pattern for haptic feedback during boot when safe mode is enabled.
long[] mSafeModeEnabledVibePattern;
/** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
boolean mEnableShiftMenuBugReports = false;
boolean mSafeMode;
WindowState mStatusBar = null;
WindowState mKeyguard = null;
KeyguardViewMediator mKeyguardMediator;
GlobalActions mGlobalActions;
boolean mShouldTurnOffOnKeyUp;
RecentApplicationsDialog mRecentAppsDialog;
Handler mHandler;
final IntentFilter mBatteryStatusFilter = new IntentFilter();
boolean mLidOpen;
int mPlugged;
boolean mRegisteredBatteryReceiver;
int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
int mLidOpenRotation;
int mCarDockRotation;
int mDeskDockRotation;
int mCarDockKeepsScreenOn;
int mDeskDockKeepsScreenOn;
boolean mCarDockEnablesAccelerometer;
boolean mDeskDockEnablesAccelerometer;
int mLidKeyboardAccessibility;
int mLidNavigationAccessibility;
boolean mScreenOn = false;
boolean mOrientationSensorEnabled = false;
int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
static final int DEFAULT_ACCELEROMETER_ROTATION = 0;
int mAccelerometerDefault = DEFAULT_ACCELEROMETER_ROTATION;
boolean mHasSoftInput = false;
// The current size of the screen.
int mW, mH;
// During layout, the current screen borders with all outer decoration
// (status bar, input method dock) accounted for.
int mCurLeft, mCurTop, mCurRight, mCurBottom;
// During layout, the frame in which content should be displayed
// to the user, accounting for all screen decoration except for any
// space they deem as available for other content. This is usually
// the same as mCur*, but may be larger if the screen decor has supplied
// content insets.
int mContentLeft, mContentTop, mContentRight, mContentBottom;
// During layout, the current screen borders along with input method
// windows are placed.
int mDockLeft, mDockTop, mDockRight, mDockBottom;
// During layout, the layer at which the doc window is placed.
int mDockLayer;
static final Rect mTmpParentFrame = new Rect();
static final Rect mTmpDisplayFrame = new Rect();
static final Rect mTmpContentFrame = new Rect();
static final Rect mTmpVisibleFrame = new Rect();
WindowState mTopFullscreenOpaqueWindowState;
boolean mForceStatusBar;
boolean mHideLockScreen;
boolean mDismissKeyguard;
boolean mHomePressed;
Intent mHomeIntent;
Intent mCarDockIntent;
Intent mDeskDockIntent;
boolean mSearchKeyPressed;
boolean mConsumeSearchKeyUp;
static final int ENDCALL_HOME = 0x1;
static final int ENDCALL_SLEEPS = 0x2;
static final int DEFAULT_ENDCALL_BEHAVIOR = ENDCALL_SLEEPS;
int mEndcallBehavior;
int mLandscapeRotation = -1;
int mPortraitRotation = -1;
// Nothing to see here, move along...
int mFancyRotationAnimation;
ShortcutManager mShortcutManager;
PowerManager.WakeLock mBroadcastWakeLock;
PowerManager.WakeLock mDockWakeLock;
class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.END_BUTTON_BEHAVIOR), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.ACCELEROMETER_ROTATION), false, this);
resolver.registerContentObserver(Settings.Secure.getUriFor(
Settings.Secure.DEFAULT_INPUT_METHOD), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
"fancy_rotation_anim"), false, this);
update();
}
@Override public void onChange(boolean selfChange) {
update();
try {
mWindowManager.setRotation(USE_LAST_ROTATION, false,
mFancyRotationAnimation);
} catch (RemoteException e) {
// Ignore
}
}
public void update() {
ContentResolver resolver = mContext.getContentResolver();
boolean updateRotation = false;
synchronized (mLock) {
mEndcallBehavior = Settings.System.getInt(resolver,
Settings.System.END_BUTTON_BEHAVIOR, DEFAULT_ENDCALL_BEHAVIOR);
mFancyRotationAnimation = Settings.System.getInt(resolver,
"fancy_rotation_anim", 0) != 0 ? 0x80 : 0;
int accelerometerDefault = Settings.System.getInt(resolver,
Settings.System.ACCELEROMETER_ROTATION, DEFAULT_ACCELEROMETER_ROTATION);
if (mAccelerometerDefault != accelerometerDefault) {
mAccelerometerDefault = accelerometerDefault;
updateOrientationListenerLp();
}
String imId = Settings.Secure.getString(resolver,
Settings.Secure.DEFAULT_INPUT_METHOD);
boolean hasSoftInput = imId != null && imId.length() > 0;
if (mHasSoftInput != hasSoftInput) {
mHasSoftInput = hasSoftInput;
updateRotation = true;
}
}
if (updateRotation) {
updateRotation(0);
}
}
}
class MyOrientationListener extends WindowOrientationListener {
MyOrientationListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int rotation) {
// Send updates based on orientation value
if (localLOGV) Log.v(TAG, "onOrientationChanged, rotation changed to " +rotation);
try {
mWindowManager.setRotation(rotation, false,
mFancyRotationAnimation);
} catch (RemoteException e) {
// Ignore
}
}
}
MyOrientationListener mOrientationListener;
boolean useSensorForOrientationLp(int appOrientation) {
// The app says use the sensor.
if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR) {
return true;
}
// The user preference says we can rotate, and the app is willing to rotate.
if (mAccelerometerDefault != 0 &&
(appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
|| appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)) {
return true;
}
// We're in a dock that has a rotation affinity, an the app is willing to rotate.
if ((mCarDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_CAR)
|| (mDeskDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_DESK)) {
// Note we override the nosensor flag here.
if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
|| appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
|| appOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
return true;
}
}
// Else, don't use the sensor.
return false;
}
/*
* We always let the sensor be switched on by default except when
* the user has explicitly disabled sensor based rotation or when the
* screen is switched off.
*/
boolean needSensorRunningLp() {
if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR) {
// If the application has explicitly requested to follow the
// orientation, then we need to turn the sensor or.
return true;
}
if ((mCarDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_CAR) ||
(mDeskDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_DESK)) {
// enable accelerometer if we are docked in a dock that enables accelerometer
// orientation management,
return true;
}
if (mAccelerometerDefault == 0) {
// If the setting for using the sensor by default is enabled, then
// we will always leave it on. Note that the user could go to
// a window that forces an orientation that does not use the
// sensor and in theory we could turn it off... however, when next
// turning it on we won't have a good value for the current
// orientation for a little bit, which can cause orientation
// changes to lag, so we'd like to keep it always on. (It will
// still be turned off when the screen is off.)
return false;
}
return true;
}
/*
* Various use cases for invoking this function
* screen turning off, should always disable listeners if already enabled
* screen turned on and current app has sensor based orientation, enable listeners
* if not already enabled
* screen turned on and current app does not have sensor orientation, disable listeners if
* already enabled
* screen turning on and current app has sensor based orientation, enable listeners if needed
* screen turning on and current app has nosensor based orientation, do nothing
*/
void updateOrientationListenerLp() {
if (!mOrientationListener.canDetectOrientation()) {
// If sensor is turned off or nonexistent for some reason
return;
}
//Could have been invoked due to screen turning on or off or
//change of the currently visible window's orientation
if (localLOGV) Log.v(TAG, "Screen status="+mScreenOn+
", current orientation="+mCurrentAppOrientation+
", SensorEnabled="+mOrientationSensorEnabled);
boolean disable = true;
if (mScreenOn) {
if (needSensorRunningLp()) {
disable = false;
//enable listener if not already enabled
if (!mOrientationSensorEnabled) {
mOrientationListener.enable();
if(localLOGV) Log.v(TAG, "Enabling listeners");
mOrientationSensorEnabled = true;
}
}
}
//check if sensors need to be disabled
if (disable && mOrientationSensorEnabled) {
mOrientationListener.disable();
if(localLOGV) Log.v(TAG, "Disabling listeners");
mOrientationSensorEnabled = false;
}
}
Runnable mPowerLongPress = new Runnable() {
public void run() {
mShouldTurnOffOnKeyUp = false;
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
showGlobalActionsDialog();
}
};
void showGlobalActionsDialog() {
if (mGlobalActions == null) {
mGlobalActions = new GlobalActions(mContext);
}
final boolean keyguardShowing = mKeyguardMediator.isShowingAndNotHidden();
mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
if (keyguardShowing) {
// since it took two seconds of long press to bring this up,
// poke the wake lock so they have some time to see the dialog.
mKeyguardMediator.pokeWakelock();
}
}
boolean isDeviceProvisioned() {
return Settings.Secure.getInt(
mContext.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
}
/**
* When a home-key longpress expires, close other system windows and launch the recent apps
*/
Runnable mHomeLongPress = new Runnable() {
public void run() {
/*
* Eat the longpress so it won't dismiss the recent apps dialog when
* the user lets go of the home key
*/
mHomePressed = false;
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS);
showRecentAppsDialog();
}
};
/**
* Create (if necessary) and launch the recent apps dialog
*/
void showRecentAppsDialog() {
if (mRecentAppsDialog == null) {
mRecentAppsDialog = new RecentApplicationsDialog(mContext);
}
mRecentAppsDialog.show();
}
/** {@inheritDoc} */
public void init(Context context, IWindowManager windowManager,
LocalPowerManager powerManager) {
mContext = context;
mWindowManager = windowManager;
mPowerManager = powerManager;
mKeyguardMediator = new KeyguardViewMediator(context, this, powerManager);
mHandler = new Handler();
mOrientationListener = new MyOrientationListener(mContext);
SettingsObserver settingsObserver = new SettingsObserver(mHandler);
settingsObserver.observe();
mShortcutManager = new ShortcutManager(context, mHandler);
mShortcutManager.observe();
mHomeIntent = new Intent(Intent.ACTION_MAIN, null);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mCarDockIntent = new Intent(Intent.ACTION_MAIN, null);
mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK);
mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null);
mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK);
mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
mBroadcastWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"PhoneWindowManager.mBroadcastWakeLock");
mDockWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK,
"PhoneWindowManager.mDockWakeLock");
mDockWakeLock.setReferenceCounted(false);
mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable"));
mLidOpenRotation = readRotation(
com.android.internal.R.integer.config_lidOpenRotation);
mCarDockRotation = readRotation(
com.android.internal.R.integer.config_carDockRotation);
mDeskDockRotation = readRotation(
com.android.internal.R.integer.config_deskDockRotation);
mCarDockKeepsScreenOn = mContext.getResources().getInteger(
com.android.internal.R.integer.config_carDockKeepsScreenOn);
mDeskDockKeepsScreenOn = mContext.getResources().getInteger(
com.android.internal.R.integer.config_deskDockKeepsScreenOn);
mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_carDockEnablesAccelerometer);
mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_deskDockEnablesAccelerometer);
mLidKeyboardAccessibility = mContext.getResources().getInteger(
com.android.internal.R.integer.config_lidKeyboardAccessibility);
mLidNavigationAccessibility = mContext.getResources().getInteger(
com.android.internal.R.integer.config_lidNavigationAccessibility);
// register for battery events
mBatteryStatusFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mPlugged = 0;
updatePlugged(context.registerReceiver(null, mBatteryStatusFilter));
// register for dock events
context.registerReceiver(mDockReceiver, new IntentFilter(Intent.ACTION_DOCK_EVENT));
mVibrator = new Vibrator();
mLongPressVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_longPressVibePattern);
mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_virtualKeyVibePattern);
mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_safeModeDisabledVibePattern);
mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_safeModeEnabledVibePattern);
}
void updatePlugged(Intent powerIntent) {
if (localLOGV) Log.v(TAG, "New battery status: " + powerIntent.getExtras());
if (powerIntent != null) {
mPlugged = powerIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
if (localLOGV) Log.v(TAG, "PLUGGED: " + mPlugged);
}
}
private int readRotation(int resID) {
try {
int rotation = mContext.getResources().getInteger(resID);
switch (rotation) {
case 0:
return Surface.ROTATION_0;
case 90:
return Surface.ROTATION_90;
case 180:
return Surface.ROTATION_180;
case 270:
return Surface.ROTATION_270;
}
} catch (Resources.NotFoundException e) {
// fall through
}
return -1;
}
/** {@inheritDoc} */
public int checkAddPermission(WindowManager.LayoutParams attrs) {
int type = attrs.type;
if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
|| type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) {
return WindowManagerImpl.ADD_OKAY;
}
String permission = null;
switch (type) {
case TYPE_TOAST:
// XXX right now the app process has complete control over
// this... should introduce a token to let the system
// monitor/control what they are doing.
break;
case TYPE_INPUT_METHOD:
case TYPE_WALLPAPER:
// The window manager will check these.
break;
case TYPE_PHONE:
case TYPE_PRIORITY_PHONE:
case TYPE_SYSTEM_ALERT:
case TYPE_SYSTEM_ERROR:
case TYPE_SYSTEM_OVERLAY:
permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
break;
default:
permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
}
if (permission != null) {
if (mContext.checkCallingOrSelfPermission(permission)
!= PackageManager.PERMISSION_GRANTED) {
return WindowManagerImpl.ADD_PERMISSION_DENIED;
}
}
return WindowManagerImpl.ADD_OKAY;
}
public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
switch (attrs.type) {
case TYPE_SYSTEM_OVERLAY:
case TYPE_TOAST:
// These types of windows can't receive input events.
attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
break;
}
}
void readLidState() {
try {
int sw = mWindowManager.getSwitchState(RawInputEvent.SW_LID);
if (sw >= 0) {
mLidOpen = sw == 0;
}
} catch (RemoteException e) {
// Ignore
}
}
private int determineHiddenState(boolean lidOpen,
int mode, int hiddenValue, int visibleValue) {
switch (mode) {
case 1:
return lidOpen ? visibleValue : hiddenValue;
case 2:
return lidOpen ? hiddenValue : visibleValue;
}
return visibleValue;
}
/** {@inheritDoc} */
public void adjustConfigurationLw(Configuration config) {
readLidState();
final boolean lidOpen = !KEYBOARD_ALWAYS_HIDDEN && mLidOpen;
mPowerManager.setKeyboardVisibility(lidOpen);
config.hardKeyboardHidden = determineHiddenState(lidOpen,
mLidKeyboardAccessibility, Configuration.HARDKEYBOARDHIDDEN_YES,
Configuration.HARDKEYBOARDHIDDEN_NO);
config.navigationHidden = determineHiddenState(lidOpen,
mLidNavigationAccessibility, Configuration.NAVIGATIONHIDDEN_YES,
Configuration.NAVIGATIONHIDDEN_NO);
config.keyboardHidden = (config.hardKeyboardHidden
== Configuration.HARDKEYBOARDHIDDEN_NO || mHasSoftInput)
? Configuration.KEYBOARDHIDDEN_NO
: Configuration.KEYBOARDHIDDEN_YES;
}
public boolean isCheekPressedAgainstScreen(MotionEvent ev) {
if(ev.getSize() > SLIDE_TOUCH_EVENT_SIZE_LIMIT) {
return true;
}
int size = ev.getHistorySize();
for(int i = 0; i < size; i++) {
if(ev.getHistoricalSize(i) > SLIDE_TOUCH_EVENT_SIZE_LIMIT) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public int windowTypeToLayerLw(int type) {
if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
return APPLICATION_LAYER;
}
switch (type) {
case TYPE_STATUS_BAR:
return STATUS_BAR_LAYER;
case TYPE_STATUS_BAR_PANEL:
return STATUS_BAR_PANEL_LAYER;
case TYPE_SEARCH_BAR:
return SEARCH_BAR_LAYER;
case TYPE_PHONE:
return PHONE_LAYER;
case TYPE_KEYGUARD:
return KEYGUARD_LAYER;
case TYPE_KEYGUARD_DIALOG:
return KEYGUARD_DIALOG_LAYER;
case TYPE_SYSTEM_ALERT:
return SYSTEM_ALERT_LAYER;
case TYPE_SYSTEM_ERROR:
return SYSTEM_ERROR_LAYER;
case TYPE_INPUT_METHOD:
return INPUT_METHOD_LAYER;
case TYPE_INPUT_METHOD_DIALOG:
return INPUT_METHOD_DIALOG_LAYER;
case TYPE_SYSTEM_OVERLAY:
return SYSTEM_OVERLAY_LAYER;
case TYPE_PRIORITY_PHONE:
return PRIORITY_PHONE_LAYER;
case TYPE_TOAST:
return TOAST_LAYER;
case TYPE_WALLPAPER:
return WALLPAPER_LAYER;
}
Log.e(TAG, "Unknown window type: " + type);
return APPLICATION_LAYER;
}
/** {@inheritDoc} */
public int subWindowTypeToLayerLw(int type) {
switch (type) {
case TYPE_APPLICATION_PANEL:
case TYPE_APPLICATION_ATTACHED_DIALOG:
return APPLICATION_PANEL_SUBLAYER;
case TYPE_APPLICATION_MEDIA:
return APPLICATION_MEDIA_SUBLAYER;
case TYPE_APPLICATION_MEDIA_OVERLAY:
return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
case TYPE_APPLICATION_SUB_PANEL:
return APPLICATION_SUB_PANEL_SUBLAYER;
}
Log.e(TAG, "Unknown sub-window type: " + type);
return 0;
}
public int getMaxWallpaperLayer() {
return STATUS_BAR_LAYER;
}
public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) {
return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD;
}
public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
return attrs.type != WindowManager.LayoutParams.TYPE_STATUS_BAR
&& attrs.type != WindowManager.LayoutParams.TYPE_WALLPAPER;
}
/** {@inheritDoc} */
public View addStartingWindow(IBinder appToken, String packageName,
int theme, CharSequence nonLocalizedLabel,
int labelRes, int icon) {
if (!SHOW_STARTING_ANIMATIONS) {
return null;
}
if (packageName == null) {
return null;
}
Context context = mContext;
boolean setTheme = false;
//Log.i(TAG, "addStartingWindow " + packageName + ": nonLocalizedLabel="
// + nonLocalizedLabel + " theme=" + Integer.toHexString(theme));
if (theme != 0 || labelRes != 0) {
try {
context = context.createPackageContext(packageName, 0);
if (theme != 0) {
context.setTheme(theme);
setTheme = true;
}
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
if (!setTheme) {
context.setTheme(com.android.internal.R.style.Theme);
}
Window win = PolicyManager.makeNewWindow(context);
if (win.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowDisablePreview, false)) {
return null;
}
Resources r = context.getResources();
win.setTitle(r.getText(labelRes, nonLocalizedLabel));
win.setType(
WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
// Force the window flags: this is a fake window, so it is not really
// touchable or focusable by the user. We also add in the ALT_FOCUSABLE_IM
// flag because we do know that the next window will take input
// focus, so we want to get the IME window up on top of us right away.
win.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
win.setLayout(WindowManager.LayoutParams.FILL_PARENT,
WindowManager.LayoutParams.FILL_PARENT);
final WindowManager.LayoutParams params = win.getAttributes();
params.token = appToken;
params.packageName = packageName;
params.windowAnimations = win.getWindowStyle().getResourceId(
com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
params.setTitle("Starting " + packageName);
try {
WindowManagerImpl wm = (WindowManagerImpl)
context.getSystemService(Context.WINDOW_SERVICE);
View view = win.getDecorView();
if (win.isFloating()) {
// Whoops, there is no way to display an animation/preview
// of such a thing! After all that work... let's skip it.
// (Note that we must do this here because it is in
// getDecorView() where the theme is evaluated... maybe
// we should peek the floating attribute from the theme
// earlier.)
return null;
}
if (localLOGV) Log.v(
TAG, "Adding starting window for " + packageName
+ " / " + appToken + ": "
+ (view.getParent() != null ? view : null));
wm.addView(view, params);
// Only return the view if it was successfully added to the
// window manager... which we can tell by it having a parent.
return view.getParent() != null ? view : null;
} catch (WindowManagerImpl.BadTokenException e) {
// ignore
Log.w(TAG, appToken + " already running, starting window not displayed");
}
return null;
}
/** {@inheritDoc} */
public void removeStartingWindow(IBinder appToken, View window) {
// RuntimeException e = new RuntimeException();
// Log.i(TAG, "remove " + appToken + " " + window, e);
if (localLOGV) Log.v(
TAG, "Removing starting window for " + appToken + ": " + window);
if (window != null) {
WindowManagerImpl wm = (WindowManagerImpl) mContext.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(window);
}
}
/**
* Preflight adding a window to the system.
*
* Currently enforces that three window types are singletons:
* <ul>
* <li>STATUS_BAR_TYPE</li>
* <li>KEYGUARD_TYPE</li>
* </ul>
*
* @param win The window to be added
* @param attrs Information about the window to be added
*
* @return If ok, WindowManagerImpl.ADD_OKAY. If too many singletons, WindowManagerImpl.ADD_MULTIPLE_SINGLETON
*/
public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
switch (attrs.type) {
case TYPE_STATUS_BAR:
if (mStatusBar != null) {
return WindowManagerImpl.ADD_MULTIPLE_SINGLETON;
}
mStatusBar = win;
break;
case TYPE_KEYGUARD:
if (mKeyguard != null) {
return WindowManagerImpl.ADD_MULTIPLE_SINGLETON;
}
mKeyguard = win;
break;
}
return WindowManagerImpl.ADD_OKAY;
}
/** {@inheritDoc} */
public void removeWindowLw(WindowState win) {
if (mStatusBar == win) {
mStatusBar = null;
}
else if (mKeyguard == win) {
mKeyguard = null;
}
}
static final boolean PRINT_ANIM = false;
/** {@inheritDoc} */
public int selectAnimationLw(WindowState win, int transit) {
if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
+ ": transit=" + transit);
if (transit == TRANSIT_PREVIEW_DONE) {
if (win.hasAppShownWindows()) {
if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
return com.android.internal.R.anim.app_starting_exit;
}
}
return 0;
}
public Animation createForceHideEnterAnimation() {
return AnimationUtils.loadAnimation(mContext,
com.android.internal.R.anim.lock_screen_behind_enter);
}
static ITelephony getPhoneInterface() {
return ITelephony.Stub.asInterface(ServiceManager.checkService(Context.TELEPHONY_SERVICE));
}
static IAudioService getAudioInterface() {
return IAudioService.Stub.asInterface(ServiceManager.checkService(Context.AUDIO_SERVICE));
}
boolean keyguardOn() {
return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode();
}
private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
};
/** {@inheritDoc} */
public boolean interceptKeyTi(WindowState win, int code, int metaKeys, boolean down,
int repeatCount, int flags) {
boolean keyguardOn = keyguardOn();
if (false) {
Log.d(TAG, "interceptKeyTi code=" + code + " down=" + down + " repeatCount="
+ repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed);
}
// Clear a pending HOME longpress if the user releases Home
// TODO: This could probably be inside the next bit of logic, but that code
// turned out to be a bit fragile so I'm doing it here explicitly, for now.
if ((code == KeyEvent.KEYCODE_HOME) && !down) {
mHandler.removeCallbacks(mHomeLongPress);
}
// If the HOME button is currently being held, then we do special
// chording with it.
if (mHomePressed) {
// If we have released the home key, and didn't do anything else
// while it was pressed, then it is time to go home!
if (code == KeyEvent.KEYCODE_HOME) {
if (!down) {
mHomePressed = false;
if ((flags&KeyEvent.FLAG_CANCELED) == 0) {
// If an incoming call is ringing, HOME is totally disabled.
// (The user is already on the InCallScreen at this point,
// and his ONLY options are to answer or reject the call.)
boolean incomingRinging = false;
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
incomingRinging = phoneServ.isRinging();
} else {
Log.w(TAG, "Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "RemoteException from getPhoneInterface()", ex);
}
if (incomingRinging) {
Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
} else {
launchHomeFromHotKey();
}
} else {
Log.i(TAG, "Ignoring HOME; event canceled.");
}
}
}
return true;
}
// First we always handle the home key here, so applications
// can never break it, although if keyguard is on, we do let
// it handle it, because that gives us the correct 5 second
// timeout.
if (code == KeyEvent.KEYCODE_HOME) {
// If a system window has focus, then it doesn't make sense
// right now to interact with applications.
WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
if (attrs != null) {
final int type = attrs.type;
if (type == WindowManager.LayoutParams.TYPE_KEYGUARD
|| type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {
// the "app" is keyguard, so give it the key
return false;
}
final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
for (int i=0; i<typeCount; i++) {
if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
// don't do anything, but also don't pass it to the app
return true;
}
}
}
if (down && repeatCount == 0) {
if (!keyguardOn) {
mHandler.postDelayed(mHomeLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
}
mHomePressed = true;
}
return true;
} else if (code == KeyEvent.KEYCODE_MENU) {
// Hijack modified menu keys for debugging features
final int chordBug = KeyEvent.META_SHIFT_ON;
if (down && repeatCount == 0) {
if (mEnableShiftMenuBugReports && (metaKeys & chordBug) == chordBug) {
Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
mContext.sendOrderedBroadcast(intent, null);
return true;
} else if (SHOW_PROCESSES_ON_ALT_MENU &&
(metaKeys & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
Intent service = new Intent();
service.setClassName(mContext, "com.android.server.LoadAverageService");
ContentResolver res = mContext.getContentResolver();
boolean shown = Settings.System.getInt(
res, Settings.System.SHOW_PROCESSES, 0) != 0;
if (!shown) {
mContext.startService(service);
} else {
mContext.stopService(service);
}
Settings.System.putInt(
res, Settings.System.SHOW_PROCESSES, shown ? 0 : 1);
return true;
}
}
} else if (code == KeyEvent.KEYCODE_NOTIFICATION) {
if (down) {
// this key doesn't exist on current hardware, but if a device
// didn't have a touchscreen, it would want one of these to open
// the status bar.
IStatusBar sbs = IStatusBar.Stub.asInterface(ServiceManager.getService("statusbar"));
if (sbs != null) {
try {
sbs.toggle();
} catch (RemoteException e) {
// we're screwed anyway, since it's in this process
throw new RuntimeException(e);
}
}
}
return true;
} else if (code == KeyEvent.KEYCODE_SEARCH) {
if (down) {
if (repeatCount == 0) {
mSearchKeyPressed = true;
}
} else {
mSearchKeyPressed = false;
if (mConsumeSearchKeyUp) {
// Consume the up-event
mConsumeSearchKeyUp = false;
return true;
}
}
}
// Shortcuts are invoked through Search+key, so intercept those here
if (mSearchKeyPressed) {
if (down && repeatCount == 0 && !keyguardOn) {
Intent shortcutIntent = mShortcutManager.getIntent(code, metaKeys);
if (shortcutIntent != null) {
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(shortcutIntent);
/*
* We launched an app, so the up-event of the search key
* should be consumed
*/
mConsumeSearchKeyUp = true;
return true;
}
}
}
return false;
}
/**
* A home key -> launch home action was detected. Take the appropriate action
* given the situation with the keyguard.
*/
void launchHomeFromHotKey() {
if (mKeyguardMediator.isShowingAndNotHidden()) {
// don't launch home if keyguard showing
} else if (!mHideLockScreen && mKeyguardMediator.isInputRestricted()) {
// when in keyguard restricted mode, must first verify unlock
// before launching home
mKeyguardMediator.verifyUnlock(new OnKeyguardExitResult() {
public void onKeyguardExitResult(boolean success) {
if (success) {
try {
ActivityManagerNative.getDefault().stopAppSwitches();
} catch (RemoteException e) {
}
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
startDockOrHome();
}
}
});
} else {
// no keyguard stuff to worry about, just launch home!
try {
ActivityManagerNative.getDefault().stopAppSwitches();
} catch (RemoteException e) {
}
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
startDockOrHome();
}
}
public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
final int fl = attrs.flags;
if ((fl &
(FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
== (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
contentInset.set(mCurLeft, mCurTop, mW - mCurRight, mH - mCurBottom);
} else {
contentInset.setEmpty();
}
}
/** {@inheritDoc} */
public void beginLayoutLw(int displayWidth, int displayHeight) {
mW = displayWidth;
mH = displayHeight;
mDockLeft = mContentLeft = mCurLeft = 0;
mDockTop = mContentTop = mCurTop = 0;
mDockRight = mContentRight = mCurRight = displayWidth;
mDockBottom = mContentBottom = mCurBottom = displayHeight;
mDockLayer = 0x10000000;
mTopFullscreenOpaqueWindowState = null;
mForceStatusBar = false;
mHideLockScreen = false;
mDismissKeyguard = false;
// decide where the status bar goes ahead of time
if (mStatusBar != null) {
final Rect pf = mTmpParentFrame;
final Rect df = mTmpDisplayFrame;
final Rect vf = mTmpVisibleFrame;
pf.left = df.left = vf.left = 0;
pf.top = df.top = vf.top = 0;
pf.right = df.right = vf.right = displayWidth;
pf.bottom = df.bottom = vf.bottom = displayHeight;
mStatusBar.computeFrameLw(pf, df, vf, vf);
if (mStatusBar.isVisibleLw()) {
// If the status bar is hidden, we don't want to cause
// windows behind it to scroll.
mDockTop = mContentTop = mCurTop = mStatusBar.getFrameLw().bottom;
if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: mDockBottom="
+ mDockBottom + " mContentBottom="
+ mContentBottom + " mCurBottom=" + mCurBottom);
}
}
}
void setAttachedWindowFrames(WindowState win, int fl, int sim,
WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) {
if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
// Here's a special case: if this attached window is a panel that is
// above the dock window, and the window it is attached to is below
// the dock window, then the frames we computed for the window it is
// attached to can not be used because the dock is effectively part
// of the underlying window and the attached window is floating on top
// of the whole thing. So, we ignore the attached window and explicitly
// compute the frames that would be appropriate without the dock.
df.left = cf.left = vf.left = mDockLeft;
df.top = cf.top = vf.top = mDockTop;
df.right = cf.right = vf.right = mDockRight;
df.bottom = cf.bottom = vf.bottom = mDockBottom;
} else {
// The effective display frame of the attached window depends on
// whether it is taking care of insetting its content. If not,
// we need to use the parent's content frame so that the entire
// window is positioned within that content. Otherwise we can use
// the display frame and let the attached window take care of
// positioning its content appropriately.
if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) {
cf.set(attached.getDisplayFrameLw());
} else {
// If the window is resizing, then we want to base the content
// frame on our attached content frame to resize... however,
// things can be tricky if the attached window is NOT in resize
// mode, in which case its content frame will be larger.
// Ungh. So to deal with that, make sure the content frame
// we end up using is not covering the IM dock.
cf.set(attached.getContentFrameLw());
if (attached.getSurfaceLayer() < mDockLayer) {
if (cf.left < mContentLeft) cf.left = mContentLeft;
if (cf.top < mContentTop) cf.top = mContentTop;
if (cf.right > mContentRight) cf.right = mContentRight;
if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
}
}
df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
vf.set(attached.getVisibleFrameLw());
}
// The LAYOUT_IN_SCREEN flag is used to determine whether the attached
// window should be positioned relative to its parent or the entire
// screen.
pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
? attached.getFrameLw() : df);
}
/** {@inheritDoc} */
public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
WindowState attached) {
// we've already done the status bar
if (win == mStatusBar) {
return;
}
if (false) {
if ("com.google.android.youtube".equals(attrs.packageName)
&& attrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
Log.i(TAG, "GOTCHA!");
}
}
final int fl = attrs.flags;
final int sim = attrs.softInputMode;
final Rect pf = mTmpParentFrame;
final Rect df = mTmpDisplayFrame;
final Rect cf = mTmpContentFrame;
final Rect vf = mTmpVisibleFrame;
if (attrs.type == TYPE_INPUT_METHOD) {
pf.left = df.left = cf.left = vf.left = mDockLeft;
pf.top = df.top = cf.top = vf.top = mDockTop;
pf.right = df.right = cf.right = vf.right = mDockRight;
pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom;
// IM dock windows always go to the bottom of the screen.
attrs.gravity = Gravity.BOTTOM;
mDockLayer = win.getSurfaceLayer();
} else {
if ((fl &
(FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
== (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
// This is the case for a normal activity window: we want it
// to cover all of the screen space, and it can take care of
// moving its contents to account for screen decorations that
// intrude into that space.
if (attached != null) {
// If this window is attached to another, our display
// frame is the same as the one we are attached to.
setAttachedWindowFrames(win, fl, sim, attached, true, pf, df, cf, vf);
} else {
pf.left = df.left = 0;
pf.top = df.top = 0;
pf.right = df.right = mW;
pf.bottom = df.bottom = mH;
if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) {
cf.left = mDockLeft;
cf.top = mDockTop;
cf.right = mDockRight;
cf.bottom = mDockBottom;
} else {
cf.left = mContentLeft;
cf.top = mContentTop;
cf.right = mContentRight;
cf.bottom = mContentBottom;
}
vf.left = mCurLeft;
vf.top = mCurTop;
vf.right = mCurRight;
vf.bottom = mCurBottom;
}
} else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0) {
// A window that has requested to fill the entire screen just
// gets everything, period.
pf.left = df.left = cf.left = 0;
pf.top = df.top = cf.top = 0;
pf.right = df.right = cf.right = mW;
pf.bottom = df.bottom = cf.bottom = mH;
vf.left = mCurLeft;
vf.top = mCurTop;
vf.right = mCurRight;
vf.bottom = mCurBottom;
} else if (attached != null) {
// A child window should be placed inside of the same visible
// frame that its parent had.
setAttachedWindowFrames(win, fl, sim, attached, false, pf, df, cf, vf);
} else {
// Otherwise, a normal window must be placed inside the content
// of all screen decorations.
pf.left = mContentLeft;
pf.top = mContentTop;
pf.right = mContentRight;
pf.bottom = mContentBottom;
if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) {
df.left = cf.left = mDockLeft;
df.top = cf.top = mDockTop;
df.right = cf.right = mDockRight;
df.bottom = cf.bottom = mDockBottom;
} else {
df.left = cf.left = mContentLeft;
df.top = cf.top = mContentTop;
df.right = cf.right = mContentRight;
df.bottom = cf.bottom = mContentBottom;
}
vf.left = mCurLeft;
vf.top = mCurTop;
vf.right = mCurRight;
vf.bottom = mCurBottom;
}
}
if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) {
df.left = df.top = cf.left = cf.top = vf.left = vf.top = -10000;
df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
}
if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
+ ": sim=#" + Integer.toHexString(sim)
+ " pf=" + pf.toShortString() + " df=" + df.toShortString()
+ " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
if (false) {
if ("com.google.android.youtube".equals(attrs.packageName)
&& attrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
if (true || localLOGV) Log.v(TAG, "Computing frame of " + win +
": sim=#" + Integer.toHexString(sim)
+ " pf=" + pf.toShortString() + " df=" + df.toShortString()
+ " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
}
}
win.computeFrameLw(pf, df, cf, vf);
if (mTopFullscreenOpaqueWindowState == null &&
win.isVisibleOrBehindKeyguardLw()) {
if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
mForceStatusBar = true;
}
if (attrs.type >= FIRST_APPLICATION_WINDOW
&& attrs.type <= LAST_APPLICATION_WINDOW
&& win.fillsScreenLw(mW, mH, false, false)) {
if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win);
mTopFullscreenOpaqueWindowState = win;
if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
if (localLOGV) Log.v(TAG, "Setting mHideLockScreen to true by win " + win);
mHideLockScreen = true;
}
}
if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0) {
if (localLOGV) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win);
mDismissKeyguard = true;
}
}
// Dock windows carve out the bottom of the screen, so normal windows
// can't appear underneath them.
if (attrs.type == TYPE_INPUT_METHOD && !win.getGivenInsetsPendingLw()) {
int top = win.getContentFrameLw().top;
top += win.getGivenContentInsetsLw().top;
if (mContentBottom > top) {
mContentBottom = top;
}
top = win.getVisibleFrameLw().top;
top += win.getGivenVisibleInsetsLw().top;
if (mCurBottom > top) {
mCurBottom = top;
}
if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
+ mDockBottom + " mContentBottom="
+ mContentBottom + " mCurBottom=" + mCurBottom);
}
}
/** {@inheritDoc} */
public int finishLayoutLw() {
int changes = 0;
boolean hiding = false;
if (mStatusBar != null) {
if (localLOGV) Log.i(TAG, "force=" + mForceStatusBar
+ " top=" + mTopFullscreenOpaqueWindowState);
if (mForceStatusBar) {
if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
} else if (mTopFullscreenOpaqueWindowState != null) {
//Log.i(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
// + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
//Log.i(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs());
WindowManager.LayoutParams lp =
mTopFullscreenOpaqueWindowState.getAttrs();
boolean hideStatusBar =
(lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
if (hideStatusBar) {
if (DEBUG_LAYOUT) Log.v(TAG, "Hiding status bar");
if (mStatusBar.hideLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
hiding = true;
} else {
if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
}
}
}
// Hide the key guard if a visible window explicitly specifies that it wants to be displayed
// when the screen is locked
if (mKeyguard != null) {
if (localLOGV) Log.v(TAG, "finishLayoutLw::mHideKeyguard="+mHideLockScreen);
if (mDismissKeyguard && !mKeyguardMediator.isSecure()) {
if (mKeyguard.hideLw(false)) {
changes |= FINISH_LAYOUT_REDO_LAYOUT
| FINISH_LAYOUT_REDO_CONFIG
| FINISH_LAYOUT_REDO_WALLPAPER;
}
if (mKeyguardMediator.isShowing()) {
mHandler.post(new Runnable() {
public void run() {
mKeyguardMediator.keyguardDone(false, false);
}
});
}
} else if (mHideLockScreen) {
if (mKeyguard.hideLw(false)) {
mKeyguardMediator.setHidden(true);
changes |= FINISH_LAYOUT_REDO_LAYOUT
| FINISH_LAYOUT_REDO_CONFIG
| FINISH_LAYOUT_REDO_WALLPAPER;
}
} else {
if (mKeyguard.showLw(false)) {
mKeyguardMediator.setHidden(false);
changes |= FINISH_LAYOUT_REDO_LAYOUT
| FINISH_LAYOUT_REDO_CONFIG
| FINISH_LAYOUT_REDO_WALLPAPER;
}
}
}
if (changes != 0 && hiding) {
IStatusBar sbs = IStatusBar.Stub.asInterface(ServiceManager.getService("statusbar"));
if (sbs != null) {
try {
// Make sure the window shade is hidden.
sbs.deactivate();
} catch (RemoteException e) {
}
}
}
return changes;
}
/** {@inheritDoc} */
public void beginAnimationLw(int displayWidth, int displayHeight) {
}
/** {@inheritDoc} */
public void animatingWindowLw(WindowState win,
WindowManager.LayoutParams attrs) {
}
/** {@inheritDoc} */
public boolean finishAnimationLw() {
return false;
}
/** {@inheritDoc} */
public boolean preprocessInputEventTq(RawInputEvent event) {
switch (event.type) {
case RawInputEvent.EV_SW:
if (event.keycode == RawInputEvent.SW_LID) {
// lid changed state
mLidOpen = event.value == 0;
boolean awakeNow = mKeyguardMediator.doLidChangeTq(mLidOpen);
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
if (awakeNow) {
// If the lid opening and we don't have to keep the
// keyguard up, then we can turn on the screen
// immediately.
mKeyguardMediator.pokeWakelock();
} else if (keyguardIsShowingTq()) {
if (mLidOpen) {
// If we are opening the lid and not hiding the
// keyguard, then we need to have it turn on the
// screen once it is shown.
mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(
KeyEvent.KEYCODE_POWER);
}
} else {
// Light up the keyboard if we are sliding up.
if (mLidOpen) {
mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
LocalPowerManager.BUTTON_EVENT);
} else {
mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
LocalPowerManager.OTHER_EVENT);
}
}
}
}
return false;
}
/** {@inheritDoc} */
public boolean isAppSwitchKeyTqTiLwLi(int keycode) {
return keycode == KeyEvent.KEYCODE_HOME
|| keycode == KeyEvent.KEYCODE_ENDCALL;
}
/** {@inheritDoc} */
public boolean isMovementKeyTi(int keycode) {
switch (keycode) {
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
return true;
}
return false;
}
/**
* @return Whether a telephone call is in progress right now.
*/
boolean isInCall() {
final ITelephony phone = getPhoneInterface();
if (phone == null) {
Log.w(TAG, "couldn't get ITelephony reference");
return false;
}
try {
return phone.isOffhook();
} catch (RemoteException e) {
Log.w(TAG, "ITelephony.isOffhhook threw RemoteException " + e);
return false;
}
}
/**
* @return Whether music is being played right now.
*/
boolean isMusicActive() {
final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
if (am == null) {
Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
return false;
}
return am.isMusicActive();
}
/**
* Tell the audio service to adjust the volume appropriate to the event.
* @param keycode
*/
void handleVolumeKey(int stream, int keycode) {
final IAudioService audio = getAudioInterface();
if (audio == null) {
Log.w(TAG, "handleVolumeKey: couldn't get IAudioService reference");
return;
}
try {
// since audio is playing, we shouldn't have to hold a wake lock
// during the call, but we do it as a precaution for the rare possibility
// that the music stops right before we call this
mBroadcastWakeLock.acquire();
audio.adjustStreamVolume(stream,
keycode == KeyEvent.KEYCODE_VOLUME_UP
? AudioManager.ADJUST_RAISE
: AudioManager.ADJUST_LOWER,
0);
} catch (RemoteException e) {
Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
} finally {
mBroadcastWakeLock.release();
}
}
static boolean isMediaKey(int code) {
if (code == KeyEvent.KEYCODE_HEADSETHOOK ||
code == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE ||
code == KeyEvent.KEYCODE_MEDIA_STOP ||
code == KeyEvent.KEYCODE_MEDIA_NEXT ||
code == KeyEvent.KEYCODE_MEDIA_PREVIOUS ||
code == KeyEvent.KEYCODE_MEDIA_PREVIOUS ||
code == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) {
return true;
}
return false;
}
/** {@inheritDoc} */
public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) {
int result = ACTION_PASS_TO_USER;
final boolean isWakeKey = isWakeKeyTq(event);
- final boolean keyguardShowing = keyguardIsShowingTq();
+ // If screen is off then we treat the case where the keyguard is open but hidden
+ // the same as if it were open and in front.
+ // This will prevent any keys other than the power button from waking the screen
+ // when the keyguard is hidden by another activity.
+ final boolean keyguardActive = (screenIsOn ?
+ mKeyguardMediator.isShowingAndNotHidden() :
+ mKeyguardMediator.isShowing());
if (false) {
Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode
- + " screenIsOn=" + screenIsOn + " keyguardShowing=" + keyguardShowing);
+ + " screenIsOn=" + screenIsOn + " keyguardActive=" + keyguardActive);
}
- if (keyguardShowing) {
+ if (keyguardActive) {
if (screenIsOn) {
// when the screen is on, always give the event to the keyguard
result |= ACTION_PASS_TO_USER;
} else {
// otherwise, don't pass it to the user
result &= ~ACTION_PASS_TO_USER;
final boolean isKeyDown =
(event.type == RawInputEvent.EV_KEY) && (event.value != 0);
if (isWakeKey && isKeyDown) {
// tell the mediator about a wake key, it may decide to
// turn on the screen depending on whether the key is
// appropriate.
if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode)
&& (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
if (isInCall()) {
// if the keyguard didn't wake the device, we are in call, and
// it is a volume key, turn on the screen so that the user
// can more easily adjust the in call volume.
mKeyguardMediator.pokeWakelock();
} else if (isMusicActive()) {
// when keyguard is showing and screen off, we need
// to handle the volume key for music here
handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode);
}
}
}
}
} else if (!screenIsOn) {
// If we are in-call with screen off and keyguard is not showing,
// then handle the volume key ourselves.
// This is necessary because the phone app will disable the keyguard
// when the proximity sensor is in use.
if (isInCall() && event.type == RawInputEvent.EV_KEY &&
(event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
result &= ~ACTION_PASS_TO_USER;
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
}
if (isWakeKey) {
// a wake key has a sole purpose of waking the device; don't pass
// it to the user
result |= ACTION_POKE_USER_ACTIVITY;
result &= ~ACTION_PASS_TO_USER;
}
}
int type = event.type;
int code = event.keycode;
boolean down = event.value != 0;
if (type == RawInputEvent.EV_KEY) {
if (code == KeyEvent.KEYCODE_ENDCALL
|| code == KeyEvent.KEYCODE_POWER) {
if (down) {
boolean handled = false;
// key repeats are generated by the window manager, and we don't see them
// here, so unless the driver is doing something it shouldn't be, we know
// this is the real press event.
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
try {
if (code == KeyEvent.KEYCODE_ENDCALL) {
handled = phoneServ.endCall();
} else if (code == KeyEvent.KEYCODE_POWER && phoneServ.isRinging()) {
// Pressing power during incoming call should silence the ringer
phoneServ.silenceRinger();
handled = true;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException" + ex);
}
} else {
Log.w(TAG, "!!! Unable to find ITelephony interface !!!");
}
// power button should turn off screen in addition to hanging up the phone
if ((handled && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) {
mShouldTurnOffOnKeyUp = false;
} else {
// only try to turn off the screen if we didn't already hang up
mShouldTurnOffOnKeyUp = true;
mHandler.postDelayed(mPowerLongPress,
ViewConfiguration.getGlobalActionKeyTimeout());
result &= ~ACTION_PASS_TO_USER;
}
} else {
mHandler.removeCallbacks(mPowerLongPress);
if (mShouldTurnOffOnKeyUp) {
mShouldTurnOffOnKeyUp = false;
boolean gohome = (mEndcallBehavior & ENDCALL_HOME) != 0;
boolean sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0;
- if (keyguardShowing
+ if (keyguardActive
|| (sleeps && !gohome)
|| (gohome && !goHome() && sleeps)) {
// they must already be on the keyguad or home screen,
// go to sleep instead
Log.d(TAG, "I'm tired mEndcallBehavior=0x"
+ Integer.toHexString(mEndcallBehavior));
result &= ~ACTION_POKE_USER_ACTIVITY;
result |= ACTION_GO_TO_SLEEP;
}
result &= ~ACTION_PASS_TO_USER;
}
}
} else if (isMediaKey(code)) {
// This key needs to be handled even if the screen is off.
// If others need to be handled while it's off, this is a reasonable
// pattern to follow.
if ((result & ACTION_PASS_TO_USER) == 0) {
// Only do this if we would otherwise not pass it to the user. In that
// case, the PhoneWindow class will do the same thing, except it will
// only do it if the showing app doesn't process the key on its own.
KeyEvent keyEvent = new KeyEvent(event.when, event.when,
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code, 0);
mBroadcastWakeLock.acquire();
mHandler.post(new PassHeadsetKey(keyEvent));
}
} else if (code == KeyEvent.KEYCODE_CALL) {
// If an incoming call is ringing, answer it!
// (We handle this key here, rather than in the InCallScreen, to make
// sure we'll respond to the key even if the InCallScreen hasn't come to
// the foreground yet.)
// We answer the call on the DOWN event, to agree with
// the "fallback" behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " CALL key-down while ringing: Answer the call!");
phoneServ.answerRingingCall();
// And *don't* pass this key thru to the current activity
// (which is presumably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "CALL button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex);
}
}
} else if ((code == KeyEvent.KEYCODE_VOLUME_UP)
|| (code == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// If an incoming call is ringing, either VOLUME key means
// "silence ringer". We handle these keys here, rather than
// in the InCallScreen, to make sure we'll respond to them
// even if the InCallScreen hasn't come to the foreground yet.
// Look for the DOWN event here, to agree with the "fallback"
// behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " VOLUME key-down while ringing: Silence ringer!");
// Silence the ringer. (It's safe to call this
// even if the ringer has already been silenced.)
phoneServ.silenceRinger();
// And *don't* pass this key thru to the current activity
// (which is probably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "VOLUME button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex);
}
}
}
}
return result;
}
class PassHeadsetKey implements Runnable {
KeyEvent mKeyEvent;
PassHeadsetKey(KeyEvent keyEvent) {
mKeyEvent = keyEvent;
}
public void run() {
if (ActivityManagerNative.isSystemReady()) {
Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
intent.putExtra(Intent.EXTRA_KEY_EVENT, mKeyEvent);
mContext.sendOrderedBroadcast(intent, null, mBroadcastDone,
mHandler, Activity.RESULT_OK, null, null);
}
}
}
BroadcastReceiver mBroadcastDone = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
mBroadcastWakeLock.release();
}
};
BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
updatePlugged(intent);
updateDockKeepingScreenOn();
}
};
BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
Intent.EXTRA_DOCK_STATE_UNDOCKED);
boolean watchBattery = mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
if (watchBattery != mRegisteredBatteryReceiver) {
mRegisteredBatteryReceiver = watchBattery;
if (watchBattery) {
updatePlugged(mContext.registerReceiver(mBatteryReceiver,
mBatteryStatusFilter));
} else {
mContext.unregisterReceiver(mBatteryReceiver);
}
}
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
updateDockKeepingScreenOn();
updateOrientationListenerLp();
}
};
/** {@inheritDoc} */
public boolean isWakeRelMovementTq(int device, int classes,
RawInputEvent event) {
// if it's tagged with one of the wake bits, it wakes up the device
return ((event.flags & (FLAG_WAKE | FLAG_WAKE_DROPPED)) != 0);
}
/** {@inheritDoc} */
public boolean isWakeAbsMovementTq(int device, int classes,
RawInputEvent event) {
// if it's tagged with one of the wake bits, it wakes up the device
return ((event.flags & (FLAG_WAKE | FLAG_WAKE_DROPPED)) != 0);
}
/**
* Given the current state of the world, should this key wake up the device?
*/
protected boolean isWakeKeyTq(RawInputEvent event) {
// There are not key maps for trackball devices, but we'd still
// like to have pressing it wake the device up, so force it here.
int keycode = event.keycode;
int flags = event.flags;
if (keycode == RawInputEvent.BTN_MOUSE) {
flags |= WindowManagerPolicy.FLAG_WAKE;
}
return (flags
& (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
}
/** {@inheritDoc} */
public void screenTurnedOff(int why) {
EventLog.writeEvent(70000, 0);
mKeyguardMediator.onScreenTurnedOff(why);
synchronized (mLock) {
mScreenOn = false;
updateOrientationListenerLp();
}
}
/** {@inheritDoc} */
public void screenTurnedOn() {
EventLog.writeEvent(70000, 1);
mKeyguardMediator.onScreenTurnedOn();
synchronized (mLock) {
mScreenOn = true;
updateOrientationListenerLp();
}
}
/** {@inheritDoc} */
public void enableKeyguard(boolean enabled) {
mKeyguardMediator.setKeyguardEnabled(enabled);
}
/** {@inheritDoc} */
public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
mKeyguardMediator.verifyUnlock(callback);
}
/** {@inheritDoc} */
public boolean keyguardIsShowingTq() {
return mKeyguardMediator.isShowingAndNotHidden();
}
/** {@inheritDoc} */
public boolean inKeyguardRestrictedKeyInputMode() {
return mKeyguardMediator.isInputRestricted();
}
void sendCloseSystemWindows() {
sendCloseSystemWindows(mContext, null);
}
void sendCloseSystemWindows(String reason) {
sendCloseSystemWindows(mContext, reason);
}
static void sendCloseSystemWindows(Context context, String reason) {
if (ActivityManagerNative.isSystemReady()) {
try {
ActivityManagerNative.getDefault().closeSystemDialogs(reason);
} catch (RemoteException e) {
}
}
}
public int rotationForOrientationLw(int orientation, int lastRotation,
boolean displayEnabled) {
if (mPortraitRotation < 0) {
// Initialize the rotation angles for each orientation once.
Display d = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
if (d.getWidth() > d.getHeight()) {
mPortraitRotation = Surface.ROTATION_90;
mLandscapeRotation = Surface.ROTATION_0;
} else {
mPortraitRotation = Surface.ROTATION_0;
mLandscapeRotation = Surface.ROTATION_90;
}
}
synchronized (mLock) {
switch (orientation) {
case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
//always return landscape if orientation set to landscape
return mLandscapeRotation;
case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
//always return portrait if orientation set to portrait
return mPortraitRotation;
}
// case for nosensor meaning ignore sensor and consider only lid
// or orientation sensor disabled
//or case.unspecified
if (mLidOpen) {
return mLidOpenRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
return mCarDockRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
return mDeskDockRotation;
} else {
if (useSensorForOrientationLp(orientation)) {
// If the user has enabled auto rotation by default, do it.
int curRotation = mOrientationListener.getCurrentRotation();
return curRotation >= 0 ? curRotation : lastRotation;
}
return Surface.ROTATION_0;
}
}
}
public boolean detectSafeMode() {
try {
int menuState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_MENU);
int sState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_S);
int dpadState = mWindowManager.getDPadKeycodeState(KeyEvent.KEYCODE_DPAD_CENTER);
int trackballState = mWindowManager.getTrackballScancodeState(RawInputEvent.BTN_MOUSE);
mSafeMode = menuState > 0 || sState > 0 || dpadState > 0 || trackballState > 0;
performHapticFeedbackLw(null, mSafeMode
? HapticFeedbackConstants.SAFE_MODE_ENABLED
: HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
if (mSafeMode) {
Log.i(TAG, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState
+ " dpad=" + dpadState + " trackball=" + trackballState + ")");
} else {
Log.i(TAG, "SAFE MODE not enabled");
}
return mSafeMode;
} catch (RemoteException e) {
// Doom! (it's also local)
throw new RuntimeException("window manager dead");
}
}
static long[] getLongIntArray(Resources r, int resid) {
int[] ar = r.getIntArray(resid);
if (ar == null) {
return null;
}
long[] out = new long[ar.length];
for (int i=0; i<ar.length; i++) {
out[i] = ar[i];
}
return out;
}
/** {@inheritDoc} */
public void systemReady() {
// tell the keyguard
mKeyguardMediator.onSystemReady();
android.os.SystemProperties.set("dev.bootcomplete", "1");
synchronized (mLock) {
updateOrientationListenerLp();
}
}
/** {@inheritDoc} */
public void enableScreenAfterBoot() {
readLidState();
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
}
void updateDockKeepingScreenOn() {
if (mPlugged != 0) {
if (localLOGV) Log.v(TAG, "Update: mDockState=" + mDockState
+ " mPlugged=" + mPlugged
+ " mCarDockKeepsScreenOn" + mCarDockKeepsScreenOn
+ " mDeskDockKeepsScreenOn" + mDeskDockKeepsScreenOn);
if (mDockState == Intent.EXTRA_DOCK_STATE_CAR
&& (mPlugged&mCarDockKeepsScreenOn) != 0) {
if (!mDockWakeLock.isHeld()) {
mDockWakeLock.acquire();
}
return;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK
&& (mPlugged&mDeskDockKeepsScreenOn) != 0) {
if (!mDockWakeLock.isHeld()) {
mDockWakeLock.acquire();
}
return;
}
}
if (mDockWakeLock.isHeld()) {
mDockWakeLock.release();
}
}
void updateRotation(int animFlags) {
mPowerManager.setKeyboardVisibility(mLidOpen);
int rotation = Surface.ROTATION_0;
if (mLidOpen) {
rotation = mLidOpenRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
rotation = mCarDockRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
rotation = mDeskDockRotation;
}
//if lid is closed orientation will be portrait
try {
//set orientation on WindowManager
mWindowManager.setRotation(rotation, true,
mFancyRotationAnimation | animFlags);
} catch (RemoteException e) {
// Ignore
}
}
/**
* Return an Intent to launch the currently active dock as home. Returns
* null if the standard home should be launched.
* @return
*/
Intent createHomeDockIntent() {
if (mDockState == Intent.EXTRA_DOCK_STATE_UNDOCKED) {
return null;
}
Intent intent;
if (mDockState == Intent.EXTRA_DOCK_STATE_CAR) {
intent = mCarDockIntent;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
intent = mDeskDockIntent;
} else {
Log.w(TAG, "Unknown dock state: " + mDockState);
return null;
}
ActivityInfo ai = intent.resolveActivityInfo(
mContext.getPackageManager(), PackageManager.GET_META_DATA);
if (ai == null) {
return null;
}
if (ai.metaData != null && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
intent = new Intent(intent);
intent.setClassName(ai.packageName, ai.name);
return intent;
}
return null;
}
void startDockOrHome() {
Intent dock = createHomeDockIntent();
if (dock != null) {
try {
mContext.startActivity(dock);
return;
} catch (ActivityNotFoundException e) {
}
}
mContext.startActivity(mHomeIntent);
}
/**
* goes to the home screen
* @return whether it did anything
*/
boolean goHome() {
if (false) {
// This code always brings home to the front.
try {
ActivityManagerNative.getDefault().stopAppSwitches();
} catch (RemoteException e) {
}
sendCloseSystemWindows();
startDockOrHome();
} else {
// This code brings home to the front or, if it is already
// at the front, puts the device to sleep.
try {
ActivityManagerNative.getDefault().stopAppSwitches();
sendCloseSystemWindows();
Intent dock = createHomeDockIntent();
if (dock != null) {
int result = ActivityManagerNative.getDefault()
.startActivity(null, dock,
dock.resolveTypeIfNeeded(mContext.getContentResolver()),
null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
return false;
}
}
int result = ActivityManagerNative.getDefault()
.startActivity(null, mHomeIntent,
mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
return false;
}
} catch (RemoteException ex) {
// bummer, the activity manager, which is in this process, is dead
}
}
return true;
}
public void setCurrentOrientationLw(int newOrientation) {
synchronized (mLock) {
if (newOrientation != mCurrentAppOrientation) {
mCurrentAppOrientation = newOrientation;
updateOrientationListenerLp();
}
}
}
public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
final boolean hapticsDisabled = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 0;
if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
return false;
}
switch (effectId) {
case HapticFeedbackConstants.LONG_PRESS:
mVibrator.vibrate(mLongPressVibePattern, -1);
return true;
case HapticFeedbackConstants.VIRTUAL_KEY:
mVibrator.vibrate(mVirtualKeyVibePattern, -1);
return true;
case HapticFeedbackConstants.SAFE_MODE_DISABLED:
mVibrator.vibrate(mSafeModeDisabledVibePattern, -1);
return true;
case HapticFeedbackConstants.SAFE_MODE_ENABLED:
mVibrator.vibrate(mSafeModeEnabledVibePattern, -1);
return true;
}
return false;
}
public void keyFeedbackFromInput(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& (event.getFlags()&KeyEvent.FLAG_VIRTUAL_HARD_KEY) != 0) {
performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
}
}
public void screenOnStoppedLw() {
if (!mKeyguardMediator.isShowingAndNotHidden() && mPowerManager.isScreenOn()) {
long curTime = SystemClock.uptimeMillis();
mPowerManager.userActivity(curTime, false, LocalPowerManager.OTHER_EVENT);
}
}
public boolean allowKeyRepeat() {
// disable key repeat when screen is off
return mScreenOn;
}
}
| false | true | public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) {
int result = ACTION_PASS_TO_USER;
final boolean isWakeKey = isWakeKeyTq(event);
final boolean keyguardShowing = keyguardIsShowingTq();
if (false) {
Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode
+ " screenIsOn=" + screenIsOn + " keyguardShowing=" + keyguardShowing);
}
if (keyguardShowing) {
if (screenIsOn) {
// when the screen is on, always give the event to the keyguard
result |= ACTION_PASS_TO_USER;
} else {
// otherwise, don't pass it to the user
result &= ~ACTION_PASS_TO_USER;
final boolean isKeyDown =
(event.type == RawInputEvent.EV_KEY) && (event.value != 0);
if (isWakeKey && isKeyDown) {
// tell the mediator about a wake key, it may decide to
// turn on the screen depending on whether the key is
// appropriate.
if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode)
&& (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
if (isInCall()) {
// if the keyguard didn't wake the device, we are in call, and
// it is a volume key, turn on the screen so that the user
// can more easily adjust the in call volume.
mKeyguardMediator.pokeWakelock();
} else if (isMusicActive()) {
// when keyguard is showing and screen off, we need
// to handle the volume key for music here
handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode);
}
}
}
}
} else if (!screenIsOn) {
// If we are in-call with screen off and keyguard is not showing,
// then handle the volume key ourselves.
// This is necessary because the phone app will disable the keyguard
// when the proximity sensor is in use.
if (isInCall() && event.type == RawInputEvent.EV_KEY &&
(event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
result &= ~ACTION_PASS_TO_USER;
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
}
if (isWakeKey) {
// a wake key has a sole purpose of waking the device; don't pass
// it to the user
result |= ACTION_POKE_USER_ACTIVITY;
result &= ~ACTION_PASS_TO_USER;
}
}
int type = event.type;
int code = event.keycode;
boolean down = event.value != 0;
if (type == RawInputEvent.EV_KEY) {
if (code == KeyEvent.KEYCODE_ENDCALL
|| code == KeyEvent.KEYCODE_POWER) {
if (down) {
boolean handled = false;
// key repeats are generated by the window manager, and we don't see them
// here, so unless the driver is doing something it shouldn't be, we know
// this is the real press event.
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
try {
if (code == KeyEvent.KEYCODE_ENDCALL) {
handled = phoneServ.endCall();
} else if (code == KeyEvent.KEYCODE_POWER && phoneServ.isRinging()) {
// Pressing power during incoming call should silence the ringer
phoneServ.silenceRinger();
handled = true;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException" + ex);
}
} else {
Log.w(TAG, "!!! Unable to find ITelephony interface !!!");
}
// power button should turn off screen in addition to hanging up the phone
if ((handled && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) {
mShouldTurnOffOnKeyUp = false;
} else {
// only try to turn off the screen if we didn't already hang up
mShouldTurnOffOnKeyUp = true;
mHandler.postDelayed(mPowerLongPress,
ViewConfiguration.getGlobalActionKeyTimeout());
result &= ~ACTION_PASS_TO_USER;
}
} else {
mHandler.removeCallbacks(mPowerLongPress);
if (mShouldTurnOffOnKeyUp) {
mShouldTurnOffOnKeyUp = false;
boolean gohome = (mEndcallBehavior & ENDCALL_HOME) != 0;
boolean sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0;
if (keyguardShowing
|| (sleeps && !gohome)
|| (gohome && !goHome() && sleeps)) {
// they must already be on the keyguad or home screen,
// go to sleep instead
Log.d(TAG, "I'm tired mEndcallBehavior=0x"
+ Integer.toHexString(mEndcallBehavior));
result &= ~ACTION_POKE_USER_ACTIVITY;
result |= ACTION_GO_TO_SLEEP;
}
result &= ~ACTION_PASS_TO_USER;
}
}
} else if (isMediaKey(code)) {
// This key needs to be handled even if the screen is off.
// If others need to be handled while it's off, this is a reasonable
// pattern to follow.
if ((result & ACTION_PASS_TO_USER) == 0) {
// Only do this if we would otherwise not pass it to the user. In that
// case, the PhoneWindow class will do the same thing, except it will
// only do it if the showing app doesn't process the key on its own.
KeyEvent keyEvent = new KeyEvent(event.when, event.when,
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code, 0);
mBroadcastWakeLock.acquire();
mHandler.post(new PassHeadsetKey(keyEvent));
}
} else if (code == KeyEvent.KEYCODE_CALL) {
// If an incoming call is ringing, answer it!
// (We handle this key here, rather than in the InCallScreen, to make
// sure we'll respond to the key even if the InCallScreen hasn't come to
// the foreground yet.)
// We answer the call on the DOWN event, to agree with
// the "fallback" behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " CALL key-down while ringing: Answer the call!");
phoneServ.answerRingingCall();
// And *don't* pass this key thru to the current activity
// (which is presumably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "CALL button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex);
}
}
} else if ((code == KeyEvent.KEYCODE_VOLUME_UP)
|| (code == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// If an incoming call is ringing, either VOLUME key means
// "silence ringer". We handle these keys here, rather than
// in the InCallScreen, to make sure we'll respond to them
// even if the InCallScreen hasn't come to the foreground yet.
// Look for the DOWN event here, to agree with the "fallback"
// behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " VOLUME key-down while ringing: Silence ringer!");
// Silence the ringer. (It's safe to call this
// even if the ringer has already been silenced.)
phoneServ.silenceRinger();
// And *don't* pass this key thru to the current activity
// (which is probably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "VOLUME button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex);
}
}
}
}
return result;
}
| public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) {
int result = ACTION_PASS_TO_USER;
final boolean isWakeKey = isWakeKeyTq(event);
// If screen is off then we treat the case where the keyguard is open but hidden
// the same as if it were open and in front.
// This will prevent any keys other than the power button from waking the screen
// when the keyguard is hidden by another activity.
final boolean keyguardActive = (screenIsOn ?
mKeyguardMediator.isShowingAndNotHidden() :
mKeyguardMediator.isShowing());
if (false) {
Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode
+ " screenIsOn=" + screenIsOn + " keyguardActive=" + keyguardActive);
}
if (keyguardActive) {
if (screenIsOn) {
// when the screen is on, always give the event to the keyguard
result |= ACTION_PASS_TO_USER;
} else {
// otherwise, don't pass it to the user
result &= ~ACTION_PASS_TO_USER;
final boolean isKeyDown =
(event.type == RawInputEvent.EV_KEY) && (event.value != 0);
if (isWakeKey && isKeyDown) {
// tell the mediator about a wake key, it may decide to
// turn on the screen depending on whether the key is
// appropriate.
if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode)
&& (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
if (isInCall()) {
// if the keyguard didn't wake the device, we are in call, and
// it is a volume key, turn on the screen so that the user
// can more easily adjust the in call volume.
mKeyguardMediator.pokeWakelock();
} else if (isMusicActive()) {
// when keyguard is showing and screen off, we need
// to handle the volume key for music here
handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode);
}
}
}
}
} else if (!screenIsOn) {
// If we are in-call with screen off and keyguard is not showing,
// then handle the volume key ourselves.
// This is necessary because the phone app will disable the keyguard
// when the proximity sensor is in use.
if (isInCall() && event.type == RawInputEvent.EV_KEY &&
(event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
result &= ~ACTION_PASS_TO_USER;
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
}
if (isWakeKey) {
// a wake key has a sole purpose of waking the device; don't pass
// it to the user
result |= ACTION_POKE_USER_ACTIVITY;
result &= ~ACTION_PASS_TO_USER;
}
}
int type = event.type;
int code = event.keycode;
boolean down = event.value != 0;
if (type == RawInputEvent.EV_KEY) {
if (code == KeyEvent.KEYCODE_ENDCALL
|| code == KeyEvent.KEYCODE_POWER) {
if (down) {
boolean handled = false;
// key repeats are generated by the window manager, and we don't see them
// here, so unless the driver is doing something it shouldn't be, we know
// this is the real press event.
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
try {
if (code == KeyEvent.KEYCODE_ENDCALL) {
handled = phoneServ.endCall();
} else if (code == KeyEvent.KEYCODE_POWER && phoneServ.isRinging()) {
// Pressing power during incoming call should silence the ringer
phoneServ.silenceRinger();
handled = true;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException" + ex);
}
} else {
Log.w(TAG, "!!! Unable to find ITelephony interface !!!");
}
// power button should turn off screen in addition to hanging up the phone
if ((handled && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) {
mShouldTurnOffOnKeyUp = false;
} else {
// only try to turn off the screen if we didn't already hang up
mShouldTurnOffOnKeyUp = true;
mHandler.postDelayed(mPowerLongPress,
ViewConfiguration.getGlobalActionKeyTimeout());
result &= ~ACTION_PASS_TO_USER;
}
} else {
mHandler.removeCallbacks(mPowerLongPress);
if (mShouldTurnOffOnKeyUp) {
mShouldTurnOffOnKeyUp = false;
boolean gohome = (mEndcallBehavior & ENDCALL_HOME) != 0;
boolean sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0;
if (keyguardActive
|| (sleeps && !gohome)
|| (gohome && !goHome() && sleeps)) {
// they must already be on the keyguad or home screen,
// go to sleep instead
Log.d(TAG, "I'm tired mEndcallBehavior=0x"
+ Integer.toHexString(mEndcallBehavior));
result &= ~ACTION_POKE_USER_ACTIVITY;
result |= ACTION_GO_TO_SLEEP;
}
result &= ~ACTION_PASS_TO_USER;
}
}
} else if (isMediaKey(code)) {
// This key needs to be handled even if the screen is off.
// If others need to be handled while it's off, this is a reasonable
// pattern to follow.
if ((result & ACTION_PASS_TO_USER) == 0) {
// Only do this if we would otherwise not pass it to the user. In that
// case, the PhoneWindow class will do the same thing, except it will
// only do it if the showing app doesn't process the key on its own.
KeyEvent keyEvent = new KeyEvent(event.when, event.when,
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code, 0);
mBroadcastWakeLock.acquire();
mHandler.post(new PassHeadsetKey(keyEvent));
}
} else if (code == KeyEvent.KEYCODE_CALL) {
// If an incoming call is ringing, answer it!
// (We handle this key here, rather than in the InCallScreen, to make
// sure we'll respond to the key even if the InCallScreen hasn't come to
// the foreground yet.)
// We answer the call on the DOWN event, to agree with
// the "fallback" behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " CALL key-down while ringing: Answer the call!");
phoneServ.answerRingingCall();
// And *don't* pass this key thru to the current activity
// (which is presumably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "CALL button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex);
}
}
} else if ((code == KeyEvent.KEYCODE_VOLUME_UP)
|| (code == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// If an incoming call is ringing, either VOLUME key means
// "silence ringer". We handle these keys here, rather than
// in the InCallScreen, to make sure we'll respond to them
// even if the InCallScreen hasn't come to the foreground yet.
// Look for the DOWN event here, to agree with the "fallback"
// behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " VOLUME key-down while ringing: Silence ringer!");
// Silence the ringer. (It's safe to call this
// even if the ringer has already been silenced.)
phoneServ.silenceRinger();
// And *don't* pass this key thru to the current activity
// (which is probably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "VOLUME button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex);
}
}
}
}
return result;
}
|
diff --git a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryAuthenticationProvider.java b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryAuthenticationProvider.java
index 47d4303..9cfb4f9 100644
--- a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryAuthenticationProvider.java
+++ b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryAuthenticationProvider.java
@@ -1,115 +1,117 @@
package hudson.plugins.active_directory;
import com4j.COM4J;
import com4j.Com4jObject;
import com4j.ComException;
import com4j.Variant;
import com4j.typelibs.activeDirectory.IADs;
import com4j.typelibs.activeDirectory.IADsGroup;
import com4j.typelibs.activeDirectory.IADsOpenDSObject;
import com4j.typelibs.activeDirectory.IADsUser;
import com4j.typelibs.ado20.ClassFactory;
import com4j.typelibs.ado20._Command;
import com4j.typelibs.ado20._Connection;
import com4j.typelibs.ado20._Recordset;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.providers.AuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* {@link AuthenticationProvider} with Active Directory, plus {@link UserDetailsService}
*
* @author Kohsuke Kawaguchi
*/
public class ActiveDirectoryAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider
implements UserDetailsService {
private final String defaultNamingContext;
/**
* ADO connection for searching Active Directory.
*/
private final _Connection con;
public ActiveDirectoryAuthenticationProvider() {
IADs rootDSE = COM4J.getObject(IADs.class, "LDAP://RootDSE", null);
defaultNamingContext = (String)rootDSE.get("defaultNamingContext");
LOGGER.info("Active Directory domain is "+defaultNamingContext);
con = ClassFactory.createConnection();
con.provider("ADsDSOObject");
con.open("Active Directory Provider",""/*default*/,""/*default*/,-1/*default*/);
}
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
// active directory authentication is not by comparing clear text password,
// so there's nothing to do here.
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
return retrieveUser(username,null);
}
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
_Command cmd = ClassFactory.createCommand();
cmd.activeConnection(con);
cmd.commandText("<LDAP://"+defaultNamingContext+">;(sAMAccountName="+username+");distinguishedName;subTree");
_Recordset rs = cmd.execute(null, Variant.MISSING, -1/*default*/);
if(rs.eof())
throw new UsernameNotFoundException("No such user: "+username);
String dn = rs.fields().item("distinguishedName").value().toString();
// now we got the DN of the user
IADsOpenDSObject dso = COM4J.getObject(IADsOpenDSObject.class,"LDAP:",null);
// turns out we don't need DN for authentication
// we can bind with the user name
// dso.openDSObject("LDAP://"+context,args[0],args[1],1);
// to do bind with DN as the user name, the flag must be 0
IADsUser usr;
try {
usr = (authentication==null
? dso.openDSObject("LDAP://"+dn, null, null, 0)
: dso.openDSObject("LDAP://"+dn, dn, password, 0))
.queryInterface(IADsUser.class);
} catch (ComException e) {
throw new BadCredentialsException("Incorrect password for "+username);
}
+ if (usr == null) // the user name was in fact a group
+ throw new UsernameNotFoundException("User not found: "+username);
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
for( Com4jObject g : usr.groups() ) {
IADsGroup grp = g.queryInterface(IADsGroup.class);
// cut "CN=" and make that the role name
groups.add(new GrantedAuthorityImpl(grp.name().substring(3)));
}
return new ActiveDirectoryUserDetail(
username, password,
!usr.accountDisabled(),
true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
}
private static final Logger LOGGER = Logger.getLogger(ActiveDirectoryAuthenticationProvider.class.getName());
}
| true | true | protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
_Command cmd = ClassFactory.createCommand();
cmd.activeConnection(con);
cmd.commandText("<LDAP://"+defaultNamingContext+">;(sAMAccountName="+username+");distinguishedName;subTree");
_Recordset rs = cmd.execute(null, Variant.MISSING, -1/*default*/);
if(rs.eof())
throw new UsernameNotFoundException("No such user: "+username);
String dn = rs.fields().item("distinguishedName").value().toString();
// now we got the DN of the user
IADsOpenDSObject dso = COM4J.getObject(IADsOpenDSObject.class,"LDAP:",null);
// turns out we don't need DN for authentication
// we can bind with the user name
// dso.openDSObject("LDAP://"+context,args[0],args[1],1);
// to do bind with DN as the user name, the flag must be 0
IADsUser usr;
try {
usr = (authentication==null
? dso.openDSObject("LDAP://"+dn, null, null, 0)
: dso.openDSObject("LDAP://"+dn, dn, password, 0))
.queryInterface(IADsUser.class);
} catch (ComException e) {
throw new BadCredentialsException("Incorrect password for "+username);
}
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
for( Com4jObject g : usr.groups() ) {
IADsGroup grp = g.queryInterface(IADsGroup.class);
// cut "CN=" and make that the role name
groups.add(new GrantedAuthorityImpl(grp.name().substring(3)));
}
return new ActiveDirectoryUserDetail(
username, password,
!usr.accountDisabled(),
true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
}
| protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
_Command cmd = ClassFactory.createCommand();
cmd.activeConnection(con);
cmd.commandText("<LDAP://"+defaultNamingContext+">;(sAMAccountName="+username+");distinguishedName;subTree");
_Recordset rs = cmd.execute(null, Variant.MISSING, -1/*default*/);
if(rs.eof())
throw new UsernameNotFoundException("No such user: "+username);
String dn = rs.fields().item("distinguishedName").value().toString();
// now we got the DN of the user
IADsOpenDSObject dso = COM4J.getObject(IADsOpenDSObject.class,"LDAP:",null);
// turns out we don't need DN for authentication
// we can bind with the user name
// dso.openDSObject("LDAP://"+context,args[0],args[1],1);
// to do bind with DN as the user name, the flag must be 0
IADsUser usr;
try {
usr = (authentication==null
? dso.openDSObject("LDAP://"+dn, null, null, 0)
: dso.openDSObject("LDAP://"+dn, dn, password, 0))
.queryInterface(IADsUser.class);
} catch (ComException e) {
throw new BadCredentialsException("Incorrect password for "+username);
}
if (usr == null) // the user name was in fact a group
throw new UsernameNotFoundException("User not found: "+username);
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
for( Com4jObject g : usr.groups() ) {
IADsGroup grp = g.queryInterface(IADsGroup.class);
// cut "CN=" and make that the role name
groups.add(new GrantedAuthorityImpl(grp.name().substring(3)));
}
return new ActiveDirectoryUserDetail(
username, password,
!usr.accountDisabled(),
true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
}
|
diff --git a/MIDIDriver/src/jp/kshoji/driver/midi/handler/MidiMessageCallback.java b/MIDIDriver/src/jp/kshoji/driver/midi/handler/MidiMessageCallback.java
index ea1bb75..c67f375 100644
--- a/MIDIDriver/src/jp/kshoji/driver/midi/handler/MidiMessageCallback.java
+++ b/MIDIDriver/src/jp/kshoji/driver/midi/handler/MidiMessageCallback.java
@@ -1,166 +1,168 @@
package jp.kshoji.driver.midi.handler;
import java.io.ByteArrayOutputStream;
import jp.kshoji.driver.midi.device.MidiInputDevice;
import jp.kshoji.driver.midi.listener.OnMidiInputEventListener;
import android.os.Handler.Callback;
import android.os.Message;
/**
* USB MIDI Message parser
*
* @author K.Shoji
*/
public final class MidiMessageCallback implements Callback {
private final OnMidiInputEventListener midiEventListener;
private final MidiInputDevice sender;
private ByteArrayOutputStream systemExclusive = null;
/**
* constructor
*
* @param device
* @param midiEventListener
*/
public MidiMessageCallback(final MidiInputDevice device, final OnMidiInputEventListener midiEventListener) {
this.midiEventListener = midiEventListener;
sender = device;
}
/*
* (non-Javadoc)
* @see android.os.Handler.Callback#handleMessage(android.os.Message)
*/
@Override
public boolean handleMessage(final Message msg) {
if (midiEventListener == null) {
return false;
}
byte[] read = (byte[]) msg.obj;
int cable;
int codeIndexNumber;
int byte1;
int byte2;
int byte3;
for (int i = 0; i < read.length; i += 4) {
cable = (read[i + 0] >> 4) & 0xf;
codeIndexNumber = read[i + 0] & 0xf;
byte1 = read[i + 1] & 0xff;
byte2 = read[i + 2] & 0xff;
byte3 = read[i + 3] & 0xff;
switch (codeIndexNumber) {
case 0:
midiEventListener.onMidiMiscellaneousFunctionCodes(sender, cable, byte1, byte2, byte3);
break;
case 1:
midiEventListener.onMidiCableEvents(sender, cable, byte1, byte2, byte3);
break;
case 2:
// system common message with 2 bytes
{
byte[] bytes = new byte[]{(byte) byte1, (byte) byte2};
midiEventListener.onMidiSystemCommonMessage(sender, cable, bytes);
}
break;
case 3:
// system common message with 3 bytes
{
byte[] bytes = new byte[]{(byte) byte1, (byte) byte2, (byte) byte3};
midiEventListener.onMidiSystemCommonMessage(sender, cable, bytes);
}
break;
case 4:
// sysex starts, and has next
synchronized (this) {
- systemExclusive = new ByteArrayOutputStream();
+ if (systemExclusive == null) {
+ systemExclusive = new ByteArrayOutputStream();
+ }
}
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
systemExclusive.write(byte3);
}
break;
case 5:
// system common message with 1byte
// sysex end with 1 byte
if (systemExclusive == null) {
byte[] bytes = new byte[]{(byte) byte1};
midiEventListener.onMidiSystemCommonMessage(sender, cable, bytes);
} else {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
midiEventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 6:
// sysex end with 2 bytes
if (systemExclusive != null) {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
midiEventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 7:
// sysex end with 3 bytes
if (systemExclusive != null) {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
systemExclusive.write(byte3);
midiEventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 8:
midiEventListener.onMidiNoteOff(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 9:
midiEventListener.onMidiNoteOn(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 10:
// poly key press
midiEventListener.onMidiPolyphonicAftertouch(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 11:
// control change
midiEventListener.onMidiControlChange(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 12:
// program change
midiEventListener.onMidiProgramChange(sender, cable, byte1 & 0xf, byte2);
break;
case 13:
// channel pressure
midiEventListener.onMidiChannelAftertouch(sender, cable, byte1 & 0xf, byte2);
break;
case 14:
// pitch bend
midiEventListener.onMidiPitchWheel(sender, cable, byte1 & 0xf, byte2 | (byte3 << 8));
break;
case 15:
// single byte
midiEventListener.onMidiSingleByte(sender, cable, byte1);
break;
default:
// do nothing.
break;
}
}
return false;
}
}
| true | true | public boolean handleMessage(final Message msg) {
if (midiEventListener == null) {
return false;
}
byte[] read = (byte[]) msg.obj;
int cable;
int codeIndexNumber;
int byte1;
int byte2;
int byte3;
for (int i = 0; i < read.length; i += 4) {
cable = (read[i + 0] >> 4) & 0xf;
codeIndexNumber = read[i + 0] & 0xf;
byte1 = read[i + 1] & 0xff;
byte2 = read[i + 2] & 0xff;
byte3 = read[i + 3] & 0xff;
switch (codeIndexNumber) {
case 0:
midiEventListener.onMidiMiscellaneousFunctionCodes(sender, cable, byte1, byte2, byte3);
break;
case 1:
midiEventListener.onMidiCableEvents(sender, cable, byte1, byte2, byte3);
break;
case 2:
// system common message with 2 bytes
{
byte[] bytes = new byte[]{(byte) byte1, (byte) byte2};
midiEventListener.onMidiSystemCommonMessage(sender, cable, bytes);
}
break;
case 3:
// system common message with 3 bytes
{
byte[] bytes = new byte[]{(byte) byte1, (byte) byte2, (byte) byte3};
midiEventListener.onMidiSystemCommonMessage(sender, cable, bytes);
}
break;
case 4:
// sysex starts, and has next
synchronized (this) {
systemExclusive = new ByteArrayOutputStream();
}
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
systemExclusive.write(byte3);
}
break;
case 5:
// system common message with 1byte
// sysex end with 1 byte
if (systemExclusive == null) {
byte[] bytes = new byte[]{(byte) byte1};
midiEventListener.onMidiSystemCommonMessage(sender, cable, bytes);
} else {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
midiEventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 6:
// sysex end with 2 bytes
if (systemExclusive != null) {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
midiEventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 7:
// sysex end with 3 bytes
if (systemExclusive != null) {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
systemExclusive.write(byte3);
midiEventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 8:
midiEventListener.onMidiNoteOff(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 9:
midiEventListener.onMidiNoteOn(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 10:
// poly key press
midiEventListener.onMidiPolyphonicAftertouch(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 11:
// control change
midiEventListener.onMidiControlChange(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 12:
// program change
midiEventListener.onMidiProgramChange(sender, cable, byte1 & 0xf, byte2);
break;
case 13:
// channel pressure
midiEventListener.onMidiChannelAftertouch(sender, cable, byte1 & 0xf, byte2);
break;
case 14:
// pitch bend
midiEventListener.onMidiPitchWheel(sender, cable, byte1 & 0xf, byte2 | (byte3 << 8));
break;
case 15:
// single byte
midiEventListener.onMidiSingleByte(sender, cable, byte1);
break;
default:
// do nothing.
break;
}
}
return false;
}
| public boolean handleMessage(final Message msg) {
if (midiEventListener == null) {
return false;
}
byte[] read = (byte[]) msg.obj;
int cable;
int codeIndexNumber;
int byte1;
int byte2;
int byte3;
for (int i = 0; i < read.length; i += 4) {
cable = (read[i + 0] >> 4) & 0xf;
codeIndexNumber = read[i + 0] & 0xf;
byte1 = read[i + 1] & 0xff;
byte2 = read[i + 2] & 0xff;
byte3 = read[i + 3] & 0xff;
switch (codeIndexNumber) {
case 0:
midiEventListener.onMidiMiscellaneousFunctionCodes(sender, cable, byte1, byte2, byte3);
break;
case 1:
midiEventListener.onMidiCableEvents(sender, cable, byte1, byte2, byte3);
break;
case 2:
// system common message with 2 bytes
{
byte[] bytes = new byte[]{(byte) byte1, (byte) byte2};
midiEventListener.onMidiSystemCommonMessage(sender, cable, bytes);
}
break;
case 3:
// system common message with 3 bytes
{
byte[] bytes = new byte[]{(byte) byte1, (byte) byte2, (byte) byte3};
midiEventListener.onMidiSystemCommonMessage(sender, cable, bytes);
}
break;
case 4:
// sysex starts, and has next
synchronized (this) {
if (systemExclusive == null) {
systemExclusive = new ByteArrayOutputStream();
}
}
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
systemExclusive.write(byte3);
}
break;
case 5:
// system common message with 1byte
// sysex end with 1 byte
if (systemExclusive == null) {
byte[] bytes = new byte[]{(byte) byte1};
midiEventListener.onMidiSystemCommonMessage(sender, cable, bytes);
} else {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
midiEventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 6:
// sysex end with 2 bytes
if (systemExclusive != null) {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
midiEventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 7:
// sysex end with 3 bytes
if (systemExclusive != null) {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
systemExclusive.write(byte3);
midiEventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 8:
midiEventListener.onMidiNoteOff(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 9:
midiEventListener.onMidiNoteOn(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 10:
// poly key press
midiEventListener.onMidiPolyphonicAftertouch(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 11:
// control change
midiEventListener.onMidiControlChange(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 12:
// program change
midiEventListener.onMidiProgramChange(sender, cable, byte1 & 0xf, byte2);
break;
case 13:
// channel pressure
midiEventListener.onMidiChannelAftertouch(sender, cable, byte1 & 0xf, byte2);
break;
case 14:
// pitch bend
midiEventListener.onMidiPitchWheel(sender, cable, byte1 & 0xf, byte2 | (byte3 << 8));
break;
case 15:
// single byte
midiEventListener.onMidiSingleByte(sender, cable, byte1);
break;
default:
// do nothing.
break;
}
}
return false;
}
|
diff --git a/src/ufly/frs/Search.java b/src/ufly/frs/Search.java
index a9a691c..0032fe9 100644
--- a/src/ufly/frs/Search.java
+++ b/src/ufly/frs/Search.java
@@ -1,191 +1,192 @@
package ufly.frs;
import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import ufly.entities.*;
@SuppressWarnings("serial")
public class Search extends UflyServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.sendRedirect("/");
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
// printParam(req,resp);
//remove old session variables from aborted bookings
HttpSession session = req.getSession();
session.setAttribute("departopt",null);
session.setAttribute("returnopt", null);
session.setAttribute("numPass", null);
req.setAttribute("origin", req.getParameter("origin"));
req.setAttribute("destination", req.getParameter("destination"));
req.setAttribute("departureDate", req.getParameter("departureDate"));
req.setAttribute("returnDate", req.getParameter("returnDate"));
String s = req.getParameter("oneWayOrReturn").toString();
s.toString();
req.setAttribute("oneWayOrReturn", req.getParameter("oneWayOrReturn"));
req.setAttribute("numPassengers",
(String) req.getParameter("numPassengers"));
Date departureDate = null;
Airport origin = null;
Date returnDate = null;
Airport destination = null;
SimpleDateFormat convertToDate = new SimpleDateFormat("MM-dd-yyyy");
String errorMessage=null;
if (req.getParameter("departureDate") != null) {
departureDate = convertToDate.parse(
req.getParameter("departureDate"), new ParsePosition(0));
}
if(departureDate == null){
errorMessage="Please provide a valid departure date";
}
if (req.getParameter("returnDate") != null) {
returnDate = convertToDate.parse(req.getParameter("returnDate"),
new ParsePosition(0));
}
- if (returnDate == null) {
+ if (returnDate == null ||
+ req.getParameter("oneWayOrReturn").equals("return")) {
//if there is no return date, pretend there is
returnDate = (Date) departureDate.clone();
- }else if (returnDate.before(departureDate)){
+ }else if (req.getParameter("oneWayOrReturn").equals("return") && returnDate.before(departureDate)){
errorMessage = "Return date must be after departure date";
}
try{
if (req.getParameter("origin") != null) {
origin = Airport.getAirportByCallSign(req.getParameter("origin"));
}
}catch(javax.jdo.JDOObjectNotFoundException e){
errorMessage = "No Airport with call sign "+req.getParameter("origin");
}
try{
if (req.getParameter("destination") != null) {
destination = Airport.getAirportByCallSign(req
.getParameter("destination"));
}
}catch(javax.jdo.JDOObjectNotFoundException e){
errorMessage = "No Airport with call sign "+req.getParameter("destination");
}
if (origin!=null && destination != null && origin.equals(destination)){
errorMessage = "origin and destination cannot be the same";
}
if( departureDate.before(new Date())){
errorMessage = "Cannot book flights in the past";
}
if(errorMessage!=null){
req.setAttribute("errorMsg",errorMessage);
req.getRequestDispatcher("/index.jsp").forward(req,resp);
return;
}
if (origin != null) {
Vector trips = getFlightsFromOrigToDestOnDate(origin, destination,
departureDate,Integer.valueOf(req.getParameter("numPassengers")));
req.setAttribute("thereTrips", trips);
trips = getFlightsFromOrigToDestOnDate(destination, origin,
returnDate,Integer.valueOf(req.getParameter("numPassengers")));
req.setAttribute("returnTrips", trips);
req.getRequestDispatcher("searchResults.jsp").forward(req, resp);
}
}
private Vector<Vector<HashMap<String, Object>>> getFlightsFromOrigToDestOnDate(
Airport origin, Airport destination, Date departureDate, Integer numPass) {
List<Flight> flights = Flight.getFlightsOriginDate(origin,
departureDate);
Vector<Vector<HashMap<String, Object>>> toRet = new Vector<Vector<HashMap<String, Object>>>();
Iterator<Flight> it = flights.iterator();
while (it.hasNext()) {
Flight f = it.next();
if (f.getSeatingArrangement().getAvailableSeats().size() <numPass){
continue;
}
if (f.getDestination().equals(destination))
// this flight goes right to the destination
{
Vector trip = new Vector<HashMap<String, Object>>(1);
HashMap flightAttributes = f.getHashMap();
trip.add(flightAttributes);
toRet.add(trip);
} else {
/*
* This flight does not go directly there,check to see if there
* are any flights going from it to our destination
*/
List<Flight> connectingFlights = Flight
.getFlightsConnectingDateTime(f.getDestination(),
destination, f.getArrival());
Iterator<Flight> connIt = connectingFlights.iterator();
HashMap<String, Object> firstLegAttr = f.getHashMap();
while (connIt.hasNext()) {
Flight nxt=connIt.next();
//filter on seats left
if (nxt.getSeatingArrangement().getAvailableSeats().size() <numPass){
continue;
}
Vector trip = new Vector<HashMap<String, Object>>(2);
trip.add(firstLegAttr);
trip.add(nxt.getHashMap());
toRet.add(trip);
}
}
}
//Collections.sort(toRet, new TripDepartureSort());
return toRet;
}
private class TripDepartureSort implements
Comparator<Vector<HashMap<String, Object>>> {
@Override
public int compare(Vector<HashMap<String, Object>> o1,
Vector<HashMap<String, Object>> o2) {
if (((Date) o1.get(0).get("departs")).before((Date) o2.get(0)
.get("departs")))
return -1;
if (((Date) o1.get(0).get("departs")).after((Date) o2.get(0).get(
"departs")))
return 1;
return 0;
}
}
private class TripDurationSort implements
Comparator<Vector<HashMap<String, Object>>> {
@Override
public int compare(Vector<HashMap<String, Object>> o1,
Vector<HashMap<String, Object>> o2) {
long firstDuration = getTotalDuration(o1);
long secondDuration = getTotalDuration(o2);
if (firstDuration < secondDuration)
return -1;
if (firstDuration > secondDuration)
return 1;
return 0;
}
private Long getTotalDuration(Vector<HashMap<String, Object>> arg) {
return ((Date) arg.lastElement().get("arrives")).getTime()
- ((Date) arg.firstElement().get("departs")).getTime();
}
}
}
| false | true | public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
// printParam(req,resp);
//remove old session variables from aborted bookings
HttpSession session = req.getSession();
session.setAttribute("departopt",null);
session.setAttribute("returnopt", null);
session.setAttribute("numPass", null);
req.setAttribute("origin", req.getParameter("origin"));
req.setAttribute("destination", req.getParameter("destination"));
req.setAttribute("departureDate", req.getParameter("departureDate"));
req.setAttribute("returnDate", req.getParameter("returnDate"));
String s = req.getParameter("oneWayOrReturn").toString();
s.toString();
req.setAttribute("oneWayOrReturn", req.getParameter("oneWayOrReturn"));
req.setAttribute("numPassengers",
(String) req.getParameter("numPassengers"));
Date departureDate = null;
Airport origin = null;
Date returnDate = null;
Airport destination = null;
SimpleDateFormat convertToDate = new SimpleDateFormat("MM-dd-yyyy");
String errorMessage=null;
if (req.getParameter("departureDate") != null) {
departureDate = convertToDate.parse(
req.getParameter("departureDate"), new ParsePosition(0));
}
if(departureDate == null){
errorMessage="Please provide a valid departure date";
}
if (req.getParameter("returnDate") != null) {
returnDate = convertToDate.parse(req.getParameter("returnDate"),
new ParsePosition(0));
}
if (returnDate == null) {
//if there is no return date, pretend there is
returnDate = (Date) departureDate.clone();
}else if (returnDate.before(departureDate)){
errorMessage = "Return date must be after departure date";
}
try{
if (req.getParameter("origin") != null) {
origin = Airport.getAirportByCallSign(req.getParameter("origin"));
}
}catch(javax.jdo.JDOObjectNotFoundException e){
errorMessage = "No Airport with call sign "+req.getParameter("origin");
}
try{
if (req.getParameter("destination") != null) {
destination = Airport.getAirportByCallSign(req
.getParameter("destination"));
}
}catch(javax.jdo.JDOObjectNotFoundException e){
errorMessage = "No Airport with call sign "+req.getParameter("destination");
}
if (origin!=null && destination != null && origin.equals(destination)){
errorMessage = "origin and destination cannot be the same";
}
if( departureDate.before(new Date())){
errorMessage = "Cannot book flights in the past";
}
if(errorMessage!=null){
req.setAttribute("errorMsg",errorMessage);
req.getRequestDispatcher("/index.jsp").forward(req,resp);
return;
}
if (origin != null) {
Vector trips = getFlightsFromOrigToDestOnDate(origin, destination,
departureDate,Integer.valueOf(req.getParameter("numPassengers")));
req.setAttribute("thereTrips", trips);
trips = getFlightsFromOrigToDestOnDate(destination, origin,
returnDate,Integer.valueOf(req.getParameter("numPassengers")));
req.setAttribute("returnTrips", trips);
req.getRequestDispatcher("searchResults.jsp").forward(req, resp);
}
}
| public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
// printParam(req,resp);
//remove old session variables from aborted bookings
HttpSession session = req.getSession();
session.setAttribute("departopt",null);
session.setAttribute("returnopt", null);
session.setAttribute("numPass", null);
req.setAttribute("origin", req.getParameter("origin"));
req.setAttribute("destination", req.getParameter("destination"));
req.setAttribute("departureDate", req.getParameter("departureDate"));
req.setAttribute("returnDate", req.getParameter("returnDate"));
String s = req.getParameter("oneWayOrReturn").toString();
s.toString();
req.setAttribute("oneWayOrReturn", req.getParameter("oneWayOrReturn"));
req.setAttribute("numPassengers",
(String) req.getParameter("numPassengers"));
Date departureDate = null;
Airport origin = null;
Date returnDate = null;
Airport destination = null;
SimpleDateFormat convertToDate = new SimpleDateFormat("MM-dd-yyyy");
String errorMessage=null;
if (req.getParameter("departureDate") != null) {
departureDate = convertToDate.parse(
req.getParameter("departureDate"), new ParsePosition(0));
}
if(departureDate == null){
errorMessage="Please provide a valid departure date";
}
if (req.getParameter("returnDate") != null) {
returnDate = convertToDate.parse(req.getParameter("returnDate"),
new ParsePosition(0));
}
if (returnDate == null ||
req.getParameter("oneWayOrReturn").equals("return")) {
//if there is no return date, pretend there is
returnDate = (Date) departureDate.clone();
}else if (req.getParameter("oneWayOrReturn").equals("return") && returnDate.before(departureDate)){
errorMessage = "Return date must be after departure date";
}
try{
if (req.getParameter("origin") != null) {
origin = Airport.getAirportByCallSign(req.getParameter("origin"));
}
}catch(javax.jdo.JDOObjectNotFoundException e){
errorMessage = "No Airport with call sign "+req.getParameter("origin");
}
try{
if (req.getParameter("destination") != null) {
destination = Airport.getAirportByCallSign(req
.getParameter("destination"));
}
}catch(javax.jdo.JDOObjectNotFoundException e){
errorMessage = "No Airport with call sign "+req.getParameter("destination");
}
if (origin!=null && destination != null && origin.equals(destination)){
errorMessage = "origin and destination cannot be the same";
}
if( departureDate.before(new Date())){
errorMessage = "Cannot book flights in the past";
}
if(errorMessage!=null){
req.setAttribute("errorMsg",errorMessage);
req.getRequestDispatcher("/index.jsp").forward(req,resp);
return;
}
if (origin != null) {
Vector trips = getFlightsFromOrigToDestOnDate(origin, destination,
departureDate,Integer.valueOf(req.getParameter("numPassengers")));
req.setAttribute("thereTrips", trips);
trips = getFlightsFromOrigToDestOnDate(destination, origin,
returnDate,Integer.valueOf(req.getParameter("numPassengers")));
req.setAttribute("returnTrips", trips);
req.getRequestDispatcher("searchResults.jsp").forward(req, resp);
}
}
|
diff --git a/src/to/joe/vanish/sniffers/Sniffer20NamedEntitySpawn.java b/src/to/joe/vanish/sniffers/Sniffer20NamedEntitySpawn.java
index 77bacfe..4427263 100644
--- a/src/to/joe/vanish/sniffers/Sniffer20NamedEntitySpawn.java
+++ b/src/to/joe/vanish/sniffers/Sniffer20NamedEntitySpawn.java
@@ -1,34 +1,34 @@
package to.joe.vanish.sniffers;
import net.minecraft.server.Packet20NamedEntitySpawn;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.getspout.spout.packet.standard.MCCraftPacket;
import org.getspout.spoutapi.packet.listener.PacketListener;
import org.getspout.spoutapi.packet.standard.MCPacket;
import to.joe.vanish.VanishManager;
public class Sniffer20NamedEntitySpawn implements PacketListener {
private final VanishManager vanish;
public Sniffer20NamedEntitySpawn(VanishManager vanish) {
this.vanish = vanish;
}
@Override
public boolean checkPacket(Player player, MCPacket packet) {
final Packet20NamedEntitySpawn packet20 = (Packet20NamedEntitySpawn) ((MCCraftPacket) packet).getPacket();
final String name = packet20.b;
if (this.vanish.getPlugin().colorationEnabled() && this.vanish.isVanished(name)) {
packet20.b = ChatColor.DARK_AQUA + name;
- if(packet20.b.length()>16){
+ if(packet20.b.length()>15){
packet20.b=packet20.b.substring(0, 15);
}
}
return !this.vanish.shouldHide(player, packet20.a);
}
}
| true | true | public boolean checkPacket(Player player, MCPacket packet) {
final Packet20NamedEntitySpawn packet20 = (Packet20NamedEntitySpawn) ((MCCraftPacket) packet).getPacket();
final String name = packet20.b;
if (this.vanish.getPlugin().colorationEnabled() && this.vanish.isVanished(name)) {
packet20.b = ChatColor.DARK_AQUA + name;
if(packet20.b.length()>16){
packet20.b=packet20.b.substring(0, 15);
}
}
return !this.vanish.shouldHide(player, packet20.a);
}
| public boolean checkPacket(Player player, MCPacket packet) {
final Packet20NamedEntitySpawn packet20 = (Packet20NamedEntitySpawn) ((MCCraftPacket) packet).getPacket();
final String name = packet20.b;
if (this.vanish.getPlugin().colorationEnabled() && this.vanish.isVanished(name)) {
packet20.b = ChatColor.DARK_AQUA + name;
if(packet20.b.length()>15){
packet20.b=packet20.b.substring(0, 15);
}
}
return !this.vanish.shouldHide(player, packet20.a);
}
|
diff --git a/src/classifier/IBuilder.java b/src/classifier/IBuilder.java
index 500866d..72fcab3 100755
--- a/src/classifier/IBuilder.java
+++ b/src/classifier/IBuilder.java
@@ -1,94 +1,94 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package classifier;
import classifier.dataset.DataSet;
import classifier.dataset.Instance;
import util.MathHelper;
import util.Pair;
/**
*
* @author Nicklas
*/
public abstract class IBuilder {
private boolean redo = true;
public Pair<IClassifier, DataSet> build(DataSet ds) {
redo = true;
IClassifier classifier = null;
DataSet modifiedDataSet = null;
while (redo) {
System.out.println("Running generateHypothesis");
classifier = generateHypothesis(ds);
modifiedDataSet = update(classifier, ds);
System.out.println("Weight updated");
System.out.println("Classififer: "+classifier);
}
return new Pair<>(classifier, modifiedDataSet);
}
protected abstract IClassifier generateHypothesis(DataSet ds);
protected DataSet update(IClassifier classifier, DataSet dataSet) {
int misses = 0;
int hits = 0;
- double error = 0.0;
+ double error = Double.MIN_VALUE;
Instance currentInstance;
int corr = 0;
double beta = 1.5;
int numberOfClasses = dataSet.getClasses().length;
for (int i = 0; i < dataSet.length(); i++) {
currentInstance = dataSet.get(i);
if (classifier.guessClass(currentInstance) != currentInstance.getCategory()) {
System.out.println("I was wrong adding weight: " + currentInstance.getWeight());
error += currentInstance.getWeight();
}
}
if (error >= (numberOfClasses - 1) / (numberOfClasses * 1.0)) {
return jiggleWeight(dataSet, beta);
} else if (error > 0 && error < (numberOfClasses - 1) / (numberOfClasses * 1.0)) {
for (int i = 0; i < dataSet.length(); i++) {
currentInstance = dataSet.get(i);
if (classifier.guessClass(currentInstance) == currentInstance.getCategory()) {
hits++;
currentInstance.setWeight(currentInstance.getWeight() * ((1 - error) / error) * (numberOfClasses - 1));
corr++;
}
}
double[] allWeights = dataSet.getInstanceWeights();
double allWeightsSummed = MathHelper.sum(allWeights);
for (Instance instance : dataSet.getInstances()) {
instance.setWeight(instance.getWeight() / allWeightsSummed);
}
System.out.println("Error: " + error + " " + ((1 - error) / error));
classifier.setWeight(Math.log(((1 - error) / error)) * (numberOfClasses - 1));
System.out.println("Classifier had " + corr + " out of " + dataSet.length() + " correct. Weight: " + classifier.getWeight());
}else if (error == 0) {
jiggleWeight(dataSet, beta);
classifier.setWeight(10+Math.log(numberOfClasses-1));
}
redo = false;
return dataSet;
}
private DataSet jiggleWeight(DataSet ds, double beta) {
for (Instance i : ds.getInstances()) {
i.setWeight(Math.max(0, i.getWeight() + random(-1 / (Math.pow(ds.length(), beta)), 1 / (Math.pow(ds.length(), beta)))));
}
double sum = MathHelper.sum(ds.getInstanceWeights());
for (Instance i : ds.getInstances()) {
i.setWeight(i.getWeight() / sum);
}
return ds;
}
private double random(double start, double end) {
return Math.random() * (end - start) - start;
}
}
| true | true | protected DataSet update(IClassifier classifier, DataSet dataSet) {
int misses = 0;
int hits = 0;
double error = 0.0;
Instance currentInstance;
int corr = 0;
double beta = 1.5;
int numberOfClasses = dataSet.getClasses().length;
for (int i = 0; i < dataSet.length(); i++) {
currentInstance = dataSet.get(i);
if (classifier.guessClass(currentInstance) != currentInstance.getCategory()) {
System.out.println("I was wrong adding weight: " + currentInstance.getWeight());
error += currentInstance.getWeight();
}
}
if (error >= (numberOfClasses - 1) / (numberOfClasses * 1.0)) {
return jiggleWeight(dataSet, beta);
} else if (error > 0 && error < (numberOfClasses - 1) / (numberOfClasses * 1.0)) {
for (int i = 0; i < dataSet.length(); i++) {
currentInstance = dataSet.get(i);
if (classifier.guessClass(currentInstance) == currentInstance.getCategory()) {
hits++;
currentInstance.setWeight(currentInstance.getWeight() * ((1 - error) / error) * (numberOfClasses - 1));
corr++;
}
}
double[] allWeights = dataSet.getInstanceWeights();
double allWeightsSummed = MathHelper.sum(allWeights);
for (Instance instance : dataSet.getInstances()) {
instance.setWeight(instance.getWeight() / allWeightsSummed);
}
System.out.println("Error: " + error + " " + ((1 - error) / error));
classifier.setWeight(Math.log(((1 - error) / error)) * (numberOfClasses - 1));
System.out.println("Classifier had " + corr + " out of " + dataSet.length() + " correct. Weight: " + classifier.getWeight());
}else if (error == 0) {
jiggleWeight(dataSet, beta);
classifier.setWeight(10+Math.log(numberOfClasses-1));
}
redo = false;
return dataSet;
}
| protected DataSet update(IClassifier classifier, DataSet dataSet) {
int misses = 0;
int hits = 0;
double error = Double.MIN_VALUE;
Instance currentInstance;
int corr = 0;
double beta = 1.5;
int numberOfClasses = dataSet.getClasses().length;
for (int i = 0; i < dataSet.length(); i++) {
currentInstance = dataSet.get(i);
if (classifier.guessClass(currentInstance) != currentInstance.getCategory()) {
System.out.println("I was wrong adding weight: " + currentInstance.getWeight());
error += currentInstance.getWeight();
}
}
if (error >= (numberOfClasses - 1) / (numberOfClasses * 1.0)) {
return jiggleWeight(dataSet, beta);
} else if (error > 0 && error < (numberOfClasses - 1) / (numberOfClasses * 1.0)) {
for (int i = 0; i < dataSet.length(); i++) {
currentInstance = dataSet.get(i);
if (classifier.guessClass(currentInstance) == currentInstance.getCategory()) {
hits++;
currentInstance.setWeight(currentInstance.getWeight() * ((1 - error) / error) * (numberOfClasses - 1));
corr++;
}
}
double[] allWeights = dataSet.getInstanceWeights();
double allWeightsSummed = MathHelper.sum(allWeights);
for (Instance instance : dataSet.getInstances()) {
instance.setWeight(instance.getWeight() / allWeightsSummed);
}
System.out.println("Error: " + error + " " + ((1 - error) / error));
classifier.setWeight(Math.log(((1 - error) / error)) * (numberOfClasses - 1));
System.out.println("Classifier had " + corr + " out of " + dataSet.length() + " correct. Weight: " + classifier.getWeight());
}else if (error == 0) {
jiggleWeight(dataSet, beta);
classifier.setWeight(10+Math.log(numberOfClasses-1));
}
redo = false;
return dataSet;
}
|
diff --git a/source/ch/cyberduck/ui/cocoa/CDLoginController.java b/source/ch/cyberduck/ui/cocoa/CDLoginController.java
index 51c7f555b..8ec6a8762 100644
--- a/source/ch/cyberduck/ui/cocoa/CDLoginController.java
+++ b/source/ch/cyberduck/ui/cocoa/CDLoginController.java
@@ -1,180 +1,179 @@
package ch.cyberduck.ui.cocoa;
/*
* Copyright (c) 2005 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to:
* [email protected]
*/
import ch.cyberduck.core.*;
import ch.cyberduck.core.LoginController;
import com.apple.cocoa.application.*;
import com.apple.cocoa.foundation.NSBundle;
import com.apple.cocoa.foundation.NSNotificationCenter;
import com.apple.cocoa.foundation.NSSelector;
import com.apple.cocoa.foundation.NSNotification;
import org.apache.log4j.Logger;
/**
* @version $Id$
*/
public class CDLoginController extends AbstractLoginController implements LoginController {
private static Logger log = Logger.getLogger(CDLoginController.class);
CDWindowController parent;
public CDLoginController(final CDWindowController parent) {
this.parent = parent;
}
public void prompt(final Protocol protocol, final Credentials credentials, final String reason, final String message)
throws LoginCanceledException {
CDSheetController c = new CDSheetController(parent) {
protected String getBundleName() {
return "Login";
}
public void awakeFromNib() {
this.update();
}
private NSTextField titleField; // IBOutlet
public void setTitleField(NSTextField titleField) {
this.titleField = titleField;
this.updateField(this.titleField, reason);
}
private NSTextField userField; // IBOutlet
public void setUserField(NSTextField userField) {
this.userField = userField;
this.updateField(this.userField, credentials.getUsername());
if(protocol.equals(Protocol.S3)) {
((NSTextFieldCell) this.userField.cell()).setPlaceholderString(
NSBundle.localizedString("Access Key ID", "S3")
);
}
NSNotificationCenter.defaultCenter().addObserver(this,
new NSSelector("userFieldTextDidChange", new Class[]{NSNotification.class}),
NSControl.ControlTextDidChangeNotification,
this.userField);
}
public void userFieldTextDidChange(NSNotification notification) {
credentials.setUsername(userField.stringValue());
this.update();
}
private NSTextField textField; // IBOutlet
public void setTextField(NSTextField textField) {
this.textField = textField;
this.updateField(this.textField, message);
}
private NSSecureTextField passField; // IBOutlet
public void setPassField(NSSecureTextField passField) {
this.passField = passField;
this.updateField(this.passField, credentials.getPassword());
if(protocol.equals(Protocol.S3)) {
((NSTextFieldCell) this.passField.cell()).setPlaceholderString(
NSBundle.localizedString("Secret Access Key", "S3")
);
}
NSNotificationCenter.defaultCenter().addObserver(this,
new NSSelector("passFieldTextDidChange", new Class[]{NSNotification.class}),
NSControl.ControlTextDidChangeNotification,
this.passField);
}
public void passFieldTextDidChange(NSNotification notification) {
credentials.setPassword(passField.stringValue());
}
private NSButton keychainCheckbox;
public void setKeychainCheckbox(NSButton keychainCheckbox) {
this.keychainCheckbox = keychainCheckbox;
this.keychainCheckbox.setState(Preferences.instance().getBoolean("connection.login.useKeychain")
&& Preferences.instance().getBoolean("connection.login.addKeychain") ? NSCell.OnState : NSCell.OffState);
this.keychainCheckbox.setTarget(this);
this.keychainCheckbox.setAction(new NSSelector("keychainCheckboxClicked", new Class[]{NSButton.class}));
}
public void keychainCheckboxClicked(final NSButton sender) {
credentials.setUseKeychain(sender.state() == NSCell.OnState);
}
private NSButton anonymousCheckbox;
public void setAnonymousCheckbox(NSButton anonymousCheckbox) {
this.anonymousCheckbox = anonymousCheckbox;
this.anonymousCheckbox.setTarget(this);
this.anonymousCheckbox.setAction(new NSSelector("anonymousCheckboxClicked", new Class[]{NSButton.class}));
}
public void anonymousCheckboxClicked(final NSButton sender) {
if(sender.state() == NSCell.OnState) {
credentials.setUsername(Preferences.instance().getProperty("connection.login.anon.name"));
credentials.setPassword(Preferences.instance().getProperty("connection.login.anon.pass"));
}
if(sender.state() == NSCell.OffState) {
credentials.setUsername(Preferences.instance().getProperty("connection.login.name"));
credentials.setPassword(null);
}
this.updateField(this.userField, credentials.getUsername());
this.updateField(this.passField, credentials.getPassword());
this.update();
}
private void update() {
this.userField.setEnabled(!credentials.isAnonymousLogin()
&& !credentials.usesPublicKeyAuthentication()
);
this.passField.setEnabled(!credentials.isAnonymousLogin());
this.keychainCheckbox.setEnabled(!credentials.isAnonymousLogin());
this.anonymousCheckbox.setState(credentials.isAnonymousLogin() ? NSCell.OnState : NSCell.OffState);
}
protected boolean validateInput() {
return StringUtils.hasLength(credentials.getUsername())
&& StringUtils.hasLength(credentials.getPassword());
}
public void callback(final int returncode) {
- if (returncode == DEFAULT_OPTION) {
- log.info("Update login credentials...");
+ if (returncode == CDSheetCallback.DEFAULT_OPTION) {
this.window().endEditingForObject(null);
credentials.setUsername((String) userField.objectValue());
credentials.setPassword((String) passField.objectValue());
}
}
};
c.beginSheet();
- if(null == credentials.getUsername() && null == credentials.getPassword()) {
+ if (c.returnCode() == CDSheetCallback.CANCEL_OPTION) {
throw new LoginCanceledException();
}
}
protected String getBundleName() {
return null;
}
}
| false | true | public void prompt(final Protocol protocol, final Credentials credentials, final String reason, final String message)
throws LoginCanceledException {
CDSheetController c = new CDSheetController(parent) {
protected String getBundleName() {
return "Login";
}
public void awakeFromNib() {
this.update();
}
private NSTextField titleField; // IBOutlet
public void setTitleField(NSTextField titleField) {
this.titleField = titleField;
this.updateField(this.titleField, reason);
}
private NSTextField userField; // IBOutlet
public void setUserField(NSTextField userField) {
this.userField = userField;
this.updateField(this.userField, credentials.getUsername());
if(protocol.equals(Protocol.S3)) {
((NSTextFieldCell) this.userField.cell()).setPlaceholderString(
NSBundle.localizedString("Access Key ID", "S3")
);
}
NSNotificationCenter.defaultCenter().addObserver(this,
new NSSelector("userFieldTextDidChange", new Class[]{NSNotification.class}),
NSControl.ControlTextDidChangeNotification,
this.userField);
}
public void userFieldTextDidChange(NSNotification notification) {
credentials.setUsername(userField.stringValue());
this.update();
}
private NSTextField textField; // IBOutlet
public void setTextField(NSTextField textField) {
this.textField = textField;
this.updateField(this.textField, message);
}
private NSSecureTextField passField; // IBOutlet
public void setPassField(NSSecureTextField passField) {
this.passField = passField;
this.updateField(this.passField, credentials.getPassword());
if(protocol.equals(Protocol.S3)) {
((NSTextFieldCell) this.passField.cell()).setPlaceholderString(
NSBundle.localizedString("Secret Access Key", "S3")
);
}
NSNotificationCenter.defaultCenter().addObserver(this,
new NSSelector("passFieldTextDidChange", new Class[]{NSNotification.class}),
NSControl.ControlTextDidChangeNotification,
this.passField);
}
public void passFieldTextDidChange(NSNotification notification) {
credentials.setPassword(passField.stringValue());
}
private NSButton keychainCheckbox;
public void setKeychainCheckbox(NSButton keychainCheckbox) {
this.keychainCheckbox = keychainCheckbox;
this.keychainCheckbox.setState(Preferences.instance().getBoolean("connection.login.useKeychain")
&& Preferences.instance().getBoolean("connection.login.addKeychain") ? NSCell.OnState : NSCell.OffState);
this.keychainCheckbox.setTarget(this);
this.keychainCheckbox.setAction(new NSSelector("keychainCheckboxClicked", new Class[]{NSButton.class}));
}
public void keychainCheckboxClicked(final NSButton sender) {
credentials.setUseKeychain(sender.state() == NSCell.OnState);
}
private NSButton anonymousCheckbox;
public void setAnonymousCheckbox(NSButton anonymousCheckbox) {
this.anonymousCheckbox = anonymousCheckbox;
this.anonymousCheckbox.setTarget(this);
this.anonymousCheckbox.setAction(new NSSelector("anonymousCheckboxClicked", new Class[]{NSButton.class}));
}
public void anonymousCheckboxClicked(final NSButton sender) {
if(sender.state() == NSCell.OnState) {
credentials.setUsername(Preferences.instance().getProperty("connection.login.anon.name"));
credentials.setPassword(Preferences.instance().getProperty("connection.login.anon.pass"));
}
if(sender.state() == NSCell.OffState) {
credentials.setUsername(Preferences.instance().getProperty("connection.login.name"));
credentials.setPassword(null);
}
this.updateField(this.userField, credentials.getUsername());
this.updateField(this.passField, credentials.getPassword());
this.update();
}
private void update() {
this.userField.setEnabled(!credentials.isAnonymousLogin()
&& !credentials.usesPublicKeyAuthentication()
);
this.passField.setEnabled(!credentials.isAnonymousLogin());
this.keychainCheckbox.setEnabled(!credentials.isAnonymousLogin());
this.anonymousCheckbox.setState(credentials.isAnonymousLogin() ? NSCell.OnState : NSCell.OffState);
}
protected boolean validateInput() {
return StringUtils.hasLength(credentials.getUsername())
&& StringUtils.hasLength(credentials.getPassword());
}
public void callback(final int returncode) {
if (returncode == DEFAULT_OPTION) {
log.info("Update login credentials...");
this.window().endEditingForObject(null);
credentials.setUsername((String) userField.objectValue());
credentials.setPassword((String) passField.objectValue());
}
}
};
c.beginSheet();
if(null == credentials.getUsername() && null == credentials.getPassword()) {
throw new LoginCanceledException();
}
}
| public void prompt(final Protocol protocol, final Credentials credentials, final String reason, final String message)
throws LoginCanceledException {
CDSheetController c = new CDSheetController(parent) {
protected String getBundleName() {
return "Login";
}
public void awakeFromNib() {
this.update();
}
private NSTextField titleField; // IBOutlet
public void setTitleField(NSTextField titleField) {
this.titleField = titleField;
this.updateField(this.titleField, reason);
}
private NSTextField userField; // IBOutlet
public void setUserField(NSTextField userField) {
this.userField = userField;
this.updateField(this.userField, credentials.getUsername());
if(protocol.equals(Protocol.S3)) {
((NSTextFieldCell) this.userField.cell()).setPlaceholderString(
NSBundle.localizedString("Access Key ID", "S3")
);
}
NSNotificationCenter.defaultCenter().addObserver(this,
new NSSelector("userFieldTextDidChange", new Class[]{NSNotification.class}),
NSControl.ControlTextDidChangeNotification,
this.userField);
}
public void userFieldTextDidChange(NSNotification notification) {
credentials.setUsername(userField.stringValue());
this.update();
}
private NSTextField textField; // IBOutlet
public void setTextField(NSTextField textField) {
this.textField = textField;
this.updateField(this.textField, message);
}
private NSSecureTextField passField; // IBOutlet
public void setPassField(NSSecureTextField passField) {
this.passField = passField;
this.updateField(this.passField, credentials.getPassword());
if(protocol.equals(Protocol.S3)) {
((NSTextFieldCell) this.passField.cell()).setPlaceholderString(
NSBundle.localizedString("Secret Access Key", "S3")
);
}
NSNotificationCenter.defaultCenter().addObserver(this,
new NSSelector("passFieldTextDidChange", new Class[]{NSNotification.class}),
NSControl.ControlTextDidChangeNotification,
this.passField);
}
public void passFieldTextDidChange(NSNotification notification) {
credentials.setPassword(passField.stringValue());
}
private NSButton keychainCheckbox;
public void setKeychainCheckbox(NSButton keychainCheckbox) {
this.keychainCheckbox = keychainCheckbox;
this.keychainCheckbox.setState(Preferences.instance().getBoolean("connection.login.useKeychain")
&& Preferences.instance().getBoolean("connection.login.addKeychain") ? NSCell.OnState : NSCell.OffState);
this.keychainCheckbox.setTarget(this);
this.keychainCheckbox.setAction(new NSSelector("keychainCheckboxClicked", new Class[]{NSButton.class}));
}
public void keychainCheckboxClicked(final NSButton sender) {
credentials.setUseKeychain(sender.state() == NSCell.OnState);
}
private NSButton anonymousCheckbox;
public void setAnonymousCheckbox(NSButton anonymousCheckbox) {
this.anonymousCheckbox = anonymousCheckbox;
this.anonymousCheckbox.setTarget(this);
this.anonymousCheckbox.setAction(new NSSelector("anonymousCheckboxClicked", new Class[]{NSButton.class}));
}
public void anonymousCheckboxClicked(final NSButton sender) {
if(sender.state() == NSCell.OnState) {
credentials.setUsername(Preferences.instance().getProperty("connection.login.anon.name"));
credentials.setPassword(Preferences.instance().getProperty("connection.login.anon.pass"));
}
if(sender.state() == NSCell.OffState) {
credentials.setUsername(Preferences.instance().getProperty("connection.login.name"));
credentials.setPassword(null);
}
this.updateField(this.userField, credentials.getUsername());
this.updateField(this.passField, credentials.getPassword());
this.update();
}
private void update() {
this.userField.setEnabled(!credentials.isAnonymousLogin()
&& !credentials.usesPublicKeyAuthentication()
);
this.passField.setEnabled(!credentials.isAnonymousLogin());
this.keychainCheckbox.setEnabled(!credentials.isAnonymousLogin());
this.anonymousCheckbox.setState(credentials.isAnonymousLogin() ? NSCell.OnState : NSCell.OffState);
}
protected boolean validateInput() {
return StringUtils.hasLength(credentials.getUsername())
&& StringUtils.hasLength(credentials.getPassword());
}
public void callback(final int returncode) {
if (returncode == CDSheetCallback.DEFAULT_OPTION) {
this.window().endEditingForObject(null);
credentials.setUsername((String) userField.objectValue());
credentials.setPassword((String) passField.objectValue());
}
}
};
c.beginSheet();
if (c.returnCode() == CDSheetCallback.CANCEL_OPTION) {
throw new LoginCanceledException();
}
}
|
diff --git a/OSas4/src/Procesai/InputStream.java b/OSas4/src/Procesai/InputStream.java
index d3f94cc..0802a9b 100644
--- a/OSas4/src/Procesai/InputStream.java
+++ b/OSas4/src/Procesai/InputStream.java
@@ -1,163 +1,163 @@
package Procesai;
import os.Primityvai;
import os.Statiniai;
import os.Statiniai.DRstring;
import os.Statiniai.VRstring;
import resources.RSS;
import resources.ResourceDescriptor;
import resources.VRSS;
import resourcesINFO.HDDObject;
import resourcesINFO.INFO;
import resourcesINFO.INFOhdd;
import resourcesINFO.INFOv;
import rm.ChannelDevice;
import rm.HDD;
import rm.Memory;
public class InputStream extends ProcessBase {
int nuskaitytiZodziai, nuoKur;
boolean nuskaitymasBaigtas = false;
@Override
public void execute() {
switch(vieta) {
case 0:
nuskaitytiZodziai = 0;
nuoKur = Statiniai.readMem;
//Blokuojasi ir laukia kanal� �renginys
vieta = 2;
Primityvai.prasytiResurso(DRstring.Kanalu_irenginys, nameI, 1);
break;
/*case 1:
vieta++;
if (Statiniai.readMem == Statiniai.vietaMem) {
//Blokuojasi ir laukia klaviat�ros pertraukimas
Primityvai.prasytiResurso(VRstring.Klaviaturos_pertraukimas, nameI, 1);
}
break;*/
case 2:
System.out.println("IS case2------------------------");
if (Statiniai.readMem < Statiniai.vietaMem && !nuskaitymasBaigtas) {
for (int i = Statiniai.readMem; i < Statiniai.vietaMem; i++) {
System.out.println("for'as case2==========");
//Padidina nuskaityt� �od�i� skai�i�
nuskaitytiZodziai++;
//Tikrinam ar nuskaityta komanda n�ra #END
if (String.valueOf(Memory.get()[Statiniai.readMem].getWord()).equals("#END")) {
Statiniai.readMem++;
//Atlaisvinamas kanal� �renginys
vieta++;
nuskaitymasBaigtas = true;
Primityvai.atlaisvintiResursa(Statiniai.DRstring.Kanalu_irenginys, nameI);
} else {
Statiniai.readMem++;
}
}
}
if (!nuskaitymasBaigtas) {
vieta = 2;
Primityvai.prasytiResurso(VRstring.Klaviaturos_pertraukimas, nameI, 1);
}
else {
vieta = 4;
System.out.println("IS kuria sintakses tikrinima!!!");
Primityvai.sukurtiResursa(Statiniai.VRstring.Sintakses_tikrinimas, true, nameI, null);
break;
}
break;
case 3:
System.out.println("nuskaityti zodziai-----------------: "+nuskaitytiZodziai);
if (!nuskaitymasBaigtas) {
vieta = 2;
Primityvai.prasytiResurso(VRstring.Klaviaturos_pertraukimas, nameI, 1);
}
else {
vieta = 5;
INFO inf = new INFOv();
((Object[])inf.o)[0] = nuoKur;
((Object[])inf.o)[1] = nuskaitytiZodziai;
Primityvai.sukurtiResursa(Statiniai.VRstring.Sintakses_tikrinimas, true, nameI, inf);
break;
}
break;
/*case 4:
vieta++;
Primityvai.prasytiResurso(VRstring.Sintakse_patikrinta, nameI, 1);
break;*/
case 5:
//Blokuojasi ir laukia sintaks� patikrinta resurso
vieta = 6;
Primityvai.prasytiResurso(VRstring.Sintakse_patikrinta, nameI, 1);
break;
case 6:
//Blokuojasi ir laukia kanal� �renginys
vieta++;
Primityvai.prasytiResurso(DRstring.Kanalu_irenginys, nameI, 1);
break;
case 7:
//Tikrinama ar buvo klaidu ar nebuvo
ResourceDescriptor sintaksesResursas = null;
for (int i = 0; i < resursai.size(); i++)
if (resursai.get(i).nameO == Statiniai.VRstring.Sintakse_patikrinta) {
for (int j = 0; j < VRSS.list.get(Statiniai.VRint.Sintakse_patikrinta).resourceList.size(); j++)
if (VRSS.list.get(Statiniai.VRint.Sintakse_patikrinta).resourceList.get(j).nameI == resursai.get(i).nameI) {
sintaksesResursas = VRSS.list.get(Statiniai.VRint.Sintakse_patikrinta).resourceList.get(j);
break;
}
break;
}
if (sintaksesResursas == null)
System.out.println("Input stream neturi sintaks�s resurso.. Baisi klaida");
if ((boolean)sintaksesResursas.info.o) {
//Jei visa sintaks� teisinga
System.out.println("Sintaks� teisinga!");
vieta++;
Primityvai.prasytiResurso(Statiniai.DRstring.HDD, nameI, 1);
} else {
//Jei sintaks� neteisinga
System.out.println("U�duotyje buvo klaid�!");
vieta = 9;
Primityvai.atlaisvintiResursa(Statiniai.DRstring.Kanalu_irenginys, nameI);
}
break;
case 8:
//Kopijuoja u�duot� � HDD
HDDObject hdd = null;
for (int i = 0; i < resursai.size(); i++)
if (resursai.get(i).nameO == Statiniai.DRstring.HDD) {
hdd = ((HDDObject)(RSS.list.get(Statiniai.DRint.HDD).resourceDescriptor.info).o);
break;
}
//gaunam kuriam bloke programa
int kurisBlokas = 0;
for (int i = 0; i < hdd.HDD_SIZE; i++)
if (hdd.hdd.get(i) == programaHDD) {
kurisBlokas = i;
break;
}
ChannelDevice.setValueOfChannel(ChannelDevice.IO, 1);
ChannelDevice.setValueOfChannel(ChannelDevice.OO, 2);
- ChannelDevice.setValueOfChannel(ChannelDevice.IA, Statiniai.vietaMem);
+ ChannelDevice.setValueOfChannel(ChannelDevice.IA, nuoKur);
ChannelDevice.setValueOfChannel(ChannelDevice.OA, kurisBlokas*255);
ChannelDevice.c = nuskaitytiZodziai;
ChannelDevice.runDevice();
vieta = 9;
Primityvai.atlaisvintiResursa(Statiniai.DRstring.Kanalu_irenginys, nameI);
break;
case 9:
vieta = 10;
Primityvai.sukurtiResursa(Statiniai.VRstring.InputStream_pabaiga, true, father, null);
break;
}
}
}
| true | true | public void execute() {
switch(vieta) {
case 0:
nuskaitytiZodziai = 0;
nuoKur = Statiniai.readMem;
//Blokuojasi ir laukia kanal� �renginys
vieta = 2;
Primityvai.prasytiResurso(DRstring.Kanalu_irenginys, nameI, 1);
break;
/*case 1:
vieta++;
if (Statiniai.readMem == Statiniai.vietaMem) {
//Blokuojasi ir laukia klaviat�ros pertraukimas
Primityvai.prasytiResurso(VRstring.Klaviaturos_pertraukimas, nameI, 1);
}
break;*/
case 2:
System.out.println("IS case2------------------------");
if (Statiniai.readMem < Statiniai.vietaMem && !nuskaitymasBaigtas) {
for (int i = Statiniai.readMem; i < Statiniai.vietaMem; i++) {
System.out.println("for'as case2==========");
//Padidina nuskaityt� �od�i� skai�i�
nuskaitytiZodziai++;
//Tikrinam ar nuskaityta komanda n�ra #END
if (String.valueOf(Memory.get()[Statiniai.readMem].getWord()).equals("#END")) {
Statiniai.readMem++;
//Atlaisvinamas kanal� �renginys
vieta++;
nuskaitymasBaigtas = true;
Primityvai.atlaisvintiResursa(Statiniai.DRstring.Kanalu_irenginys, nameI);
} else {
Statiniai.readMem++;
}
}
}
if (!nuskaitymasBaigtas) {
vieta = 2;
Primityvai.prasytiResurso(VRstring.Klaviaturos_pertraukimas, nameI, 1);
}
else {
vieta = 4;
System.out.println("IS kuria sintakses tikrinima!!!");
Primityvai.sukurtiResursa(Statiniai.VRstring.Sintakses_tikrinimas, true, nameI, null);
break;
}
break;
case 3:
System.out.println("nuskaityti zodziai-----------------: "+nuskaitytiZodziai);
if (!nuskaitymasBaigtas) {
vieta = 2;
Primityvai.prasytiResurso(VRstring.Klaviaturos_pertraukimas, nameI, 1);
}
else {
vieta = 5;
INFO inf = new INFOv();
((Object[])inf.o)[0] = nuoKur;
((Object[])inf.o)[1] = nuskaitytiZodziai;
Primityvai.sukurtiResursa(Statiniai.VRstring.Sintakses_tikrinimas, true, nameI, inf);
break;
}
break;
/*case 4:
vieta++;
Primityvai.prasytiResurso(VRstring.Sintakse_patikrinta, nameI, 1);
break;*/
case 5:
//Blokuojasi ir laukia sintaks� patikrinta resurso
vieta = 6;
Primityvai.prasytiResurso(VRstring.Sintakse_patikrinta, nameI, 1);
break;
case 6:
//Blokuojasi ir laukia kanal� �renginys
vieta++;
Primityvai.prasytiResurso(DRstring.Kanalu_irenginys, nameI, 1);
break;
case 7:
//Tikrinama ar buvo klaidu ar nebuvo
ResourceDescriptor sintaksesResursas = null;
for (int i = 0; i < resursai.size(); i++)
if (resursai.get(i).nameO == Statiniai.VRstring.Sintakse_patikrinta) {
for (int j = 0; j < VRSS.list.get(Statiniai.VRint.Sintakse_patikrinta).resourceList.size(); j++)
if (VRSS.list.get(Statiniai.VRint.Sintakse_patikrinta).resourceList.get(j).nameI == resursai.get(i).nameI) {
sintaksesResursas = VRSS.list.get(Statiniai.VRint.Sintakse_patikrinta).resourceList.get(j);
break;
}
break;
}
if (sintaksesResursas == null)
System.out.println("Input stream neturi sintaks�s resurso.. Baisi klaida");
if ((boolean)sintaksesResursas.info.o) {
//Jei visa sintaks� teisinga
System.out.println("Sintaks� teisinga!");
vieta++;
Primityvai.prasytiResurso(Statiniai.DRstring.HDD, nameI, 1);
} else {
//Jei sintaks� neteisinga
System.out.println("U�duotyje buvo klaid�!");
vieta = 9;
Primityvai.atlaisvintiResursa(Statiniai.DRstring.Kanalu_irenginys, nameI);
}
break;
case 8:
//Kopijuoja u�duot� � HDD
HDDObject hdd = null;
for (int i = 0; i < resursai.size(); i++)
if (resursai.get(i).nameO == Statiniai.DRstring.HDD) {
hdd = ((HDDObject)(RSS.list.get(Statiniai.DRint.HDD).resourceDescriptor.info).o);
break;
}
//gaunam kuriam bloke programa
int kurisBlokas = 0;
for (int i = 0; i < hdd.HDD_SIZE; i++)
if (hdd.hdd.get(i) == programaHDD) {
kurisBlokas = i;
break;
}
ChannelDevice.setValueOfChannel(ChannelDevice.IO, 1);
ChannelDevice.setValueOfChannel(ChannelDevice.OO, 2);
ChannelDevice.setValueOfChannel(ChannelDevice.IA, Statiniai.vietaMem);
ChannelDevice.setValueOfChannel(ChannelDevice.OA, kurisBlokas*255);
ChannelDevice.c = nuskaitytiZodziai;
ChannelDevice.runDevice();
vieta = 9;
Primityvai.atlaisvintiResursa(Statiniai.DRstring.Kanalu_irenginys, nameI);
break;
case 9:
vieta = 10;
Primityvai.sukurtiResursa(Statiniai.VRstring.InputStream_pabaiga, true, father, null);
break;
}
}
| public void execute() {
switch(vieta) {
case 0:
nuskaitytiZodziai = 0;
nuoKur = Statiniai.readMem;
//Blokuojasi ir laukia kanal� �renginys
vieta = 2;
Primityvai.prasytiResurso(DRstring.Kanalu_irenginys, nameI, 1);
break;
/*case 1:
vieta++;
if (Statiniai.readMem == Statiniai.vietaMem) {
//Blokuojasi ir laukia klaviat�ros pertraukimas
Primityvai.prasytiResurso(VRstring.Klaviaturos_pertraukimas, nameI, 1);
}
break;*/
case 2:
System.out.println("IS case2------------------------");
if (Statiniai.readMem < Statiniai.vietaMem && !nuskaitymasBaigtas) {
for (int i = Statiniai.readMem; i < Statiniai.vietaMem; i++) {
System.out.println("for'as case2==========");
//Padidina nuskaityt� �od�i� skai�i�
nuskaitytiZodziai++;
//Tikrinam ar nuskaityta komanda n�ra #END
if (String.valueOf(Memory.get()[Statiniai.readMem].getWord()).equals("#END")) {
Statiniai.readMem++;
//Atlaisvinamas kanal� �renginys
vieta++;
nuskaitymasBaigtas = true;
Primityvai.atlaisvintiResursa(Statiniai.DRstring.Kanalu_irenginys, nameI);
} else {
Statiniai.readMem++;
}
}
}
if (!nuskaitymasBaigtas) {
vieta = 2;
Primityvai.prasytiResurso(VRstring.Klaviaturos_pertraukimas, nameI, 1);
}
else {
vieta = 4;
System.out.println("IS kuria sintakses tikrinima!!!");
Primityvai.sukurtiResursa(Statiniai.VRstring.Sintakses_tikrinimas, true, nameI, null);
break;
}
break;
case 3:
System.out.println("nuskaityti zodziai-----------------: "+nuskaitytiZodziai);
if (!nuskaitymasBaigtas) {
vieta = 2;
Primityvai.prasytiResurso(VRstring.Klaviaturos_pertraukimas, nameI, 1);
}
else {
vieta = 5;
INFO inf = new INFOv();
((Object[])inf.o)[0] = nuoKur;
((Object[])inf.o)[1] = nuskaitytiZodziai;
Primityvai.sukurtiResursa(Statiniai.VRstring.Sintakses_tikrinimas, true, nameI, inf);
break;
}
break;
/*case 4:
vieta++;
Primityvai.prasytiResurso(VRstring.Sintakse_patikrinta, nameI, 1);
break;*/
case 5:
//Blokuojasi ir laukia sintaks� patikrinta resurso
vieta = 6;
Primityvai.prasytiResurso(VRstring.Sintakse_patikrinta, nameI, 1);
break;
case 6:
//Blokuojasi ir laukia kanal� �renginys
vieta++;
Primityvai.prasytiResurso(DRstring.Kanalu_irenginys, nameI, 1);
break;
case 7:
//Tikrinama ar buvo klaidu ar nebuvo
ResourceDescriptor sintaksesResursas = null;
for (int i = 0; i < resursai.size(); i++)
if (resursai.get(i).nameO == Statiniai.VRstring.Sintakse_patikrinta) {
for (int j = 0; j < VRSS.list.get(Statiniai.VRint.Sintakse_patikrinta).resourceList.size(); j++)
if (VRSS.list.get(Statiniai.VRint.Sintakse_patikrinta).resourceList.get(j).nameI == resursai.get(i).nameI) {
sintaksesResursas = VRSS.list.get(Statiniai.VRint.Sintakse_patikrinta).resourceList.get(j);
break;
}
break;
}
if (sintaksesResursas == null)
System.out.println("Input stream neturi sintaks�s resurso.. Baisi klaida");
if ((boolean)sintaksesResursas.info.o) {
//Jei visa sintaks� teisinga
System.out.println("Sintaks� teisinga!");
vieta++;
Primityvai.prasytiResurso(Statiniai.DRstring.HDD, nameI, 1);
} else {
//Jei sintaks� neteisinga
System.out.println("U�duotyje buvo klaid�!");
vieta = 9;
Primityvai.atlaisvintiResursa(Statiniai.DRstring.Kanalu_irenginys, nameI);
}
break;
case 8:
//Kopijuoja u�duot� � HDD
HDDObject hdd = null;
for (int i = 0; i < resursai.size(); i++)
if (resursai.get(i).nameO == Statiniai.DRstring.HDD) {
hdd = ((HDDObject)(RSS.list.get(Statiniai.DRint.HDD).resourceDescriptor.info).o);
break;
}
//gaunam kuriam bloke programa
int kurisBlokas = 0;
for (int i = 0; i < hdd.HDD_SIZE; i++)
if (hdd.hdd.get(i) == programaHDD) {
kurisBlokas = i;
break;
}
ChannelDevice.setValueOfChannel(ChannelDevice.IO, 1);
ChannelDevice.setValueOfChannel(ChannelDevice.OO, 2);
ChannelDevice.setValueOfChannel(ChannelDevice.IA, nuoKur);
ChannelDevice.setValueOfChannel(ChannelDevice.OA, kurisBlokas*255);
ChannelDevice.c = nuskaitytiZodziai;
ChannelDevice.runDevice();
vieta = 9;
Primityvai.atlaisvintiResursa(Statiniai.DRstring.Kanalu_irenginys, nameI);
break;
case 9:
vieta = 10;
Primityvai.sukurtiResursa(Statiniai.VRstring.InputStream_pabaiga, true, father, null);
break;
}
}
|
diff --git a/chronicle-demo/src/main/java/vanilla/java/processingengine/GWMain.java b/chronicle-demo/src/main/java/vanilla/java/processingengine/GWMain.java
index d9a61af..8584c27 100755
--- a/chronicle-demo/src/main/java/vanilla/java/processingengine/GWMain.java
+++ b/chronicle-demo/src/main/java/vanilla/java/processingengine/GWMain.java
@@ -1,218 +1,218 @@
/*
* Copyright 2013 Peter Lawrey
*
* 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 vanilla.java.processingengine;
import net.openhft.affinity.AffinitySupport;
import net.openhft.chronicle.ChronicleConfig;
import net.openhft.chronicle.IndexedChronicle;
import net.openhft.chronicle.tools.ChronicleTools;
import org.jetbrains.annotations.NotNull;
import vanilla.java.processingengine.api.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
/**
* For a latency test Start first: PEMain Then run: GEMain 2 false When the count down is reached: GEMain 1 false
*
* @author peter.lawrey
*/
/*
on a dual core i7-4500 laptop
Processed 10,000,000 events in and out in 100.2 seconds
The latency distribution was 0.5, 0.6/3.4, 322/947 (3,683) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
The latency distribution was 0.6, 0.7/3.1, 15/544 (1,856) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 10,000,000 events in and out in 50.1 seconds
The latency distribution was 0.6, 0.7/4.0, 132/3563 (6,319) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
The latency distribution was 0.5, 0.6/3.2, 58/1557 (4,031) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 10,000,000 events in and out in 20.0 seconds
The latency distribution was 0.4, 1.5/32.5, 2420/6440 (9,733) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
The latency distribution was 0.6, 0.7/3.3, 17/380 (537) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
The latency distribution was 0.5, 1.2/4.3, 226/1800 (2,482) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 10,000,000 events in and out in 10.1 seconds
The latency distribution was 31386.8, 80422.8/97564.0, 99054/99780 (100,282) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
The latency distribution was 0.5, 40561.4/54889.5, 56752/56876 (56,902) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
on a hex core i7 using isolated CPUs (all runs, good and bad)
Processed 10,000,000 events in and out in 100.2 seconds
The latency distribution was 0.3, 0.3/1.5, 2/13 (6,312) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 100,000,000 events in and out in 1001.0 seconds
The latency distribution was 0.3, 0.3/1.6, 2/13 (4,072) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 10,000,000 events in and out in 50.1 seconds
The latency distribution was 0.3, 0.3/1.5, 2/11 (91) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 10,000,000 events in and out in 20.0 seconds
The latency distribution was 0.3, 0.3/1.6, 2/12 (77) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 100,000,000 events in and out in 200.2 seconds
The latency distribution was 0.3, 0.3/1.5, 3/11 (84) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 100,000,000 events in and out in 100.1 seconds
The latency distribution was 0.3, 0.9/2.9, 6/25 (2,571) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 100,000,000 events in and out in 50.1 seconds
The latency distribution was 27.7, 185.4/598.6, 1815/3830 (4,014) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 100,000,000 events in and out in 50.1 seconds
The latency distribution was 1.9, 14.4/38.9, 69/376 (528) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
Processed 100,000,000 events in and out in 50.1 seconds
The latency distribution was 16.5, 81.7/199.2, 379/581 (623) us for the 50, 90/99, 99.9/99.99 %tile, (worst)
*/
public class GWMain {
public static final int WARMUP = Integer.getInteger("warmup", 100 * 1000); // number of events
public static final long EVENT_SPACING = Integer.getInteger("event-spacing", 5 * 1000);
public static final int ORDERS = Integer.getInteger("orders", 10 * 1000 * 1000);
public static void main(@NotNull String... args) throws IOException, InterruptedException {
if (args.length < 2) {
System.err.print("java " + GWMain.class.getName() + " [1 or 2] {throughput}");
System.exit(-1);
}
ChronicleTools.warmup();
final int gwId = Integer.parseInt(args[0]);
final boolean throughputTest = Boolean.parseBoolean(args[1]);
String tmp = System.getProperty("java.io.tmpdir");
// String tmp = System.getProperty("user.home");
String gw2pePath = tmp + "/demo/gw2pe" + gwId;
String pePath = tmp + "/demo/pe";
// setup
ChronicleConfig config = ChronicleConfig.DEFAULT.clone();
// config.dataBlockSize(4 * 1024);
// config.indexBlockSize(4 * 1024);
IndexedChronicle gw2pe = new IndexedChronicle(gw2pePath, config);
Gw2PeEvents gw2PeWriter = new Gw2PeWriter(gw2pe.createAppender());
IndexedChronicle pe2gw = new IndexedChronicle(pePath, config);
final long[] times = new long[ORDERS];
final AtomicInteger reportCount = new AtomicInteger(-WARMUP);
Pe2GwEvents listener = new Pe2GwEvents() {
@Override
public void report(@NotNull MetaData metaData, SmallReport smallReport) {
if (metaData.sourceId != gwId) return;
int count = reportCount.getAndIncrement();
if (!throughputTest) {
- times[Math.abs(count)] = (metaData.inReadTimestamp - metaData.inWriteTimestamp);
+ times[Math.abs(count)] = (metaData.outReadTimestamp - metaData.inWriteTimestamp);
}
// System.out.println(reportCount);
}
};
final Pe2GwReader pe2GwReader = new Pe2GwReader(gwId, pe2gw.createTailer(), listener);
// synchronize the start.
if (gwId > 1) {
int startTime = (int) ((System.currentTimeMillis() / 1000 - 5) % 10) + 5;
System.out.println("Count down");
for (int i = startTime; i > 0; i--) {
System.out.print(i + " ");
System.out.flush();
//noinspection BusyWait
Thread.sleep(1000);
}
}
// In reality, this would be in the same thread.
// A second thread is used here to ensure there is no Co-ordinated Omission
// where the producer slows down to suit the consumer which makes delays seem far less significant.
Thread t = new Thread(new Runnable() {
@Override
public void run() {
AffinitySupport.setAffinity(1L << 3);
while (reportCount.get() < ORDERS) {
pe2GwReader.readOne();
}
}
});
t.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
int n = 0;
while (reportCount.get() < ORDERS) {
while (reportCount.get() < n)
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
int count = reportCount.get();
System.out.println("processed " + count);
n += 1000000;
}
}
});
t2.start();
AffinitySupport.setAffinity(1L << 1);
// run loop
SmallCommand command = new SmallCommand();
@SuppressWarnings("MismatchedQueryAndUpdateOfStringBuilder")
StringBuilder clientOrderId = command.clientOrderId;
System.out.println("Started");
long start = System.nanoTime();
for (int i = 0; i < ORDERS + WARMUP; i++) {
if (i == WARMUP)
start = System.nanoTime();
clientOrderId.setLength(0);
clientOrderId.append("orderId-");
clientOrderId.append(gwId);
clientOrderId.append('-');
clientOrderId.append(i);
command.instrument = "XAU/EUR";
command.price = 1209.41;
command.quantity = 1000;
command.side = (i & 1) == 0 ? Side.BUY : Side.SELL;
if (!throughputTest) {
long expectedTime = start + i * EVENT_SPACING - 30;
while (System.nanoTime() < expectedTime) {
//
}
}
gw2PeWriter.small(null, command);
}
System.out.println("Received " + reportCount.get());
t.join();
long time = System.nanoTime() - start;
Arrays.sort(times);
System.out.printf("Processed %,d events in and out in %.1f seconds%n", ORDERS, time / 1e9);
if (!throughputTest) {
System.out.printf("The latency distribution was %.1f, %.1f/%.1f, %d/%d (%,d) us for the 50, 90/99, 99.9/99.99 %%tile, (worst)%n",
times[ORDERS / 2] / 1e3,
times[ORDERS * 9 / 10] / 1e3,
times[ORDERS - ORDERS / 100] / 1e3,
times[ORDERS - ORDERS / 1000] / 1000,
times[ORDERS - ORDERS / 10000] / 1000,
times[ORDERS - 1] / 1000
);
}
gw2pe.close();
pe2gw.close();
}
}
| true | true | public static void main(@NotNull String... args) throws IOException, InterruptedException {
if (args.length < 2) {
System.err.print("java " + GWMain.class.getName() + " [1 or 2] {throughput}");
System.exit(-1);
}
ChronicleTools.warmup();
final int gwId = Integer.parseInt(args[0]);
final boolean throughputTest = Boolean.parseBoolean(args[1]);
String tmp = System.getProperty("java.io.tmpdir");
// String tmp = System.getProperty("user.home");
String gw2pePath = tmp + "/demo/gw2pe" + gwId;
String pePath = tmp + "/demo/pe";
// setup
ChronicleConfig config = ChronicleConfig.DEFAULT.clone();
// config.dataBlockSize(4 * 1024);
// config.indexBlockSize(4 * 1024);
IndexedChronicle gw2pe = new IndexedChronicle(gw2pePath, config);
Gw2PeEvents gw2PeWriter = new Gw2PeWriter(gw2pe.createAppender());
IndexedChronicle pe2gw = new IndexedChronicle(pePath, config);
final long[] times = new long[ORDERS];
final AtomicInteger reportCount = new AtomicInteger(-WARMUP);
Pe2GwEvents listener = new Pe2GwEvents() {
@Override
public void report(@NotNull MetaData metaData, SmallReport smallReport) {
if (metaData.sourceId != gwId) return;
int count = reportCount.getAndIncrement();
if (!throughputTest) {
times[Math.abs(count)] = (metaData.inReadTimestamp - metaData.inWriteTimestamp);
}
// System.out.println(reportCount);
}
};
final Pe2GwReader pe2GwReader = new Pe2GwReader(gwId, pe2gw.createTailer(), listener);
// synchronize the start.
if (gwId > 1) {
int startTime = (int) ((System.currentTimeMillis() / 1000 - 5) % 10) + 5;
System.out.println("Count down");
for (int i = startTime; i > 0; i--) {
System.out.print(i + " ");
System.out.flush();
//noinspection BusyWait
Thread.sleep(1000);
}
}
// In reality, this would be in the same thread.
// A second thread is used here to ensure there is no Co-ordinated Omission
// where the producer slows down to suit the consumer which makes delays seem far less significant.
Thread t = new Thread(new Runnable() {
@Override
public void run() {
AffinitySupport.setAffinity(1L << 3);
while (reportCount.get() < ORDERS) {
pe2GwReader.readOne();
}
}
});
t.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
int n = 0;
while (reportCount.get() < ORDERS) {
while (reportCount.get() < n)
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
int count = reportCount.get();
System.out.println("processed " + count);
n += 1000000;
}
}
});
t2.start();
AffinitySupport.setAffinity(1L << 1);
// run loop
SmallCommand command = new SmallCommand();
@SuppressWarnings("MismatchedQueryAndUpdateOfStringBuilder")
StringBuilder clientOrderId = command.clientOrderId;
System.out.println("Started");
long start = System.nanoTime();
for (int i = 0; i < ORDERS + WARMUP; i++) {
if (i == WARMUP)
start = System.nanoTime();
clientOrderId.setLength(0);
clientOrderId.append("orderId-");
clientOrderId.append(gwId);
clientOrderId.append('-');
clientOrderId.append(i);
command.instrument = "XAU/EUR";
command.price = 1209.41;
command.quantity = 1000;
command.side = (i & 1) == 0 ? Side.BUY : Side.SELL;
if (!throughputTest) {
long expectedTime = start + i * EVENT_SPACING - 30;
while (System.nanoTime() < expectedTime) {
//
}
}
gw2PeWriter.small(null, command);
}
System.out.println("Received " + reportCount.get());
t.join();
long time = System.nanoTime() - start;
Arrays.sort(times);
System.out.printf("Processed %,d events in and out in %.1f seconds%n", ORDERS, time / 1e9);
if (!throughputTest) {
System.out.printf("The latency distribution was %.1f, %.1f/%.1f, %d/%d (%,d) us for the 50, 90/99, 99.9/99.99 %%tile, (worst)%n",
times[ORDERS / 2] / 1e3,
times[ORDERS * 9 / 10] / 1e3,
times[ORDERS - ORDERS / 100] / 1e3,
times[ORDERS - ORDERS / 1000] / 1000,
times[ORDERS - ORDERS / 10000] / 1000,
times[ORDERS - 1] / 1000
);
}
gw2pe.close();
pe2gw.close();
}
| public static void main(@NotNull String... args) throws IOException, InterruptedException {
if (args.length < 2) {
System.err.print("java " + GWMain.class.getName() + " [1 or 2] {throughput}");
System.exit(-1);
}
ChronicleTools.warmup();
final int gwId = Integer.parseInt(args[0]);
final boolean throughputTest = Boolean.parseBoolean(args[1]);
String tmp = System.getProperty("java.io.tmpdir");
// String tmp = System.getProperty("user.home");
String gw2pePath = tmp + "/demo/gw2pe" + gwId;
String pePath = tmp + "/demo/pe";
// setup
ChronicleConfig config = ChronicleConfig.DEFAULT.clone();
// config.dataBlockSize(4 * 1024);
// config.indexBlockSize(4 * 1024);
IndexedChronicle gw2pe = new IndexedChronicle(gw2pePath, config);
Gw2PeEvents gw2PeWriter = new Gw2PeWriter(gw2pe.createAppender());
IndexedChronicle pe2gw = new IndexedChronicle(pePath, config);
final long[] times = new long[ORDERS];
final AtomicInteger reportCount = new AtomicInteger(-WARMUP);
Pe2GwEvents listener = new Pe2GwEvents() {
@Override
public void report(@NotNull MetaData metaData, SmallReport smallReport) {
if (metaData.sourceId != gwId) return;
int count = reportCount.getAndIncrement();
if (!throughputTest) {
times[Math.abs(count)] = (metaData.outReadTimestamp - metaData.inWriteTimestamp);
}
// System.out.println(reportCount);
}
};
final Pe2GwReader pe2GwReader = new Pe2GwReader(gwId, pe2gw.createTailer(), listener);
// synchronize the start.
if (gwId > 1) {
int startTime = (int) ((System.currentTimeMillis() / 1000 - 5) % 10) + 5;
System.out.println("Count down");
for (int i = startTime; i > 0; i--) {
System.out.print(i + " ");
System.out.flush();
//noinspection BusyWait
Thread.sleep(1000);
}
}
// In reality, this would be in the same thread.
// A second thread is used here to ensure there is no Co-ordinated Omission
// where the producer slows down to suit the consumer which makes delays seem far less significant.
Thread t = new Thread(new Runnable() {
@Override
public void run() {
AffinitySupport.setAffinity(1L << 3);
while (reportCount.get() < ORDERS) {
pe2GwReader.readOne();
}
}
});
t.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
int n = 0;
while (reportCount.get() < ORDERS) {
while (reportCount.get() < n)
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
int count = reportCount.get();
System.out.println("processed " + count);
n += 1000000;
}
}
});
t2.start();
AffinitySupport.setAffinity(1L << 1);
// run loop
SmallCommand command = new SmallCommand();
@SuppressWarnings("MismatchedQueryAndUpdateOfStringBuilder")
StringBuilder clientOrderId = command.clientOrderId;
System.out.println("Started");
long start = System.nanoTime();
for (int i = 0; i < ORDERS + WARMUP; i++) {
if (i == WARMUP)
start = System.nanoTime();
clientOrderId.setLength(0);
clientOrderId.append("orderId-");
clientOrderId.append(gwId);
clientOrderId.append('-');
clientOrderId.append(i);
command.instrument = "XAU/EUR";
command.price = 1209.41;
command.quantity = 1000;
command.side = (i & 1) == 0 ? Side.BUY : Side.SELL;
if (!throughputTest) {
long expectedTime = start + i * EVENT_SPACING - 30;
while (System.nanoTime() < expectedTime) {
//
}
}
gw2PeWriter.small(null, command);
}
System.out.println("Received " + reportCount.get());
t.join();
long time = System.nanoTime() - start;
Arrays.sort(times);
System.out.printf("Processed %,d events in and out in %.1f seconds%n", ORDERS, time / 1e9);
if (!throughputTest) {
System.out.printf("The latency distribution was %.1f, %.1f/%.1f, %d/%d (%,d) us for the 50, 90/99, 99.9/99.99 %%tile, (worst)%n",
times[ORDERS / 2] / 1e3,
times[ORDERS * 9 / 10] / 1e3,
times[ORDERS - ORDERS / 100] / 1e3,
times[ORDERS - ORDERS / 1000] / 1000,
times[ORDERS - ORDERS / 10000] / 1000,
times[ORDERS - 1] / 1000
);
}
gw2pe.close();
pe2gw.close();
}
|
diff --git a/src/main/java/tripleplay/util/Layers.java b/src/main/java/tripleplay/util/Layers.java
index be002e13..32aaa15d 100644
--- a/src/main/java/tripleplay/util/Layers.java
+++ b/src/main/java/tripleplay/util/Layers.java
@@ -1,57 +1,57 @@
//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.util;
import playn.core.GroupLayer;
import playn.core.Layer;
import pythagoras.f.Point;
import pythagoras.f.Rectangle;
import pythagoras.f.Transform;
/**
* Provides utility functions for dealing with Layers
*/
public class Layers
{
/**
* Computes the total bounds of the layer hierarchy rooted at <code>root</code>.
* The returned Rectangle will be in <code>root</code>'s coordinate system.
*/
public static Rectangle totalBounds (Layer root)
{
Rectangle r = new Rectangle();
addBounds(root, root, r);
return r;
}
/**
* Helper function for totalBounds()
*/
protected static void addBounds (Layer root, Layer l, Rectangle bounds)
{
Transform t = l.transform();
Point loc = Layer.Util.layerToParent(l, root, t.tx(), t.ty());
if (l == root) {
// initialize bounds
bounds.setLocation(loc);
} else {
bounds.add(loc);
}
if (l instanceof Layer.HasSize) {
Layer.HasSize lhs = (Layer.HasSize) l;
bounds.add(
- Layer.Util.layerToParent(l, root, loc.x + lhs.width(), loc.y + lhs.height()));
+ Layer.Util.layerToParent(l, root, t.tx() + lhs.width(), t.ty() + lhs.height()));
}
if (l instanceof GroupLayer) {
GroupLayer group = (GroupLayer) l;
for (int ii = 0, ll = group.size(); ii < ll; ++ii) {
addBounds(root, group.get(ii), bounds);
}
}
}
}
| true | true | protected static void addBounds (Layer root, Layer l, Rectangle bounds)
{
Transform t = l.transform();
Point loc = Layer.Util.layerToParent(l, root, t.tx(), t.ty());
if (l == root) {
// initialize bounds
bounds.setLocation(loc);
} else {
bounds.add(loc);
}
if (l instanceof Layer.HasSize) {
Layer.HasSize lhs = (Layer.HasSize) l;
bounds.add(
Layer.Util.layerToParent(l, root, loc.x + lhs.width(), loc.y + lhs.height()));
}
if (l instanceof GroupLayer) {
GroupLayer group = (GroupLayer) l;
for (int ii = 0, ll = group.size(); ii < ll; ++ii) {
addBounds(root, group.get(ii), bounds);
}
}
}
| protected static void addBounds (Layer root, Layer l, Rectangle bounds)
{
Transform t = l.transform();
Point loc = Layer.Util.layerToParent(l, root, t.tx(), t.ty());
if (l == root) {
// initialize bounds
bounds.setLocation(loc);
} else {
bounds.add(loc);
}
if (l instanceof Layer.HasSize) {
Layer.HasSize lhs = (Layer.HasSize) l;
bounds.add(
Layer.Util.layerToParent(l, root, t.tx() + lhs.width(), t.ty() + lhs.height()));
}
if (l instanceof GroupLayer) {
GroupLayer group = (GroupLayer) l;
for (int ii = 0, ll = group.size(); ii < ll; ++ii) {
addBounds(root, group.get(ii), bounds);
}
}
}
|
diff --git a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/ProtocolObjects.java b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/ProtocolObjects.java
index 8dbb8c98f..6d45338da 100644
--- a/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/ProtocolObjects.java
+++ b/sip-servlets-test-suite/testsuite/src/test/java/org/mobicents/servlet/sip/testsuite/ProtocolObjects.java
@@ -1,149 +1,149 @@
/*
* 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.mobicents.servlet.sip.testsuite;
import java.util.HashSet;
import java.util.Properties;
import javax.sip.ObjectInUseException;
import javax.sip.SipException;
import javax.sip.SipFactory;
import javax.sip.SipProvider;
import javax.sip.SipStack;
import javax.sip.address.AddressFactory;
import javax.sip.header.HeaderFactory;
import javax.sip.message.MessageFactory;
/**
* @author M. Ranganathan
*
*/
public class ProtocolObjects {
public final AddressFactory addressFactory;
public final MessageFactory messageFactory;
public final HeaderFactory headerFactory;
public final SipStack sipStack;
private int logLevel = 32;
String logFileDirectory = "logs/";
public final String transport;
private boolean isStarted;
public ProtocolObjects(String stackname, String pathname, String transport,
- boolean autoDialog, String outboundProxy, String threadPoolSize, String reentrantLister) {
+ boolean autoDialog, String outboundProxy, String threadPoolSize, String reentrantListener) {
this.transport = transport;
SipFactory sipFactory = SipFactory.getInstance();
sipFactory.resetFactory();
sipFactory.setPathName(pathname);
Properties properties = new Properties();
properties.setProperty("javax.sip.STACK_NAME", stackname);
if(outboundProxy != null) {
properties.setProperty("javax.sip.OUTBOUND_PROXY", outboundProxy + "/"
+ transport);
}
// The following properties are specific to nist-sip
// and are not necessarily part of any other jain-sip
// implementation.
properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", logFileDirectory
+ stackname + "debuglog.txt");
properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
logFileDirectory + stackname + "log.xml");
properties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT",
(autoDialog ? "on" : "off"));
// For the forked subscribe notify test
properties.setProperty("javax.sip.FORKABLE_EVENTS", "foo");
// Dont use the router for all requests.
// properties.setProperty("javax.sip.USE_ROUTER_FOR_ALL_URIS", "false");
properties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", threadPoolSize == null ? "1" : threadPoolSize);
- properties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", reentrantLister == null ? "false" : reentrantLister);
+ properties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", reentrantListener == null ? "false" : reentrantListener);
// Set to 0 in your production code for max speed.
// You need 16 for logging traces. 32 for debug + traces.
// Your code will limp at 32 but it is best for debugging.
properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", Integer.valueOf(
logLevel).toString());
try {
// Create SipStack object
sipStack = sipFactory.createSipStack(properties);
System.out.println("createSipStack " + sipStack);
} catch (Exception e) {
// could not find
// gov.nist.jain.protocol.ip.sip.SipStackImpl
// in the classpath
e.printStackTrace();
System.err.println(e.getMessage());
throw new RuntimeException("Stack failed to initialize");
}
try {
headerFactory = sipFactory.createHeaderFactory();
addressFactory = sipFactory.createAddressFactory();
messageFactory = sipFactory.createMessageFactory();
} catch (SipException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public synchronized void destroy() {
HashSet<SipProvider> hashSet = new HashSet<SipProvider>();
for (SipProvider sipProvider : hashSet) {
hashSet.add(sipProvider);
}
for (SipProvider sipProvider : hashSet) {
for (int j = 0; j < 5; j++) {
try {
sipStack.deleteSipProvider(sipProvider);
} catch (ObjectInUseException ex) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
}
sipStack.stop();
}
public void start() throws Exception {
if (this.isStarted)
return;
sipStack.start();
this.isStarted = true;
}
}
| false | true | public ProtocolObjects(String stackname, String pathname, String transport,
boolean autoDialog, String outboundProxy, String threadPoolSize, String reentrantLister) {
this.transport = transport;
SipFactory sipFactory = SipFactory.getInstance();
sipFactory.resetFactory();
sipFactory.setPathName(pathname);
Properties properties = new Properties();
properties.setProperty("javax.sip.STACK_NAME", stackname);
if(outboundProxy != null) {
properties.setProperty("javax.sip.OUTBOUND_PROXY", outboundProxy + "/"
+ transport);
}
// The following properties are specific to nist-sip
// and are not necessarily part of any other jain-sip
// implementation.
properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", logFileDirectory
+ stackname + "debuglog.txt");
properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
logFileDirectory + stackname + "log.xml");
properties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT",
(autoDialog ? "on" : "off"));
// For the forked subscribe notify test
properties.setProperty("javax.sip.FORKABLE_EVENTS", "foo");
// Dont use the router for all requests.
// properties.setProperty("javax.sip.USE_ROUTER_FOR_ALL_URIS", "false");
properties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", threadPoolSize == null ? "1" : threadPoolSize);
properties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", reentrantLister == null ? "false" : reentrantLister);
// Set to 0 in your production code for max speed.
// You need 16 for logging traces. 32 for debug + traces.
// Your code will limp at 32 but it is best for debugging.
properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", Integer.valueOf(
logLevel).toString());
try {
// Create SipStack object
sipStack = sipFactory.createSipStack(properties);
System.out.println("createSipStack " + sipStack);
} catch (Exception e) {
// could not find
// gov.nist.jain.protocol.ip.sip.SipStackImpl
// in the classpath
e.printStackTrace();
System.err.println(e.getMessage());
throw new RuntimeException("Stack failed to initialize");
}
try {
headerFactory = sipFactory.createHeaderFactory();
addressFactory = sipFactory.createAddressFactory();
messageFactory = sipFactory.createMessageFactory();
} catch (SipException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
| public ProtocolObjects(String stackname, String pathname, String transport,
boolean autoDialog, String outboundProxy, String threadPoolSize, String reentrantListener) {
this.transport = transport;
SipFactory sipFactory = SipFactory.getInstance();
sipFactory.resetFactory();
sipFactory.setPathName(pathname);
Properties properties = new Properties();
properties.setProperty("javax.sip.STACK_NAME", stackname);
if(outboundProxy != null) {
properties.setProperty("javax.sip.OUTBOUND_PROXY", outboundProxy + "/"
+ transport);
}
// The following properties are specific to nist-sip
// and are not necessarily part of any other jain-sip
// implementation.
properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", logFileDirectory
+ stackname + "debuglog.txt");
properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
logFileDirectory + stackname + "log.xml");
properties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT",
(autoDialog ? "on" : "off"));
// For the forked subscribe notify test
properties.setProperty("javax.sip.FORKABLE_EVENTS", "foo");
// Dont use the router for all requests.
// properties.setProperty("javax.sip.USE_ROUTER_FOR_ALL_URIS", "false");
properties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", threadPoolSize == null ? "1" : threadPoolSize);
properties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", reentrantListener == null ? "false" : reentrantListener);
// Set to 0 in your production code for max speed.
// You need 16 for logging traces. 32 for debug + traces.
// Your code will limp at 32 but it is best for debugging.
properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", Integer.valueOf(
logLevel).toString());
try {
// Create SipStack object
sipStack = sipFactory.createSipStack(properties);
System.out.println("createSipStack " + sipStack);
} catch (Exception e) {
// could not find
// gov.nist.jain.protocol.ip.sip.SipStackImpl
// in the classpath
e.printStackTrace();
System.err.println(e.getMessage());
throw new RuntimeException("Stack failed to initialize");
}
try {
headerFactory = sipFactory.createHeaderFactory();
addressFactory = sipFactory.createAddressFactory();
messageFactory = sipFactory.createMessageFactory();
} catch (SipException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
|
diff --git a/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/LoadProtocolButton.java b/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/LoadProtocolButton.java
index a1604f3..3bf0251 100644
--- a/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/LoadProtocolButton.java
+++ b/fingerpaint/src/nl/tue/fingerpaint/client/gui/buttons/LoadProtocolButton.java
@@ -1,66 +1,66 @@
package nl.tue.fingerpaint.client.gui.buttons;
import io.ashton.fastpress.client.fast.PressEvent;
import io.ashton.fastpress.client.fast.PressHandler;
import java.util.List;
import com.google.gwt.user.client.Timer;
import nl.tue.fingerpaint.client.gui.GuiState;
import nl.tue.fingerpaint.client.model.ApplicationState;
import nl.tue.fingerpaint.client.resources.FingerpaintConstants;
import nl.tue.fingerpaint.client.storage.StorageManager;
/**
* Button that can be used to load a protocol from the local storage.
*
* @author Group Fingerpaint
*/
public class LoadProtocolButton extends FastButton implements PressHandler {
/**
* Reference to the model. Used to get the currently selected geometry.
*/
protected ApplicationState as;
/**
* Construct a new button that can be used to load a protocol from the local
* storage.
*
* @param appState
* Reference to the model, used to retrieve the currently
* selected geometry.
*/
public LoadProtocolButton(ApplicationState appState) {
super(FingerpaintConstants.INSTANCE.btnLoadProt());
this.as = appState;
addPressHandler(this);
ensureDebugId("loadProtocolButton");
}
/**
* Creates a panel with the names of all locally stored distributions.
* @param event The event that has fired.
*/
@Override
public void onPress(PressEvent event) {
GuiState.loadPanel.setIsLoading();
Timer runLater = new Timer() {
@Override
public void run() {
GuiState.loadVerticalPanel.clear();
List<String> geometryProtocols = StorageManager.INSTANCE
.getProtocols(as.getGeometryChoice());
GuiState.loadProtocolCellList.fillCellList(geometryProtocols);
GuiState.loadVerticalPanel.addList(GuiState.loadProtocolCellList);
GuiState.loadVerticalPanel.add(GuiState.closeLoadButton);
- GuiState.loadPanel.center();
+ GuiState.loadPanel.show();
}
};
runLater.schedule(100);
}
}
| true | true | public void onPress(PressEvent event) {
GuiState.loadPanel.setIsLoading();
Timer runLater = new Timer() {
@Override
public void run() {
GuiState.loadVerticalPanel.clear();
List<String> geometryProtocols = StorageManager.INSTANCE
.getProtocols(as.getGeometryChoice());
GuiState.loadProtocolCellList.fillCellList(geometryProtocols);
GuiState.loadVerticalPanel.addList(GuiState.loadProtocolCellList);
GuiState.loadVerticalPanel.add(GuiState.closeLoadButton);
GuiState.loadPanel.center();
}
};
runLater.schedule(100);
}
| public void onPress(PressEvent event) {
GuiState.loadPanel.setIsLoading();
Timer runLater = new Timer() {
@Override
public void run() {
GuiState.loadVerticalPanel.clear();
List<String> geometryProtocols = StorageManager.INSTANCE
.getProtocols(as.getGeometryChoice());
GuiState.loadProtocolCellList.fillCellList(geometryProtocols);
GuiState.loadVerticalPanel.addList(GuiState.loadProtocolCellList);
GuiState.loadVerticalPanel.add(GuiState.closeLoadButton);
GuiState.loadPanel.show();
}
};
runLater.schedule(100);
}
|
diff --git a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchListImportExportTopComponent.java b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchListImportExportTopComponent.java
index 935b6aa0f..c0bbdc2e7 100644
--- a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchListImportExportTopComponent.java
+++ b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchListImportExportTopComponent.java
@@ -1,686 +1,683 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.keywordsearch;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
/**
* Top component which displays something.
*/
@ConvertAsProperties(dtd = "-//org.sleuthkit.autopsy.keywordsearch//KeywordSearchListImportExport//EN",
autostore = false)
@TopComponent.Description(preferredID = "KeywordSearchListImportExportTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE",
persistenceType = TopComponent.PERSISTENCE_NEVER)
@TopComponent.Registration(mode = "explorer", openAtStartup = false)
@ActionID(category = "Window", id = "org.sleuthkit.autopsy.keywordsearch.KeywordSearchListImportExportTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_KeywordSearchListImportExportAction",
preferredID = "KeywordSearchListImportExportTopComponent")
public final class KeywordSearchListImportExportTopComponent extends TopComponent implements KeywordSearchTopComponentInterface {
private Logger logger = Logger.getLogger(KeywordSearchListImportExportTopComponent.class.getName());
private KeywordListTableModel tableModel;
public KeywordSearchListImportExportTopComponent() {
tableModel = new KeywordListTableModel();
initComponents();
customizeComponents();
setName(NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "CTL_KeywordSearchListImportExportTopComponent"));
setToolTipText(NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "HINT_KeywordSearchListImportExportTopComponent"));
}
private void customizeComponents() {
importButton.setToolTipText("Import list(s) of keywords from an external file.");
exportButton.setToolTipText("Export selected list(s) of keywords to an external file.");
deleteButton.setToolTipText("Delete selected list(s) of keywords.");
listsTable.setAutoscrolls(true);
//listsTable.setTableHeader(null);
listsTable.setShowHorizontalLines(false);
listsTable.setShowVerticalLines(false);
listsTable.getParent().setBackground(listsTable.getBackground());
//customize column witdhs
listsTable.setSize(260, 200);
final int width = listsTable.getSize().width;
TableColumn column = null;
for (int i = 0; i < 4; i++) {
column = listsTable.getColumnModel().getColumn(i);
switch (i) {
case 0:
case 1:
case 2:
column.setCellRenderer(new CellTooltipRenderer());
column.setPreferredWidth(((int) (width * 0.28)));
column.setResizable(true);
break;
case 3:
column.setPreferredWidth(((int) (width * 0.15)));
column.setResizable(false);
break;
default:
break;
}
}
listsTable.setCellSelectionEnabled(false);
tableModel.resync();
if (KeywordSearchListsXML.getCurrent().getNumberLists() == 0) {
exportButton.setEnabled(false);
}
KeywordSearchListsXML.getCurrent().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(KeywordSearchListsXML.ListsEvt.LIST_ADDED.toString())
|| evt.getPropertyName().equals(KeywordSearchListsXML.ListsEvt.LIST_DELETED.toString())) {
tableModel.resync();
if (Integer.valueOf((Integer) evt.getNewValue()) == 0) {
exportButton.setEnabled(false);
deleteButton.setEnabled(false);
}
//else if (Integer.valueOf((Integer) evt.getOldValue()) == 0) {
// exportButton.setEnabled(true);
//}
} else if (evt.getPropertyName().equals(KeywordSearchListsXML.ListsEvt.LIST_UPDATED.toString())) {
tableModel.resync((String) evt.getNewValue()); //changed list name
}
}
});
initButtons();
}
private void initButtons() {
if (tableModel.getSelectedLists().isEmpty()) {
deleteButton.setEnabled(false);
exportButton.setEnabled(false);
} else {
deleteButton.setEnabled(true);
exportButton.setEnabled(true);
}
}
/** 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() {
mainScrollPane = new javax.swing.JScrollPane();
mainPanel = new javax.swing.JPanel();
filesIndexedNameLabel = new javax.swing.JLabel();
filesIndexedValLabel = new javax.swing.JLabel();
importButton = new javax.swing.JButton();
exportButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
listsTable = new javax.swing.JTable();
topLabel = new javax.swing.JLabel();
mainScrollPane.setPreferredSize(new java.awt.Dimension(349, 433));
mainPanel.setPreferredSize(new java.awt.Dimension(349, 433));
org.openide.awt.Mnemonics.setLocalizedText(filesIndexedNameLabel, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.filesIndexedNameLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(filesIndexedValLabel, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.filesIndexedValLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(importButton, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.importButton.text")); // NOI18N
importButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
importButtonActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(exportButton, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.exportButton.text")); // NOI18N
exportButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exportButtonActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(deleteButton, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.deleteButton.text")); // NOI18N
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
listsTable.setModel(tableModel);
listsTable.setShowHorizontalLines(false);
listsTable.setShowVerticalLines(false);
listsTable.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(listsTable);
- topLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
+ topLabel.setFont(new java.awt.Font("Tahoma", 0, 12));
org.openide.awt.Mnemonics.setLocalizedText(topLabel, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.topLabel.text")); // NOI18N
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(topLabel)
.addGroup(mainPanelLayout.createSequentialGroup()
- .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addContainerGap())
- .addGroup(mainPanelLayout.createSequentialGroup()
- .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(topLabel)
- .addGroup(mainPanelLayout.createSequentialGroup()
- .addComponent(importButton)
- .addGap(33, 33, 33)
- .addComponent(exportButton)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
- .addComponent(deleteButton))
- .addGroup(mainPanelLayout.createSequentialGroup()
- .addComponent(filesIndexedNameLabel)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addComponent(filesIndexedValLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
- .addContainerGap(84, Short.MAX_VALUE))))
+ .addComponent(filesIndexedNameLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(filesIndexedValLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
+ .addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
+ .addComponent(importButton)
+ .addGap(33, 33, 33)
+ .addComponent(exportButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(deleteButton))
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)))
+ .addContainerGap())
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(topLabel)
.addGap(34, 34, 34)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(importButton)
- .addComponent(deleteButton)
- .addComponent(exportButton))
+ .addComponent(exportButton)
+ .addComponent(deleteButton))
.addGap(35, 35, 35)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(filesIndexedNameLabel)
.addComponent(filesIndexedValLabel))
.addContainerGap(64, Short.MAX_VALUE))
);
mainScrollPane.setViewportView(mainPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
public void importButtonAction(java.awt.event.ActionEvent evt) {
importButtonActionPerformed(evt);
}
private void importButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importButtonActionPerformed
final String FEATURE_NAME = "Keyword List Import";
JFileChooser chooser = new JFileChooser();
final String EXTENSION = "xml";
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Keyword List XML file", EXTENSION);
chooser.setFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File selFile = chooser.getSelectedFile();
if (selFile == null) {
return;
}
//force append extension if not given
String fileAbs = selFile.getAbsolutePath();
final KeywordSearchListsXML reader = new KeywordSearchListsXML(fileAbs);
if (!reader.load()) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Error importing keyword list from file " + fileAbs, KeywordSearchUtil.DIALOG_MESSAGE_TYPE.ERROR);
return;
}
List<KeywordSearchList> toImport = reader.getListsL();
List<KeywordSearchList> toImportConfirmed = new ArrayList<KeywordSearchList>();
final KeywordSearchListsXML writer = KeywordSearchListsXML.getCurrent();
for (KeywordSearchList list : toImport) {
//check name collisions
if (writer.listExists(list.getName())) {
Object[] options = {"Yes, overwrite",
"No, skip",
"Cancel import"};
int choice = JOptionPane.showOptionDialog(this,
"Keyword list <" + list.getName() + "> already exists locally, overwrite?",
"Import list conflict",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (choice == JOptionPane.OK_OPTION) {
toImportConfirmed.add(list);
} else if (choice == JOptionPane.CANCEL_OPTION) {
break;
}
} else {
//no conflict
toImportConfirmed.add(list);
}
}
if (toImportConfirmed.isEmpty()) {
return;
}
if (writer.writeLists(toImportConfirmed)) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Keyword list imported", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO);
}
initButtons();
}
}//GEN-LAST:event_importButtonActionPerformed
private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
final String FEATURE_NAME = "Keyword List Export";
List<String> toExport = tableModel.getSelectedLists();
if (toExport.isEmpty()) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Please select keyword lists to export", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.ERROR);
return;
}
JFileChooser chooser = new JFileChooser();
final String EXTENSION = "xml";
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Keyword List XML file", EXTENSION);
chooser.setFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File selFile = chooser.getSelectedFile();
if (selFile == null) {
return;
}
//force append extension if not given
String fileAbs = selFile.getAbsolutePath();
if (!fileAbs.endsWith("." + EXTENSION)) {
fileAbs = fileAbs + "." + EXTENSION;
selFile = new File(fileAbs);
}
boolean shouldWrite = true;
if (selFile.exists()) {
shouldWrite = KeywordSearchUtil.displayConfirmDialog(FEATURE_NAME, "File " + selFile.getName() + " exists, overwrite?", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN);
}
if (!shouldWrite) {
return;
}
final KeywordSearchListsXML reader = KeywordSearchListsXML.getCurrent();
List<KeywordSearchList> toWrite = new ArrayList<KeywordSearchList>();
for (String listName : toExport) {
toWrite.add(reader.getList(listName));
}
final KeywordSearchListsXML exporter = new KeywordSearchListsXML(fileAbs);
boolean written = exporter.writeLists(toWrite);
if (written) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Keyword lists exported", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO);
return;
}
}
}//GEN-LAST:event_exportButtonActionPerformed
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
tableModel.deleteSelected();
initButtons();
}//GEN-LAST:event_deleteButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton deleteButton;
private javax.swing.JButton exportButton;
private javax.swing.JLabel filesIndexedNameLabel;
private javax.swing.JLabel filesIndexedValLabel;
private javax.swing.JButton importButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable listsTable;
private javax.swing.JPanel mainPanel;
private javax.swing.JScrollPane mainScrollPane;
private javax.swing.JLabel topLabel;
// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
}
@Override
public void componentClosed() {
}
void writeProperties(java.util.Properties p) {
p.setProperty("version", "1.0");
}
void readProperties(java.util.Properties p) {
}
@Override
public void addSearchButtonListener(ActionListener l) {
}
@Override
public List<Keyword> getQueryList() {
return null;
}
@Override
public String getQueryText() {
return null;
}
@Override
public boolean isLuceneQuerySelected() {
return false;
}
@Override
public boolean isMultiwordQuery() {
return false;
}
@Override
public boolean isRegexQuerySelected() {
return false;
}
@Override
public void setFilesIndexed(int filesIndexed) {
filesIndexedValLabel.setText(Integer.toString(filesIndexed));
}
private class KeywordListTableModel extends AbstractTableModel {
//data
private KeywordSearchListsXML listsHandle = KeywordSearchListsXML.getCurrent();
private Set<TableEntry> listData = new TreeSet<TableEntry>();
@Override
public int getColumnCount() {
return 4;
}
@Override
public int getRowCount() {
return listData.size();
}
@Override
public String getColumnName(int column) {
String colName = null;
switch (column) {
case 0:
colName = "Name";
break;
case 1:
colName = "Created";
break;
case 2:
colName = "Modified";
break;
case 3:
colName = "Sel.";
break;
default:
;
}
return colName;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object ret = null;
TableEntry entry = null;
//iterate until row
Iterator<TableEntry> it = listData.iterator();
for (int i = 0; i <= rowIndex; ++i) {
entry = it.next();
}
switch (columnIndex) {
case 0:
ret = (Object) entry.name;
break;
case 1:
ret = (Object) entry.created;
break;
case 2:
ret = (Object) entry.modified;
break;
case 3:
ret = (Object) entry.isActive;
break;
default:
break;
}
return ret;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 3 ? true : false;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == 3) {
TableEntry entry = null;
//iterate until row
Iterator<TableEntry> it = listData.iterator();
for (int i = 0; i <= rowIndex && it.hasNext(); ++i) {
entry = it.next();
}
if (entry != null)
entry.isActive = (Boolean) aValue;
initButtons();
}
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
List<String> getAllLists() {
List<String> ret = new ArrayList<String>();
for (TableEntry e : listData) {
ret.add(e.name);
}
return ret;
}
List<String> getSelectedLists() {
List<String> ret = new ArrayList<String>();
for (TableEntry e : listData) {
if (e.isActive && !e.name.equals("")) {
ret.add(e.name);
}
}
return ret;
}
boolean listExists(String list) {
List<String> all = getAllLists();
return all.contains(list);
}
//delete selected from handle, events are fired from the handle
void deleteSelected() {
List<TableEntry> toDel = new ArrayList<TableEntry>();
for (TableEntry e : listData) {
if (e.isActive && !e.name.equals("")) {
toDel.add(e);
}
}
for (TableEntry del : toDel) {
listsHandle.deleteList(del.name);
}
}
//resync model from handle, then update table
void resync() {
listData.clear();
addLists(listsHandle.getListsL());
fireTableDataChanged();
}
//resync single model entry from handle, then update table
void resync(String listName) {
TableEntry found = null;
for (TableEntry e : listData) {
if (e.name.equals(listName)) {
found = e;
break;
}
}
if (found != null) {
listData.remove(found);
addList(listsHandle.getList(listName));
}
fireTableDataChanged();
}
//add list to the model
private void addList(KeywordSearchList list) {
if (!listExists(list.getName())) {
listData.add(new TableEntry(list));
}
}
//add lists to the model
private void addLists(List<KeywordSearchList> lists) {
for (KeywordSearchList list : lists) {
if (!listExists(list.getName())) {
listData.add(new TableEntry(list));
}
}
}
//single model entry
class TableEntry implements Comparable {
private DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String name;
String created;
String modified;
Boolean isActive;
TableEntry(KeywordSearchList list, Boolean isActive) {
this.name = list.getName();
this.created = dateFormatter.format(list.getDateCreated());
this.modified = dateFormatter.format(list.getDateModified());
this.isActive = isActive;
}
TableEntry(KeywordSearchList list) {
this.name = list.getName();
this.created = dateFormatter.format(list.getDateCreated());
this.modified = dateFormatter.format(list.getDateModified());
this.isActive = false;
}
@Override
public int compareTo(Object o) {
return this.name.compareTo(((TableEntry) o).name);
}
}
}
/**
* tooltips that show text
*/
private static class CellTooltipRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
if (column < 3) {
String val = (String) table.getModel().getValueAt(row, column);
setToolTipText(val);
setText(val);
}
return this;
}
}
}
| false | true | private void initComponents() {
mainScrollPane = new javax.swing.JScrollPane();
mainPanel = new javax.swing.JPanel();
filesIndexedNameLabel = new javax.swing.JLabel();
filesIndexedValLabel = new javax.swing.JLabel();
importButton = new javax.swing.JButton();
exportButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
listsTable = new javax.swing.JTable();
topLabel = new javax.swing.JLabel();
mainScrollPane.setPreferredSize(new java.awt.Dimension(349, 433));
mainPanel.setPreferredSize(new java.awt.Dimension(349, 433));
org.openide.awt.Mnemonics.setLocalizedText(filesIndexedNameLabel, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.filesIndexedNameLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(filesIndexedValLabel, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.filesIndexedValLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(importButton, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.importButton.text")); // NOI18N
importButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
importButtonActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(exportButton, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.exportButton.text")); // NOI18N
exportButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exportButtonActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(deleteButton, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.deleteButton.text")); // NOI18N
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
listsTable.setModel(tableModel);
listsTable.setShowHorizontalLines(false);
listsTable.setShowVerticalLines(false);
listsTable.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(listsTable);
topLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(topLabel, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.topLabel.text")); // NOI18N
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(mainPanelLayout.createSequentialGroup()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(topLabel)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(importButton)
.addGap(33, 33, 33)
.addComponent(exportButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
.addComponent(deleteButton))
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(filesIndexedNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(filesIndexedValLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(84, Short.MAX_VALUE))))
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(topLabel)
.addGap(34, 34, 34)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(importButton)
.addComponent(deleteButton)
.addComponent(exportButton))
.addGap(35, 35, 35)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(filesIndexedNameLabel)
.addComponent(filesIndexedValLabel))
.addContainerGap(64, Short.MAX_VALUE))
);
mainScrollPane.setViewportView(mainPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
mainScrollPane = new javax.swing.JScrollPane();
mainPanel = new javax.swing.JPanel();
filesIndexedNameLabel = new javax.swing.JLabel();
filesIndexedValLabel = new javax.swing.JLabel();
importButton = new javax.swing.JButton();
exportButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
listsTable = new javax.swing.JTable();
topLabel = new javax.swing.JLabel();
mainScrollPane.setPreferredSize(new java.awt.Dimension(349, 433));
mainPanel.setPreferredSize(new java.awt.Dimension(349, 433));
org.openide.awt.Mnemonics.setLocalizedText(filesIndexedNameLabel, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.filesIndexedNameLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(filesIndexedValLabel, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.filesIndexedValLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(importButton, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.importButton.text")); // NOI18N
importButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
importButtonActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(exportButton, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.exportButton.text")); // NOI18N
exportButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exportButtonActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(deleteButton, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.deleteButton.text")); // NOI18N
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
listsTable.setModel(tableModel);
listsTable.setShowHorizontalLines(false);
listsTable.setShowVerticalLines(false);
listsTable.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(listsTable);
topLabel.setFont(new java.awt.Font("Tahoma", 0, 12));
org.openide.awt.Mnemonics.setLocalizedText(topLabel, org.openide.util.NbBundle.getMessage(KeywordSearchListImportExportTopComponent.class, "KeywordSearchListImportExportTopComponent.topLabel.text")); // NOI18N
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(topLabel)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(filesIndexedNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(filesIndexedValLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
.addComponent(importButton)
.addGap(33, 33, 33)
.addComponent(exportButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(deleteButton))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(topLabel)
.addGap(34, 34, 34)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(importButton)
.addComponent(exportButton)
.addComponent(deleteButton))
.addGap(35, 35, 35)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(filesIndexedNameLabel)
.addComponent(filesIndexedValLabel))
.addContainerGap(64, Short.MAX_VALUE))
);
mainScrollPane.setViewportView(mainPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java
index 8ff090cbe..a2a77ebb2 100644
--- a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java
+++ b/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java
@@ -1,79 +1,78 @@
/* ====================================================================
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.
==================================================================== */
package org.apache.poi.ss.formula.functions;
import junit.framework.TestCase;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.eval.StringEval;
import org.apache.poi.ss.formula.eval.ValueEval;
/**
* Tests for {@link Dec2Hex}
*
* @author cedric dot walter @ gmail dot com
*/
public final class TestDec2Hex extends TestCase {
private static ValueEval invokeValue(String number1, String number2) {
ValueEval[] args = new ValueEval[] { new StringEval(number1), new StringEval(number2), };
return new Dec2Hex().evaluate(args, -1, -1);
}
private static ValueEval invokeValue(String number1) {
ValueEval[] args = new ValueEval[] { new StringEval(number1), };
return new Dec2Hex().evaluate(args, -1, -1);
}
private static void confirmValue(String msg, String number1, String number2, String expected) {
ValueEval result = invokeValue(number1, number2);
assertEquals(StringEval.class, result.getClass());
assertEquals(msg, expected, ((StringEval) result).getStringValue());
}
private static void confirmValue(String msg, String number1, String expected) {
ValueEval result = invokeValue(number1);
assertEquals(StringEval.class, result.getClass());
assertEquals(msg, expected, ((StringEval) result).getStringValue());
}
private static void confirmValueError(String msg, String number1, String number2, ErrorEval numError) {
ValueEval result = invokeValue(number1, number2);
assertEquals(ErrorEval.class, result.getClass());
assertEquals(msg, numError, result);
}
public void testBasic() {
confirmValue("Converts decimal 100 to hexadecimal with 0 characters (64)", "100","0", "64");
confirmValue("Converts decimal 100 to hexadecimal with 4 characters (0064)", "100","4", "0064");
confirmValue("Converts decimal 100 to hexadecimal with 5 characters (0064)", "100","5", "00064");
confirmValue("Converts decimal 100 to hexadecimal with 10 (default) characters", "100","10", "0000000064");
confirmValue("If argument places contains a decimal value, dec2hex ignores the numbers to the right side of the decimal point.", "100","10.0", "0000000064");
- confirmValue("Converts decimal -54 to hexadecimal, 0 is ignored", "-54", "0", "00000FFFCA");
- confirmValue("Converts decimal -54 to hexadecimal, 2 is ignored","-54", "2", "00000FFFCA");
- confirmValue("places is optionnal","-54", "00000FFFCA");
+ confirmValue("Converts decimal -54 to hexadecimal, 2 is ignored","-54", "2", "FFFFFFFFCA");
+ confirmValue("places is optionnal","-54", "FFFFFFFFCA");
}
public void testErrors() {
confirmValueError("Out of range min number","-549755813889","0", ErrorEval.NUM_ERROR);
confirmValueError("Out of range max number","549755813888","0", ErrorEval.NUM_ERROR);
confirmValueError("negative places not allowed","549755813888","-10", ErrorEval.NUM_ERROR);
confirmValueError("non number places not allowed","ABCDEF","0", ErrorEval.VALUE_INVALID);
}
}
| true | true | public void testBasic() {
confirmValue("Converts decimal 100 to hexadecimal with 0 characters (64)", "100","0", "64");
confirmValue("Converts decimal 100 to hexadecimal with 4 characters (0064)", "100","4", "0064");
confirmValue("Converts decimal 100 to hexadecimal with 5 characters (0064)", "100","5", "00064");
confirmValue("Converts decimal 100 to hexadecimal with 10 (default) characters", "100","10", "0000000064");
confirmValue("If argument places contains a decimal value, dec2hex ignores the numbers to the right side of the decimal point.", "100","10.0", "0000000064");
confirmValue("Converts decimal -54 to hexadecimal, 0 is ignored", "-54", "0", "00000FFFCA");
confirmValue("Converts decimal -54 to hexadecimal, 2 is ignored","-54", "2", "00000FFFCA");
confirmValue("places is optionnal","-54", "00000FFFCA");
}
| public void testBasic() {
confirmValue("Converts decimal 100 to hexadecimal with 0 characters (64)", "100","0", "64");
confirmValue("Converts decimal 100 to hexadecimal with 4 characters (0064)", "100","4", "0064");
confirmValue("Converts decimal 100 to hexadecimal with 5 characters (0064)", "100","5", "00064");
confirmValue("Converts decimal 100 to hexadecimal with 10 (default) characters", "100","10", "0000000064");
confirmValue("If argument places contains a decimal value, dec2hex ignores the numbers to the right side of the decimal point.", "100","10.0", "0000000064");
confirmValue("Converts decimal -54 to hexadecimal, 2 is ignored","-54", "2", "FFFFFFFFCA");
confirmValue("places is optionnal","-54", "FFFFFFFFCA");
}
|
diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java
index 39e912fb..8bc26f67 100644
--- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java
+++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java
@@ -1,313 +1,314 @@
package com.earth2me.essentials.protect;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import com.earth2me.essentials.protect.data.IProtectedBlock;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPlaceEvent;
public class EssentialsProtectBlockListener extends BlockListener
{
final private transient IProtect prot;
final private transient IEssentials ess;
public EssentialsProtectBlockListener(final IProtect parent)
{
this.prot = parent;
this.ess = prot.getEssentials();
}
@Override
public void onBlockPlace(final BlockPlaceEvent event)
{
if (event.isCancelled())
{
return;
}
final User user = ess.getUser(event.getPlayer());
if (prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild())
{
event.setCancelled(true);
return;
}
final Block blockPlaced = event.getBlockPlaced();
final int id = blockPlaced.getTypeId();
if (prot.checkProtectionItems(ProtectConfig.blacklist_placement, id) && !user.isAuthorized("essentials.protect.exemptplacement"))
{
event.setCancelled(true);
return;
}
if (prot.checkProtectionItems(ProtectConfig.alert_on_placement, id))
{
prot.alert(user, blockPlaced.getType().toString(), Util.i18n("alertPlaced"));
}
final Block below = blockPlaced.getFace(BlockFace.DOWN);
if (below.getType() == Material.RAILS
&& prot.getSettingBool(ProtectConfig.prevent_block_on_rail)
&& prot.getStorage().isProtected(below, user.getName()))
{
event.setCancelled(true);
return;
}
final List<Block> protect = new ArrayList<Block>();
if (blockPlaced.getType() == Material.RAILS
&& prot.getSettingBool(ProtectConfig.protect_rails)
&& user.isAuthorized("essentials.protect"))
{
protect.add(blockPlaced);
if (prot.getSettingBool(ProtectConfig.protect_below_rails))
{
protect.add(blockPlaced.getFace(BlockFace.DOWN));
}
}
if ((blockPlaced.getType() == Material.SIGN_POST || blockPlaced.getType() == Material.WALL_SIGN)
&& prot.getSettingBool(ProtectConfig.protect_signs)
&& user.isAuthorized("essentials.protect"))
{
protect.add(blockPlaced);
if (prot.getSettingBool(ProtectConfig.protect_against_signs))
{
protect.add(event.getBlockAgainst());
}
}
for (Block block : protect)
{
prot.getStorage().protectBlock(block, user.getName());
}
}
@Override
public void onBlockIgnite(BlockIgniteEvent event)
{
Block block = event.getBlock();
if (block.getType() == Material.RAILS
&& prot.getSettingBool(ProtectConfig.protect_rails))
{
event.setCancelled(true);
return;
}
if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST)
&& prot.getSettingBool(ProtectConfig.protect_signs))
{
event.setCancelled(true);
return;
}
if (event.getBlock().getType() == Material.OBSIDIAN
|| event.getBlock().getFace(BlockFace.DOWN).getType() == Material.OBSIDIAN)
{
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_portal_creation));
return;
}
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD))
{
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_fire_spread));
return;
}
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL))
{
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_flint_fire));
return;
}
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LAVA))
{
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lava_fire_spread));
return;
}
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LIGHTNING))
{
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lightning_fire_spread));
return;
}
}
@Override
public void onBlockFromTo(final BlockFromToEvent event)
{
if (event.isCancelled())
{
return;
}
final Block toBlock = event.getToBlock();
if (toBlock.getType() == Material.RAILS
&& prot.getSettingBool(ProtectConfig.protect_rails))
{
event.setCancelled(true);
return;
}
if ((toBlock.getType() == Material.WALL_SIGN || toBlock.getType() == Material.SIGN_POST)
&& prot.getSettingBool(ProtectConfig.protect_signs))
{
event.setCancelled(true);
return;
}
final Block block = event.getBlock();
if (block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER)
{
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_flow));
return;
}
if (block.getType() == Material.LAVA || block.getType() == Material.STATIONARY_LAVA)
{
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_lava_flow));
return;
}
if (block.getType() == Material.AIR)
{
event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_bucket_flow));
return;
}
}
@Override
public void onBlockBurn(final BlockBurnEvent event)
{
final Block block = event.getBlock();
if (block.getType() == Material.RAILS && prot.getSettingBool(ProtectConfig.protect_rails))
{
event.setCancelled(true);
return;
}
if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST)
&& prot.getSettingBool(ProtectConfig.protect_signs))
{
event.setCancelled(true);
return;
}
if (prot.getSettingBool(ProtectConfig.prevent_fire_spread))
{
event.setCancelled(true);
return;
}
}
private final static BlockFace[] faces = new BlockFace[]
{
BlockFace.NORTH,
BlockFace.EAST,
BlockFace.SOUTH,
BlockFace.WEST,
BlockFace.UP,
BlockFace.DOWN,
BlockFace.SELF
};
@Override
public void onBlockBreak(final BlockBreakEvent event)
{
if (event.isCancelled())
{
return;
}
final User user = ess.getUser(event.getPlayer());
if (prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild())
{
event.setCancelled(true);
return;
}
final Block block = event.getBlock();
final int typeId = block.getTypeId();
if (prot.checkProtectionItems(ProtectConfig.blacklist_break, typeId)
&& !user.isAuthorized("essentials.protect.exemptbreak"))
{
event.setCancelled(true);
return;
}
final Material type = block.getType();
if (prot.checkProtectionItems(ProtectConfig.alert_on_break, typeId))
{
prot.alert(user, type.toString(), Util.i18n("alertBroke"));
}
final IProtectedBlock storage = prot.getStorage();
if (user.isAuthorized("essentials.protect.admin"))
{
if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS)
{
storage.unprotectBlock(block);
if (type == Material.RAILS || type == Material.SIGN_POST)
{
final Block below = block.getFace(BlockFace.DOWN);
storage.unprotectBlock(below);
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
else
{
for (BlockFace blockFace : faces)
- {
- final Block against = block.getFace(blockFace);
- storage.unprotectBlock(against);
- }
+ {
+ final Block against = block.getFace(blockFace);
+ storage.unprotectBlock(against);
}
- return;
+ }
}
else
{
final boolean isProtected = storage.isProtected(block, user.getName());
- if (!isProtected)
+ if (isProtected)
+ {
+ event.setCancelled(true);
+ }
+ else
{
if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS)
{
storage.unprotectBlock(block);
if (type == Material.RAILS || type == Material.SIGN_POST)
{
final Block below = block.getFace(BlockFace.DOWN);
storage.unprotectBlock(below);
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
- event.setCancelled(true);
- return;
}
}
}
| false | true | public void onBlockBreak(final BlockBreakEvent event)
{
if (event.isCancelled())
{
return;
}
final User user = ess.getUser(event.getPlayer());
if (prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild())
{
event.setCancelled(true);
return;
}
final Block block = event.getBlock();
final int typeId = block.getTypeId();
if (prot.checkProtectionItems(ProtectConfig.blacklist_break, typeId)
&& !user.isAuthorized("essentials.protect.exemptbreak"))
{
event.setCancelled(true);
return;
}
final Material type = block.getType();
if (prot.checkProtectionItems(ProtectConfig.alert_on_break, typeId))
{
prot.alert(user, type.toString(), Util.i18n("alertBroke"));
}
final IProtectedBlock storage = prot.getStorage();
if (user.isAuthorized("essentials.protect.admin"))
{
if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS)
{
storage.unprotectBlock(block);
if (type == Material.RAILS || type == Material.SIGN_POST)
{
final Block below = block.getFace(BlockFace.DOWN);
storage.unprotectBlock(below);
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
return;
}
else
{
final boolean isProtected = storage.isProtected(block, user.getName());
if (!isProtected)
{
if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS)
{
storage.unprotectBlock(block);
if (type == Material.RAILS || type == Material.SIGN_POST)
{
final Block below = block.getFace(BlockFace.DOWN);
storage.unprotectBlock(below);
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
event.setCancelled(true);
return;
}
}
| public void onBlockBreak(final BlockBreakEvent event)
{
if (event.isCancelled())
{
return;
}
final User user = ess.getUser(event.getPlayer());
if (prot.getSettingBool(ProtectConfig.disable_build) && !user.canBuild())
{
event.setCancelled(true);
return;
}
final Block block = event.getBlock();
final int typeId = block.getTypeId();
if (prot.checkProtectionItems(ProtectConfig.blacklist_break, typeId)
&& !user.isAuthorized("essentials.protect.exemptbreak"))
{
event.setCancelled(true);
return;
}
final Material type = block.getType();
if (prot.checkProtectionItems(ProtectConfig.alert_on_break, typeId))
{
prot.alert(user, type.toString(), Util.i18n("alertBroke"));
}
final IProtectedBlock storage = prot.getStorage();
if (user.isAuthorized("essentials.protect.admin"))
{
if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS)
{
storage.unprotectBlock(block);
if (type == Material.RAILS || type == Material.SIGN_POST)
{
final Block below = block.getFace(BlockFace.DOWN);
storage.unprotectBlock(below);
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
else
{
final boolean isProtected = storage.isProtected(block, user.getName());
if (isProtected)
{
event.setCancelled(true);
}
else
{
if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS)
{
storage.unprotectBlock(block);
if (type == Material.RAILS || type == Material.SIGN_POST)
{
final Block below = block.getFace(BlockFace.DOWN);
storage.unprotectBlock(below);
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
else
{
for (BlockFace blockFace : faces)
{
final Block against = block.getFace(blockFace);
storage.unprotectBlock(against);
}
}
}
}
}
|
diff --git a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/wizards/MavenProjectWizardArchetypePage.java b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/wizards/MavenProjectWizardArchetypePage.java
index 3e8ceb5..db00389 100644
--- a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/wizards/MavenProjectWizardArchetypePage.java
+++ b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/wizards/MavenProjectWizardArchetypePage.java
@@ -1,953 +1,953 @@
/*******************************************************************************
* Copyright (c) 2008-2010 Sonatype, Inc.
* 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:
* Sonatype, Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.m2e.core.wizards;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.IWizardContainer;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.apache.maven.archetype.catalog.Archetype;
import org.apache.maven.archetype.catalog.ArchetypeCatalog;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.DefaultArtifactRepository;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.eclipse.m2e.core.MavenImages;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.archetype.ArchetypeCatalogFactory;
import org.eclipse.m2e.core.archetype.ArchetypeCatalogFactory.NexusIndexerCatalogFactory;
import org.eclipse.m2e.core.archetype.ArchetypeManager;
import org.eclipse.m2e.core.core.MavenLogger;
import org.eclipse.m2e.core.core.Messages;
import org.eclipse.m2e.core.embedder.ArtifactKey;
import org.eclipse.m2e.core.embedder.IMaven;
import org.eclipse.m2e.core.index.IMutableIndex;
import org.eclipse.m2e.core.index.IndexListener;
import org.eclipse.m2e.core.index.IndexManager;
import org.eclipse.m2e.core.project.ProjectImportConfiguration;
import org.eclipse.m2e.core.repository.IRepository;
import org.eclipse.m2e.core.util.M2EUtils;
/**
* Maven Archetype selection wizard page presents the user with a list of available Maven Archetypes available for
* creating new project.
*/
public class MavenProjectWizardArchetypePage extends AbstractMavenWizardPage implements IndexListener {
private static final String KEY_CATALOG = "catalog"; //$NON-NLS-1$
private static final String ALL_CATALOGS = org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_all;
public static final Comparator<Archetype> ARCHETYPE_COMPARATOR = new Comparator<Archetype>() {
public int compare(Archetype a1, Archetype a2) {
String g1 = a1.getGroupId();
String g2 = a2.getGroupId();
int res = g1.compareTo(g2);
if(res != 0) {
return res;
}
String i1 = a1.getArtifactId();
String i2 = a2.getArtifactId();
res = i1.compareTo(i2);
if(res != 0) {
return res;
}
String v1 = a1.getVersion();
String v2 = a2.getVersion();
if(v1 == null) {
return v2 == null ? 0 : -1;
}
return v1.compareTo(v2);
}
};
ComboViewer catalogsComboViewer;
Text filterText;
/** the archetype table viewer */
TableViewer viewer;
/** the description value label */
Text descriptionText;
Button showLastVersionButton;
Button includeShapshotsButton;
Button addArchetypeButton;
/** the list of available archetypes */
volatile Collection<Archetype> archetypes;
Collection<Archetype> lastVersionArchetypes;
/** a flag indicating if the archetype selection is actually used in the wizard */
private boolean isUsed = true;
ArchetypeCatalogFactory catalogFactory = null;
/**
* Default constructor. Sets the title and description of this wizard page and marks it as not being complete as user
* input is required for continuing.
*/
public MavenProjectWizardArchetypePage(ProjectImportConfiguration projectImportConfiguration) {
super("MavenProjectWizardArchetypePage", projectImportConfiguration); //$NON-NLS-1$
setTitle(Messages.getString("wizard.project.page.archetype.title")); //$NON-NLS-1$
setDescription(Messages.getString("wizard.project.page.archetype.description")); //$NON-NLS-1$
setPageComplete(false);
}
/** Creates the page controls. */
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(3, false));
createViewer(composite);
createAdvancedSettings(composite, new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1));
MavenPlugin.getDefault().getIndexManager().addIndexListener(this);
setControl(composite);
}
/** Creates the archetype table viewer. */
private void createViewer(Composite parent) {
Label catalogsLabel = new Label(parent, SWT.NONE);
catalogsLabel.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_lblCatalog);
Composite catalogsComposite = new Composite(parent, SWT.NONE);
GridLayout catalogsCompositeLayout = new GridLayout();
catalogsCompositeLayout.marginWidth = 0;
catalogsCompositeLayout.marginHeight = 0;
catalogsCompositeLayout.numColumns = 2;
catalogsComposite.setLayout(catalogsCompositeLayout);
catalogsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1));
catalogsComboViewer = new ComboViewer(catalogsComposite);
catalogsComboViewer.getControl().setData("name", "catalogsCombo"); //$NON-NLS-1$ //$NON-NLS-2$
catalogsComboViewer.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
catalogsComboViewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object input) {
if(input instanceof Collection) {
return ((Collection<?>) input).toArray();
}
return new Object[0];
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public void dispose() {
}
});
catalogsComboViewer.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
if(element instanceof ArchetypeCatalogFactory) {
return ((ArchetypeCatalogFactory) element).getDescription();
} else if(element instanceof String) {
return element.toString();
}
return super.getText(element);
}
});
catalogsComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if(selection instanceof IStructuredSelection) {
Object factory = ((IStructuredSelection) selection).getFirstElement();
if(factory instanceof ArchetypeCatalogFactory) {
catalogFactory = (ArchetypeCatalogFactory) factory;
} else if(factory instanceof String) {
catalogFactory = null;
}
reloadViewer();
} else {
catalogFactory = null;
loadArchetypes(null, null, null);
}
//remember what was switched to here
if(dialogSettings != null && catalogFactory != null) {
dialogSettings.put(KEY_CATALOG, catalogFactory.getId());
}
}
});
final ArchetypeManager archetypeManager = MavenPlugin.getDefault().getArchetypeManager();
Collection<ArchetypeCatalogFactory> archetypeCatalogs = archetypeManager.getArchetypeCatalogs();
ArrayList allCatalogs = new ArrayList(archetypeManager.getArchetypeCatalogs());
allCatalogs.add(0, ALL_CATALOGS);
catalogsComboViewer.setInput(allCatalogs);
Button configureButton = new Button(catalogsComposite, SWT.NONE);
configureButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
configureButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnConfigure);
configureButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PreferencesUtil.createPreferenceDialogOn(getShell(),
- "org.eclipse.m2e.preferences.MavenArchetypesPreferencePage", null, null).open(); //$NON-NLS-1$
+ "org.eclipse.m2e.core.preferences.MavenArchetypesPreferencePage", null, null).open(); //$NON-NLS-1$
if(catalogFactory == null || archetypeManager.getArchetypeCatalogFactory(catalogFactory.getId()) == null) {
catalogFactory = archetypeManager.getArchetypeCatalogFactory(NexusIndexerCatalogFactory.ID);
}
catalogsComboViewer.setInput(archetypeManager.getArchetypeCatalogs());
catalogsComboViewer.setSelection(new StructuredSelection(catalogFactory));
}
});
Label filterLabel = new Label(parent, SWT.NONE);
filterLabel.setLayoutData(new GridData());
filterLabel.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_lblFilter);
QuickViewerFilter quickViewerFilter = new QuickViewerFilter();
LastVersionFilter versionFilter = new LastVersionFilter();
IncludeSnapshotsFilter snapshotsFilter = new IncludeSnapshotsFilter();
filterText = new Text(parent, SWT.BORDER);
filterText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
filterText.addModifyListener(quickViewerFilter);
filterText.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.keyCode == SWT.ARROW_DOWN) {
viewer.getTable().setFocus();
viewer.getTable().setSelection(0);
viewer.setSelection(new StructuredSelection(viewer.getElementAt(0)), true);
}
}
});
ToolBar toolBar = new ToolBar(parent, SWT.FLAT);
toolBar.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
final ToolItem clearToolItem = new ToolItem(toolBar, SWT.PUSH);
clearToolItem.setEnabled(false);
clearToolItem.setImage(MavenImages.IMG_CLEAR);
clearToolItem.setDisabledImage(MavenImages.IMG_CLEAR_DISABLED);
clearToolItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
filterText.setText(""); //$NON-NLS-1$
}
});
filterText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
clearToolItem.setEnabled(filterText.getText().length() > 0);
}
});
SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, false, true, 3, 1);
// gd_sashForm.widthHint = 500;
gd_sashForm.heightHint = 200;
sashForm.setLayoutData(gd_sashForm);
sashForm.setLayout(new GridLayout());
Composite composite1 = new Composite(sashForm, SWT.NONE);
GridLayout gridLayout1 = new GridLayout();
gridLayout1.horizontalSpacing = 0;
gridLayout1.marginWidth = 0;
gridLayout1.marginHeight = 0;
composite1.setLayout(gridLayout1);
viewer = new TableViewer(composite1, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
Table table = viewer.getTable();
table.setData("name", "archetypesTable"); //$NON-NLS-1$ //$NON-NLS-2$
table.setHeaderVisible(true);
TableColumn column1 = new TableColumn(table, SWT.LEFT);
column1.setWidth(150);
column1.setText(Messages.getString("wizard.project.page.archetype.column.groupId")); //$NON-NLS-1$
TableColumn column0 = new TableColumn(table, SWT.LEFT);
column0.setWidth(150);
column0.setText(Messages.getString("wizard.project.page.archetype.column.artifactId")); //$NON-NLS-1$
TableColumn column2 = new TableColumn(table, SWT.LEFT);
column2.setWidth(100);
column2.setText(Messages.getString("wizard.project.page.archetype.column.version")); //$NON-NLS-1$
GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, true);
tableData.widthHint = 400;
tableData.heightHint = 200;
table.setLayoutData(tableData);
viewer.setLabelProvider(new ArchetypeLabelProvider());
viewer.setComparator(new ViewerComparator() {
public int compare(Viewer viewer, Object e1, Object e2) {
return ARCHETYPE_COMPARATOR.compare((Archetype) e1, (Archetype) e2);
}
});
viewer.addFilter(quickViewerFilter);
viewer.addFilter(versionFilter);
viewer.addFilter(snapshotsFilter);
viewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
if(inputElement instanceof Collection) {
return ((Collection<?>) inputElement).toArray();
}
return new Object[0];
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
});
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Archetype archetype = getArchetype();
if(archetype != null) {
String repositoryUrl = archetype.getRepository();
String description = archetype.getDescription();
String text = description == null ? "" : description; //$NON-NLS-1$
text = text.replaceAll("\n", "").replaceAll("\\s{2,}", " "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
if(repositoryUrl != null) {
text += text.length() > 0 ? "\n" + repositoryUrl : repositoryUrl; //$NON-NLS-1$
}
descriptionText.setText(text);
setPageComplete(true);
} else {
descriptionText.setText(""); //$NON-NLS-1$
setPageComplete(false);
}
}
});
viewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent openevent) {
if(canFlipToNextPage()) {
getContainer().showPage(getNextPage());
}
}
});
Composite composite2 = new Composite(sashForm, SWT.NONE);
GridLayout gridLayout2 = new GridLayout();
gridLayout2.marginHeight = 0;
gridLayout2.marginWidth = 0;
gridLayout2.horizontalSpacing = 0;
composite2.setLayout(gridLayout2);
descriptionText = new Text(composite2, SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY | SWT.MULTI | SWT.BORDER);
GridData descriptionTextData = new GridData(SWT.FILL, SWT.FILL, true, true);
descriptionTextData.heightHint = 40;
descriptionText.setLayoutData(descriptionTextData);
//whole dialog resizes badly without the width hint to the desc text
descriptionTextData.widthHint = 250;
sashForm.setWeights(new int[] {80, 20});
Composite buttonComposite = new Composite(parent, SWT.NONE);
GridData gd_buttonComposite = new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1);
buttonComposite.setLayoutData(gd_buttonComposite);
GridLayout gridLayout = new GridLayout();
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
gridLayout.numColumns = 3;
buttonComposite.setLayout(gridLayout);
showLastVersionButton = new Button(buttonComposite, SWT.CHECK);
showLastVersionButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
showLastVersionButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnLast);
showLastVersionButton.setSelection(true);
showLastVersionButton.addSelectionListener(versionFilter);
includeShapshotsButton = new Button(buttonComposite, SWT.CHECK);
GridData buttonData = new GridData(SWT.LEFT, SWT.CENTER, true, false);
buttonData.horizontalIndent = 25;
includeShapshotsButton.setLayoutData(buttonData);
includeShapshotsButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnSnapshots);
includeShapshotsButton.setSelection(false);
includeShapshotsButton.addSelectionListener(snapshotsFilter);
addArchetypeButton = new Button(buttonComposite, SWT.NONE);
addArchetypeButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnAdd);
addArchetypeButton.setData("name", "addArchetypeButton"); //$NON-NLS-1$ //$NON-NLS-2$
buttonData = new GridData(SWT.RIGHT, SWT.CENTER, true, false);
buttonData.horizontalIndent = 35;
addArchetypeButton.setLayoutData(buttonData);
addArchetypeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
CustomArchetypeDialog dialog = new CustomArchetypeDialog(getShell(),
org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_add_title);
if(dialog.open() == Window.OK) {
String archetypeGroupId = dialog.getArchetypeGroupId();
String archetypeArtifactId = dialog.getArchetypeArtifactId();
String archetypeVersion = dialog.getArchetypeVersion();
String repositoryUrl = dialog.getRepositoryUrl();
downloadArchetype(archetypeGroupId, archetypeArtifactId, archetypeVersion, repositoryUrl);
}
}
});
}
protected IWizardContainer getContainer() {
return super.getContainer();
}
public void addArchetypeSelectionListener(ISelectionChangedListener listener) {
viewer.addSelectionChangedListener(listener);
}
public void dispose() {
MavenPlugin.getDefault().getIndexManager().removeIndexListener(this);
super.dispose();
}
public List<Archetype> getArchetypesForCatalog() {
if(catalogFactory == null) {
return getAllArchetypes();
}
try {
return catalogFactory.getArchetypeCatalog().getArchetypes();
} catch(CoreException ce) {
setErrorMessage(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_error_read);
return null;
}
}
private List<Archetype> getAllArchetypes() {
ArchetypeManager manager = MavenPlugin.getDefault().getArchetypeManager();
Collection<ArchetypeCatalogFactory> archetypeCatalogs = manager.getArchetypeCatalogs();
ArrayList<Archetype> list = new ArrayList<Archetype>();
for(ArchetypeCatalogFactory catalog : archetypeCatalogs) {
try {
//temporary hack to get around 'Test Remote Catalog' blowing up on download
//described in https://issues.sonatype.org/browse/MNGECLIPSE-1792
if(catalog.getDescription().startsWith("Test")) { //$NON-NLS-1$
continue;
}
@SuppressWarnings("unchecked")
List arcs = catalog.getArchetypeCatalog().getArchetypes();
if(arcs != null) {
list.addAll(arcs);
}
} catch(Exception ce) {
MavenLogger.log("Unable to read archetype catalog: " + catalog.getId(), ce);
}
}
return list;
}
/** Loads the available archetypes. */
void loadArchetypes(final String groupId, final String artifactId, final String version) {
Job job = new Job(Messages.getString("wizard.project.page.archetype.retrievingArchetypes")) { //$NON-NLS-1$
protected IStatus run(IProgressMonitor monitor) {
try {
List<Archetype> catalogArchetypes = getArchetypesForCatalog();
if(catalogArchetypes == null || catalogArchetypes.size() == 0) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if(catalogFactory != null && "Nexus Indexer".equals(catalogFactory.getDescription())) { //$NON-NLS-1$
setErrorMessage(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_error_no);
}
}
});
} else {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(null);
}
});
}
if(catalogArchetypes == null) {
return Status.CANCEL_STATUS;
}
TreeSet<Archetype> archs = new TreeSet<Archetype>(ARCHETYPE_COMPARATOR);
archs.addAll(catalogArchetypes);
archetypes = archs;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
updateViewer(groupId, artifactId, version);
}
});
} catch(Exception e) {
monitor.done();
return Status.CANCEL_STATUS;
}
return Status.OK_STATUS;
}
};
job.schedule();
}
public Set<Archetype> filterVersions(Collection<Archetype> archetypes) {
HashMap<String, Archetype> filteredArchetypes = new HashMap<String, Archetype>();
for(Archetype currentArchetype : archetypes) {
String key = getArchetypeKey(currentArchetype);
Archetype archetype = filteredArchetypes.get(key);
if(archetype == null) {
filteredArchetypes.put(key, currentArchetype);
} else {
DefaultArtifactVersion currentVersion = new DefaultArtifactVersion(currentArchetype.getVersion());
DefaultArtifactVersion version = new DefaultArtifactVersion(archetype.getVersion());
if(currentVersion.compareTo(version) > 0) {
filteredArchetypes.put(key, currentArchetype);
}
}
}
TreeSet<Archetype> result = new TreeSet<Archetype>(new Comparator<Archetype>() {
public int compare(Archetype a1, Archetype a2) {
String k1 = a1.getGroupId() + ":" + a1.getArtifactId() + ":" + a1.getVersion(); //$NON-NLS-1$ //$NON-NLS-2$
String k2 = a2.getGroupId() + ":" + a2.getArtifactId() + ":" + a2.getVersion(); //$NON-NLS-1$ //$NON-NLS-2$
return k1.compareTo(k2);
}
});
result.addAll(filteredArchetypes.values());
return result;
}
private String getArchetypeKey(Archetype archetype) {
return archetype.getGroupId() + ":" + archetype.getArtifactId(); //$NON-NLS-1$
}
ArchetypeCatalog getArchetypeCatalog() throws CoreException {
return catalogFactory == null ? null : catalogFactory.getArchetypeCatalog();
}
/** Sets the flag that the archetype selection is used in the wizard. */
public void setUsed(boolean isUsed) {
this.isUsed = isUsed;
}
/** Overrides the default to return "true" if the page is not used. */
public boolean isPageComplete() {
return !isUsed || super.isPageComplete();
}
/** Sets the focus to the table component. */
public void setVisible(boolean visible) {
super.setVisible(visible);
if(visible) {
ArchetypeManager archetypeManager = MavenPlugin.getDefault().getArchetypeManager();
String catalogId = dialogSettings.get(KEY_CATALOG);
catalogFactory = null;
if(catalogId != null) {
catalogFactory = archetypeManager.getArchetypeCatalogFactory(catalogId);
}
catalogsComboViewer.setSelection(new StructuredSelection(catalogFactory == null ? ALL_CATALOGS : catalogFactory));
viewer.getTable().setFocus();
Archetype selected = getArchetype();
if(selected != null) {
viewer.reveal(selected);
}
}
}
/** Returns the selected archetype. */
public Archetype getArchetype() {
return (Archetype) ((IStructuredSelection) viewer.getSelection()).getFirstElement();
}
void updateViewer(String groupId, String artifactId, String version) {
lastVersionArchetypes = filterVersions(archetypes);
viewer.setInput(archetypes);
selectArchetype(groupId, artifactId, version);
Table table = viewer.getTable();
int columnCount = table.getColumnCount();
int width = 0;
for(int i = 0; i < columnCount; i++ ) {
TableColumn column = table.getColumn(i);
column.pack();
width += column.getWidth();
}
GridData tableData = (GridData) table.getLayoutData();
int oldHint = tableData.widthHint;
if(width > oldHint) {
tableData.widthHint = width;
}
getShell().pack(true);
tableData.widthHint = oldHint;
}
protected void selectArchetype(String groupId, String artifactId, String version) {
Archetype archetype = findArchetype(groupId, artifactId, version);
Table table = viewer.getTable();
if(archetype != null) {
viewer.setSelection(new StructuredSelection(archetype), true);
int n = table.getSelectionIndex();
table.setSelection(n);
}
}
/** Locates an archetype with given ids. */
protected Archetype findArchetype(String groupId, String artifactId, String version) {
for(Archetype archetype : archetypes) {
if(archetype.getGroupId().equals(groupId) && archetype.getArtifactId().equals(artifactId)) {
if(version == null || version.equals(archetype.getVersion())) {
return archetype;
}
}
}
return version == null ? null : findArchetype(groupId, artifactId, null);
}
protected void downloadArchetype(final String archetypeGroupId, final String archetypeArtifactId,
final String archetypeVersion, final String repositoryUrl) {
final String archetypeName = archetypeGroupId + ":" + archetypeArtifactId + ":" + archetypeVersion; //$NON-NLS-1$ //$NON-NLS-2$
try {
getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InterruptedException {
monitor.beginTask(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_task_downloading
+ archetypeName, IProgressMonitor.UNKNOWN);
try {
final IMaven maven = MavenPlugin.getDefault().getMaven();
final MavenPlugin plugin = MavenPlugin.getDefault();
final List<ArtifactRepository> remoteRepositories;
if(repositoryUrl.length() == 0) {
remoteRepositories = maven.getArtifactRepositories(); // XXX should use ArchetypeManager.getArhetypeRepositories()
} else {
ArtifactRepository repository = new DefaultArtifactRepository( //
"archetype", repositoryUrl, new DefaultRepositoryLayout(), null, null); //$NON-NLS-1$
remoteRepositories = Collections.singletonList(repository);
}
monitor.subTask(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_task_resolving);
Artifact pomArtifact = maven.resolve(archetypeGroupId, archetypeArtifactId, archetypeVersion,
"pom", null, remoteRepositories, monitor); //$NON-NLS-1$
monitor.worked(1);
if(monitor.isCanceled()) {
throw new InterruptedException();
}
File pomFile = pomArtifact.getFile();
if(pomFile.exists()) {
monitor.subTask(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_task_resolving2);
Artifact jarArtifact = maven.resolve(archetypeGroupId, archetypeArtifactId, archetypeVersion,
"jar", null, remoteRepositories, monitor); //$NON-NLS-1$
monitor.worked(1);
if(monitor.isCanceled()) {
throw new InterruptedException();
}
File jarFile = jarArtifact.getFile();
monitor.subTask(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_task_reading);
monitor.worked(1);
if(monitor.isCanceled()) {
throw new InterruptedException();
}
monitor.subTask(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_task_indexing);
IndexManager indexManager = plugin.getIndexManager();
IMutableIndex localIndex = indexManager.getLocalIndex();
localIndex.addArtifact(jarFile, new ArtifactKey(pomArtifact));
//save out the archetype
//TODO move this logig out of UI code!
Archetype archetype = new Archetype();
archetype.setGroupId(archetypeGroupId);
archetype.setArtifactId(archetypeArtifactId);
archetype.setVersion(archetypeVersion);
archetype.setRepository(repositoryUrl);
org.apache.maven.archetype.Archetype archetyper = MavenPlugin.getDefault().getArchetype();
archetyper.updateLocalCatalog(archetype);
loadArchetypes(archetypeGroupId, archetypeArtifactId, archetypeVersion);
} else {
final Artifact pom = pomArtifact;
//the user tried to add an archetype that couldn't be resolved on the server
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
setErrorMessage(NLS.bind(
org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_error_resolve,
pom.toString()));
}
});
}
} catch(InterruptedException ex) {
throw ex;
} catch(final Exception ex) {
final String msg = NLS.bind(
org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_error_resolve2, archetypeName);
MavenLogger.log(msg, ex);
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
setErrorMessage(msg + "\n" + ex.toString()); //$NON-NLS-1$
}
});
} finally {
monitor.done();
}
}
});
} catch(InterruptedException ex) {
// ignore
} catch(InvocationTargetException ex) {
String msg = NLS.bind(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_error_resolve2,
archetypeName);
MavenLogger.log(msg, ex);
setErrorMessage(msg + "\n" + ex.toString()); //$NON-NLS-1$
}
}
/**
* ArchetypeLabelProvider
*/
protected static class ArchetypeLabelProvider extends LabelProvider implements ITableLabelProvider {
/** Returns the element text */
public String getColumnText(Object element, int columnIndex) {
if(element instanceof Archetype) {
Archetype archetype = (Archetype) element;
switch(columnIndex) {
case 0:
return archetype.getGroupId();
case 1:
return archetype.getArtifactId();
case 2:
return archetype.getVersion();
}
}
return super.getText(element);
}
/** Returns the element text */
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
}
/**
* QuickViewerFilter
*/
protected class QuickViewerFilter extends ViewerFilter implements ModifyListener {
private String currentFilter;
public boolean select(Viewer viewer, Object parentElement, Object element) {
if(currentFilter == null || currentFilter.length() == 0) {
return true;
}
Archetype archetype = (Archetype) element;
return archetype.getGroupId().indexOf(currentFilter) > -1
|| archetype.getArtifactId().indexOf(currentFilter) > -1;
}
public void modifyText(ModifyEvent e) {
this.currentFilter = filterText.getText().trim();
viewer.refresh();
}
}
protected class IncludeSnapshotsFilter extends ViewerFilter implements SelectionListener {
/**
*
*/
private static final String SNAPSHOT = "SNAPSHOT"; //$NON-NLS-1$
private boolean includeSnapshots = false;
public boolean select(Viewer viewer, Object parentElement, Object element) {
if(element instanceof Archetype) {
String version = ((Archetype) element).getVersion();
boolean isSnap = false;
if(M2EUtils.nullOrEmpty(version)) {
isSnap = false;
} else if(version.lastIndexOf(SNAPSHOT) >= 0) {
isSnap = true;
}
return includeSnapshots ? true : !isSnap;
}
return false;
}
public void widgetSelected(SelectionEvent e) {
this.includeSnapshots = includeShapshotsButton.getSelection();
viewer.refresh();
Archetype archetype = getArchetype();
//can be null in some cases, don't try to reveal
if(archetype != null) {
viewer.reveal(archetype);
}
viewer.getTable().setSelection(viewer.getTable().getSelectionIndex());
viewer.getTable().setFocus();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
}
protected class LastVersionFilter extends ViewerFilter implements SelectionListener {
private boolean showLastVersion = true;
public boolean select(Viewer viewer, Object parentElement, Object element) {
return showLastVersion ? lastVersionArchetypes.contains(element) : true;
}
public void widgetSelected(SelectionEvent e) {
this.showLastVersion = showLastVersionButton.getSelection();
viewer.refresh();
Archetype archetype = getArchetype();
//can be null in some cases, don't try to reveal
if(archetype != null) {
viewer.reveal(archetype);
}
viewer.getTable().setSelection(viewer.getTable().getSelectionIndex());
viewer.getTable().setFocus();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
}
/* (non-Javadoc)
* @see org.eclipse.m2e.index.IndexListener#indexAdded(org.eclipse.m2e.repository.IRepository)
*/
public void indexAdded(IRepository repository) {
}
//reload the table when index updating finishes
//try to preserve selection in case this is a rebuild
protected void reloadViewer() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if(isCurrentPage()) {
StructuredSelection sel = (StructuredSelection) viewer.getSelection();
Archetype selArchetype = null;
if(sel != null && sel.getFirstElement() != null) {
selArchetype = (Archetype) sel.getFirstElement();
}
if(selArchetype != null) {
loadArchetypes(selArchetype.getGroupId(), selArchetype.getArtifactId(), selArchetype.getVersion());
} else {
loadArchetypes("org.apache.maven.archetypes", "maven-archetype-quickstart", "1.0"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
});
}
/* (non-Javadoc)
* @see org.eclipse.m2e.index.IndexListener#indexChanged(org.eclipse.m2e.repository.IRepository)
*/
public void indexChanged(IRepository repository) {
reloadViewer();
}
/* (non-Javadoc)
* @see org.eclipse.m2e.index.IndexListener#indexRemoved(org.eclipse.m2e.repository.IRepository)
*/
public void indexRemoved(IRepository repository) {
}
/* (non-Javadoc)
* @see org.eclipse.m2e.index.IndexListener#indexUpdating(org.eclipse.m2e.repository.IRepository)
*/
public void indexUpdating(IRepository repository) {
}
}
| true | true | private void createViewer(Composite parent) {
Label catalogsLabel = new Label(parent, SWT.NONE);
catalogsLabel.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_lblCatalog);
Composite catalogsComposite = new Composite(parent, SWT.NONE);
GridLayout catalogsCompositeLayout = new GridLayout();
catalogsCompositeLayout.marginWidth = 0;
catalogsCompositeLayout.marginHeight = 0;
catalogsCompositeLayout.numColumns = 2;
catalogsComposite.setLayout(catalogsCompositeLayout);
catalogsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1));
catalogsComboViewer = new ComboViewer(catalogsComposite);
catalogsComboViewer.getControl().setData("name", "catalogsCombo"); //$NON-NLS-1$ //$NON-NLS-2$
catalogsComboViewer.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
catalogsComboViewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object input) {
if(input instanceof Collection) {
return ((Collection<?>) input).toArray();
}
return new Object[0];
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public void dispose() {
}
});
catalogsComboViewer.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
if(element instanceof ArchetypeCatalogFactory) {
return ((ArchetypeCatalogFactory) element).getDescription();
} else if(element instanceof String) {
return element.toString();
}
return super.getText(element);
}
});
catalogsComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if(selection instanceof IStructuredSelection) {
Object factory = ((IStructuredSelection) selection).getFirstElement();
if(factory instanceof ArchetypeCatalogFactory) {
catalogFactory = (ArchetypeCatalogFactory) factory;
} else if(factory instanceof String) {
catalogFactory = null;
}
reloadViewer();
} else {
catalogFactory = null;
loadArchetypes(null, null, null);
}
//remember what was switched to here
if(dialogSettings != null && catalogFactory != null) {
dialogSettings.put(KEY_CATALOG, catalogFactory.getId());
}
}
});
final ArchetypeManager archetypeManager = MavenPlugin.getDefault().getArchetypeManager();
Collection<ArchetypeCatalogFactory> archetypeCatalogs = archetypeManager.getArchetypeCatalogs();
ArrayList allCatalogs = new ArrayList(archetypeManager.getArchetypeCatalogs());
allCatalogs.add(0, ALL_CATALOGS);
catalogsComboViewer.setInput(allCatalogs);
Button configureButton = new Button(catalogsComposite, SWT.NONE);
configureButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
configureButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnConfigure);
configureButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PreferencesUtil.createPreferenceDialogOn(getShell(),
"org.eclipse.m2e.preferences.MavenArchetypesPreferencePage", null, null).open(); //$NON-NLS-1$
if(catalogFactory == null || archetypeManager.getArchetypeCatalogFactory(catalogFactory.getId()) == null) {
catalogFactory = archetypeManager.getArchetypeCatalogFactory(NexusIndexerCatalogFactory.ID);
}
catalogsComboViewer.setInput(archetypeManager.getArchetypeCatalogs());
catalogsComboViewer.setSelection(new StructuredSelection(catalogFactory));
}
});
Label filterLabel = new Label(parent, SWT.NONE);
filterLabel.setLayoutData(new GridData());
filterLabel.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_lblFilter);
QuickViewerFilter quickViewerFilter = new QuickViewerFilter();
LastVersionFilter versionFilter = new LastVersionFilter();
IncludeSnapshotsFilter snapshotsFilter = new IncludeSnapshotsFilter();
filterText = new Text(parent, SWT.BORDER);
filterText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
filterText.addModifyListener(quickViewerFilter);
filterText.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.keyCode == SWT.ARROW_DOWN) {
viewer.getTable().setFocus();
viewer.getTable().setSelection(0);
viewer.setSelection(new StructuredSelection(viewer.getElementAt(0)), true);
}
}
});
ToolBar toolBar = new ToolBar(parent, SWT.FLAT);
toolBar.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
final ToolItem clearToolItem = new ToolItem(toolBar, SWT.PUSH);
clearToolItem.setEnabled(false);
clearToolItem.setImage(MavenImages.IMG_CLEAR);
clearToolItem.setDisabledImage(MavenImages.IMG_CLEAR_DISABLED);
clearToolItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
filterText.setText(""); //$NON-NLS-1$
}
});
filterText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
clearToolItem.setEnabled(filterText.getText().length() > 0);
}
});
SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, false, true, 3, 1);
// gd_sashForm.widthHint = 500;
gd_sashForm.heightHint = 200;
sashForm.setLayoutData(gd_sashForm);
sashForm.setLayout(new GridLayout());
Composite composite1 = new Composite(sashForm, SWT.NONE);
GridLayout gridLayout1 = new GridLayout();
gridLayout1.horizontalSpacing = 0;
gridLayout1.marginWidth = 0;
gridLayout1.marginHeight = 0;
composite1.setLayout(gridLayout1);
viewer = new TableViewer(composite1, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
Table table = viewer.getTable();
table.setData("name", "archetypesTable"); //$NON-NLS-1$ //$NON-NLS-2$
table.setHeaderVisible(true);
TableColumn column1 = new TableColumn(table, SWT.LEFT);
column1.setWidth(150);
column1.setText(Messages.getString("wizard.project.page.archetype.column.groupId")); //$NON-NLS-1$
TableColumn column0 = new TableColumn(table, SWT.LEFT);
column0.setWidth(150);
column0.setText(Messages.getString("wizard.project.page.archetype.column.artifactId")); //$NON-NLS-1$
TableColumn column2 = new TableColumn(table, SWT.LEFT);
column2.setWidth(100);
column2.setText(Messages.getString("wizard.project.page.archetype.column.version")); //$NON-NLS-1$
GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, true);
tableData.widthHint = 400;
tableData.heightHint = 200;
table.setLayoutData(tableData);
viewer.setLabelProvider(new ArchetypeLabelProvider());
viewer.setComparator(new ViewerComparator() {
public int compare(Viewer viewer, Object e1, Object e2) {
return ARCHETYPE_COMPARATOR.compare((Archetype) e1, (Archetype) e2);
}
});
viewer.addFilter(quickViewerFilter);
viewer.addFilter(versionFilter);
viewer.addFilter(snapshotsFilter);
viewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
if(inputElement instanceof Collection) {
return ((Collection<?>) inputElement).toArray();
}
return new Object[0];
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
});
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Archetype archetype = getArchetype();
if(archetype != null) {
String repositoryUrl = archetype.getRepository();
String description = archetype.getDescription();
String text = description == null ? "" : description; //$NON-NLS-1$
text = text.replaceAll("\n", "").replaceAll("\\s{2,}", " "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
if(repositoryUrl != null) {
text += text.length() > 0 ? "\n" + repositoryUrl : repositoryUrl; //$NON-NLS-1$
}
descriptionText.setText(text);
setPageComplete(true);
} else {
descriptionText.setText(""); //$NON-NLS-1$
setPageComplete(false);
}
}
});
viewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent openevent) {
if(canFlipToNextPage()) {
getContainer().showPage(getNextPage());
}
}
});
Composite composite2 = new Composite(sashForm, SWT.NONE);
GridLayout gridLayout2 = new GridLayout();
gridLayout2.marginHeight = 0;
gridLayout2.marginWidth = 0;
gridLayout2.horizontalSpacing = 0;
composite2.setLayout(gridLayout2);
descriptionText = new Text(composite2, SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY | SWT.MULTI | SWT.BORDER);
GridData descriptionTextData = new GridData(SWT.FILL, SWT.FILL, true, true);
descriptionTextData.heightHint = 40;
descriptionText.setLayoutData(descriptionTextData);
//whole dialog resizes badly without the width hint to the desc text
descriptionTextData.widthHint = 250;
sashForm.setWeights(new int[] {80, 20});
Composite buttonComposite = new Composite(parent, SWT.NONE);
GridData gd_buttonComposite = new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1);
buttonComposite.setLayoutData(gd_buttonComposite);
GridLayout gridLayout = new GridLayout();
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
gridLayout.numColumns = 3;
buttonComposite.setLayout(gridLayout);
showLastVersionButton = new Button(buttonComposite, SWT.CHECK);
showLastVersionButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
showLastVersionButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnLast);
showLastVersionButton.setSelection(true);
showLastVersionButton.addSelectionListener(versionFilter);
includeShapshotsButton = new Button(buttonComposite, SWT.CHECK);
GridData buttonData = new GridData(SWT.LEFT, SWT.CENTER, true, false);
buttonData.horizontalIndent = 25;
includeShapshotsButton.setLayoutData(buttonData);
includeShapshotsButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnSnapshots);
includeShapshotsButton.setSelection(false);
includeShapshotsButton.addSelectionListener(snapshotsFilter);
addArchetypeButton = new Button(buttonComposite, SWT.NONE);
addArchetypeButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnAdd);
addArchetypeButton.setData("name", "addArchetypeButton"); //$NON-NLS-1$ //$NON-NLS-2$
buttonData = new GridData(SWT.RIGHT, SWT.CENTER, true, false);
buttonData.horizontalIndent = 35;
addArchetypeButton.setLayoutData(buttonData);
addArchetypeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
CustomArchetypeDialog dialog = new CustomArchetypeDialog(getShell(),
org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_add_title);
if(dialog.open() == Window.OK) {
String archetypeGroupId = dialog.getArchetypeGroupId();
String archetypeArtifactId = dialog.getArchetypeArtifactId();
String archetypeVersion = dialog.getArchetypeVersion();
String repositoryUrl = dialog.getRepositoryUrl();
downloadArchetype(archetypeGroupId, archetypeArtifactId, archetypeVersion, repositoryUrl);
}
}
});
}
| private void createViewer(Composite parent) {
Label catalogsLabel = new Label(parent, SWT.NONE);
catalogsLabel.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_lblCatalog);
Composite catalogsComposite = new Composite(parent, SWT.NONE);
GridLayout catalogsCompositeLayout = new GridLayout();
catalogsCompositeLayout.marginWidth = 0;
catalogsCompositeLayout.marginHeight = 0;
catalogsCompositeLayout.numColumns = 2;
catalogsComposite.setLayout(catalogsCompositeLayout);
catalogsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1));
catalogsComboViewer = new ComboViewer(catalogsComposite);
catalogsComboViewer.getControl().setData("name", "catalogsCombo"); //$NON-NLS-1$ //$NON-NLS-2$
catalogsComboViewer.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
catalogsComboViewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object input) {
if(input instanceof Collection) {
return ((Collection<?>) input).toArray();
}
return new Object[0];
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public void dispose() {
}
});
catalogsComboViewer.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
if(element instanceof ArchetypeCatalogFactory) {
return ((ArchetypeCatalogFactory) element).getDescription();
} else if(element instanceof String) {
return element.toString();
}
return super.getText(element);
}
});
catalogsComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if(selection instanceof IStructuredSelection) {
Object factory = ((IStructuredSelection) selection).getFirstElement();
if(factory instanceof ArchetypeCatalogFactory) {
catalogFactory = (ArchetypeCatalogFactory) factory;
} else if(factory instanceof String) {
catalogFactory = null;
}
reloadViewer();
} else {
catalogFactory = null;
loadArchetypes(null, null, null);
}
//remember what was switched to here
if(dialogSettings != null && catalogFactory != null) {
dialogSettings.put(KEY_CATALOG, catalogFactory.getId());
}
}
});
final ArchetypeManager archetypeManager = MavenPlugin.getDefault().getArchetypeManager();
Collection<ArchetypeCatalogFactory> archetypeCatalogs = archetypeManager.getArchetypeCatalogs();
ArrayList allCatalogs = new ArrayList(archetypeManager.getArchetypeCatalogs());
allCatalogs.add(0, ALL_CATALOGS);
catalogsComboViewer.setInput(allCatalogs);
Button configureButton = new Button(catalogsComposite, SWT.NONE);
configureButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
configureButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnConfigure);
configureButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PreferencesUtil.createPreferenceDialogOn(getShell(),
"org.eclipse.m2e.core.preferences.MavenArchetypesPreferencePage", null, null).open(); //$NON-NLS-1$
if(catalogFactory == null || archetypeManager.getArchetypeCatalogFactory(catalogFactory.getId()) == null) {
catalogFactory = archetypeManager.getArchetypeCatalogFactory(NexusIndexerCatalogFactory.ID);
}
catalogsComboViewer.setInput(archetypeManager.getArchetypeCatalogs());
catalogsComboViewer.setSelection(new StructuredSelection(catalogFactory));
}
});
Label filterLabel = new Label(parent, SWT.NONE);
filterLabel.setLayoutData(new GridData());
filterLabel.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_lblFilter);
QuickViewerFilter quickViewerFilter = new QuickViewerFilter();
LastVersionFilter versionFilter = new LastVersionFilter();
IncludeSnapshotsFilter snapshotsFilter = new IncludeSnapshotsFilter();
filterText = new Text(parent, SWT.BORDER);
filterText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
filterText.addModifyListener(quickViewerFilter);
filterText.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.keyCode == SWT.ARROW_DOWN) {
viewer.getTable().setFocus();
viewer.getTable().setSelection(0);
viewer.setSelection(new StructuredSelection(viewer.getElementAt(0)), true);
}
}
});
ToolBar toolBar = new ToolBar(parent, SWT.FLAT);
toolBar.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
final ToolItem clearToolItem = new ToolItem(toolBar, SWT.PUSH);
clearToolItem.setEnabled(false);
clearToolItem.setImage(MavenImages.IMG_CLEAR);
clearToolItem.setDisabledImage(MavenImages.IMG_CLEAR_DISABLED);
clearToolItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
filterText.setText(""); //$NON-NLS-1$
}
});
filterText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
clearToolItem.setEnabled(filterText.getText().length() > 0);
}
});
SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, false, true, 3, 1);
// gd_sashForm.widthHint = 500;
gd_sashForm.heightHint = 200;
sashForm.setLayoutData(gd_sashForm);
sashForm.setLayout(new GridLayout());
Composite composite1 = new Composite(sashForm, SWT.NONE);
GridLayout gridLayout1 = new GridLayout();
gridLayout1.horizontalSpacing = 0;
gridLayout1.marginWidth = 0;
gridLayout1.marginHeight = 0;
composite1.setLayout(gridLayout1);
viewer = new TableViewer(composite1, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
Table table = viewer.getTable();
table.setData("name", "archetypesTable"); //$NON-NLS-1$ //$NON-NLS-2$
table.setHeaderVisible(true);
TableColumn column1 = new TableColumn(table, SWT.LEFT);
column1.setWidth(150);
column1.setText(Messages.getString("wizard.project.page.archetype.column.groupId")); //$NON-NLS-1$
TableColumn column0 = new TableColumn(table, SWT.LEFT);
column0.setWidth(150);
column0.setText(Messages.getString("wizard.project.page.archetype.column.artifactId")); //$NON-NLS-1$
TableColumn column2 = new TableColumn(table, SWT.LEFT);
column2.setWidth(100);
column2.setText(Messages.getString("wizard.project.page.archetype.column.version")); //$NON-NLS-1$
GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, true);
tableData.widthHint = 400;
tableData.heightHint = 200;
table.setLayoutData(tableData);
viewer.setLabelProvider(new ArchetypeLabelProvider());
viewer.setComparator(new ViewerComparator() {
public int compare(Viewer viewer, Object e1, Object e2) {
return ARCHETYPE_COMPARATOR.compare((Archetype) e1, (Archetype) e2);
}
});
viewer.addFilter(quickViewerFilter);
viewer.addFilter(versionFilter);
viewer.addFilter(snapshotsFilter);
viewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
if(inputElement instanceof Collection) {
return ((Collection<?>) inputElement).toArray();
}
return new Object[0];
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
});
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Archetype archetype = getArchetype();
if(archetype != null) {
String repositoryUrl = archetype.getRepository();
String description = archetype.getDescription();
String text = description == null ? "" : description; //$NON-NLS-1$
text = text.replaceAll("\n", "").replaceAll("\\s{2,}", " "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
if(repositoryUrl != null) {
text += text.length() > 0 ? "\n" + repositoryUrl : repositoryUrl; //$NON-NLS-1$
}
descriptionText.setText(text);
setPageComplete(true);
} else {
descriptionText.setText(""); //$NON-NLS-1$
setPageComplete(false);
}
}
});
viewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent openevent) {
if(canFlipToNextPage()) {
getContainer().showPage(getNextPage());
}
}
});
Composite composite2 = new Composite(sashForm, SWT.NONE);
GridLayout gridLayout2 = new GridLayout();
gridLayout2.marginHeight = 0;
gridLayout2.marginWidth = 0;
gridLayout2.horizontalSpacing = 0;
composite2.setLayout(gridLayout2);
descriptionText = new Text(composite2, SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY | SWT.MULTI | SWT.BORDER);
GridData descriptionTextData = new GridData(SWT.FILL, SWT.FILL, true, true);
descriptionTextData.heightHint = 40;
descriptionText.setLayoutData(descriptionTextData);
//whole dialog resizes badly without the width hint to the desc text
descriptionTextData.widthHint = 250;
sashForm.setWeights(new int[] {80, 20});
Composite buttonComposite = new Composite(parent, SWT.NONE);
GridData gd_buttonComposite = new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1);
buttonComposite.setLayoutData(gd_buttonComposite);
GridLayout gridLayout = new GridLayout();
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
gridLayout.numColumns = 3;
buttonComposite.setLayout(gridLayout);
showLastVersionButton = new Button(buttonComposite, SWT.CHECK);
showLastVersionButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
showLastVersionButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnLast);
showLastVersionButton.setSelection(true);
showLastVersionButton.addSelectionListener(versionFilter);
includeShapshotsButton = new Button(buttonComposite, SWT.CHECK);
GridData buttonData = new GridData(SWT.LEFT, SWT.CENTER, true, false);
buttonData.horizontalIndent = 25;
includeShapshotsButton.setLayoutData(buttonData);
includeShapshotsButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnSnapshots);
includeShapshotsButton.setSelection(false);
includeShapshotsButton.addSelectionListener(snapshotsFilter);
addArchetypeButton = new Button(buttonComposite, SWT.NONE);
addArchetypeButton.setText(org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_btnAdd);
addArchetypeButton.setData("name", "addArchetypeButton"); //$NON-NLS-1$ //$NON-NLS-2$
buttonData = new GridData(SWT.RIGHT, SWT.CENTER, true, false);
buttonData.horizontalIndent = 35;
addArchetypeButton.setLayoutData(buttonData);
addArchetypeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
CustomArchetypeDialog dialog = new CustomArchetypeDialog(getShell(),
org.eclipse.m2e.core.internal.Messages.MavenProjectWizardArchetypePage_add_title);
if(dialog.open() == Window.OK) {
String archetypeGroupId = dialog.getArchetypeGroupId();
String archetypeArtifactId = dialog.getArchetypeArtifactId();
String archetypeVersion = dialog.getArchetypeVersion();
String repositoryUrl = dialog.getRepositoryUrl();
downloadArchetype(archetypeGroupId, archetypeArtifactId, archetypeVersion, repositoryUrl);
}
}
});
}
|
diff --git a/cyklotron-core/src/main/java/net/cyklotron/cms/documents/internal/CalendarSearchMethod.java b/cyklotron-core/src/main/java/net/cyklotron/cms/documents/internal/CalendarSearchMethod.java
index 67573f846..3570ba1b2 100644
--- a/cyklotron-core/src/main/java/net/cyklotron/cms/documents/internal/CalendarSearchMethod.java
+++ b/cyklotron-core/src/main/java/net/cyklotron/cms/documents/internal/CalendarSearchMethod.java
@@ -1,246 +1,246 @@
package net.cyklotron.cms.documents.internal;
import java.util.Date;
import java.util.Locale;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.util.Version;
import org.jcontainer.dna.Logger;
import org.objectledge.coral.session.CoralSession;
import org.objectledge.coral.store.Resource;
import org.objectledge.parameters.Parameters;
import org.objectledge.table.TableState;
import net.cyklotron.cms.documents.DocumentNodeResource;
import net.cyklotron.cms.search.SearchConstants;
import net.cyklotron.cms.search.SearchService;
import net.cyklotron.cms.search.SearchUtil;
import net.cyklotron.cms.search.searching.PageableResultsSearchMethod;
/**
* Calendar search method implementation.
*
* @author <a href="mailto:[email protected]">Damian Gajda</a>
* @version $Id: CalendarSearchMethod.java,v 1.8 2005-08-10 05:31:05 rafal Exp $
*/
public class CalendarSearchMethod extends PageableResultsSearchMethod
{
private Logger log;
private Date startDate;
private Date endDate;
private String[] fieldNames;
private Query query;
private String textQuery;
public CalendarSearchMethod(
SearchService searchService,
Parameters parameters,
Locale locale,
Logger log,
Date startDate,
Date endDate)
{
super(searchService, parameters, locale);
this.startDate = startDate;
this.endDate = endDate;
this.log = log;
}
public CalendarSearchMethod(
SearchService searchService,
Parameters parameters,
Locale locale,
Logger log,
Date startDate,
Date endDate,
String textQuery)
{
this(searchService, parameters, locale, log, startDate, endDate);
this.textQuery = textQuery;
}
@Override
public Query getQuery(CoralSession coralSession)
throws Exception
{
return getQuery(coralSession, getFieldNames());
}
@Override
public String getQueryString(CoralSession coralSession)
{
try
{
Query query = getQuery(coralSession, getFieldNames());
return query.toString();
}
catch(Exception e)
{
return "";
}
}
private String[] getFieldNames()
{
if(fieldNames == null)
{
fieldNames = DEFAULT_FIELD_NAMES;
String qField = parameters.get("field","any");
if(!qField.equals("any"))
{
fieldNames = new String[1];
fieldNames[0] = qField;
}
}
return fieldNames;
}
@Override
public void setupTableState(TableState state)
{
super.setupTableState(state);
// block page changes ??
//state.setCurrentPage(1);
}
private Query getQuery(CoralSession coralSession, String[] fieldNames)
throws Exception
{
if(query == null)
{
long firstCatId = parameters.getLong("category_id_1",-1);
long secondCatId = parameters.getLong("category_id_2",-1);
long[] categoriesIds = parameters.getLongs("categories");
long[] categories = new long[categoriesIds.length+2];
System.arraycopy(categoriesIds, 0, categories, 0, categoriesIds.length);
categories[categoriesIds.length] = firstCatId;
categories[categoriesIds.length+1] = secondCatId;
String range = parameters.get("range","all");
query = getQuery(coralSession, startDate, endDate, range, categories, textQuery);
}
return query;
}
private Query getQuery(CoralSession coralSession, Date startDate, Date endDate, String range, long[] categoriesIds, String textQuery)
throws Exception
{
Analyzer analyzer = searchService.getAnalyzer(locale);
BooleanQuery aQuery = new BooleanQuery();
if(textQuery.length() > 0)
{
QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_30, DEFAULT_FIELD_NAMES,
analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
parser.setDateResolution(DateTools.Resolution.SECOND);
Query q = parser.parse(textQuery);
aQuery.add(q, BooleanClause.Occur.MUST);
}
Term lowerEndDate = new Term("eventEnd", SearchUtil.dateToString(startDate));
Term upperStartDate = new Term("eventStart", SearchUtil.dateToString(endDate));
Term lowerStartDate = new Term("eventStart", SearchUtil.dateToString(startDate));
Term upperEndDate = new Term("eventEnd", SearchUtil.dateToString(endDate));
if(range.equals("all"))
{
CalendarAllRangeQuery calQuery = new CalendarAllRangeQuery(log, startDate, endDate);
aQuery.add(new BooleanClause(calQuery, BooleanClause.Occur.MUST));
}
else if(range.equals("in"))
{
TermRangeQuery dateRange = new TermRangeQuery(lowerEndDate.field(),
lowerEndDate.text(), upperEndDate.text(), true, true);
TermRangeQuery dateRange2 = new TermRangeQuery(lowerStartDate.field(), lowerStartDate
.text(), upperStartDate.text(), true, true);
aQuery.add(new BooleanClause(dateRange, BooleanClause.Occur.MUST));
aQuery.add(new BooleanClause(dateRange2, BooleanClause.Occur.MUST));
}
else if(range.equals("ending"))
{
TermRangeQuery dateRange = new TermRangeQuery(lowerEndDate.field(),
lowerEndDate.text(), upperEndDate
.text(), true, true);
aQuery.add(new BooleanClause(dateRange, BooleanClause.Occur.MUST));
}
else if(range.equals("starting"))
{
- TermRangeQuery dateRange2 = new TermRangeQuery(lowerEndDate.field(), lowerEndDate
- .text(), upperEndDate.text(), true, true);
+ TermRangeQuery dateRange2 = new TermRangeQuery(lowerStartDate.field(), lowerStartDate
+ .text(), upperStartDate.text(), true, true);
aQuery.add(new BooleanClause(dateRange2, BooleanClause.Occur.MUST));
}
for (int i = 0; i < categoriesIds.length; i++)
{
if(categoriesIds[i] != -1)
{
Resource category = coralSession.getStore().getResource(categoriesIds[i]);
Query categoryQuery = getQueryForCategory(coralSession, category);
aQuery.add(new BooleanClause(categoryQuery, BooleanClause.Occur.MUST));
}
}
aQuery.add(new BooleanClause(new TermQuery(new Term("titleCalendar",
DocumentNodeResource.EMPTY_TITLE)), BooleanClause.Occur.MUST_NOT));
return aQuery;
}
@Override
public String getErrorQueryString()
{
return "";
}
private Query getQueryForCategory(CoralSession coralSession, Resource category)
{
BooleanQuery query = new BooleanQuery();
addQueriesForCategories(coralSession, query, category);
return query;
}
private void addQueriesForCategories(CoralSession coralSession, BooleanQuery query, Resource parentCategory)
{
TermQuery oneCategoryQuery = new TermQuery(new Term(SearchConstants.FIELD_CATEGORY,
parentCategory.getPath()));
query.add(new BooleanClause(oneCategoryQuery, BooleanClause.Occur.SHOULD));
Resource[] children = coralSession.getStore().getResource(parentCategory);
for (int i = 0; i < children.length; i++)
{
addQueriesForCategories(coralSession, query, children[i]);
}
}
@Override
public SortField[] getSortFields()
{
if(parameters.isDefined("sort_field") &&
parameters.isDefined("sort_order"))
{
return super.getSortFields();
}
else
{
//SortField field = new SortField("eventStart", "desc".equals("desc"));
SortField field2 = new SortField(SearchConstants.FIELD_ID, SortField.LONG, "desc"
.equals("desc"));
return new SortField[] { field2};
}
}
}
| true | true | private Query getQuery(CoralSession coralSession, Date startDate, Date endDate, String range, long[] categoriesIds, String textQuery)
throws Exception
{
Analyzer analyzer = searchService.getAnalyzer(locale);
BooleanQuery aQuery = new BooleanQuery();
if(textQuery.length() > 0)
{
QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_30, DEFAULT_FIELD_NAMES,
analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
parser.setDateResolution(DateTools.Resolution.SECOND);
Query q = parser.parse(textQuery);
aQuery.add(q, BooleanClause.Occur.MUST);
}
Term lowerEndDate = new Term("eventEnd", SearchUtil.dateToString(startDate));
Term upperStartDate = new Term("eventStart", SearchUtil.dateToString(endDate));
Term lowerStartDate = new Term("eventStart", SearchUtil.dateToString(startDate));
Term upperEndDate = new Term("eventEnd", SearchUtil.dateToString(endDate));
if(range.equals("all"))
{
CalendarAllRangeQuery calQuery = new CalendarAllRangeQuery(log, startDate, endDate);
aQuery.add(new BooleanClause(calQuery, BooleanClause.Occur.MUST));
}
else if(range.equals("in"))
{
TermRangeQuery dateRange = new TermRangeQuery(lowerEndDate.field(),
lowerEndDate.text(), upperEndDate.text(), true, true);
TermRangeQuery dateRange2 = new TermRangeQuery(lowerStartDate.field(), lowerStartDate
.text(), upperStartDate.text(), true, true);
aQuery.add(new BooleanClause(dateRange, BooleanClause.Occur.MUST));
aQuery.add(new BooleanClause(dateRange2, BooleanClause.Occur.MUST));
}
else if(range.equals("ending"))
{
TermRangeQuery dateRange = new TermRangeQuery(lowerEndDate.field(),
lowerEndDate.text(), upperEndDate
.text(), true, true);
aQuery.add(new BooleanClause(dateRange, BooleanClause.Occur.MUST));
}
else if(range.equals("starting"))
{
TermRangeQuery dateRange2 = new TermRangeQuery(lowerEndDate.field(), lowerEndDate
.text(), upperEndDate.text(), true, true);
aQuery.add(new BooleanClause(dateRange2, BooleanClause.Occur.MUST));
}
for (int i = 0; i < categoriesIds.length; i++)
{
if(categoriesIds[i] != -1)
{
Resource category = coralSession.getStore().getResource(categoriesIds[i]);
Query categoryQuery = getQueryForCategory(coralSession, category);
aQuery.add(new BooleanClause(categoryQuery, BooleanClause.Occur.MUST));
}
}
aQuery.add(new BooleanClause(new TermQuery(new Term("titleCalendar",
DocumentNodeResource.EMPTY_TITLE)), BooleanClause.Occur.MUST_NOT));
return aQuery;
}
| private Query getQuery(CoralSession coralSession, Date startDate, Date endDate, String range, long[] categoriesIds, String textQuery)
throws Exception
{
Analyzer analyzer = searchService.getAnalyzer(locale);
BooleanQuery aQuery = new BooleanQuery();
if(textQuery.length() > 0)
{
QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_30, DEFAULT_FIELD_NAMES,
analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
parser.setDateResolution(DateTools.Resolution.SECOND);
Query q = parser.parse(textQuery);
aQuery.add(q, BooleanClause.Occur.MUST);
}
Term lowerEndDate = new Term("eventEnd", SearchUtil.dateToString(startDate));
Term upperStartDate = new Term("eventStart", SearchUtil.dateToString(endDate));
Term lowerStartDate = new Term("eventStart", SearchUtil.dateToString(startDate));
Term upperEndDate = new Term("eventEnd", SearchUtil.dateToString(endDate));
if(range.equals("all"))
{
CalendarAllRangeQuery calQuery = new CalendarAllRangeQuery(log, startDate, endDate);
aQuery.add(new BooleanClause(calQuery, BooleanClause.Occur.MUST));
}
else if(range.equals("in"))
{
TermRangeQuery dateRange = new TermRangeQuery(lowerEndDate.field(),
lowerEndDate.text(), upperEndDate.text(), true, true);
TermRangeQuery dateRange2 = new TermRangeQuery(lowerStartDate.field(), lowerStartDate
.text(), upperStartDate.text(), true, true);
aQuery.add(new BooleanClause(dateRange, BooleanClause.Occur.MUST));
aQuery.add(new BooleanClause(dateRange2, BooleanClause.Occur.MUST));
}
else if(range.equals("ending"))
{
TermRangeQuery dateRange = new TermRangeQuery(lowerEndDate.field(),
lowerEndDate.text(), upperEndDate
.text(), true, true);
aQuery.add(new BooleanClause(dateRange, BooleanClause.Occur.MUST));
}
else if(range.equals("starting"))
{
TermRangeQuery dateRange2 = new TermRangeQuery(lowerStartDate.field(), lowerStartDate
.text(), upperStartDate.text(), true, true);
aQuery.add(new BooleanClause(dateRange2, BooleanClause.Occur.MUST));
}
for (int i = 0; i < categoriesIds.length; i++)
{
if(categoriesIds[i] != -1)
{
Resource category = coralSession.getStore().getResource(categoriesIds[i]);
Query categoryQuery = getQueryForCategory(coralSession, category);
aQuery.add(new BooleanClause(categoryQuery, BooleanClause.Occur.MUST));
}
}
aQuery.add(new BooleanClause(new TermQuery(new Term("titleCalendar",
DocumentNodeResource.EMPTY_TITLE)), BooleanClause.Occur.MUST_NOT));
return aQuery;
}
|
diff --git a/src/net/java/otr4j/io/SerializationUtils.java b/src/net/java/otr4j/io/SerializationUtils.java
index 95240250..d8934dd7 100644
--- a/src/net/java/otr4j/io/SerializationUtils.java
+++ b/src/net/java/otr4j/io/SerializationUtils.java
@@ -1,334 +1,334 @@
/*
* otr4j, the open source java otr library.
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package net.java.otr4j.io;
import info.guardianproject.bouncycastle.util.encoders.Base64;
import info.guardianproject.otr.OtrConstants;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.PublicKey;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.interfaces.DHPublicKey;
import net.java.otr4j.io.messages.AbstractEncodedMessage;
import net.java.otr4j.io.messages.AbstractMessage;
import net.java.otr4j.io.messages.DHCommitMessage;
import net.java.otr4j.io.messages.DHKeyMessage;
import net.java.otr4j.io.messages.DataMessage;
import net.java.otr4j.io.messages.ErrorMessage;
import net.java.otr4j.io.messages.MysteriousT;
import net.java.otr4j.io.messages.PlainTextMessage;
import net.java.otr4j.io.messages.QueryMessage;
import net.java.otr4j.io.messages.RevealSignatureMessage;
import net.java.otr4j.io.messages.SignatureM;
import net.java.otr4j.io.messages.SignatureMessage;
import net.java.otr4j.io.messages.SignatureX;
/** @author George Politis */
public class SerializationUtils {
// Mysterious X IO.
public static SignatureX toMysteriousX(byte[] b) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(b);
OtrInputStream ois = new OtrInputStream(in);
SignatureX x = ois.readMysteriousX();
ois.close();
return x;
}
public static byte[] toByteArray(SignatureX x) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OtrOutputStream oos = new OtrOutputStream(out);
oos.writeMysteriousX(x);
byte[] b = out.toByteArray();
oos.close();
return b;
}
// Mysterious M IO.
public static byte[] toByteArray(SignatureM m) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OtrOutputStream oos = new OtrOutputStream(out);
oos.writeMysteriousX(m);
byte[] b = out.toByteArray();
oos.close();
return b;
}
// Mysterious T IO.
public static byte[] toByteArray(MysteriousT t) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OtrOutputStream oos = new OtrOutputStream(out);
oos.writeMysteriousT(t);
byte[] b = out.toByteArray();
out.close();
return b;
}
// Basic IO.
public static byte[] writeData(byte[] b) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OtrOutputStream oos = new OtrOutputStream(out);
oos.writeData(b);
byte[] otrb = out.toByteArray();
out.close();
return otrb;
}
// BigInteger IO.
public static byte[] writeMpi(BigInteger bigInt) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OtrOutputStream oos = new OtrOutputStream(out);
oos.writeBigInt(bigInt);
byte[] b = out.toByteArray();
oos.close();
return b;
}
public static BigInteger readMpi(byte[] b) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(b);
OtrInputStream ois = new OtrInputStream(in);
BigInteger bigint = ois.readBigInt();
ois.close();
return bigint;
}
// Public Key IO.
public static byte[] writePublicKey(PublicKey pubKey) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OtrOutputStream oos = new OtrOutputStream(out);
oos.writePublicKey(pubKey);
byte[] b = out.toByteArray();
oos.close();
return b;
}
// Message IO.
public static String toString(AbstractMessage m) throws IOException {
StringWriter writer = new StringWriter();
writer.write(SerializationConstants.HEAD);
switch (m.messageType) {
case AbstractMessage.MESSAGE_ERROR:
ErrorMessage error = (ErrorMessage) m;
writer.write(SerializationConstants.HEAD_ERROR);
writer.write(error.error);
break;
case AbstractMessage.MESSAGE_PLAINTEXT:
PlainTextMessage plaintxt = (PlainTextMessage) m;
writer.write(plaintxt.cleanText);
if (plaintxt.versions != null && plaintxt.versions.size() > 0) {
writer.write(" \\t \\t\\t\\t\\t \\t \\t \\t ");
for (int version : plaintxt.versions) {
if (version == 1)
writer.write(" \\t\\t \\t ");
if (version == 2)
writer.write(" \\t \\t \\t ");
}
}
break;
case AbstractMessage.MESSAGE_QUERY:
QueryMessage query = (QueryMessage) m;
if (query.versions.size() == 1 && query.versions.get(0) == 1) {
writer.write(SerializationConstants.HEAD_QUERY_Q);
} else {
writer.write(SerializationConstants.HEAD_QUERY_V);
for (int version : query.versions)
writer.write(String.valueOf(version));
writer.write(SerializationConstants.HEAD_QUERY_Q);
}
writer.write(OtrConstants.CommonRequest);
break;
case AbstractEncodedMessage.MESSAGE_DHKEY:
case AbstractEncodedMessage.MESSAGE_REVEALSIG:
case AbstractEncodedMessage.MESSAGE_SIGNATURE:
case AbstractEncodedMessage.MESSAGE_DH_COMMIT:
case AbstractEncodedMessage.MESSAGE_DATA:
ByteArrayOutputStream o = new ByteArrayOutputStream();
OtrOutputStream s = new OtrOutputStream(o);
switch (m.messageType) {
case AbstractEncodedMessage.MESSAGE_DHKEY:
DHKeyMessage dhkey = (DHKeyMessage) m;
s.writeShort(dhkey.protocolVersion);
s.writeByte(dhkey.messageType);
s.writeDHPublicKey(dhkey.dhPublicKey);
break;
case AbstractEncodedMessage.MESSAGE_REVEALSIG:
RevealSignatureMessage revealsig = (RevealSignatureMessage) m;
s.writeShort(revealsig.protocolVersion);
s.writeByte(revealsig.messageType);
s.writeData(revealsig.revealedKey);
s.writeData(revealsig.xEncrypted);
s.writeMac(revealsig.xEncryptedMAC);
break;
case AbstractEncodedMessage.MESSAGE_SIGNATURE:
SignatureMessage sig = (SignatureMessage) m;
s.writeShort(sig.protocolVersion);
s.writeByte(sig.messageType);
s.writeData(sig.xEncrypted);
s.writeMac(sig.xEncryptedMAC);
break;
case AbstractEncodedMessage.MESSAGE_DH_COMMIT:
DHCommitMessage dhcommit = (DHCommitMessage) m;
s.writeShort(dhcommit.protocolVersion);
s.writeByte(dhcommit.messageType);
s.writeData(dhcommit.dhPublicKeyEncrypted);
s.writeData(dhcommit.dhPublicKeyHash);
break;
case AbstractEncodedMessage.MESSAGE_DATA:
DataMessage data = (DataMessage) m;
s.writeShort(data.protocolVersion);
s.writeByte(data.messageType);
s.writeByte(data.flags);
s.writeInt(data.senderKeyID);
s.writeInt(data.recipientKeyID);
s.writeDHPublicKey(data.nextDH);
s.writeCtr(data.ctr);
s.writeData(data.encryptedMessage);
s.writeMac(data.mac);
s.writeData(data.oldMACKeys);
break;
}
writer.write(SerializationConstants.HEAD_ENCODED);
writer.write(new String(Base64.encode(o.toByteArray())));
writer.write(".");
break;
default:
throw new IOException("Illegal message type.");
}
return writer.toString();
}
static final Pattern patternWhitespace = Pattern
.compile("( \\t \\t\\t\\t\\t \\t \\t \\t )( \\t \\t \\t )?( \\t\\t \\t )?");
public static AbstractMessage toMessage(String s) throws IOException {
if (s == null || s.length() <= 1)
return null;
if (s.indexOf(SerializationConstants.HEAD) != 0
|| s.length() <= SerializationConstants.HEAD.length()) {
// Try to detect whitespace tag.
final Matcher matcher = patternWhitespace.matcher(s);
boolean v1 = false;
boolean v2 = false;
while (matcher.find()) {
if (!v1 && matcher.start(2) > -1)
v1 = true;
if (!v2 && matcher.start(3) > -1)
v2 = true;
if (v1 && v2)
break;
}
String cleanText = matcher.replaceAll("");
List<Integer> versions;
if (v1 && v2) {
versions = new Vector<Integer>(2);
versions.add(0, 1);
versions.add(0, 2);
} else if (v1) {
versions = new Vector<Integer>(1);
versions.add(0, 1);
} else if (v2) {
versions = new Vector<Integer>(1);
versions.add(2);
} else
versions = null;
return new PlainTextMessage(versions, cleanText);
} else {
char contentType = s.charAt(SerializationConstants.HEAD.length());
String content = s.substring(SerializationConstants.HEAD.length() + 1);
switch (contentType) {
case SerializationConstants.HEAD_ENCODED:
ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(content
.getBytes()));
OtrInputStream otr = new OtrInputStream(bin);
// We have an encoded message.
int protocolVersion = otr.readShort();
int messageType = otr.readByte();
switch (messageType) {
case AbstractEncodedMessage.MESSAGE_DATA:
int flags = otr.readByte();
int senderKeyID = otr.readInt();
int recipientKeyID = otr.readInt();
DHPublicKey nextDH = otr.readDHPublicKey();
byte[] ctr = otr.readCtr();
byte[] encryptedMessage = otr.readData();
byte[] mac = otr.readMac();
byte[] oldMacKeys = otr.readMac();
return new DataMessage(protocolVersion, flags, senderKeyID, recipientKeyID,
nextDH, ctr, encryptedMessage, mac, oldMacKeys);
case AbstractEncodedMessage.MESSAGE_DH_COMMIT:
byte[] dhPublicKeyEncrypted = otr.readData();
byte[] dhPublicKeyHash = otr.readData();
return new DHCommitMessage(protocolVersion, dhPublicKeyHash,
dhPublicKeyEncrypted);
case AbstractEncodedMessage.MESSAGE_DHKEY:
DHPublicKey dhPublicKey = otr.readDHPublicKey();
return new DHKeyMessage(protocolVersion, dhPublicKey);
case AbstractEncodedMessage.MESSAGE_REVEALSIG: {
byte[] revealedKey = otr.readData();
byte[] xEncrypted = otr.readData();
byte[] xEncryptedMac = otr.readMac();
return new RevealSignatureMessage(protocolVersion, xEncrypted, xEncryptedMac,
revealedKey);
}
case AbstractEncodedMessage.MESSAGE_SIGNATURE: {
byte[] xEncryted = otr.readData();
byte[] xEncryptedMac = otr.readMac();
return new SignatureMessage(protocolVersion, xEncryted, xEncryptedMac);
}
default:
throw new IOException("Illegal message type.");
}
case SerializationConstants.HEAD_MESSAGE:
return new ErrorMessage(AbstractMessage.MESSAGE_ERROR, content);
case SerializationConstants.HEAD_QUERY_V:
case SerializationConstants.HEAD_QUERY_Q:
List<Integer> versions = new Vector<Integer>();
String versionString = null;
if (SerializationConstants.HEAD_QUERY_Q == contentType) {
versions.add(1);
if (content.charAt(0) == 'v') {
versionString = content.substring(1, content.indexOf('?'));
}
} else if (SerializationConstants.HEAD_QUERY_V == contentType) {
versionString = content.substring(0, content.indexOf('?'));
}
if (versionString != null) {
StringReader sr = new StringReader(versionString);
int c;
while ((c = sr.read()) != -1)
if (!versions.contains(c))
versions.add(Integer.parseInt(String.valueOf((char) c)));
}
QueryMessage query = new QueryMessage(versions);
return query;
default:
- throw new IOException("Uknown message type.");
+ throw new IOException("Unknown message type.");
}
}
}
}
| true | true | public static AbstractMessage toMessage(String s) throws IOException {
if (s == null || s.length() <= 1)
return null;
if (s.indexOf(SerializationConstants.HEAD) != 0
|| s.length() <= SerializationConstants.HEAD.length()) {
// Try to detect whitespace tag.
final Matcher matcher = patternWhitespace.matcher(s);
boolean v1 = false;
boolean v2 = false;
while (matcher.find()) {
if (!v1 && matcher.start(2) > -1)
v1 = true;
if (!v2 && matcher.start(3) > -1)
v2 = true;
if (v1 && v2)
break;
}
String cleanText = matcher.replaceAll("");
List<Integer> versions;
if (v1 && v2) {
versions = new Vector<Integer>(2);
versions.add(0, 1);
versions.add(0, 2);
} else if (v1) {
versions = new Vector<Integer>(1);
versions.add(0, 1);
} else if (v2) {
versions = new Vector<Integer>(1);
versions.add(2);
} else
versions = null;
return new PlainTextMessage(versions, cleanText);
} else {
char contentType = s.charAt(SerializationConstants.HEAD.length());
String content = s.substring(SerializationConstants.HEAD.length() + 1);
switch (contentType) {
case SerializationConstants.HEAD_ENCODED:
ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(content
.getBytes()));
OtrInputStream otr = new OtrInputStream(bin);
// We have an encoded message.
int protocolVersion = otr.readShort();
int messageType = otr.readByte();
switch (messageType) {
case AbstractEncodedMessage.MESSAGE_DATA:
int flags = otr.readByte();
int senderKeyID = otr.readInt();
int recipientKeyID = otr.readInt();
DHPublicKey nextDH = otr.readDHPublicKey();
byte[] ctr = otr.readCtr();
byte[] encryptedMessage = otr.readData();
byte[] mac = otr.readMac();
byte[] oldMacKeys = otr.readMac();
return new DataMessage(protocolVersion, flags, senderKeyID, recipientKeyID,
nextDH, ctr, encryptedMessage, mac, oldMacKeys);
case AbstractEncodedMessage.MESSAGE_DH_COMMIT:
byte[] dhPublicKeyEncrypted = otr.readData();
byte[] dhPublicKeyHash = otr.readData();
return new DHCommitMessage(protocolVersion, dhPublicKeyHash,
dhPublicKeyEncrypted);
case AbstractEncodedMessage.MESSAGE_DHKEY:
DHPublicKey dhPublicKey = otr.readDHPublicKey();
return new DHKeyMessage(protocolVersion, dhPublicKey);
case AbstractEncodedMessage.MESSAGE_REVEALSIG: {
byte[] revealedKey = otr.readData();
byte[] xEncrypted = otr.readData();
byte[] xEncryptedMac = otr.readMac();
return new RevealSignatureMessage(protocolVersion, xEncrypted, xEncryptedMac,
revealedKey);
}
case AbstractEncodedMessage.MESSAGE_SIGNATURE: {
byte[] xEncryted = otr.readData();
byte[] xEncryptedMac = otr.readMac();
return new SignatureMessage(protocolVersion, xEncryted, xEncryptedMac);
}
default:
throw new IOException("Illegal message type.");
}
case SerializationConstants.HEAD_MESSAGE:
return new ErrorMessage(AbstractMessage.MESSAGE_ERROR, content);
case SerializationConstants.HEAD_QUERY_V:
case SerializationConstants.HEAD_QUERY_Q:
List<Integer> versions = new Vector<Integer>();
String versionString = null;
if (SerializationConstants.HEAD_QUERY_Q == contentType) {
versions.add(1);
if (content.charAt(0) == 'v') {
versionString = content.substring(1, content.indexOf('?'));
}
} else if (SerializationConstants.HEAD_QUERY_V == contentType) {
versionString = content.substring(0, content.indexOf('?'));
}
if (versionString != null) {
StringReader sr = new StringReader(versionString);
int c;
while ((c = sr.read()) != -1)
if (!versions.contains(c))
versions.add(Integer.parseInt(String.valueOf((char) c)));
}
QueryMessage query = new QueryMessage(versions);
return query;
default:
throw new IOException("Uknown message type.");
}
}
}
| public static AbstractMessage toMessage(String s) throws IOException {
if (s == null || s.length() <= 1)
return null;
if (s.indexOf(SerializationConstants.HEAD) != 0
|| s.length() <= SerializationConstants.HEAD.length()) {
// Try to detect whitespace tag.
final Matcher matcher = patternWhitespace.matcher(s);
boolean v1 = false;
boolean v2 = false;
while (matcher.find()) {
if (!v1 && matcher.start(2) > -1)
v1 = true;
if (!v2 && matcher.start(3) > -1)
v2 = true;
if (v1 && v2)
break;
}
String cleanText = matcher.replaceAll("");
List<Integer> versions;
if (v1 && v2) {
versions = new Vector<Integer>(2);
versions.add(0, 1);
versions.add(0, 2);
} else if (v1) {
versions = new Vector<Integer>(1);
versions.add(0, 1);
} else if (v2) {
versions = new Vector<Integer>(1);
versions.add(2);
} else
versions = null;
return new PlainTextMessage(versions, cleanText);
} else {
char contentType = s.charAt(SerializationConstants.HEAD.length());
String content = s.substring(SerializationConstants.HEAD.length() + 1);
switch (contentType) {
case SerializationConstants.HEAD_ENCODED:
ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(content
.getBytes()));
OtrInputStream otr = new OtrInputStream(bin);
// We have an encoded message.
int protocolVersion = otr.readShort();
int messageType = otr.readByte();
switch (messageType) {
case AbstractEncodedMessage.MESSAGE_DATA:
int flags = otr.readByte();
int senderKeyID = otr.readInt();
int recipientKeyID = otr.readInt();
DHPublicKey nextDH = otr.readDHPublicKey();
byte[] ctr = otr.readCtr();
byte[] encryptedMessage = otr.readData();
byte[] mac = otr.readMac();
byte[] oldMacKeys = otr.readMac();
return new DataMessage(protocolVersion, flags, senderKeyID, recipientKeyID,
nextDH, ctr, encryptedMessage, mac, oldMacKeys);
case AbstractEncodedMessage.MESSAGE_DH_COMMIT:
byte[] dhPublicKeyEncrypted = otr.readData();
byte[] dhPublicKeyHash = otr.readData();
return new DHCommitMessage(protocolVersion, dhPublicKeyHash,
dhPublicKeyEncrypted);
case AbstractEncodedMessage.MESSAGE_DHKEY:
DHPublicKey dhPublicKey = otr.readDHPublicKey();
return new DHKeyMessage(protocolVersion, dhPublicKey);
case AbstractEncodedMessage.MESSAGE_REVEALSIG: {
byte[] revealedKey = otr.readData();
byte[] xEncrypted = otr.readData();
byte[] xEncryptedMac = otr.readMac();
return new RevealSignatureMessage(protocolVersion, xEncrypted, xEncryptedMac,
revealedKey);
}
case AbstractEncodedMessage.MESSAGE_SIGNATURE: {
byte[] xEncryted = otr.readData();
byte[] xEncryptedMac = otr.readMac();
return new SignatureMessage(protocolVersion, xEncryted, xEncryptedMac);
}
default:
throw new IOException("Illegal message type.");
}
case SerializationConstants.HEAD_MESSAGE:
return new ErrorMessage(AbstractMessage.MESSAGE_ERROR, content);
case SerializationConstants.HEAD_QUERY_V:
case SerializationConstants.HEAD_QUERY_Q:
List<Integer> versions = new Vector<Integer>();
String versionString = null;
if (SerializationConstants.HEAD_QUERY_Q == contentType) {
versions.add(1);
if (content.charAt(0) == 'v') {
versionString = content.substring(1, content.indexOf('?'));
}
} else if (SerializationConstants.HEAD_QUERY_V == contentType) {
versionString = content.substring(0, content.indexOf('?'));
}
if (versionString != null) {
StringReader sr = new StringReader(versionString);
int c;
while ((c = sr.read()) != -1)
if (!versions.contains(c))
versions.add(Integer.parseInt(String.valueOf((char) c)));
}
QueryMessage query = new QueryMessage(versions);
return query;
default:
throw new IOException("Unknown message type.");
}
}
}
|
diff --git a/org.jiayun.commons4e/src/org/jiayun/commons4e/internal/lang/generators/CompareToGenerator.java b/org.jiayun.commons4e/src/org/jiayun/commons4e/internal/lang/generators/CompareToGenerator.java
index 2624a39..7ba77c3 100644
--- a/org.jiayun.commons4e/src/org/jiayun/commons4e/internal/lang/generators/CompareToGenerator.java
+++ b/org.jiayun.commons4e/src/org/jiayun/commons4e/internal/lang/generators/CompareToGenerator.java
@@ -1,185 +1,185 @@
//$Id$
package org.jiayun.commons4e.internal.lang.generators;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
import org.jiayun.commons4e.internal.ui.dialogs.OrderableFieldDialog;
import org.jiayun.commons4e.internal.util.JavaUtils;
import org.jiayun.commons4e.internal.util.PreferenceUtils;
/**
* @author jiayun
*/
public final class CompareToGenerator implements ILangGenerator {
private static final ILangGenerator instance = new CompareToGenerator();
private CompareToGenerator() {
}
public static ILangGenerator getInstance() {
return instance;
}
/*
* (non-Javadoc)
*
* @see org.jiayun.commons4e.internal.lang.generators.ILangGenerator#generate(org.eclipse.swt.widgets.Shell,
* org.eclipse.jdt.core.IType)
*/
public void generate(Shell parentShell, IType objectClass) {
Set excludedMethods = new HashSet();
IMethod existingMethod = objectClass.getMethod("compareTo",
new String[] { "QObject;" });
if (!existingMethod.exists()) {
existingMethod = objectClass.getMethod("compareTo",
new String[] { "Q" + objectClass.getElementName() + ";" });
}
if (existingMethod.exists()) {
excludedMethods.add(existingMethod);
}
try {
OrderableFieldDialog dialog = new OrderableFieldDialog(parentShell,
"Generate CompareTo Method", objectClass, JavaUtils
.getNonStaticNonCacheFields(objectClass),
excludedMethods, !JavaUtils
- .isImplementedOrExtendedInSupertype(objectClass,
+ .isImplementedInSupertype(objectClass,
"Comparable"));
int returnCode = dialog.open();
if (returnCode == Window.OK) {
if (existingMethod.exists()) {
existingMethod.delete(true, null);
}
IField[] checkedFields = dialog.getCheckedFields();
IJavaElement insertPosition = dialog.getElementPosition();
boolean appendSuper = dialog.getAppendSuper();
boolean generateComment = dialog.getGenerateComment();
generateCompareTo(parentShell, objectClass, checkedFields,
insertPosition, appendSuper, generateComment);
}
} catch (CoreException e) {
MessageDialog.openError(parentShell, "Method Generation Failed", e
.getMessage());
} catch (BadLocationException e) {
MessageDialog.openError(parentShell, "Method Generation Failed", e
.getMessage());
}
}
private void generateCompareTo(final Shell parentShell,
final IType objectClass, final IField[] checkedFields,
final IJavaElement insertPosition, final boolean appendSuper,
final boolean generateComment) throws PartInitException,
JavaModelException, MalformedTreeException, BadLocationException {
ICompilationUnit cu = objectClass.getCompilationUnit();
IEditorPart javaEditor = JavaUI.openInEditor(cu);
boolean implementedOrExtendedInSuperType = JavaUtils
.isImplementedOrExtendedInSupertype(objectClass, "Comparable");
boolean generify = PreferenceUtils.getGenerifyCompareTo()
&& PreferenceUtils
.isSourceLevelGreaterThanOrEqualTo5(objectClass
.getJavaProject())
&& !implementedOrExtendedInSuperType;
if (!implementedOrExtendedInSuperType) {
try {
if (generify) {
JavaUtils.addSuperInterface(objectClass, "Comparable<"
+ objectClass.getElementName() + ">");
} else {
JavaUtils.addSuperInterface(objectClass, "Comparable");
}
} catch (InvalidInputException e) {
MessageDialog.openError(parentShell, "Error",
"Failed to add Comparable to implements clause:\n"
+ e.getMessage());
}
}
String source = createMethod(objectClass, checkedFields, appendSuper,
generateComment, generify);
String formattedContent = JavaUtils.formatCode(parentShell,
objectClass, source);
objectClass.getCompilationUnit().createImport(
"org.apache.commons.lang.builder.CompareToBuilder", null, null);
IMethod created = objectClass.createMethod(formattedContent,
insertPosition, true, null);
JavaUI.revealInEditor(javaEditor, (IJavaElement) created);
}
private String createMethod(final IType objectClass,
final IField[] checkedFields, final boolean appendSuper,
final boolean generateComment, final boolean generify) {
StringBuffer content = new StringBuffer();
if (generateComment) {
content.append("/* (non-Javadoc)\n");
content
.append(" * @see java.lang.Comparable#compareTo(java.lang.Object)\n");
content.append(" */\n");
}
String other;
if (generify) {
content.append("public int compareTo(final "
+ objectClass.getElementName() + " other) {\n");
other = "other";
} else {
content.append("public int compareTo(final Object other) {\n");
content.append(objectClass.getElementName());
content.append(" castOther = (");
content.append(objectClass.getElementName());
content.append(") other;\n");
other = "castOther";
}
content.append("return new CompareToBuilder()");
if (appendSuper) {
content.append(".appendSuper(super.compareTo(other))");
}
for (int i = 0; i < checkedFields.length; i++) {
content.append(".append(");
content.append(checkedFields[i].getElementName());
content.append(", " + other + ".");
content.append(checkedFields[i].getElementName());
content.append(")");
}
content.append(".toComparison();\n");
content.append("}\n\n");
return content.toString();
}
}
| true | true | public void generate(Shell parentShell, IType objectClass) {
Set excludedMethods = new HashSet();
IMethod existingMethod = objectClass.getMethod("compareTo",
new String[] { "QObject;" });
if (!existingMethod.exists()) {
existingMethod = objectClass.getMethod("compareTo",
new String[] { "Q" + objectClass.getElementName() + ";" });
}
if (existingMethod.exists()) {
excludedMethods.add(existingMethod);
}
try {
OrderableFieldDialog dialog = new OrderableFieldDialog(parentShell,
"Generate CompareTo Method", objectClass, JavaUtils
.getNonStaticNonCacheFields(objectClass),
excludedMethods, !JavaUtils
.isImplementedOrExtendedInSupertype(objectClass,
"Comparable"));
int returnCode = dialog.open();
if (returnCode == Window.OK) {
if (existingMethod.exists()) {
existingMethod.delete(true, null);
}
IField[] checkedFields = dialog.getCheckedFields();
IJavaElement insertPosition = dialog.getElementPosition();
boolean appendSuper = dialog.getAppendSuper();
boolean generateComment = dialog.getGenerateComment();
generateCompareTo(parentShell, objectClass, checkedFields,
insertPosition, appendSuper, generateComment);
}
} catch (CoreException e) {
MessageDialog.openError(parentShell, "Method Generation Failed", e
.getMessage());
} catch (BadLocationException e) {
MessageDialog.openError(parentShell, "Method Generation Failed", e
.getMessage());
}
}
| public void generate(Shell parentShell, IType objectClass) {
Set excludedMethods = new HashSet();
IMethod existingMethod = objectClass.getMethod("compareTo",
new String[] { "QObject;" });
if (!existingMethod.exists()) {
existingMethod = objectClass.getMethod("compareTo",
new String[] { "Q" + objectClass.getElementName() + ";" });
}
if (existingMethod.exists()) {
excludedMethods.add(existingMethod);
}
try {
OrderableFieldDialog dialog = new OrderableFieldDialog(parentShell,
"Generate CompareTo Method", objectClass, JavaUtils
.getNonStaticNonCacheFields(objectClass),
excludedMethods, !JavaUtils
.isImplementedInSupertype(objectClass,
"Comparable"));
int returnCode = dialog.open();
if (returnCode == Window.OK) {
if (existingMethod.exists()) {
existingMethod.delete(true, null);
}
IField[] checkedFields = dialog.getCheckedFields();
IJavaElement insertPosition = dialog.getElementPosition();
boolean appendSuper = dialog.getAppendSuper();
boolean generateComment = dialog.getGenerateComment();
generateCompareTo(parentShell, objectClass, checkedFields,
insertPosition, appendSuper, generateComment);
}
} catch (CoreException e) {
MessageDialog.openError(parentShell, "Method Generation Failed", e
.getMessage());
} catch (BadLocationException e) {
MessageDialog.openError(parentShell, "Method Generation Failed", e
.getMessage());
}
}
|
diff --git a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/components/browser/dnd/TreeDropTarget.java b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/components/browser/dnd/TreeDropTarget.java
index a84e55819..73bee5edb 100644
--- a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/components/browser/dnd/TreeDropTarget.java
+++ b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/components/browser/dnd/TreeDropTarget.java
@@ -1,221 +1,224 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo 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.
*
* OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.components.browser.dnd;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetContext;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
import javax.swing.JTree;
import javax.swing.tree.TreePath;
import org.openflexo.components.browser.BrowserElement;
import org.openflexo.components.browser.ProjectBrowser;
import org.openflexo.components.browser.view.BrowserView;
import org.openflexo.foundation.FlexoEditor;
import org.openflexo.toolbox.ToolBox;
/**
* @author bmangez <B>Class Description</B>
*/
public class TreeDropTarget implements DropTargetListener {
private static Cursor VALID_CURSOR;
private static Cursor INVALID_CURSOR;
static {
try {
VALID_CURSOR = Cursor.getSystemCustomCursor("MoveDrop32x32");
INVALID_CURSOR = Cursor.getSystemCustomCursor("Invalid32x32");
} catch (Exception e) {
e.printStackTrace();
VALID_CURSOR = Cursor.getDefaultCursor();
INVALID_CURSOR = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
}
}
protected DropTarget target;
protected BrowserView.FlexoJTree targetTree;
protected ProjectBrowser _browser;
public TreeDropTarget(BrowserView.FlexoJTree tree, ProjectBrowser browser) {
targetTree = tree;
target = new DropTarget(targetTree, this);
_browser = browser;
}
protected FlexoEditor getEditor() {
return targetTree.getBrowserView().getEditor();
}
/*
* Drop Event Handlers
*/
private BrowserElement getNodeForEvent(DropTargetDragEvent dtde) {
Point p = dtde.getLocation();
DropTargetContext dtc = dtde.getDropTargetContext();
JTree tree = (JTree) dtc.getComponent();
TreePath path = tree.getClosestPathForLocation(p.x, p.y);
if (path == null) {
return null;
} else {
return (BrowserElement) path.getLastPathComponent();
}
}
@Override
public void dragEnter(DropTargetDragEvent dtde) {
dtde.acceptDrag(DnDConstants.ACTION_MOVE);
BrowserElement node = getNodeForEvent(dtde);
TreePath path = targetTree.getClosestPathForLocation(dtde.getLocation().x, dtde.getLocation().y);
if (!targetTree.getModel().isLeaf(path.getLastPathComponent()) && !targetTree.isExpanded(path)) {
targetTree.handleAutoExpand(path);
}
targetTree.paintDraggedNode(dtde.getLocation());
/*
if (node==null || !sourceIsDroppableInTarget(getSourceNode(dtde.getTransferable()), node)) {
dtde.rejectDrag();
} else {
targetTree.setSelectionPath(path);
// start by supporting move operations
dtde.acceptDrag(DnDConstants.ACTION_MOVE);
}*/
}
@Override
public void dragOver(DropTargetDragEvent dtde) {
BrowserElement node = getNodeForEvent(dtde);
TreePath path = targetTree.getClosestPathForLocation(dtde.getLocation().x, dtde.getLocation().y);
TreePath realPath = targetTree.getPathForLocation(dtde.getLocation().x, dtde.getLocation().y);
if (realPath != null && !targetTree.getModel().isLeaf(realPath.getLastPathComponent()) && !targetTree.isExpanded(path)) {
targetTree.handleAutoExpand(realPath);
} else {
targetTree.stopExpandCountDown();
}
targetTree.paintDraggedNode(dtde.getLocation());
targetTree.setSelectionPath(realPath);
BrowserElement source = getSourceNode(dtde.getTransferable());
if (source == node) {
return;
}
if (node == null || !targetAcceptsSource(node, source)) {
dtde.rejectDrag();
if (ToolBox.getPLATFORM() == ToolBox.MACOS && _browser != null && _browser.getSelectionManager() != null
&& _browser.getSelectionManager().getController() != null
&& _browser.getSelectionManager().getController().getFlexoFrame() != null) {
_browser.getSelectionManager().getController().getFlexoFrame().setCursor(INVALID_CURSOR);
}
} else {
targetTree.setSelectionPath(path);
// start by supporting move operations
dtde.acceptDrag(DnDConstants.ACTION_MOVE);
if (ToolBox.getPLATFORM() == ToolBox.MACOS) {
_browser.getSelectionManager().getController().getFlexoFrame().setCursor(VALID_CURSOR);
}
}
}
@Override
public void dragExit(DropTargetEvent dte) {
targetTree.stopExpandCountDown();
targetTree.clearDraggedNode();
}
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
@Override
public void drop(DropTargetDropEvent dtde) {
targetTree.stopExpandCountDown();
targetTree.clearDraggedNode();
Point pt = dtde.getLocation();
DropTargetContext dtc = dtde.getDropTargetContext();
JTree tree = (JTree) dtc.getComponent();
TreePath parentpath = tree.getClosestPathForLocation(pt.x, pt.y);
+ if (parentpath == null) {
+ return;
+ }
BrowserElement destination = (BrowserElement) parentpath.getLastPathComponent();
try {
Transferable transferable = dtde.getTransferable();
DataFlavor[] dataFlavors = transferable.getTransferDataFlavors();
for (int i = 0; i < dataFlavors.length; i++) {
if (transferable.isDataFlavorSupported(dataFlavors[i])) {
BrowserElement moved = null;
try {
moved = (BrowserElement) transferable.getTransferData(dataFlavors[i]);
} catch (ClassCastException e) {
dtde.rejectDrop();
return;
}
if (targetAcceptsSource(destination, moved) && handleDrop(moved, destination)) {
dtde.acceptDrop(dtde.getDropAction());
dtde.dropComplete(true);
return;
}
}
}
dtde.rejectDrop();
} catch (Exception e) {
e.printStackTrace();
dtde.rejectDrop();
}
}
private BrowserElement getSourceNode(Transferable transferable) {
if (transferable instanceof ElementMovable) {
return ((ElementMovable) transferable).path;
}
DataFlavor[] dataFlavors = transferable.getTransferDataFlavors();
for (int i = 0; i < dataFlavors.length; i++) {
if (transferable.isDataFlavorSupported(dataFlavors[i])) {
BrowserElement moved = null;
try {
moved = (BrowserElement) transferable.getTransferData(dataFlavors[i]);
return moved;
} catch (ClassCastException e) {
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
}
}
return null;
}
public boolean handleDrop(BrowserElement source, BrowserElement target) {
return false;
}
public boolean targetAcceptsSource(BrowserElement target, BrowserElement source) {
return false;
}
}
| true | true | public void drop(DropTargetDropEvent dtde) {
targetTree.stopExpandCountDown();
targetTree.clearDraggedNode();
Point pt = dtde.getLocation();
DropTargetContext dtc = dtde.getDropTargetContext();
JTree tree = (JTree) dtc.getComponent();
TreePath parentpath = tree.getClosestPathForLocation(pt.x, pt.y);
BrowserElement destination = (BrowserElement) parentpath.getLastPathComponent();
try {
Transferable transferable = dtde.getTransferable();
DataFlavor[] dataFlavors = transferable.getTransferDataFlavors();
for (int i = 0; i < dataFlavors.length; i++) {
if (transferable.isDataFlavorSupported(dataFlavors[i])) {
BrowserElement moved = null;
try {
moved = (BrowserElement) transferable.getTransferData(dataFlavors[i]);
} catch (ClassCastException e) {
dtde.rejectDrop();
return;
}
if (targetAcceptsSource(destination, moved) && handleDrop(moved, destination)) {
dtde.acceptDrop(dtde.getDropAction());
dtde.dropComplete(true);
return;
}
}
}
dtde.rejectDrop();
} catch (Exception e) {
e.printStackTrace();
dtde.rejectDrop();
}
}
| public void drop(DropTargetDropEvent dtde) {
targetTree.stopExpandCountDown();
targetTree.clearDraggedNode();
Point pt = dtde.getLocation();
DropTargetContext dtc = dtde.getDropTargetContext();
JTree tree = (JTree) dtc.getComponent();
TreePath parentpath = tree.getClosestPathForLocation(pt.x, pt.y);
if (parentpath == null) {
return;
}
BrowserElement destination = (BrowserElement) parentpath.getLastPathComponent();
try {
Transferable transferable = dtde.getTransferable();
DataFlavor[] dataFlavors = transferable.getTransferDataFlavors();
for (int i = 0; i < dataFlavors.length; i++) {
if (transferable.isDataFlavorSupported(dataFlavors[i])) {
BrowserElement moved = null;
try {
moved = (BrowserElement) transferable.getTransferData(dataFlavors[i]);
} catch (ClassCastException e) {
dtde.rejectDrop();
return;
}
if (targetAcceptsSource(destination, moved) && handleDrop(moved, destination)) {
dtde.acceptDrop(dtde.getDropAction());
dtde.dropComplete(true);
return;
}
}
}
dtde.rejectDrop();
} catch (Exception e) {
e.printStackTrace();
dtde.rejectDrop();
}
}
|
diff --git a/src/com/onarandombox/MultiverseCore/command/commands/TeleportCommand.java b/src/com/onarandombox/MultiverseCore/command/commands/TeleportCommand.java
index 2481366..40653d3 100644
--- a/src/com/onarandombox/MultiverseCore/command/commands/TeleportCommand.java
+++ b/src/com/onarandombox/MultiverseCore/command/commands/TeleportCommand.java
@@ -1,87 +1,87 @@
package com.onarandombox.MultiverseCore.command.commands;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.onarandombox.MultiverseCore.MVTeleport;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.command.BaseCommand;
import com.onarandombox.utils.Destination;
import com.onarandombox.utils.DestinationType;
public class TeleportCommand extends BaseCommand {
private MVTeleport playerTeleporter;
public TeleportCommand(MultiverseCore plugin) {
super(plugin);
this.name = "Teleport";
this.description = "Teleports you to a different world.";
this.usage = "/mvtp" + ChatColor.GOLD + "[PLAYER]" + ChatColor.GREEN + " {WORLD}";
this.minArgs = 1;
this.maxArgs = 2;
this.identifiers.add("mvtp");
this.playerTeleporter = new MVTeleport(plugin);
this.permission = "multiverse.world.tp.self";
this.requiresOp = true;
}
@Override
public void execute(CommandSender sender, String[] args) {
// Check if the command was sent from a Player.
Player teleporter = null;
Player teleportee = null;
if (sender instanceof Player) {
teleporter = (Player) sender;
}
String worldName;
if (args.length == 2) {
if (teleporter != null && !this.plugin.ph.hasPermission(sender, "multiverse.world.tp.other", true)) {
sender.sendMessage("You don't have permission to teleport another player.");
return;
}
teleportee = this.plugin.getServer().getPlayer(args[0]);
if (teleportee == null) {
sender.sendMessage("Sorry, I couldn't find player: " + args[0]);
return;
}
worldName = args[1];
} else {
worldName = args[0];
if (!(sender instanceof Player)) {
sender.sendMessage("You can only teleport other players from the command line.");
return;
}
teleporter = (Player) sender;
teleportee = (Player) sender;
}
Destination d = Destination.parseDestination(worldName, this.plugin);
if (!(d.getType() == DestinationType.World)) {
sender.sendMessage("Multiverse does not know about this world: " + worldName);
return;
}
if (teleporter != null && !this.plugin.ph.canEnterWorld(teleporter, this.plugin.getServer().getWorld(d.getName()))) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("Doesn't look like you're allowed to go " + ChatColor.RED + "there...");
} else {
teleporter.sendMessage("Doesn't look like you're allowed to send " + ChatColor.GOLD + teleportee.getName() + ChatColor.WHITE + " to " + ChatColor.RED + "there...");
}
} else if (teleporter != null && !this.plugin.ph.canTravelFromWorld(teleporter, this.plugin.getServer().getWorld(d.getName()))) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("DOH! Doesn't look like you can get to " + ChatColor.RED + d.getName() + " from " + ChatColor.GREEN + teleporter.getWorld().getName());
} else {
teleporter.sendMessage("DOH! Doesn't look like " + ChatColor.GREEN + teleporter.getWorld().getName() + " can get to " + ChatColor.RED + d.getName() + " from where they are...");
}
}
Location l = this.playerTeleporter.getSafeDestination(this.plugin.getServer().getWorld(d.getName()).getSpawnLocation());
- teleporter.teleport(l);
+ teleportee.teleport(l);
}
}
| true | true | public void execute(CommandSender sender, String[] args) {
// Check if the command was sent from a Player.
Player teleporter = null;
Player teleportee = null;
if (sender instanceof Player) {
teleporter = (Player) sender;
}
String worldName;
if (args.length == 2) {
if (teleporter != null && !this.plugin.ph.hasPermission(sender, "multiverse.world.tp.other", true)) {
sender.sendMessage("You don't have permission to teleport another player.");
return;
}
teleportee = this.plugin.getServer().getPlayer(args[0]);
if (teleportee == null) {
sender.sendMessage("Sorry, I couldn't find player: " + args[0]);
return;
}
worldName = args[1];
} else {
worldName = args[0];
if (!(sender instanceof Player)) {
sender.sendMessage("You can only teleport other players from the command line.");
return;
}
teleporter = (Player) sender;
teleportee = (Player) sender;
}
Destination d = Destination.parseDestination(worldName, this.plugin);
if (!(d.getType() == DestinationType.World)) {
sender.sendMessage("Multiverse does not know about this world: " + worldName);
return;
}
if (teleporter != null && !this.plugin.ph.canEnterWorld(teleporter, this.plugin.getServer().getWorld(d.getName()))) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("Doesn't look like you're allowed to go " + ChatColor.RED + "there...");
} else {
teleporter.sendMessage("Doesn't look like you're allowed to send " + ChatColor.GOLD + teleportee.getName() + ChatColor.WHITE + " to " + ChatColor.RED + "there...");
}
} else if (teleporter != null && !this.plugin.ph.canTravelFromWorld(teleporter, this.plugin.getServer().getWorld(d.getName()))) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("DOH! Doesn't look like you can get to " + ChatColor.RED + d.getName() + " from " + ChatColor.GREEN + teleporter.getWorld().getName());
} else {
teleporter.sendMessage("DOH! Doesn't look like " + ChatColor.GREEN + teleporter.getWorld().getName() + " can get to " + ChatColor.RED + d.getName() + " from where they are...");
}
}
Location l = this.playerTeleporter.getSafeDestination(this.plugin.getServer().getWorld(d.getName()).getSpawnLocation());
teleporter.teleport(l);
}
| public void execute(CommandSender sender, String[] args) {
// Check if the command was sent from a Player.
Player teleporter = null;
Player teleportee = null;
if (sender instanceof Player) {
teleporter = (Player) sender;
}
String worldName;
if (args.length == 2) {
if (teleporter != null && !this.plugin.ph.hasPermission(sender, "multiverse.world.tp.other", true)) {
sender.sendMessage("You don't have permission to teleport another player.");
return;
}
teleportee = this.plugin.getServer().getPlayer(args[0]);
if (teleportee == null) {
sender.sendMessage("Sorry, I couldn't find player: " + args[0]);
return;
}
worldName = args[1];
} else {
worldName = args[0];
if (!(sender instanceof Player)) {
sender.sendMessage("You can only teleport other players from the command line.");
return;
}
teleporter = (Player) sender;
teleportee = (Player) sender;
}
Destination d = Destination.parseDestination(worldName, this.plugin);
if (!(d.getType() == DestinationType.World)) {
sender.sendMessage("Multiverse does not know about this world: " + worldName);
return;
}
if (teleporter != null && !this.plugin.ph.canEnterWorld(teleporter, this.plugin.getServer().getWorld(d.getName()))) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("Doesn't look like you're allowed to go " + ChatColor.RED + "there...");
} else {
teleporter.sendMessage("Doesn't look like you're allowed to send " + ChatColor.GOLD + teleportee.getName() + ChatColor.WHITE + " to " + ChatColor.RED + "there...");
}
} else if (teleporter != null && !this.plugin.ph.canTravelFromWorld(teleporter, this.plugin.getServer().getWorld(d.getName()))) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("DOH! Doesn't look like you can get to " + ChatColor.RED + d.getName() + " from " + ChatColor.GREEN + teleporter.getWorld().getName());
} else {
teleporter.sendMessage("DOH! Doesn't look like " + ChatColor.GREEN + teleporter.getWorld().getName() + " can get to " + ChatColor.RED + d.getName() + " from where they are...");
}
}
Location l = this.playerTeleporter.getSafeDestination(this.plugin.getServer().getWorld(d.getName()).getSpawnLocation());
teleportee.teleport(l);
}
|
diff --git a/src/se/kayarr/ircbot/modules/DatabaseTestModule.java b/src/se/kayarr/ircbot/modules/DatabaseTestModule.java
index 9bd2e56..806aa04 100644
--- a/src/se/kayarr/ircbot/modules/DatabaseTestModule.java
+++ b/src/se/kayarr/ircbot/modules/DatabaseTestModule.java
@@ -1,56 +1,56 @@
package se.kayarr.ircbot.modules;
import java.sql.SQLException;
import org.pircbotx.Channel;
import org.pircbotx.PircBotX;
import org.pircbotx.User;
import se.kayarr.ircbot.backend.CommandHandler;
import se.kayarr.ircbot.backend.CommandManager;
import se.kayarr.ircbot.backend.Module;
import se.kayarr.ircbot.database.Database;
import se.kayarr.ircbot.database.Table;
import se.kayarr.ircbot.database.TableHandler;
public class DatabaseTestModule extends Module implements CommandHandler, TableHandler {
private static final int TEST_TABLE_VERSION = 1;
private Table testTable;
@Override
public void initialize() {
CommandManager.get().newCommand()
.addAlias("dbtest")
.handler(this)
.finish();
testTable = Database.moduleData().table("test_table", TEST_TABLE_VERSION, this);
}
@Override
public void onTableCreate(Table table) throws SQLException {
table.createIfNonexistant("TEXT VARCHAR");
}
@Override
public void onTableUpgrade(Table table, int oldVersion, int newVersion) throws SQLException {
}
@Override
public void onHandleCommand(PircBotX bot, Channel channel, User user,
String command, String parameters) {
bot.sendMessage(channel, "Adding text '" + parameters + "'");
try {
- testTable.newInsert().put("TEXT", parameters).insert();
+ testTable.newInsert().put("TEXT", "'" + parameters + "'").insert();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
| true | true | public void onHandleCommand(PircBotX bot, Channel channel, User user,
String command, String parameters) {
bot.sendMessage(channel, "Adding text '" + parameters + "'");
try {
testTable.newInsert().put("TEXT", parameters).insert();
}
catch (SQLException e) {
e.printStackTrace();
}
}
| public void onHandleCommand(PircBotX bot, Channel channel, User user,
String command, String parameters) {
bot.sendMessage(channel, "Adding text '" + parameters + "'");
try {
testTable.newInsert().put("TEXT", "'" + parameters + "'").insert();
}
catch (SQLException e) {
e.printStackTrace();
}
}
|
diff --git a/src/main/java/eu/europeana/portal2/querymodel/query/FacetQueryLinksImpl.java b/src/main/java/eu/europeana/portal2/querymodel/query/FacetQueryLinksImpl.java
index afca0fd0..8612db92 100644
--- a/src/main/java/eu/europeana/portal2/querymodel/query/FacetQueryLinksImpl.java
+++ b/src/main/java/eu/europeana/portal2/querymodel/query/FacetQueryLinksImpl.java
@@ -1,181 +1,182 @@
package eu.europeana.portal2.querymodel.query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import eu.europeana.corelib.definitions.solr.model.Query;
import eu.europeana.portal2.web.model.facets.Facet;
import eu.europeana.portal2.web.model.facets.LabelFrequency;
import eu.europeana.portal2.web.util.QueryUtil;
public class FacetQueryLinksImpl implements FacetQueryLinks {
private final Logger log = Logger.getLogger(getClass().getName());
private static final String FACET_PROMPT = "&qf=";
private static final String RIGHTS_FACET = "RIGHTS";
private String type;
private boolean facetSelected = false;
private List<FacetCountLink> links = new ArrayList<FacetCountLink>() {
private static final long serialVersionUID = 8698647778113603995L;
@Override
public boolean add(FacetCountLink newFacetCountLink) {
if (contains(newFacetCountLink) && RIGHTS_FACET.equals(type)) {
FacetCountLink existing = get(indexOf(newFacetCountLink));
existing.update(newFacetCountLink);
return false;
}
return super.add(newFacetCountLink);
}
};
public static List<FacetQueryLinks> createDecoratedFacets(List<Facet> facetFields, Query solrQuery) {
List<FacetQueryLinks> list = new ArrayList<FacetQueryLinks>();
if (facetFields != null) {
for (Facet facetField : facetFields) {
list.add(new FacetQueryLinksImpl(facetField, solrQuery));
}
}
return list;
}
private FacetQueryLinksImpl(Facet facetField, Query query) {
this.type = facetField.getName();
if (facetField.getFields().isEmpty()) {
return;
}
Map<String, List<String>> refinements = QueryUtil.getFilterQueriesWithoutPhrases(query);
StringBuilder baseUrl = new StringBuilder();
if (refinements != null) {
for (String term : refinements.get(QueryUtil.REFINEMENTS)) {
baseUrl.append(FACET_PROMPT).append(term);
}
}
for (LabelFrequency item : facetField.getFields()) {
if (isTemporarilyPreventYear0000(this.type, item.getLabel())) {
continue;
}
boolean remove = false;
StringBuilder url = new StringBuilder(baseUrl.toString());
// iterating over actual qf values
if (query.getRefinements() != null) {
for (String qfTerm : refinements.get(QueryUtil.FACETS)) {
if (!qfTerm.equals("-TYPE:Wikipedia")) {
String[] parts = qfTerm.split(":", 2);
String qfField = parts[0];
String qfValue = parts[1];
if (isTemporarilyPreventYear0000(qfField, qfValue)) {
continue;
}
boolean doAppend = true;
+ String comparableQf = qfValue;
if (qfField.equals(RIGHTS_FACET)) {
- qfValue = qfValue.replace("http\\:", "http:");
+ comparableQf = qfValue.replace("http\\:", "http:");
}
if (qfField.equalsIgnoreCase(facetField.getName())) {
- if (QueryUtil.escapeValue(item.getLabel()).equalsIgnoreCase(qfValue)
- || qfValue.equals(EuropeanaRightsConverter.convertCc(item.getLabel()))) {
+ if (QueryUtil.escapeValue(item.getLabel()).equalsIgnoreCase(comparableQf)
+ || comparableQf.equals(EuropeanaRightsConverter.convertCc(item.getLabel()))) {
remove = true;
facetSelected = true;
doAppend = false;
}
}
if (doAppend) {
url.append(FACET_PROMPT).append(qfField).append(':')
.append(QueryUtil.createPhraseValue(qfField, qfValue));
}
}
}
}
// adding the current facet to the query link
if (!remove) {
url.append(FACET_PROMPT);
url.append(facetField.getName());
url.append(":");
if (RIGHTS_FACET.equals(type)) {
EuropeanaRightsConverter.License license = EuropeanaRightsConverter.convert(item.getLabel());
String value = (license.getModifiedURI() != null) ? license.getModifiedURI() : license.getOriginalURI();
url.append(value);
} else {
// escape Solr special chars in item.label
url.append(
QueryUtil.createPhraseValue(
facetField.getName(),
QueryUtil.escapeValue(item.getLabel())
)
);
}
}
if (RIGHTS_FACET.equals(type)) {
EuropeanaRightsConverter.License license = EuropeanaRightsConverter.convert(item.getLabel());
item.setLabel(license.getOriginalURI());
links.add(
new FacetCountLinkImpl(
RightsOption.safeValueByUrl(license.getOriginalURI()),
item, url.toString(), remove));
} else {
links.add(new FacetCountLinkImpl(item, url.toString(), remove));
}
}
}
/**
* At one point the normalizer was letting unparseable values of year, coded
* ast 0000, through to the index. This bandage solution prevents them from
* being presented.
*
* @param facetName
* year
* @param facetValue
* 0000
*
* @return true if it matches
*/
private static boolean isTemporarilyPreventYear0000(String facetName,
String facetValue) {
return "YEAR".equals(facetName) && "0000".equals(facetValue);
}
/*
* (non-Javadoc)
*
* @see eu.europeana.core.querymodel.query.FacetQueryLinks#getType()
*/
@Override
public String getType() {
return type;
}
/*
* (non-Javadoc)
*
* @see eu.europeana.core.querymodel.query.FacetQueryLinks#getLinks()
*/
@Override
public List<FacetCountLink> getLinks() {
return links;
}
/*
* (non-Javadoc)
*
* @see eu.europeana.core.querymodel.query.FacetQueryLinks#isSelected()
*/
@Override
public boolean isSelected() {
return facetSelected;
}
@Override
public String toString() {
return type + " (" + links +")";
}
}
| false | true | private FacetQueryLinksImpl(Facet facetField, Query query) {
this.type = facetField.getName();
if (facetField.getFields().isEmpty()) {
return;
}
Map<String, List<String>> refinements = QueryUtil.getFilterQueriesWithoutPhrases(query);
StringBuilder baseUrl = new StringBuilder();
if (refinements != null) {
for (String term : refinements.get(QueryUtil.REFINEMENTS)) {
baseUrl.append(FACET_PROMPT).append(term);
}
}
for (LabelFrequency item : facetField.getFields()) {
if (isTemporarilyPreventYear0000(this.type, item.getLabel())) {
continue;
}
boolean remove = false;
StringBuilder url = new StringBuilder(baseUrl.toString());
// iterating over actual qf values
if (query.getRefinements() != null) {
for (String qfTerm : refinements.get(QueryUtil.FACETS)) {
if (!qfTerm.equals("-TYPE:Wikipedia")) {
String[] parts = qfTerm.split(":", 2);
String qfField = parts[0];
String qfValue = parts[1];
if (isTemporarilyPreventYear0000(qfField, qfValue)) {
continue;
}
boolean doAppend = true;
if (qfField.equals(RIGHTS_FACET)) {
qfValue = qfValue.replace("http\\:", "http:");
}
if (qfField.equalsIgnoreCase(facetField.getName())) {
if (QueryUtil.escapeValue(item.getLabel()).equalsIgnoreCase(qfValue)
|| qfValue.equals(EuropeanaRightsConverter.convertCc(item.getLabel()))) {
remove = true;
facetSelected = true;
doAppend = false;
}
}
if (doAppend) {
url.append(FACET_PROMPT).append(qfField).append(':')
.append(QueryUtil.createPhraseValue(qfField, qfValue));
}
}
}
}
// adding the current facet to the query link
if (!remove) {
url.append(FACET_PROMPT);
url.append(facetField.getName());
url.append(":");
if (RIGHTS_FACET.equals(type)) {
EuropeanaRightsConverter.License license = EuropeanaRightsConverter.convert(item.getLabel());
String value = (license.getModifiedURI() != null) ? license.getModifiedURI() : license.getOriginalURI();
url.append(value);
} else {
// escape Solr special chars in item.label
url.append(
QueryUtil.createPhraseValue(
facetField.getName(),
QueryUtil.escapeValue(item.getLabel())
)
);
}
}
if (RIGHTS_FACET.equals(type)) {
EuropeanaRightsConverter.License license = EuropeanaRightsConverter.convert(item.getLabel());
item.setLabel(license.getOriginalURI());
links.add(
new FacetCountLinkImpl(
RightsOption.safeValueByUrl(license.getOriginalURI()),
item, url.toString(), remove));
} else {
links.add(new FacetCountLinkImpl(item, url.toString(), remove));
}
}
}
| private FacetQueryLinksImpl(Facet facetField, Query query) {
this.type = facetField.getName();
if (facetField.getFields().isEmpty()) {
return;
}
Map<String, List<String>> refinements = QueryUtil.getFilterQueriesWithoutPhrases(query);
StringBuilder baseUrl = new StringBuilder();
if (refinements != null) {
for (String term : refinements.get(QueryUtil.REFINEMENTS)) {
baseUrl.append(FACET_PROMPT).append(term);
}
}
for (LabelFrequency item : facetField.getFields()) {
if (isTemporarilyPreventYear0000(this.type, item.getLabel())) {
continue;
}
boolean remove = false;
StringBuilder url = new StringBuilder(baseUrl.toString());
// iterating over actual qf values
if (query.getRefinements() != null) {
for (String qfTerm : refinements.get(QueryUtil.FACETS)) {
if (!qfTerm.equals("-TYPE:Wikipedia")) {
String[] parts = qfTerm.split(":", 2);
String qfField = parts[0];
String qfValue = parts[1];
if (isTemporarilyPreventYear0000(qfField, qfValue)) {
continue;
}
boolean doAppend = true;
String comparableQf = qfValue;
if (qfField.equals(RIGHTS_FACET)) {
comparableQf = qfValue.replace("http\\:", "http:");
}
if (qfField.equalsIgnoreCase(facetField.getName())) {
if (QueryUtil.escapeValue(item.getLabel()).equalsIgnoreCase(comparableQf)
|| comparableQf.equals(EuropeanaRightsConverter.convertCc(item.getLabel()))) {
remove = true;
facetSelected = true;
doAppend = false;
}
}
if (doAppend) {
url.append(FACET_PROMPT).append(qfField).append(':')
.append(QueryUtil.createPhraseValue(qfField, qfValue));
}
}
}
}
// adding the current facet to the query link
if (!remove) {
url.append(FACET_PROMPT);
url.append(facetField.getName());
url.append(":");
if (RIGHTS_FACET.equals(type)) {
EuropeanaRightsConverter.License license = EuropeanaRightsConverter.convert(item.getLabel());
String value = (license.getModifiedURI() != null) ? license.getModifiedURI() : license.getOriginalURI();
url.append(value);
} else {
// escape Solr special chars in item.label
url.append(
QueryUtil.createPhraseValue(
facetField.getName(),
QueryUtil.escapeValue(item.getLabel())
)
);
}
}
if (RIGHTS_FACET.equals(type)) {
EuropeanaRightsConverter.License license = EuropeanaRightsConverter.convert(item.getLabel());
item.setLabel(license.getOriginalURI());
links.add(
new FacetCountLinkImpl(
RightsOption.safeValueByUrl(license.getOriginalURI()),
item, url.toString(), remove));
} else {
links.add(new FacetCountLinkImpl(item, url.toString(), remove));
}
}
}
|
diff --git a/ini/trakem2/persistence/FSLoader.java b/ini/trakem2/persistence/FSLoader.java
index 3148ba6d..ca5e6bfb 100644
--- a/ini/trakem2/persistence/FSLoader.java
+++ b/ini/trakem2/persistence/FSLoader.java
@@ -1,1993 +1,1993 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005, 2006 Albert Cardona and Rodney Douglas.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
/s published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt )
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.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.persistence;
import ij.IJ;
import ij.ImagePlus;
import ini.trakem2.imaging.VirtualStack; //import ij.VirtualStack; // only after 1.38q
import ij.io.*;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij.process.FloatProcessor;
import ij.process.ColorProcessor;
import ij.process.ImageStatistics;
import ij.measure.Measurements;
import ij.gui.YesNoCancelDialog;
import ini.trakem2.Project;
import ini.trakem2.ControlWindow;
import ini.trakem2.display.Ball;
import ini.trakem2.display.DLabel;
import ini.trakem2.display.Display;
import ini.trakem2.display.Displayable;
import ini.trakem2.display.Layer;
import ini.trakem2.display.LayerSet;
import ini.trakem2.display.Patch;
import ini.trakem2.imaging.PatchStack;
import ini.trakem2.display.Pipe;
import ini.trakem2.display.Profile;
import ini.trakem2.display.YesNoDialog;
import ini.trakem2.display.ZDisplayable;
import ini.trakem2.tree.Attribute;
import ini.trakem2.tree.LayerThing;
import ini.trakem2.tree.ProjectAttribute;
import ini.trakem2.tree.ProjectThing;
import ini.trakem2.tree.TemplateThing;
import ini.trakem2.tree.TemplateAttribute;
import ini.trakem2.tree.Thing;
import ini.trakem2.tree.TrakEM2MLParser;
import ini.trakem2.tree.DTDParser;
import ini.trakem2.utils.*;
import ini.trakem2.io.*;
import ini.trakem2.imaging.FloatProcessorT2;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.ColorModel;
import java.awt.RenderingHints;
import java.awt.geom.Area;
import java.awt.geom.AffineTransform;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.KeyStroke;
import org.xml.sax.InputSource;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import mpi.fruitfly.math.datastructures.FloatArray2D;
import mpi.fruitfly.registration.ImageFilter;
import mpi.fruitfly.general.MultiThreading;
import java.util.concurrent.atomic.AtomicInteger;
/** A class to rely on memory only; except images which are rolled from a folder or their original location and flushed when memory is needed for more. Ideally there would be a given folder for storing items temporarily of permanently as the "project folder", but I haven't implemented it. */
public final class FSLoader extends Loader {
/** Largest id seen so far. */
private long max_id = -1;
private final HashMap<Long,String> ht_paths = new HashMap<Long,String>();
/** For saving and overwriting. */
private String project_file_path = null;
/** Path to the directory hosting the file image pyramids. */
private String dir_mipmaps = null;
/** Path to the directory the user provided when creating the project. */
private String dir_storage = null;
/** Path to dir_storage + "trakem2.images/" */
private String dir_image_storage = null;
/** Queue and execute Runnable tasks. */
static private Dispatcher dispatcher = new Dispatcher();
public FSLoader() {
super(); // register
super.v_loaders.remove(this); //will be readded on successful open
}
public FSLoader(final String storage_folder) {
this();
if (null == storage_folder) this.dir_storage = super.getStorageFolder(); // home dir
else this.dir_storage = storage_folder;
if (!this.dir_storage.endsWith("/")) this.dir_storage += "/";
if (!Loader.canReadAndWriteTo(dir_storage)) {
Utils.log("WARNING can't read/write to the storage_folder at " + dir_storage);
} else {
createMipMapsDir(this.dir_storage);
}
}
/** Create a new FSLoader copying some key parameters such as preprocessor plugin, and storage and mipmap folders.*/
public FSLoader(final Loader source) {
this();
this.dir_storage = source.getStorageFolder(); // can never be null
this.dir_mipmaps = source.getMipMapsFolder();
if (null == this.dir_mipmaps) createMipMapsDir(this.dir_storage);
setPreprocessor(source.getPreprocessor());
}
public String getProjectXMLPath() {
if (null == project_file_path) return null;
return project_file_path.toString(); // a copy of it
}
public String getStorageFolder() {
if (null == dir_storage) return super.getStorageFolder(); // the user's home
return dir_storage.toString(); // a copy
}
/** Returns a folder proven to be writable for images can be stored into. */
public String getImageStorageFolder() {
if (null == dir_image_storage) {
String s = getStorageFolder() + "trakem2.images/";
File f = new File(s);
if (f.exists() && f.isDirectory() && f.canWrite()) {
dir_image_storage = s;
return dir_image_storage;
}
else {
try {
f.mkdirs();
dir_image_storage = s;
} catch (Exception e) {
e.printStackTrace();
return getStorageFolder(); // fall back
}
}
}
return dir_image_storage;
}
/** Returns TMLHandler.getProjectData() . If the path is null it'll be asked for. */
public Object[] openFSProject(String path, final boolean open_displays) {
// clean path of double-slashes, safely (and painfully)
if (null != path) {
path = path.replace('\\','/');
path = path.trim();
int itwo = path.indexOf("//");
while (-1 != itwo) {
if (0 == itwo /* samba disk */
|| (5 == itwo && "http:".equals(path.substring(0, 5)))) {
// do nothing
} else {
path = path.substring(0, itwo) + path.substring(itwo+1);
}
itwo = path.indexOf("//", itwo+1);
}
}
//
if (null == path) {
String user = System.getProperty("user.name");
OpenDialog od = new OpenDialog("Select Project", OpenDialog.getDefaultDirectory(), null);
String file = od.getFileName();
if (null == file || file.toLowerCase().startsWith("null")) return null;
String dir = od.getDirectory().replace('\\', '/');
if (!dir.endsWith("/")) dir += "/";
this.project_file_path = dir + file;
Utils.log2("project file path 1: " + this.project_file_path);
} else {
this.project_file_path = path;
Utils.log2("project file path 2: " + this.project_file_path);
}
Utils.log2("Loader.openFSProject: path is " + path);
// check if any of the open projects uses the same file path, and refuse to open if so:
if (null != FSLoader.getOpenProject(project_file_path, this)) {
Utils.showMessage("The project is already open.");
return null;
}
Object[] data = null;
// parse file, according to expected format as indicated by the extension:
if (this.project_file_path.toLowerCase().endsWith(".xml")) {
InputStream i_stream = null;
TMLHandler handler = new TMLHandler(this.project_file_path, this);
if (handler.isUnreadable()) {
handler = null;
} else {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
if (isURL(this.project_file_path)) {
i_stream = new java.net.URL(this.project_file_path).openStream();
} else {
i_stream = new BufferedInputStream(new FileInputStream(this.project_file_path));
}
InputSource input_source = new InputSource(i_stream);
setMassiveMode(true);
parser.parse(input_source, handler);
} catch (java.io.FileNotFoundException fnfe) {
Utils.log("ERROR: File not found: " + path);
handler = null;
} catch (Exception e) {
IJError.print(e);
handler = null;
} finally {
setMassiveMode(false);
if (null != i_stream) {
try {
i_stream.close();
} catch (Exception e) {
IJError.print(e);
}
}
}
}
if (null == handler) {
Utils.showMessage("Error when reading the project .xml file.");
return null;
}
data = handler.getProjectData(open_displays);
}
if (null == data) {
Utils.showMessage("Error when parsing the project .xml file.");
return null;
}
// else, good
super.v_loaders.add(this);
return data;
}
// Only one thread at a time may access this method.
synchronized static private final Project getOpenProject(final String project_file_path, final Loader caller) {
if (null == v_loaders) return null;
final Loader[] lo = (Loader[])v_loaders.toArray(new Loader[0]); // atomic way to get the list of loaders
for (int i=0; i<lo.length; i++) {
if (lo[i].equals(caller)) continue;
if (lo[i] instanceof FSLoader && ((FSLoader)lo[i]).project_file_path.equals(project_file_path)) {
return Project.findProject(lo[i]);
}
}
return null;
}
static public final Project getOpenProject(final String project_file_path) {
return getOpenProject(project_file_path, null);
}
public boolean isReady() {
return null != ht_paths;
}
public void destroy() {
super.destroy();
Utils.showStatus("", false);
dispatcher.quit();
// remove empty trakem2.mipmaps folder if any
if (null != dir_mipmaps && !dir_mipmaps.equals(dir_storage)) {
File f = new File(dir_mipmaps);
if (f.isDirectory() && 0 == f.list(new FilenameFilter() {
public boolean accept(File fdir, String name) {
File file = new File(dir_mipmaps + name);
if (file.isHidden() || '.' == name.charAt(0)) return false;
return true;
}
}).length) {
try { f.delete(); } catch (Exception e) { Utils.log("Could not remove empty trakem2.mipmaps directory."); }
}
}
}
/** Get the next unique id, not shared by any other object within the same project. */
public long getNextId() {
long nid = -1;
synchronized (db_lock) {
lock();
nid = ++max_id;
unlock();
}
return nid;
}
/** Loaded in full from XML file */
public double[][][] fetchBezierArrays(long id) {
return null;
}
/** Loaded in full from XML file */
public ArrayList fetchPipePoints(long id) {
return null;
}
/** Loaded in full from XML file */
public ArrayList fetchBallPoints(long id) {
return null;
}
/** Loaded in full from XML file */
public Area fetchArea(long area_list_id, long layer_id) {
return null;
}
public ImagePlus fetchImagePlus(final Patch p) {
return (ImagePlus)fetchImage(p, Layer.IMAGEPLUS);
}
/** Fetch the ImageProcessor in a synchronized manner, so that there are no conflicts in retrieving the ImageProcessor for a specific stack slice, for example. */
public ImageProcessor fetchImageProcessor(final Patch p) {
return (ImageProcessor)fetchImage(p, Layer.IMAGEPROCESSOR);
}
/** So far accepts Layer.IMAGEPLUS and Layer.IMAGEPROCESSOR as format. */
public Object fetchImage(final Patch p, final int format) {
ImagePlus imp = null;
ImageProcessor ip = null;
String slice = null;
String path = null;
long n_bytes = 0;
PatchLoadingLock plock = null;
synchronized (db_lock) {
lock();
imp = imps.get(p.getId());
try {
path = getAbsolutePath(p);
int i_sl = -1;
if (null != path) i_sl = path.lastIndexOf("-----#slice=");
if (-1 != i_sl) {
// activate proper slice
if (null != imp) {
// check that the stack is large enough (user may have changed it)
final int ia = Integer.parseInt(path.substring(i_sl + 12));
if (ia <= imp.getNSlices()) {
if (null == imp.getStack() || null == imp.getStack().getPixels(ia)) {
// reload (happens when closing a stack that was opened before importing it, and then trying to paint, for example)
imps.remove(p.getId());
imp = null;
} else {
imp.setSlice(ia);
switch (format) {
case Layer.IMAGEPROCESSOR:
ip = imp.getStack().getProcessor(ia);
unlock();
return ip;
case Layer.IMAGEPLUS:
unlock();
return imp;
default:
Utils.log("FSLoader.fetchImage: Unknown format " + format);
return null;
}
}
} else {
unlock();
return null; // beyond bonds!
}
}
}
// for non-stack images
if (null != imp) {
unlock();
switch (format) {
case Layer.IMAGEPROCESSOR:
return imp.getProcessor();
case Layer.IMAGEPLUS:
return imp;
default:
Utils.log("FSLoader.fetchImage: Unknown format " + format);
return null;
}
}
if (-1 != i_sl) {
slice = path.substring(i_sl);
// set path proper
path = path.substring(0, i_sl);
}
releaseMemory(); // ensure there is a minimum % of free memory
plock = getOrMakePatchLoadingLock(p, 0);
unlock();
} catch (Exception e) {
IJError.print(e);
return null;
}
}
synchronized (plock) {
plock.lock();
imp = imps.get(p.getId());
if (null != imp) {
// was loaded by a different thread
plock.unlock();
switch (format) {
case Layer.IMAGEPROCESSOR:
return imp.getProcessor();
case Layer.IMAGEPLUS:
return imp;
default:
Utils.log("FSLoader.fetchImage: Unknown format " + format);
return null;
}
}
// going to load:
// reserve memory:
synchronized (db_lock) {
lock();
n_bytes = estimateImageFileSize(p, 0);
max_memory -= n_bytes;
unlock();
}
releaseToFit(n_bytes);
imp = openImage(path);
preProcess(imp);
synchronized (db_lock) {
try {
lock();
max_memory += n_bytes;
if (null == imp) {
if (!hs_unloadable.contains(p)) {
Utils.log("FSLoader.fetchImagePlus: no image exists for patch " + p + " at path " + path);
hs_unloadable.add(p);
}
removePatchLoadingLock(plock);
unlock();
plock.unlock();
return null;
}
// update all clients of the stack, if any
if (null != slice) {
String rel_path = getPath(p); // possibly relative
final int r_isl = rel_path.lastIndexOf("-----#slice");
if (-1 != r_isl) rel_path = rel_path.substring(0, r_isl); // should always happen
for (Iterator<Map.Entry<Long,String>> it = ht_paths.entrySet().iterator(); it.hasNext(); ) {
final Map.Entry<Long,String> entry = it.next();
final String str = entry.getValue(); // this is like calling getPath(p)
//Utils.log2("processing " + str);
if (0 != str.indexOf(rel_path)) {
//Utils.log2("SKIP str is: " + str + "\t but path is: " + rel_path);
continue; // get only those whose path is identical, of course!
}
final int isl = str.lastIndexOf("-----#slice=");
if (-1 != isl) {
//int i_slice = Integer.parseInt(str.substring(isl + 12));
final long lid = entry.getKey();
imps.put(lid, imp);
imp.setSlice(Integer.parseInt(str.substring(isl + 12)));
// kludge, but what else short of a gigantic hashtable
try {
final Patch pa = (Patch)p.getLayerSet().findDisplayable(lid);
pa.putMinAndMax(imp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// set proper active slice
final int ia = Integer.parseInt(slice.substring(12));
imp.setSlice(ia);
if (Layer.IMAGEPROCESSOR == format) ip = imp.getStack().getProcessor(ia); // otherwise creates one new for nothing
} else {
// for non-stack images
p.putMinAndMax(imp); // non-destructive contrast: min and max
// puts the Patch min and max values into the ImagePlus processor.
imps.put(p.getId(), imp);
if (Layer.IMAGEPROCESSOR == format) ip = imp.getProcessor();
}
// imp is cached, so:
removePatchLoadingLock(plock);
} catch (Exception e) {
IJError.print(e);
}
unlock();
plock.unlock();
switch (format) {
case Layer.IMAGEPROCESSOR:
return ip; // not imp.getProcessor because after unlocking the slice may have changed for stacks.
case Layer.IMAGEPLUS:
return imp;
default:
Utils.log("FSLoader.fetchImage: Unknown format " + format);
return null;
}
}
}
}
/** Loaded in full from XML file */
public Object[] fetchLabel(DLabel label) {
return null;
}
/** Loads and returns the original image, which is not cached, or returns null if it's not different than the working image. */
synchronized public ImagePlus fetchOriginal(final Patch patch) {
String original_path = patch.getOriginalPath();
if (null == original_path) return null;
// else, reserve memory and open it:
long n_bytes = estimateImageFileSize(patch, 0);
// reserve memory:
synchronized (db_lock) {
lock();
max_memory -= n_bytes;
unlock();
}
try {
return openImage(original_path);
} catch (Throwable t) {
IJError.print(t);
} finally {
synchronized (db_lock) {
lock();
max_memory += n_bytes;
unlock();
}
}
return null;
}
public void prepare(Layer layer) {
//Utils.log2("FSLoader.prepare(Layer): not implemented.");
super.prepare(layer);
}
/* GENERIC, from DBObject calls. Records the id of the object in the HashMap ht_dbo.
* Always returns true. Does not check if another object has the same id.
*/
public boolean addToDatabase(final DBObject ob) {
synchronized (db_lock) {
lock();
setChanged(true);
final long id = ob.getId();
if (id > max_id) {
max_id = id;
}
unlock();
}
return true;
}
public boolean updateInDatabase(final DBObject ob, final String key) {
setChanged(true);
if (ob.getClass() == Patch.class) {
Patch p = (Patch)ob;
if (key.equals("tiff_working")) return null != setImageFile(p, fetchImagePlus(p));
}
return true;
}
public boolean removeFromDatabase(final DBObject ob) {
synchronized (db_lock) {
lock();
setChanged(true);
// remove from the hashtable
final long loid = ob.getId();
Utils.log2("removing " + Project.getName(ob.getClass()) + " " + ob);
if (ob instanceof Patch) {
// STRATEGY change: images are not owned by the FSLoader.
Patch p = (Patch)ob;
if (!ob.getProject().getBooleanProperty("keep_mipmaps")) removeMipMaps(p);
ht_paths.remove(p.getId()); // after removeMipMaps !
mawts.removeAndFlush(loid);
final ImagePlus imp = imps.remove(loid);
if (null != imp) {
if (imp.getStackSize() > 1) {
if (null == imp.getProcessor()) {}
else if (null == imp.getProcessor().getPixels()) {}
else Loader.flush(imp); // only once
} else {
Loader.flush(imp);
}
}
cannot_regenerate.remove(p);
unlock();
flushMipMaps(p.getId()); // locks on its own
return true;
}
unlock();
}
return true;
}
/** Returns the absolute path to a file that contains the given ImagePlus image - which may be the path as described in the ImagePlus FileInfo object itself, or a totally new file.
* If the Patch p current image path is different than its original image path, then the file is overwritten if it exists already.
*/
public String setImageFile(final Patch p, final ImagePlus imp) {
if (null == imp) return null;
try {
String path = getAbsolutePath(p);
String slice = null;
//
// path can be null if the image is pasted, or from a copy, or totally new
if (null != path) {
int i_sl = path.lastIndexOf("-----#slice=");
if (-1 != i_sl) {
slice = path.substring(i_sl);
path = path.substring(0, i_sl);
}
} else {
// no path, inspect image FileInfo's path if the image has no changes
if (!imp.changes) {
final FileInfo fi = imp.getOriginalFileInfo();
if (null != fi && null != fi.directory && null != fi.fileName) {
final String fipath = fi.directory.replace('\\', '/') + "/" + fi.fileName;
if (new File(fipath).exists()) {
// no need to save a new image, it exists and has no changes
updatePaths(p, fipath, null != slice);
cacheAll(p, imp);
Utils.log2("Reusing image file: path exists for fileinfo at " + fipath);
return fipath;
}
}
}
}
if (null != path) {
final String starting_path = path;
// Save as a separate image in a new path within the storage folder
String filename = path.substring(path.lastIndexOf('/') +1);
//Utils.log2("filename 1: " + filename);
// remove .tif extension if there
if (filename.endsWith(".tif")) filename = filename.substring(0, filename.length() -3); // keep the dot
//Utils.log2("filename 2: " + filename);
// check if file ends with a tag of form ".id1234." where 1234 is p.getId()
final String tag = ".id" + p.getId() + ".";
if (!filename.endsWith(tag)) filename += tag.substring(1); // without the starting dot, since it has one already
// reappend extension
filename += "tif";
//Utils.log2("filename 3: " + filename);
path = getImageStorageFolder() + filename;
if (path.equals(p.getOriginalPath())) {
// Houston, we have a problem: a user reused a non-original image
File file = null;
int i = 1;
final int itag = path.lastIndexOf(tag);
do {
path = path.substring(0, itag) + "." + i + tag + "tif";
i++;
file = new File(path);
} while (file.exists());
}
//Utils.log2("path to use: " + path);
final String path2 = super.exportImage(p, imp, path, true);
//Utils.log2("path exported to: " + path2);
// update paths' hashtable
if (null != path2) {
updatePaths(p, path2, null != slice);
cacheAll(p, imp);
hs_unloadable.remove(p);
return path2;
} else {
Utils.log("WARNING could not save image at " + path);
// undo
updatePaths(p, starting_path, null != slice);
return null;
}
}
} catch (Exception e) {
IJError.print(e);
}
return null;
}
private final String makeFileTitle(final Patch p) {
String title = p.getTitle();
if (null == title) return "image-" + p.getId();
title = asSafePath(title);
if (0 == title.length()) return "image-" + p.getId();
return title;
}
/** Associate patch with imp, and all slices as well if any. */
private void cacheAll(final Patch p, final ImagePlus imp) {
if (p.isStack()) {
for (Patch pa : p.getStackPatches()) {
cache(pa, imp);
}
} else {
cache(p, imp);
}
}
/** For the Patch and for any associated slices if the patch is part of a stack. */
private void updatePaths(final Patch patch, final String path, final boolean is_stack) {
synchronized (db_lock) {
lock();
try {
// ensure the old path is cached in the Patch, to get set as the original if there is no original.
if (is_stack) {
for (Patch p : patch.getStackPatches()) {
long pid = p.getId();
String str = ht_paths.get(pid);
int isl = str.lastIndexOf("-----#slice=");
updatePatchPath(p, path + str.substring(isl));
}
} else {
Utils.log2("path to set: " + path);
Utils.log2("path before: " + ht_paths.get(patch.getId()));
updatePatchPath(patch, path);
Utils.log2("path after: " + ht_paths.get(patch.getId()));
}
} catch (Throwable e) {
IJError.print(e);
} finally {
unlock();
}
}
}
/** With slice info appended at the end; only if it exists, otherwise null. */
public String getAbsolutePath(final Patch patch) {
String abs_path = patch.getCurrentPath();
if (null != abs_path) return abs_path;
// else, compute, set and return it:
String path = ht_paths.get(patch.getId());
if (null == path) return null;
// substract slice info if there
int i_sl = path.lastIndexOf("-----#slice=");
String slice = null;
if (-1 != i_sl) {
slice = path.substring(i_sl);
path = path.substring(0, i_sl);
}
if (isRelativePath(path)) {
// path is relative: preprend the parent folder of the xml file
path = getParentFolder() + path;
if (!isURL(path) && !new File(path).exists()) {
Utils.log("Path for patch " + patch + " does not exist: " + path);
return null;
}
// else assume that it exists
}
// reappend slice info if existent
if (null != slice) path += slice;
// set it
patch.cacheCurrentPath(path);
return path;
}
public static final boolean isURL(final String path) {
return null != path && 0 == path.indexOf("http://");
}
public static final boolean isRelativePath(final String path) {
if (((!IJ.isWindows() && 0 != path.indexOf('/')) || (IJ.isWindows() && 1 != path.indexOf(":/"))) && 0 != path.indexOf("http://") && 0 != path.indexOf("//")) { // "//" is for Samba networks (since the \\ has been converted to // before)
return true;
}
return false;
}
/** All backslashes are converted to slashes to avoid havoc in MSWindows. */
public void addedPatchFrom(String path, final Patch patch) {
if (null == path) {
Utils.log("Null path for patch: " + patch);
return;
}
updatePatchPath(patch, path);
}
/** This method has the exclusivity in calling ht_paths.put, because it ensures the path won't have escape characters. */
private final void updatePatchPath(final Patch patch, String path) { // reversed order in purpose, relative to addedPatchFrom
// avoid W1nd0ws nightmares
path = path.replace('\\', '/'); // replacing with chars, in place
// remove double slashes that a user may have slipped in
final int start = isURL(path) ? 6 : (IJ.isWindows() ? 3 : 1);
while (-1 != path.indexOf("//", start)) {
// avoid the potential C:// of windows and the starting // of a samba network
path = path.substring(0, start) + path.substring(start).replace("//", "/");
}
// cache path as absolute
patch.cacheCurrentPath(isRelativePath(path) ? getParentFolder() + path : path);
// if path is absolute, try to make it relative
path = makeRelativePath(path);
// store
ht_paths.put(patch.getId(), path);
//Utils.log2("Updated patch path " + ht_paths.get(patch.getId()) + " for patch " + patch);
}
/** Takes a String and returns a copy with the following conversions: / to -, space to _, and \ to -. */
public String asSafePath(final String name) {
return name.trim().replace('/', '-').replace(' ', '_').replace('\\','-');
}
/** Overwrites the XML file. If some images do not exist in the file system, a directory with the same name of the XML file plus an "_images" tag appended will be created and images saved there. */
public String save(final Project project) {
String result = null;
if (null == project_file_path) {
String xml_path = super.saveAs(project, null, false);
if (null == xml_path) return null;
else {
this.project_file_path = xml_path;
ControlWindow.updateTitle(project);
result = this.project_file_path;
}
} else {
File fxml = new File(project_file_path);
result = super.export(project, fxml, false);
}
if (null != result) Utils.logAll(Utils.now() + " Saved " + project);
return result;
}
public String saveAs(Project project) {
String path = super.saveAs(project, null, false);
if (null != path) {
// update the xml path to point to the new one
this.project_file_path = path;
Utils.log2("After saveAs, new xml path is: " + path);
}
ControlWindow.updateTitle(project);
return path;
}
/** Meant for programmatic access, such as calls to project.saveAs(path, overwrite) which call exactly this method. */
public String saveAs(final String path, final boolean overwrite) {
if (null == path) {
Utils.log("Cannot save on null path.");
return null;
}
String path2 = path;
if (!path2.endsWith(".xml")) path2 += ".xml";
File fxml = new File(path2);
if (!fxml.canWrite()) {
// write to storage folder instead
String path3 = path2;
path2 = getStorageFolder() + fxml.getName();
Utils.logAll("WARNING can't write to " + path3 + "\n --> will write instead to " + path2);
fxml = new File(path2);
}
if (!overwrite) {
int i = 1;
while (fxml.exists()) {
String parent = fxml.getParent().replace('\\','/');
if (!parent.endsWith("/")) parent += "/";
String name = fxml.getName();
name = name.substring(0, name.length() - 4);
path2 = parent + name + "-" + i + ".xml";
fxml = new File(path2);
i++;
}
}
Project project = Project.findProject(this);
path2 = super.saveAs(project, path2, false);
if (null != path2) {
project_file_path = path2;
Utils.logAll("After saveAs, new xml path is: " + path2);
ControlWindow.updateTitle(project);
}
return path2;
}
/** Returns the stored path for the given Patch image, which may be relative and may contain slice information appended.*/
public String getPath(final Patch patch) {
return ht_paths.get(patch.getId());
}
/** Takes the given path and tries to makes it relative to this instance's project_file_path, if possible. Otherwise returns the argument as is. */
private String makeRelativePath(String path) {
if (null == project_file_path) {
//unsaved project
return path;
}
if (null == path) {
return null;
}
// fix W1nd0ws paths
path = path.replace('\\', '/'); // char-based, no parsing problems
// remove slice tag
String slice = null;
int isl = path.lastIndexOf("-----#slice");
if (-1 != isl) {
slice = path.substring(isl);
path = path.substring(0, isl);
}
//
if (isRelativePath(path)) {
// already relative
if (-1 != isl) path += slice;
return path;
}
// the long and verbose way, to be cross-platform. Should work with URLs just the same.
File xf = new File(project_file_path);
File fpath = new File(path);
if (fpath.getParentFile().equals(xf.getParentFile())) {
path = path.substring(xf.getParent().length());
// remove prepended file separator, if any, to label the path as relative
if (0 == path.indexOf('/')) path = path.substring(1);
} else if (fpath.equals(xf.getParentFile())) {
return "";
}
if (-1 != isl) path += slice;
//Utils.log("made relative path: " + path);
return path;
}
/** Adds a "Save" and "Save as" menu items. */
public void setupMenuItems(final JMenu menu, final Project project) {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String command = ae.getActionCommand();
if (command.equals("Save")) {
save(project);
} else if (command.equals("Save as...")) {
saveAs(project);
}
}
};
JMenuItem item;
item = new JMenuItem("Save"); item.addActionListener(listener); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true));
item = new JMenuItem("Save as..."); item.addActionListener(listener); menu.add(item);
}
/** Returns the last Patch. */
protected Patch importStackAsPatches(final Project project, final Layer first_layer, final ImagePlus imp_stack, final boolean as_copy, final String filepath) {
Utils.log2("FSLoader.importStackAsPatches filepath=" + filepath);
String target_dir = null;
if (as_copy) {
DirectoryChooser dc = new DirectoryChooser("Folder to save images");
target_dir = dc.getDirectory();
if (null == target_dir) return null; // user canceled dialog
if (target_dir.length() -1 != target_dir.lastIndexOf('/')) {
target_dir += "/";
}
}
final boolean virtual = imp_stack.getStack().isVirtual();
int pos_x = (int)first_layer.getLayerWidth()/2 - imp_stack.getWidth()/2;
int pos_y = (int)first_layer.getLayerHeight()/2 - imp_stack.getHeight()/2;
final double thickness = first_layer.getThickness();
final String title = Utils.removeExtension(imp_stack.getTitle()).replace(' ', '_');
Utils.showProgress(0);
Patch previous_patch = null;
final int n = imp_stack.getStackSize();
for (int i=1; i<=n; i++) {
Layer layer = first_layer;
double z = first_layer.getZ() + (i-1) * thickness;
if (i > 1) layer = first_layer.getParent().getLayer(z, thickness, true); // will create new layer if not found
if (null == layer) {
Utils.log("Display.importStack: could not create new layers.");
return null;
}
String patch_path = null;
ImagePlus imp_patch_i = null;
if (virtual) { // because we love inefficiency, every time all this is done again
VirtualStack vs = (VirtualStack)imp_stack.getStack();
String vs_dir = vs.getDirectory().replace('\\', '/');
if (!vs_dir.endsWith("/")) vs_dir += "/";
String iname = vs.getFileName(i);
patch_path = vs_dir + iname;
releaseMemory();
imp_patch_i = openImage(patch_path);
} else {
ImageProcessor ip = imp_stack.getStack().getProcessor(i);
if (as_copy) ip = ip.duplicate();
imp_patch_i = new ImagePlus(title + "__slice=" + i, ip);
}
preProcess(imp_patch_i);
String label = imp_stack.getStack().getSliceLabel(i);
if (null == label) label = "";
Patch patch = null;
if (as_copy) {
patch_path = target_dir + imp_patch_i.getTitle() + ".zip";
ini.trakem2.io.ImageSaver.saveAsZip(imp_patch_i, patch_path);
patch = new Patch(project, label + " " + title + " " + i, pos_x, pos_y, imp_patch_i);
} else if (virtual) {
patch = new Patch(project, label, pos_x, pos_y, imp_patch_i);
} else {
patch_path = filepath + "-----#slice=" + i;
//Utils.log2("path is "+ patch_path);
final AffineTransform atp = new AffineTransform();
atp.translate(pos_x, pos_y);
patch = new Patch(project, getNextId(), label + " " + title + " " + i, imp_stack.getWidth(), imp_stack.getHeight(), imp_stack.getType(), false, imp_stack.getProcessor().getMin(), imp_stack.getProcessor().getMax(), atp);
patch.addToDatabase();
//Utils.log2("type is " + imp_stack.getType());
}
addedPatchFrom(patch_path, patch);
if (!as_copy) {
cache(patch, imp_stack); // uses the entire stack, shared among all Patch instances
}
if (isMipMapsEnabled()) generateMipMaps(patch);
if (null != previous_patch) patch.link(previous_patch);
layer.add(patch);
previous_patch = patch;
Utils.showProgress(i * (1.0 / n));
}
Utils.showProgress(1.0);
// update calibration
//if ( TODO
// return the last patch
return previous_patch;
}
/** Specific options for the Loader which exist as attributes to the Project XML node. */
public void parseXMLOptions(final HashMap ht_attributes) {
Object ob = ht_attributes.remove("preprocessor");
if (null != ob) {
setPreprocessor((String)ob);
}
// Adding some logic to support old projects which lack a storage folder and a mipmaps folder
// and also to prevent errors such as those created when manualy tinkering with the XML file
// or renaming directories, etc.
ob = ht_attributes.remove("storage_folder");
if (null != ob) {
String sf = ((String)ob).replace('\\', '/');
if (isRelativePath(sf)) {
sf = getParentFolder() + sf;
}
if (isURL(sf)) {
// can't be an URL
Utils.log2("Can't have an URL as the path of a storage folder.");
} else {
File f = new File(sf);
if (f.exists() && f.isDirectory()) {
this.dir_storage = sf;
} else {
Utils.log2("storage_folder was not found or is invalid: " + ob);
}
}
}
if (null == this.dir_storage) {
// select the directory where the xml file lives.
this.dir_storage = getParentFolder();
if (null == this.dir_storage || isURL(this.dir_storage)) this.dir_storage = null;
if (null == this.dir_storage && ControlWindow.isGUIEnabled()) {
Utils.log2("Asking user for a storage folder in a dialog."); // tip for headless runners whose program gets "stuck"
DirectoryChooser dc = new DirectoryChooser("REQUIRED: select a storage folder");
this.dir_storage = dc.getDirectory();
}
if (null == this.dir_storage) {
IJ.showMessage("TrakEM2 requires a storage folder.\nTemporarily your home directory will be used.");
this.dir_storage = System.getProperty("user.home").replace('\\', '/');
}
}
// fix
if (null != this.dir_storage && !this.dir_storage.endsWith("/")) this.dir_storage += "/";
Utils.log2("storage folder is " + this.dir_storage);
//
ob = ht_attributes.remove("mipmaps_folder");
if (null != ob) {
String mf = ((String)ob).replace('\\', '/');
if (isRelativePath(mf)) {
mf = getParentFolder() + mf;
}
if (isURL(mf)) {
this.dir_mipmaps = mf;
// TODO must disable input somehow, so that images are not edited.
} else {
File f = new File(mf);
if (f.exists() && f.isDirectory()) {
this.dir_mipmaps = mf;
} else {
Utils.log2("mipmaps_folder was not found or is invalid: " + ob);
}
}
}
if (null == this.dir_mipmaps) {
// create a new one inside the dir_storage, which can't be null
createMipMapsDir(dir_storage);
if (null != this.dir_mipmaps && ControlWindow.isGUIEnabled() && null != IJ.getInstance()) {
Utils.log2("Asking user Yes/No to generate mipmaps on the background."); // tip for headless runners whose program gets "stuck"
YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "Generate mipmaps", "Generate mipmaps in the background for all images?");
if (yn.yesPressed()) {
final Loader lo = this;
new Thread() {
public void run() {
try {
// wait while parsing the rest of the XML file
while (!v_loaders.contains(lo)) {
Thread.sleep(1000);
}
Project pj = Project.findProject(lo);
lo.generateMipMaps(pj.getRootLayerSet().getDisplayables(Patch.class));
} catch (Exception e) {}
}
}.start();
}
}
}
// fix
if (null != this.dir_mipmaps && !this.dir_mipmaps.endsWith("/")) this.dir_mipmaps += "/";
Utils.log2("mipmaps folder is " + this.dir_mipmaps);
}
/** Specific options for the Loader which exist as attributes to the Project XML node. */
public void insertXMLOptions(StringBuffer sb_body, String indent) {
if (null != preprocessor) sb_body.append(indent).append("preprocessor=\"").append(preprocessor).append("\"\n");
if (null != dir_mipmaps) sb_body.append(indent).append("mipmaps_folder=\"").append(makeRelativePath(dir_mipmaps)).append("\"\n");
if (null != dir_storage) sb_body.append(indent).append("storage_folder=\"").append(makeRelativePath(dir_storage)).append("\"\n");
}
/** Return the path to the folder containing the project XML file. */
private final String getParentFolder() {
return this.project_file_path.substring(0, this.project_file_path.lastIndexOf('/')+1);
}
/* ************** MIPMAPS **********************/
/** Returns the path to the directory hosting the file image pyramids. */
public String getMipMapsFolder() {
return dir_mipmaps;
}
/** Image to BufferedImage. Can be used for hardware-accelerated resizing, since the whole awt is painted to a target w,h area in the returned new BufferedImage. */
private final BufferedImage[] IToBI(final Image awt, final int w, final int h, final Object interpolation_hint, final IndexColorModel icm, final BufferedImage alpha) {
BufferedImage bi;
final boolean area_averaging = interpolation_hint.getClass() == Integer.class && Loader.AREA_AVERAGING == ((Integer)interpolation_hint).intValue();
if (null != icm) bi = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_INDEXED, icm);
else if (null != alpha) bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
else bi = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
final Graphics2D g = bi.createGraphics();
if (area_averaging) {
final Image img = awt.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING); // Creates ALWAYS an RGB image, so must repaint back to a single-channel image, avoiding unnecessary blow up of memory.
g.drawImage(img, 0, 0, null);
} else {
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation_hint);
g.drawImage(awt, 0, 0, w, h, null); // draws it scaled
}
BufferedImage ba = alpha;
if (null != alpha) {
FloatProcessor fp_alpha = null;
// resize alpha mask if necessary:
if (w != awt.getWidth(null) || h != awt.getHeight(null)) {
ba = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
if (area_averaging) {
ba.createGraphics().drawImage(alpha.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING), 0, 0, null); // getScaledInstance returns an RGB image always, hence must paint it to a gray one
} else {
final Graphics2D ga = ba.createGraphics();
ga.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation_hint);
ga.drawImage(alpha, 0, 0, w, h, null); // draws it scaled to target area w*h
}
}
fp_alpha = (FloatProcessor) new ByteProcessor(ba).convertToFloat();
// Set all non-white pixels to zero (eliminate shadowy border caused by interpolation)
final float[] pix = (float[])fp_alpha.getPixels();
for (int i=0; i<pix.length; i++)
if (Math.abs(pix[i] - 255) > 0.001f) pix[i] = 0;
bi.getAlphaRaster().setPixels(0, 0, w, h, (float[])fp_alpha.getPixels());
}
return new BufferedImage[]{bi, ba};
}
private Object getHint(final int mode) {
Object hint = null;
switch (mode) {
case Loader.BICUBIC:
hint = RenderingHints.VALUE_INTERPOLATION_BICUBIC; break;
case Loader.BILINEAR:
hint = RenderingHints.VALUE_INTERPOLATION_BILINEAR; break;
case Loader.AREA_AVERAGING:
hint = new Integer(mode); break;
case Loader.NEAREST_NEIGHBOR:
default:
hint = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR; break;
}
return hint;
}
/** WARNING will resize the FloatProcessorT2 source in place, unlike ImageJ standard FloatProcessor class. */
static final private byte[] gaussianBlurResizeInHalf(final FloatProcessorT2 source, final int source_width, final int source_height, final int target_width, final int target_height) {
source.setPixels(source_width, source_height, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])source.getPixels(), source_width, source_height), 0.75f).data);
source.resizeInPlace(target_width, target_height);
return (byte[])source.convertToByte(false).getPixels(); // no interpolation: gaussian took care of that
}
private static final BufferedImage createARGBImage(final int width, final int height, final int[] pix, final float[] alpha) {
final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bi.createGraphics().drawImage(new ColorProcessor(width, height, pix).createImage(), 0, 0, null);
bi.getAlphaRaster().setPixels(0, 0, width, height, alpha);
return bi;
}
/** Given an image and its source file name (without directory prepended), generate
* a pyramid of images until reaching an image not smaller than 32x32 pixels.<br />
* Such images are stored as jpeg 85% quality in a folder named trakem2.mipmaps.<br />
* The Patch id and a ".jpg" extension will be appended to the filename in all cases.<br />
* Any equally named files will be overwritten.
*/
public boolean generateMipMaps(final Patch patch) {
//Utils.log2("mipmaps for " + patch);
if (null == dir_mipmaps) createMipMapsDir(null);
if (null == dir_mipmaps || isURL(dir_mipmaps)) return false;
final String path = getAbsolutePath(patch);
if (null == path) {
Utils.log2("generateMipMaps: cannot find path for Patch " + patch);
cannot_regenerate.add(patch);
return false;
}
synchronized (gm_lock) {
gm_lock();
if (hs_regenerating_mipmaps.contains(patch)) {
// already being done
gm_unlock();
Utils.log2("Already being done: " + patch);
return false;
}
hs_regenerating_mipmaps.add(patch);
gm_unlock();
}
String srmode = patch.getProject().getProperty("image_resizing_mode");
int resizing_mode = GAUSSIAN;
if (null != srmode) resizing_mode = Loader.getMode(srmode);
try {
// Now:
// 1 - Ask the Patch to apply a coordinate transform, or rather, create a function that gets the coordinate transform from the Patch and applies it to the 'ip'.
// 2 - Then (1) should return both the transformed image and the alpha mask
ImageProcessor ip;
FloatProcessor alpha_mask = null;
final int type = patch.getType();
Patch.CTImage cti = patch.createTransformedImage();
if (null == cti) {
// The original image, from the file:
ip = fetchImageProcessor(patch);
} else {
// The non-linearly transformed image
ip = cti.target;
alpha_mask = cti.mask;
cti = null;
}
final String filename = new StringBuffer(new File(path).getName()).append('.').append(patch.getId()).append(".jpg").toString();
int w = ip.getWidth();
int h = ip.getHeight();
// sigma = sqrt(2^level - 0.5^2)
// where 0.5 is the estimated sigma for a full-scale image
// which means sigma = 0.75 for the full-scale image (has level 0)
// prepare a 0.75 sigma image from the original
ColorModel cm = ip.getColorModel();
int k = 0; // the scale level. Proper scale is: 1 / pow(2, k)
// but since we scale 50% relative the previous, it's always 0.75
if (ImagePlus.COLOR_RGB == type) {
// TODO releaseToFit proper
releaseToFit(w * h * 4 * 5);
final ColorProcessor cp = (ColorProcessor)ip;
final FloatProcessorT2 red = new FloatProcessorT2(w, h, 0, 255); cp.toFloat(0, red);
final FloatProcessorT2 green = new FloatProcessorT2(w, h, 0, 255); cp.toFloat(1, green);
final FloatProcessorT2 blue = new FloatProcessorT2(w, h, 0, 255); cp.toFloat(2, blue);
final FloatProcessorT2 alpha = null != alpha_mask ? new FloatProcessorT2(alpha_mask) : null;
// sw,sh are the dimensions of the image to blur
// w,h are the dimensions to scale the blurred image to
int sw = w,
sh = h;
final String target_dir0 = getLevelDir(dir_mipmaps, 0);
// No alpha channel:
// - use gaussian resizing
// - use standard ImageJ java.awt.Image creation
// Generate level 0 first:
if (!(null == alpha ? ini.trakem2.io.ImageSaver.saveAsJpeg(cp, target_dir0 + filename, 0.85f, false)
: ini.trakem2.io.ImageSaver.saveAsJpegAlpha(createARGBImage(w, h, (int[])cp.getPixels(), (float[])alpha.getPixels()), target_dir0 + filename, 0.85f))) {
cannot_regenerate.add(patch);
} else {
do {
// 1 - Prepare values for the next scaled image
sw = w;
sh = h;
w /= 2;
h /= 2;
k++;
// 2 - Check that the target folder for the desired scale exists
final String target_dir = getLevelDir(dir_mipmaps, k);
if (null == target_dir) continue;
// 3 - Blur the previous image to 0.75 sigma, and scale it
final byte[] r = gaussianBlurResizeInHalf(red, sw, sh, w, h); // will resize 'red' FloatProcessor in place.
final byte[] g = gaussianBlurResizeInHalf(green, sw, sh, w, h); // idem
final byte[] b = gaussianBlurResizeInHalf(blue, sw, sh, w, h); // idem
final byte[] a = null == alpha ? null
: gaussianBlurResizeInHalf(alpha, sw, sh, w, h); // idem
if (null != a) {
// set all non-white pixels to black: solves border problem
for (int i=0; i<a.length; i++) {
if (255 != (a[i]&0xff)) a[i] = 0; // TODO I am sure there is a bitwise operation to do this in one step. Some thing like: a[i] &= 127;
}
}
// 4 - Compose ColorProcessor
final int[] pix = new int[w * h];
if (null == alpha) {
for (int i=0; i<pix.length; i++) {
pix[i] = (r[i]<<16) + (g[i]<<8) + b[i];
}
final ColorProcessor cp2 = new ColorProcessor(w, h, pix);
cp2.setMinAndMax(patch.getMin(), patch.getMax());
// 5 - Save as jpeg
if (!ini.trakem2.io.ImageSaver.saveAsJpeg(cp2, target_dir + filename, 0.85f, false)) {
cannot_regenerate.add(patch);
break;
}
} else {
// LIKELY no need to set alpha raster later in createARGBImage ... TODO
for (int i=0; i<pix.length; i++) {
pix[i] = (a[i]<<24) + (r[i]<<16) + (g[i]<<8) + b[i];
}
if (!ini.trakem2.io.ImageSaver.saveAsJpegAlpha(createARGBImage(w, h, pix, (float[])alpha.getPixels()), target_dir + filename, 0.85f)) {
cannot_regenerate.add(patch);
break;
}
}
- } while (w >= 64 && h >= 64); // not smaller than 32x32
+ } while (w >= 32 && h >= 32); // not smaller than 32x32
}
} else {
// Greyscale:
//
// TODO releaseToFit proper
releaseToFit(w * h * 4 * 5);
final boolean as_grey = !ip.isColorLut(); // TODO won't work with alpha masks, I guess
if (as_grey && null == cm) { // TODO needs fixing for 'half' method
cm = GRAY_LUT;
}
if (Loader.GAUSSIAN == resizing_mode) {
FloatProcessor fp = (FloatProcessor) ip.convertToFloat();
fp.setMinAndMax(patch.getMin(), patch.getMax()); // no scaling, so values should do fine directly.
FloatProcessor fp_alpha = alpha_mask;
int sw=w, sh=h;
do {
// 0 - blur the previous image to 0.75 sigma
if (0 != k) { // not doing so at the end because it would add one unnecessary blurring
fp = new FloatProcessorT2(sw, sh, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])fp.getPixels(), sw, sh), 0.75f).data, cm);
if (null != fp_alpha) fp_alpha = new FloatProcessorT2(sw, sh, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])fp_alpha.getPixels(), sw, sh), 0.75f).data, null);
}
// 1 - check that the target folder for the desired scale exists
final String target_dir = getLevelDir(dir_mipmaps, k);
if (null == target_dir) continue;
// 2 - generate scaled image
if (0 != k) {
fp = (FloatProcessor)fp.resize(w, h);
fp.setMinAndMax(patch.getMin(), patch.getMax()); // the resize doesn't preserve the min and max!
if (null != fp_alpha) fp_alpha = (FloatProcessor)fp_alpha.resize(w, h);
}
if (null != alpha_mask) {
// 3 - save as jpeg with alpha
final int[] pix = (int[])fp.convertToRGB().getPixels();
final float[] a = (float[])fp_alpha.getPixels();
// Set all non-white pixels to zero
for (int g=0; g<a.length; g++)
if (Math.abs(a[g] - 255) > 0.001f) a[g] = 0;
if (!ini.trakem2.io.ImageSaver.saveAsJpegAlpha(createARGBImage(w, h, pix, a), target_dir + filename, 0.85f)) {
cannot_regenerate.add(patch);
break;
}
} else {
// 3 - save as 8-bit jpeg
final ImageProcessor ip2 = Utils.convertTo(fp, type, false); // no scaling, since the conversion to float above didn't change the range. This is needed because of the min and max
ip2.setMinAndMax(patch.getMin(), patch.getMax());
if (null != cm) ip2.setColorModel(cm); // the LUT
if (!ini.trakem2.io.ImageSaver.saveAsJpeg(ip2, target_dir + filename, 0.85f, as_grey)) {
cannot_regenerate.add(patch);
break;
}
}
// 4 - prepare values for the next scaled image
sw = w;
sh = h;
w /= 2;
h /= 2;
k++;
} while (w >= 32 && h >= 32); // not smaller than 32x32
} else {
// use java hardware-accelerated resizing
Image awt = ip.createImage();
/* // will be done anyway by IToBI function
if (null != alpha_mask) {
BufferedImage bu = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
bu.createGraphics().drawImage(awt, 0, 0, null);
bu.getAlphaRaster().setPixels(0, 0, w, h, (float[])alpha_mask.getPixels());
awt = bu;
}
*/
BufferedImage balpha = null;
if (null != alpha_mask) {
alpha_mask.setMinAndMax(0, 255);
Image aa = alpha_mask.createImage();
if (aa instanceof BufferedImage) balpha = (BufferedImage)aa;
else {
balpha = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
balpha.createGraphics().drawImage(aa, 0, 0, null);
}
}
BufferedImage bi = null;
final Object hint = getHint(resizing_mode);
final IndexColorModel icm = (IndexColorModel)cm;
do {
// check that the target folder for the desired scale exists
final String target_dir = getLevelDir(dir_mipmaps, k);
if (null == target_dir) continue;
// obtain half image
// for level 0 and others, when awt is not a bi or needs to be reduced in size (to new w,h)
final BufferedImage[] res = IToBI(awt, w, h, hint, icm, balpha); // can't just cast even if it's a BI already, because color type is wrong
bi = res[0];
balpha = res[1];
// prepare next iteration
if (awt != bi) awt.flush();
awt = bi;
w /= 2;
h /= 2;
k++;
// save this iteration
if ( (null != alpha_mask &&
!ini.trakem2.io.ImageSaver.saveAsJpegAlpha(bi, target_dir + filename, 0.85f))
|| (null == alpha_mask &&
!ini.trakem2.io.ImageSaver.saveAsJpeg(bi, target_dir + filename, 0.85f, as_grey))) {
cannot_regenerate.add(patch);
break;
}
} while (w >= 32 && h >= 32);
bi.flush();
}
}
return true;
} catch (Throwable e) {
IJError.print(e);
cannot_regenerate.add(patch);
return false;
} finally {
// gets executed even when returning from the catch statement or within the try/catch block
synchronized (gm_lock) {
gm_lock();
hs_regenerating_mipmaps.remove(patch);
gm_unlock();
}
}
}
/** Generate image pyramids and store them into files under the dir_mipmaps for each Patch object in the Project. The method is multithreaded, using as many processors as available to the JVM.
*
* @param al : the list of Patch instances to generate mipmaps for.
* @param overwrite : whether to overwrite any existing mipmaps, or save only those that don't exist yet for whatever reason. This flag provides the means for minimal effort mipmap regeneration.)
* */
public Bureaucrat generateMipMaps(final ArrayList al, final boolean overwrite) {
if (null == al || 0 == al.size()) return null;
if (null == dir_mipmaps) createMipMapsDir(null);
if (isURL(dir_mipmaps)) {
Utils.log("Mipmaps folder is an URL, can't save files into it.");
return null;
}
final Worker worker = new Worker("Generating MipMaps") {
public void run() {
this.setAsBackground(true);
this.startedWorking();
try {
final Worker wo = this;
Utils.log2("starting mipmap generation ..");
final int size = al.size();
final Patch[] pa = new Patch[size];
final Thread[] threads = MultiThreading.newThreads();
al.toArray(pa);
final AtomicInteger ai = new AtomicInteger(0);
for (int ithread = 0; ithread < threads.length; ++ithread) {
threads[ithread] = new Thread(new Runnable() {
public void run() {
for (int k = ai.getAndIncrement(); k < size; k = ai.getAndIncrement()) {
if (wo.hasQuitted()) {
return;
}
wo.setTaskName("Generating MipMaps " + (k+1) + "/" + size);
try {
boolean ow = overwrite;
if (!overwrite) {
// check if all the files exists. If one doesn't, then overwrite all anyway
int w = (int)pa[k].getWidth();
int h = (int)pa[k].getHeight();
int level = 0;
final String filename = new File(getAbsolutePath(pa[k])).getName() + "." + pa[k].getId() + ".jpg";
while (w >= 64 && h >= 64) {
w /= 2;
h /= 2;
level++;
if (!new File(dir_mipmaps + level + "/" + filename).exists()) {
ow = true;
break;
}
}
}
if (!ow) continue;
if ( ! generateMipMaps(pa[k]) ) {
// some error ocurred
Utils.log2("Could not generate mipmaps for patch " + pa[k]);
}
} catch (Exception e) {
IJError.print(e);
}
}
}
});
}
MultiThreading.startAndJoin(threads);
} catch (Exception e) {
IJError.print(e);
}
this.finishedWorking();
}
};
Bureaucrat burro = new Bureaucrat(worker, ((Patch)al.get(0)).getProject());
burro.goHaveBreakfast();
return burro;
}
private final String getLevelDir(final String dir_mipmaps, final int level) {
// synch, so that multithreaded generateMipMaps won't collide trying to create dirs
synchronized (db_lock) {
lock();
final String path = new StringBuffer(dir_mipmaps).append(level).append('/').toString();
if (isURL(dir_mipmaps)) {
unlock();
return path;
}
final File file = new File(path);
if (file.exists() && file.isDirectory()) {
unlock();
return path;
}
// else, create it
try {
file.mkdir();
unlock();
return path;
} catch (Exception e) {
IJError.print(e);
}
unlock();
}
return null;
}
/** If parent path is null, it's asked for.*/
public boolean createMipMapsDir(String parent_path) {
if (null == parent_path) {
// try to create it in the same directory where the XML file is
if (null != dir_storage) {
File f = new File(dir_storage + "trakem2.mipmaps");
if (!f.exists()) {
try {
if (f.mkdir()) {
this.dir_mipmaps = f.getAbsolutePath().replace('\\', '/');
if (!dir_mipmaps.endsWith("/")) this.dir_mipmaps += "/";
return true;
}
} catch (Exception e) {}
} else if (f.isDirectory()) {
this.dir_mipmaps = f.getAbsolutePath().replace('\\', '/');
if (!dir_mipmaps.endsWith("/")) this.dir_mipmaps += "/";
return true;
}
// else can't use it
} else if (null != project_file_path) {
final File fxml = new File(project_file_path);
final File fparent = fxml.getParentFile();
if (null != fparent && fparent.isDirectory()) {
File f = new File(fparent.getAbsolutePath().replace('\\', '/') + "/" + fxml.getName() + ".mipmaps");
try {
if (f.mkdir()) {
this.dir_mipmaps = f.getAbsolutePath().replace('\\', '/');
if (!dir_mipmaps.endsWith("/")) this.dir_mipmaps += "/";
return true;
}
} catch (Exception e) {}
}
}
// else, ask for a new folder
final DirectoryChooser dc = new DirectoryChooser("Select MipMaps parent directory");
parent_path = dc.getDirectory();
if (null == parent_path) return false;
if (!parent_path.endsWith("/")) parent_path += "/";
}
// examine parent path
final File file = new File(parent_path);
if (file.exists()) {
if (file.isDirectory()) {
// all OK
this.dir_mipmaps = parent_path + "trakem2.mipmaps/";
try {
File f = new File(this.dir_mipmaps);
if (!f.exists()) {
f.mkdir();
}
} catch (Exception e) {
IJError.print(e);
return false;
}
} else {
Utils.showMessage("Selected parent path is not a directory. Please choose another one.");
return createMipMapsDir(null);
}
} else {
Utils.showMessage("Parent path does not exist. Please select a new one.");
return createMipMapsDir(null);
}
return true;
}
/** Remove all mipmap images from the cache, and optionally set the dir_mipmaps to null. */
public void flushMipMaps(boolean forget_dir_mipmaps) {
if (null == dir_mipmaps) return;
synchronized (db_lock) {
lock();
if (forget_dir_mipmaps) this.dir_mipmaps = null;
mawts.removeAllPyramids(); // does not remove level 0 awts (i.e. the 100% images)
unlock();
}
}
/** Remove from the cache all images of level larger than zero corresponding to the given patch id. */
public void flushMipMaps(final long id) {
if (null == dir_mipmaps) return;
synchronized (db_lock) {
lock();
try {
mawts.removePyramid(id); // does not remove level 0 awts (i.e. the 100% images)
} catch (Exception e) { e.printStackTrace(); }
unlock();
}
}
/** Gets data from the Patch and queues a new task to do the file removal in a separate task manager thread. */
public void removeMipMaps(final Patch p) {
if (null == dir_mipmaps) return;
try {
// remove the files
final int width = (int)p.getWidth();
final int height = (int)p.getHeight();
final String path = getAbsolutePath(p);
if (null == path) return; // missing file
final String filename = new File(path).getName() + "." + p.getId() + ".jpg";
// cue the task in a dispatcher:
dispatcher.exec(new Runnable() { public void run() { // copy-paste as a replacement for (defmacro ... we luv java
int w = width;
int h = height;
int k = 0; // the level
while (w >= 64 && h >= 64) { // not smaller than 32x32
final File f = new File(dir_mipmaps + k + "/" + filename);
if (f.exists()) {
try {
if (!f.delete()) {
Utils.log2("Could not remove file " + f.getAbsolutePath());
}
} catch (Exception e) {
IJError.print(e);
}
}
w /= 2;
h /= 2;
k++;
}
}});
} catch (Exception e) {
IJError.print(e);
}
}
/** Checks whether this Loader is using a directory of image pyramids for each Patch or not. */
public boolean isMipMapsEnabled() {
return null != dir_mipmaps;
}
/** Return the closest level to @param level that exists as a file.
* If no valid path is found for the patch, returns ERROR_PATH_NOT_FOUND.
*/
public int getClosestMipMapLevel(final Patch patch, int level) {
if (null == dir_mipmaps) return 0;
try {
final String path = getAbsolutePath(patch);
if (null == path) return ERROR_PATH_NOT_FOUND;
final String filename = new File(path).getName() + ".jpg";
if (isURL(dir_mipmaps)) {
if (level <= 0) return 0;
// choose the smallest dimension
final double dim = patch.getWidth() < patch.getHeight() ? patch.getWidth() : patch.getHeight();
// find max level that keeps dim over 64 pixels
int lev = 1;
while (true) {
if ((dim * (1 / Math.pow(2, lev))) < 64) {
lev--; // the previous one
break;
}
lev++;
}
if (level > lev) return lev;
return level;
} else {
while (true) {
File f = new File(dir_mipmaps + level + "/" + filename);
if (f.exists()) {
return level;
}
// stop at 50% images (there are no mipmaps for level 0)
if (level <= 1) {
return 0;
}
// try the next level
level--;
}
}
} catch (Exception e) {
IJError.print(e);
}
return 0;
}
/** A temporary list of Patch instances for which a pyramid is being generated. */
final private HashSet hs_regenerating_mipmaps = new HashSet();
/** A lock for the generation of mipmaps. */
final private Object gm_lock = new Object();
private boolean gm_locked = false;
protected final void gm_lock() {
//Utils.printCaller(this, 7);
while (gm_locked) { try { gm_lock.wait(); } catch (InterruptedException ie) {} }
gm_locked = true;
}
protected final void gm_unlock() {
//Utils.printCaller(this, 7);
if (gm_locked) {
gm_locked = false;
gm_lock.notifyAll();
}
}
/** Checks if the mipmap file for the Patch and closest upper level to the desired magnification exists. */
public boolean checkMipMapFileExists(final Patch p, final double magnification) {
if (null == dir_mipmaps) return false;
final int level = getMipMapLevel(magnification, maxDim(p));
if (isURL(dir_mipmaps)) return true; // just assume that it does
if (new File(dir_mipmaps + level + "/" + new File(getAbsolutePath(p)).getName() + "." + p.getId() + ".jpg").exists()) return true;
return false;
}
final HashSet<Patch> cannot_regenerate = new HashSet<Patch>();
/** Loads the file containing the scaled image corresponding to the given level (or the maximum possible level, if too large) and returns it as an awt.Image, or null if not found. Will also regenerate the mipmaps, i.e. recreate the pre-scaled jpeg images if they are missing. Does not frees memory on its own. */
protected Image fetchMipMapAWT(final Patch patch, final int level) {
if (null == dir_mipmaps) {
Utils.log2("null dir_mipmaps");
return null;
}
try {
// TODO should wait if the file is currently being generated
// (it's somewhat handled by a double-try to open the jpeg image)
final int max_level = getHighestMipMapLevel(patch);
final String filepath = getInternalFileName(patch);
if (null == filepath) {
Utils.log2("null filepath!");
return null;
}
final String path = new StringBuffer(dir_mipmaps).append( level > max_level ? max_level : level ).append('/').append(filepath).append('.').append(patch.getId()).append(".jpg").toString();
Image img = null;
if (null != patch.getCoordinateTransform()) {
img = ImageSaver.openJpegAlpha(path);
} else {
switch (patch.getType()) {
case ImagePlus.GRAY16:
case ImagePlus.GRAY8:
case ImagePlus.GRAY32:
img = ImageSaver.openGreyJpeg(path);
break;
default:
IJ.redirectErrorMessages();
ImagePlus imp = opener.openImage(path); // considers URL as well
if (null != imp) return patch.createImage(imp); // considers c_alphas
//img = patch.adjustChannels(Toolkit.getDefaultToolkit().createImage(path)); // doesn't work
//img = patch.adjustChannels(ImageSaver.openColorJpeg(path)); // doesn't work
//Utils.log2("color jpeg path: "+ path);
//Utils.log2("exists ? " + new File(path).exists());
break;
}
}
if (null != img) return img;
// if we got so far ... try to regenerate the mipmaps
if (!mipmaps_regen) {
return null;
}
// check that REALLY the file doesn't exist.
if (cannot_regenerate.contains(patch)) {
Utils.log("Cannot regenerate mipmaps for patch " + patch);
return null;
}
//Utils.log2("getMipMapAwt: imp is " + imp + " for path " + dir_mipmaps + level + "/" + new File(getAbsolutePath(patch)).getName() + "." + patch.getId() + ".jpg");
// Regenerate in the case of not asking for an image under 64x64
double scale = 1 / Math.pow(2, level);
if (level > 0 && (patch.getWidth() * scale >= 64 || patch.getHeight() * scale >= 64) && isMipMapsEnabled()) {
// regenerate
synchronized (gm_lock) {
gm_lock();
if (hs_regenerating_mipmaps.contains(patch)) {
// already being done
gm_unlock();
return null;
}
// else, start it
Worker worker = new Worker("Regenerating mipmaps") {
public void run() {
this.setAsBackground(true);
this.startedWorking();
try {
generateMipMaps(patch);
} catch (Exception e) {
IJError.print(e);
}
Display.repaint(patch.getLayer(), patch, 0);
this.finishedWorking();
}
};
Bureaucrat burro = new Bureaucrat(worker, patch.getProject());
burro.goHaveBreakfast();
gm_unlock();
}
return null;
}
} catch (Exception e) {
IJError.print(e);
}
return null;
}
/** Compute the number of bytes that the ImagePlus of a Patch will take. Assumes a large header of 1024 bytes. If the image is saved as a grayscale jpeg the returned bytes will be 5 times as expected, because jpeg images are opened as int[] and then copied to a byte[] if all channels have the same values for all pixels. */ // The header is unnecessary because it's read, but not stored except for some of its variables; it works here as a safety buffer space.
public long estimateImageFileSize(final Patch p, final int level) {
if (level > 0) {
// jpeg image to be loaded:
final double scale = 1 / Math.pow(2, level);
return (long)(p.getWidth() * scale * p.getHeight() * scale * 5 + 1024);
}
long size = (long)(p.getWidth() * p.getHeight());
int bytes_per_pixel = 1;
final int type = p.getType();
switch (type) {
case ImagePlus.GRAY32:
bytes_per_pixel = 5; // 4 for the FloatProcessor, and 1 for the pixels8 to make an image
break;
case ImagePlus.GRAY16:
bytes_per_pixel = 3; // 2 for the ShortProcessor, and 1 for the pixels8
case ImagePlus.COLOR_RGB:
bytes_per_pixel = 4;
break;
case ImagePlus.GRAY8:
case ImagePlus.COLOR_256:
bytes_per_pixel = 1;
// check jpeg, which can only encode RGB (taken care of above) and 8-bit and 8-bit color images:
String path = ht_paths.get(p.getId());
if (null != path && path.endsWith(".jpg")) bytes_per_pixel = 5; //4 for the int[] and 1 for the byte[]
break;
default:
bytes_per_pixel = 5; // conservative
break;
}
return size * bytes_per_pixel + 1024;
}
public String makeProjectName() {
if (null == project_file_path || 0 == project_file_path.length()) return super.makeProjectName();
final String name = new File(project_file_path).getName();
final int i_dot = name.lastIndexOf('.');
if (-1 == i_dot) return name;
if (0 == i_dot) return super.makeProjectName();
return name.substring(0, i_dot);
}
/** Returns the path where the imp is saved to: the storage folder plus a name. */
public String handlePathlessImage(final ImagePlus imp) {
final FileInfo fi = imp.getOriginalFileInfo();
if (null == fi.fileName || fi.fileName.equals("")) {
fi.fileName = "img_" + System.currentTimeMillis() + ".tif";
}
if (!fi.fileName.endsWith(".tif")) fi.fileName += ".tif";
fi.directory = dir_storage;
if (imp.getNSlices() > 1) {
new FileSaver(imp).saveAsTiffStack(dir_storage + fi.fileName);
} else {
new FileSaver(imp).saveAsTiff(dir_storage + fi.fileName);
}
Utils.log2("Saved a copy into the storage folder:\n" + dir_storage + fi.fileName);
return dir_storage + fi.fileName;
}
/** Generates layer-wise mipmaps with constant tile width and height. The mipmaps include only images.
* Mipmaps area generated all the way down until the entire canvas fits within one single tile.
*/
public Bureaucrat generateLayerMipMaps(final Layer[] la, final int starting_level) {
// hard-coded dimensions for layer mipmaps.
final int WIDTH = 512;
final int HEIGHT = 512;
//
// Each tile needs some coding system on where it belongs. For example in its file name, such as <layer_id>_Xi_Yi
//
// Generate the starting level mipmaps, and then the others from it by gaussian or whatever is indicated in the project image_resizing_mode property.
return null;
}
}
| true | true | public boolean generateMipMaps(final Patch patch) {
//Utils.log2("mipmaps for " + patch);
if (null == dir_mipmaps) createMipMapsDir(null);
if (null == dir_mipmaps || isURL(dir_mipmaps)) return false;
final String path = getAbsolutePath(patch);
if (null == path) {
Utils.log2("generateMipMaps: cannot find path for Patch " + patch);
cannot_regenerate.add(patch);
return false;
}
synchronized (gm_lock) {
gm_lock();
if (hs_regenerating_mipmaps.contains(patch)) {
// already being done
gm_unlock();
Utils.log2("Already being done: " + patch);
return false;
}
hs_regenerating_mipmaps.add(patch);
gm_unlock();
}
String srmode = patch.getProject().getProperty("image_resizing_mode");
int resizing_mode = GAUSSIAN;
if (null != srmode) resizing_mode = Loader.getMode(srmode);
try {
// Now:
// 1 - Ask the Patch to apply a coordinate transform, or rather, create a function that gets the coordinate transform from the Patch and applies it to the 'ip'.
// 2 - Then (1) should return both the transformed image and the alpha mask
ImageProcessor ip;
FloatProcessor alpha_mask = null;
final int type = patch.getType();
Patch.CTImage cti = patch.createTransformedImage();
if (null == cti) {
// The original image, from the file:
ip = fetchImageProcessor(patch);
} else {
// The non-linearly transformed image
ip = cti.target;
alpha_mask = cti.mask;
cti = null;
}
final String filename = new StringBuffer(new File(path).getName()).append('.').append(patch.getId()).append(".jpg").toString();
int w = ip.getWidth();
int h = ip.getHeight();
// sigma = sqrt(2^level - 0.5^2)
// where 0.5 is the estimated sigma for a full-scale image
// which means sigma = 0.75 for the full-scale image (has level 0)
// prepare a 0.75 sigma image from the original
ColorModel cm = ip.getColorModel();
int k = 0; // the scale level. Proper scale is: 1 / pow(2, k)
// but since we scale 50% relative the previous, it's always 0.75
if (ImagePlus.COLOR_RGB == type) {
// TODO releaseToFit proper
releaseToFit(w * h * 4 * 5);
final ColorProcessor cp = (ColorProcessor)ip;
final FloatProcessorT2 red = new FloatProcessorT2(w, h, 0, 255); cp.toFloat(0, red);
final FloatProcessorT2 green = new FloatProcessorT2(w, h, 0, 255); cp.toFloat(1, green);
final FloatProcessorT2 blue = new FloatProcessorT2(w, h, 0, 255); cp.toFloat(2, blue);
final FloatProcessorT2 alpha = null != alpha_mask ? new FloatProcessorT2(alpha_mask) : null;
// sw,sh are the dimensions of the image to blur
// w,h are the dimensions to scale the blurred image to
int sw = w,
sh = h;
final String target_dir0 = getLevelDir(dir_mipmaps, 0);
// No alpha channel:
// - use gaussian resizing
// - use standard ImageJ java.awt.Image creation
// Generate level 0 first:
if (!(null == alpha ? ini.trakem2.io.ImageSaver.saveAsJpeg(cp, target_dir0 + filename, 0.85f, false)
: ini.trakem2.io.ImageSaver.saveAsJpegAlpha(createARGBImage(w, h, (int[])cp.getPixels(), (float[])alpha.getPixels()), target_dir0 + filename, 0.85f))) {
cannot_regenerate.add(patch);
} else {
do {
// 1 - Prepare values for the next scaled image
sw = w;
sh = h;
w /= 2;
h /= 2;
k++;
// 2 - Check that the target folder for the desired scale exists
final String target_dir = getLevelDir(dir_mipmaps, k);
if (null == target_dir) continue;
// 3 - Blur the previous image to 0.75 sigma, and scale it
final byte[] r = gaussianBlurResizeInHalf(red, sw, sh, w, h); // will resize 'red' FloatProcessor in place.
final byte[] g = gaussianBlurResizeInHalf(green, sw, sh, w, h); // idem
final byte[] b = gaussianBlurResizeInHalf(blue, sw, sh, w, h); // idem
final byte[] a = null == alpha ? null
: gaussianBlurResizeInHalf(alpha, sw, sh, w, h); // idem
if (null != a) {
// set all non-white pixels to black: solves border problem
for (int i=0; i<a.length; i++) {
if (255 != (a[i]&0xff)) a[i] = 0; // TODO I am sure there is a bitwise operation to do this in one step. Some thing like: a[i] &= 127;
}
}
// 4 - Compose ColorProcessor
final int[] pix = new int[w * h];
if (null == alpha) {
for (int i=0; i<pix.length; i++) {
pix[i] = (r[i]<<16) + (g[i]<<8) + b[i];
}
final ColorProcessor cp2 = new ColorProcessor(w, h, pix);
cp2.setMinAndMax(patch.getMin(), patch.getMax());
// 5 - Save as jpeg
if (!ini.trakem2.io.ImageSaver.saveAsJpeg(cp2, target_dir + filename, 0.85f, false)) {
cannot_regenerate.add(patch);
break;
}
} else {
// LIKELY no need to set alpha raster later in createARGBImage ... TODO
for (int i=0; i<pix.length; i++) {
pix[i] = (a[i]<<24) + (r[i]<<16) + (g[i]<<8) + b[i];
}
if (!ini.trakem2.io.ImageSaver.saveAsJpegAlpha(createARGBImage(w, h, pix, (float[])alpha.getPixels()), target_dir + filename, 0.85f)) {
cannot_regenerate.add(patch);
break;
}
}
} while (w >= 64 && h >= 64); // not smaller than 32x32
}
} else {
// Greyscale:
//
// TODO releaseToFit proper
releaseToFit(w * h * 4 * 5);
final boolean as_grey = !ip.isColorLut(); // TODO won't work with alpha masks, I guess
if (as_grey && null == cm) { // TODO needs fixing for 'half' method
cm = GRAY_LUT;
}
if (Loader.GAUSSIAN == resizing_mode) {
FloatProcessor fp = (FloatProcessor) ip.convertToFloat();
fp.setMinAndMax(patch.getMin(), patch.getMax()); // no scaling, so values should do fine directly.
FloatProcessor fp_alpha = alpha_mask;
int sw=w, sh=h;
do {
// 0 - blur the previous image to 0.75 sigma
if (0 != k) { // not doing so at the end because it would add one unnecessary blurring
fp = new FloatProcessorT2(sw, sh, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])fp.getPixels(), sw, sh), 0.75f).data, cm);
if (null != fp_alpha) fp_alpha = new FloatProcessorT2(sw, sh, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])fp_alpha.getPixels(), sw, sh), 0.75f).data, null);
}
// 1 - check that the target folder for the desired scale exists
final String target_dir = getLevelDir(dir_mipmaps, k);
if (null == target_dir) continue;
// 2 - generate scaled image
if (0 != k) {
fp = (FloatProcessor)fp.resize(w, h);
fp.setMinAndMax(patch.getMin(), patch.getMax()); // the resize doesn't preserve the min and max!
if (null != fp_alpha) fp_alpha = (FloatProcessor)fp_alpha.resize(w, h);
}
if (null != alpha_mask) {
// 3 - save as jpeg with alpha
final int[] pix = (int[])fp.convertToRGB().getPixels();
final float[] a = (float[])fp_alpha.getPixels();
// Set all non-white pixels to zero
for (int g=0; g<a.length; g++)
if (Math.abs(a[g] - 255) > 0.001f) a[g] = 0;
if (!ini.trakem2.io.ImageSaver.saveAsJpegAlpha(createARGBImage(w, h, pix, a), target_dir + filename, 0.85f)) {
cannot_regenerate.add(patch);
break;
}
} else {
// 3 - save as 8-bit jpeg
final ImageProcessor ip2 = Utils.convertTo(fp, type, false); // no scaling, since the conversion to float above didn't change the range. This is needed because of the min and max
ip2.setMinAndMax(patch.getMin(), patch.getMax());
if (null != cm) ip2.setColorModel(cm); // the LUT
if (!ini.trakem2.io.ImageSaver.saveAsJpeg(ip2, target_dir + filename, 0.85f, as_grey)) {
cannot_regenerate.add(patch);
break;
}
}
// 4 - prepare values for the next scaled image
sw = w;
sh = h;
w /= 2;
h /= 2;
k++;
} while (w >= 32 && h >= 32); // not smaller than 32x32
} else {
// use java hardware-accelerated resizing
Image awt = ip.createImage();
/* // will be done anyway by IToBI function
if (null != alpha_mask) {
BufferedImage bu = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
bu.createGraphics().drawImage(awt, 0, 0, null);
bu.getAlphaRaster().setPixels(0, 0, w, h, (float[])alpha_mask.getPixels());
awt = bu;
}
*/
BufferedImage balpha = null;
if (null != alpha_mask) {
alpha_mask.setMinAndMax(0, 255);
Image aa = alpha_mask.createImage();
if (aa instanceof BufferedImage) balpha = (BufferedImage)aa;
else {
balpha = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
balpha.createGraphics().drawImage(aa, 0, 0, null);
}
}
BufferedImage bi = null;
final Object hint = getHint(resizing_mode);
final IndexColorModel icm = (IndexColorModel)cm;
do {
// check that the target folder for the desired scale exists
final String target_dir = getLevelDir(dir_mipmaps, k);
if (null == target_dir) continue;
// obtain half image
// for level 0 and others, when awt is not a bi or needs to be reduced in size (to new w,h)
final BufferedImage[] res = IToBI(awt, w, h, hint, icm, balpha); // can't just cast even if it's a BI already, because color type is wrong
bi = res[0];
balpha = res[1];
// prepare next iteration
if (awt != bi) awt.flush();
awt = bi;
w /= 2;
h /= 2;
k++;
// save this iteration
if ( (null != alpha_mask &&
!ini.trakem2.io.ImageSaver.saveAsJpegAlpha(bi, target_dir + filename, 0.85f))
|| (null == alpha_mask &&
!ini.trakem2.io.ImageSaver.saveAsJpeg(bi, target_dir + filename, 0.85f, as_grey))) {
cannot_regenerate.add(patch);
break;
}
} while (w >= 32 && h >= 32);
bi.flush();
}
}
return true;
} catch (Throwable e) {
IJError.print(e);
cannot_regenerate.add(patch);
return false;
} finally {
// gets executed even when returning from the catch statement or within the try/catch block
synchronized (gm_lock) {
gm_lock();
hs_regenerating_mipmaps.remove(patch);
gm_unlock();
}
}
}
| public boolean generateMipMaps(final Patch patch) {
//Utils.log2("mipmaps for " + patch);
if (null == dir_mipmaps) createMipMapsDir(null);
if (null == dir_mipmaps || isURL(dir_mipmaps)) return false;
final String path = getAbsolutePath(patch);
if (null == path) {
Utils.log2("generateMipMaps: cannot find path for Patch " + patch);
cannot_regenerate.add(patch);
return false;
}
synchronized (gm_lock) {
gm_lock();
if (hs_regenerating_mipmaps.contains(patch)) {
// already being done
gm_unlock();
Utils.log2("Already being done: " + patch);
return false;
}
hs_regenerating_mipmaps.add(patch);
gm_unlock();
}
String srmode = patch.getProject().getProperty("image_resizing_mode");
int resizing_mode = GAUSSIAN;
if (null != srmode) resizing_mode = Loader.getMode(srmode);
try {
// Now:
// 1 - Ask the Patch to apply a coordinate transform, or rather, create a function that gets the coordinate transform from the Patch and applies it to the 'ip'.
// 2 - Then (1) should return both the transformed image and the alpha mask
ImageProcessor ip;
FloatProcessor alpha_mask = null;
final int type = patch.getType();
Patch.CTImage cti = patch.createTransformedImage();
if (null == cti) {
// The original image, from the file:
ip = fetchImageProcessor(patch);
} else {
// The non-linearly transformed image
ip = cti.target;
alpha_mask = cti.mask;
cti = null;
}
final String filename = new StringBuffer(new File(path).getName()).append('.').append(patch.getId()).append(".jpg").toString();
int w = ip.getWidth();
int h = ip.getHeight();
// sigma = sqrt(2^level - 0.5^2)
// where 0.5 is the estimated sigma for a full-scale image
// which means sigma = 0.75 for the full-scale image (has level 0)
// prepare a 0.75 sigma image from the original
ColorModel cm = ip.getColorModel();
int k = 0; // the scale level. Proper scale is: 1 / pow(2, k)
// but since we scale 50% relative the previous, it's always 0.75
if (ImagePlus.COLOR_RGB == type) {
// TODO releaseToFit proper
releaseToFit(w * h * 4 * 5);
final ColorProcessor cp = (ColorProcessor)ip;
final FloatProcessorT2 red = new FloatProcessorT2(w, h, 0, 255); cp.toFloat(0, red);
final FloatProcessorT2 green = new FloatProcessorT2(w, h, 0, 255); cp.toFloat(1, green);
final FloatProcessorT2 blue = new FloatProcessorT2(w, h, 0, 255); cp.toFloat(2, blue);
final FloatProcessorT2 alpha = null != alpha_mask ? new FloatProcessorT2(alpha_mask) : null;
// sw,sh are the dimensions of the image to blur
// w,h are the dimensions to scale the blurred image to
int sw = w,
sh = h;
final String target_dir0 = getLevelDir(dir_mipmaps, 0);
// No alpha channel:
// - use gaussian resizing
// - use standard ImageJ java.awt.Image creation
// Generate level 0 first:
if (!(null == alpha ? ini.trakem2.io.ImageSaver.saveAsJpeg(cp, target_dir0 + filename, 0.85f, false)
: ini.trakem2.io.ImageSaver.saveAsJpegAlpha(createARGBImage(w, h, (int[])cp.getPixels(), (float[])alpha.getPixels()), target_dir0 + filename, 0.85f))) {
cannot_regenerate.add(patch);
} else {
do {
// 1 - Prepare values for the next scaled image
sw = w;
sh = h;
w /= 2;
h /= 2;
k++;
// 2 - Check that the target folder for the desired scale exists
final String target_dir = getLevelDir(dir_mipmaps, k);
if (null == target_dir) continue;
// 3 - Blur the previous image to 0.75 sigma, and scale it
final byte[] r = gaussianBlurResizeInHalf(red, sw, sh, w, h); // will resize 'red' FloatProcessor in place.
final byte[] g = gaussianBlurResizeInHalf(green, sw, sh, w, h); // idem
final byte[] b = gaussianBlurResizeInHalf(blue, sw, sh, w, h); // idem
final byte[] a = null == alpha ? null
: gaussianBlurResizeInHalf(alpha, sw, sh, w, h); // idem
if (null != a) {
// set all non-white pixels to black: solves border problem
for (int i=0; i<a.length; i++) {
if (255 != (a[i]&0xff)) a[i] = 0; // TODO I am sure there is a bitwise operation to do this in one step. Some thing like: a[i] &= 127;
}
}
// 4 - Compose ColorProcessor
final int[] pix = new int[w * h];
if (null == alpha) {
for (int i=0; i<pix.length; i++) {
pix[i] = (r[i]<<16) + (g[i]<<8) + b[i];
}
final ColorProcessor cp2 = new ColorProcessor(w, h, pix);
cp2.setMinAndMax(patch.getMin(), patch.getMax());
// 5 - Save as jpeg
if (!ini.trakem2.io.ImageSaver.saveAsJpeg(cp2, target_dir + filename, 0.85f, false)) {
cannot_regenerate.add(patch);
break;
}
} else {
// LIKELY no need to set alpha raster later in createARGBImage ... TODO
for (int i=0; i<pix.length; i++) {
pix[i] = (a[i]<<24) + (r[i]<<16) + (g[i]<<8) + b[i];
}
if (!ini.trakem2.io.ImageSaver.saveAsJpegAlpha(createARGBImage(w, h, pix, (float[])alpha.getPixels()), target_dir + filename, 0.85f)) {
cannot_regenerate.add(patch);
break;
}
}
} while (w >= 32 && h >= 32); // not smaller than 32x32
}
} else {
// Greyscale:
//
// TODO releaseToFit proper
releaseToFit(w * h * 4 * 5);
final boolean as_grey = !ip.isColorLut(); // TODO won't work with alpha masks, I guess
if (as_grey && null == cm) { // TODO needs fixing for 'half' method
cm = GRAY_LUT;
}
if (Loader.GAUSSIAN == resizing_mode) {
FloatProcessor fp = (FloatProcessor) ip.convertToFloat();
fp.setMinAndMax(patch.getMin(), patch.getMax()); // no scaling, so values should do fine directly.
FloatProcessor fp_alpha = alpha_mask;
int sw=w, sh=h;
do {
// 0 - blur the previous image to 0.75 sigma
if (0 != k) { // not doing so at the end because it would add one unnecessary blurring
fp = new FloatProcessorT2(sw, sh, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])fp.getPixels(), sw, sh), 0.75f).data, cm);
if (null != fp_alpha) fp_alpha = new FloatProcessorT2(sw, sh, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])fp_alpha.getPixels(), sw, sh), 0.75f).data, null);
}
// 1 - check that the target folder for the desired scale exists
final String target_dir = getLevelDir(dir_mipmaps, k);
if (null == target_dir) continue;
// 2 - generate scaled image
if (0 != k) {
fp = (FloatProcessor)fp.resize(w, h);
fp.setMinAndMax(patch.getMin(), patch.getMax()); // the resize doesn't preserve the min and max!
if (null != fp_alpha) fp_alpha = (FloatProcessor)fp_alpha.resize(w, h);
}
if (null != alpha_mask) {
// 3 - save as jpeg with alpha
final int[] pix = (int[])fp.convertToRGB().getPixels();
final float[] a = (float[])fp_alpha.getPixels();
// Set all non-white pixels to zero
for (int g=0; g<a.length; g++)
if (Math.abs(a[g] - 255) > 0.001f) a[g] = 0;
if (!ini.trakem2.io.ImageSaver.saveAsJpegAlpha(createARGBImage(w, h, pix, a), target_dir + filename, 0.85f)) {
cannot_regenerate.add(patch);
break;
}
} else {
// 3 - save as 8-bit jpeg
final ImageProcessor ip2 = Utils.convertTo(fp, type, false); // no scaling, since the conversion to float above didn't change the range. This is needed because of the min and max
ip2.setMinAndMax(patch.getMin(), patch.getMax());
if (null != cm) ip2.setColorModel(cm); // the LUT
if (!ini.trakem2.io.ImageSaver.saveAsJpeg(ip2, target_dir + filename, 0.85f, as_grey)) {
cannot_regenerate.add(patch);
break;
}
}
// 4 - prepare values for the next scaled image
sw = w;
sh = h;
w /= 2;
h /= 2;
k++;
} while (w >= 32 && h >= 32); // not smaller than 32x32
} else {
// use java hardware-accelerated resizing
Image awt = ip.createImage();
/* // will be done anyway by IToBI function
if (null != alpha_mask) {
BufferedImage bu = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
bu.createGraphics().drawImage(awt, 0, 0, null);
bu.getAlphaRaster().setPixels(0, 0, w, h, (float[])alpha_mask.getPixels());
awt = bu;
}
*/
BufferedImage balpha = null;
if (null != alpha_mask) {
alpha_mask.setMinAndMax(0, 255);
Image aa = alpha_mask.createImage();
if (aa instanceof BufferedImage) balpha = (BufferedImage)aa;
else {
balpha = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
balpha.createGraphics().drawImage(aa, 0, 0, null);
}
}
BufferedImage bi = null;
final Object hint = getHint(resizing_mode);
final IndexColorModel icm = (IndexColorModel)cm;
do {
// check that the target folder for the desired scale exists
final String target_dir = getLevelDir(dir_mipmaps, k);
if (null == target_dir) continue;
// obtain half image
// for level 0 and others, when awt is not a bi or needs to be reduced in size (to new w,h)
final BufferedImage[] res = IToBI(awt, w, h, hint, icm, balpha); // can't just cast even if it's a BI already, because color type is wrong
bi = res[0];
balpha = res[1];
// prepare next iteration
if (awt != bi) awt.flush();
awt = bi;
w /= 2;
h /= 2;
k++;
// save this iteration
if ( (null != alpha_mask &&
!ini.trakem2.io.ImageSaver.saveAsJpegAlpha(bi, target_dir + filename, 0.85f))
|| (null == alpha_mask &&
!ini.trakem2.io.ImageSaver.saveAsJpeg(bi, target_dir + filename, 0.85f, as_grey))) {
cannot_regenerate.add(patch);
break;
}
} while (w >= 32 && h >= 32);
bi.flush();
}
}
return true;
} catch (Throwable e) {
IJError.print(e);
cannot_regenerate.add(patch);
return false;
} finally {
// gets executed even when returning from the catch statement or within the try/catch block
synchronized (gm_lock) {
gm_lock();
hs_regenerating_mipmaps.remove(patch);
gm_unlock();
}
}
}
|
diff --git a/java/marytts/server/MaryProperties.java b/java/marytts/server/MaryProperties.java
index 7a5bf069e..47a98ffa1 100755
--- a/java/marytts/server/MaryProperties.java
+++ b/java/marytts/server/MaryProperties.java
@@ -1,834 +1,834 @@
/**
* Copyright 2000-2006 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* This file is part of MARY TTS.
*
* MARY TTS 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, version 3 of the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package marytts.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.JOptionPane;
import marytts.exceptions.NoSuchPropertyException;
import marytts.modules.ModuleRegistry;
import marytts.signalproc.effects.BaseAudioEffect;
import marytts.tools.installvoices.VoiceInstaller;
import marytts.util.InstallationUtils;
import marytts.util.MaryUtils;
/**
* A static class reading once, at program start, properties
* from a number of external property files,
* and providing them via static
* getter methods to anyone wishing to read them.
* At program start, this will read all the config files in the MARY_BASE/conf
* directory that end in *.config. See the config files for more information.
*
* @author Marc Schröder
*/
public class MaryProperties
{
// The underlying Properties object
private static Properties p = null;
// Global configuration settings independent of any particular request:
private static String maryBase = null;
private static boolean logToFile = false;
private static Vector<String> moduleInitInfo = new Vector<String>();
private static Vector<String> synthClasses = new Vector<String>();
private static Vector<String> audioEffectClasses = new Vector<String>();
private static Vector<String> audioEffectNames = new Vector<String>();
private static Vector<String> audioEffectSampleParams = new Vector<String>();
private static Vector<String> audioEffectHelpTexts = new Vector<String>();
private static Map<Locale,String> locale2prefix = new HashMap<Locale,String>();
private static Object[] localSchemas;
/** The mary base directory, e.g. /usr/local/mary */
public static String maryBase()
{
if (maryBase == null) {
maryBase = System.getProperty("mary.base");
if (maryBase == null)
throw new RuntimeException("System property mary.base not defined");
maryBase = expandPath(maryBase);
}
return maryBase;
}
/** Whether to log to the log file or to the screen */
public static boolean logToFile() { return logToFile; }
/** Names of the classes to use as modules, plus optional parameter info.
* @see marytts.modules.ModuleRegistry#instantiateModule(String) for details on expected format.
*/
public static Vector<String> moduleInitInfo() { return moduleInitInfo; }
/** Names of the classes to use as waveform synthesizers. */
public static Vector<String> synthesizerClasses() { return synthClasses; }
/** Names of the classes to use as audio effects. */
public static Vector<String> effectClasses() { return audioEffectClasses; }
/** Names of audio effects. */
public static Vector<String> effectNames() { return audioEffectNames; }
/** Sample Parameters of audio effects. */
public static Vector<String> effectSampleParams() { return audioEffectSampleParams; }
/** Help text of audio effects. */
public static Vector<String> effectHelpTexts() { return audioEffectHelpTexts; }
/** An Object[] containing File objects referencing local Schema files */
public static Object[] localSchemas() { return localSchemas; }
/**
* Read the properties from property files and command line.
* Properties are read from
* <ul>
* <li> the System properties, as specified on the command line; </li>
* <li> MARY_BASE/conf/*.config </li>
* </ul>
* The system properties settings have precedence,
* i.e. it is possible to override single config settings on the
* command line.
* <br>
* This method will also do dependency checking, and propose to download
* missing packages from the MARY installer.
*/
public static void readProperties()
throws Exception {
// Throws all sorts of exceptions, each of them should lead to
// a program halt: We cannot start up properly.
if (p != null) // we have done this already
return;
File confDir = new File(maryBase()+"/conf");
if (!confDir.exists()) {
throw new FileNotFoundException("Configuration directory not found: "+ confDir.getPath());
}
File[] configFiles = confDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".config");
}
});
assert configFiles != null;
if (configFiles.length == 0) {
throw new FileNotFoundException("No configuration files found in directory: "+ confDir.getPath());
}
List<Properties> allConfigs = readConfigFiles(configFiles);
boolean allThere = checkDependencies(allConfigs);
if (!allThere) System.exit(1);
// Add properties from individual config files to global properties:
// Global mary properties
p = new Properties();
for (Properties oneP : allConfigs) {
for (Iterator keyIt=oneP.keySet().iterator(); keyIt.hasNext(); ) {
String key = (String) keyIt.next();
// Ignore dependency-related properties:
if (key.equals("name") || key.equals("provides") || key.startsWith("requires")) {
continue;
}
String value = oneP.getProperty(key);
// Properties with keys ending in ".list" are to be appended in global properties.
if (key.endsWith(".list")) {
String prevValue = p.getProperty(key);
if (prevValue != null) {
value = prevValue + " " + value;
}
}
p.setProperty(key, value);
}
}
// Overwrite settings from config files with those set on the
// command line (System properties):
p.putAll(System.getProperties());
// Reciprocally, put all settings in p into the system properties
// (to allow for non-Mary config settings, e.g. for tritonus).
// If one day we find this to be too unflexible, we can also
// identify a subset of properties to put into the System properties,
// e.g. by prepending them with a "system." prefix. For now, this seems
// unnecessary.
System.getProperties().putAll(p);
// OK, now the individual settings
// If necessary, derive shprot.base from mary.base:
if (getProperty("shprot.base") == null) {
p.setProperty("shprot.base", maryBase + File.separator + "lib" +
File.separator + "modules" + File.separator + "shprot");
System.setProperty("shprot.base", getProperty("shprot.base"));
}
String helperString;
StringTokenizer st;
Set<String> ignoreModuleClasses = new HashSet<String>();
helperString = getProperty("ignore.modules.classes.list");
if (helperString != null) {
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, ", \t\n\r\f");
while (st.hasMoreTokens()) {
ignoreModuleClasses.add(st.nextToken());
}
}
helperString = needProperty("modules.classes.list");
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, " \t\n\r\f");
while (st.hasMoreTokens()) {
String className = st.nextToken();
if (!ignoreModuleClasses.contains(className))
moduleInitInfo.add(className);
}
helperString = needProperty("synthesizers.classes.list");
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, " \t\n\r\f");
while (st.hasMoreTokens()) {
synthClasses.add(st.nextToken());
}
String audioEffectClassName, audioEffectName, audioEffectParam, audioEffectSampleParam, audioEffectHelpText;
helperString = getProperty("audioeffects.classes.list");
if (helperString!=null)
{
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, " \t\n\r\f");
while (st.hasMoreTokens()) {
audioEffectClassName = st.nextToken();
audioEffectClasses.add(audioEffectClassName);
BaseAudioEffect ae = null;
try {
ae = (BaseAudioEffect)Class.forName(audioEffectClassName).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ae.setParams(ae.getExampleParameters());
audioEffectName = ae.getName();
audioEffectNames.add(audioEffectName);
audioEffectSampleParam = ae.getExampleParameters();
audioEffectSampleParams.add(audioEffectSampleParam);
audioEffectHelpText = ae.getHelpText();
audioEffectHelpTexts.add(audioEffectHelpText);
}
}
helperString = getProperty("schema.local");
if (helperString!=null)
{
st = new StringTokenizer(helperString);
Vector<File> v = new Vector<File>();
while (st.hasMoreTokens()) {
String schemaFilename = expandPath(st.nextToken());
File schemaFile = new File(schemaFilename);
if (!schemaFile.canRead())
throw new Exception("Cannot read Schema file: " + schemaFilename);
v.add(schemaFile);
}
localSchemas = v.toArray();
}
// Setup locale translation table:
- locale2prefix.put(Locale.ENGLISH, "english");
+ locale2prefix.put(Locale.US, "english");
locale2prefix.put(Locale.GERMAN, "german");
locale2prefix.put(new Locale("tib"), "tibetan");
}
/**
* Read the config files from the config directory and return them
* as a list of Property objects
* @return a list of property objects, each representing a config file.
* Each property object has one key/value pair added: "configfile", which
* points to the path on the filesystem from where the config file was loaded.
* @throws Exception if problem occurred that impairs a proper system startup
*/
private static List<Properties> readConfigFiles(File[] configFiles) throws Exception
{
/////////////////// Read config files ////////////////////
List<Properties> allConfigs = new LinkedList<Properties>();
for (int i=0; i<configFiles.length; i++) {
// Ignore config file?
if (System.getProperty("ignore."+configFiles[i].getName()) != null)
continue;
String path = configFiles[i].getPath();
// Properties for one config file
Properties oneP = new Properties();
oneP.setProperty("configfile", path);
oneP.load(new FileInputStream(configFiles[i]));
allConfigs.add(oneP);
}
return allConfigs;
}
/**
* Check dependencies between components, and try to download and install components
* that are missing.
* @param allConfigs a list of Properties objects as loaded by readConfigFiles().
* @return true if all dependencies are OK
* @throws Exception if a problem occurs
*/
private static boolean checkDependencies(List<Properties> allConfigs)
throws Exception
{
// Keep track of "requires" and "provides" settings, in order to check if
// all requirements are satisfied.
Map<String,List<Properties>> requiresMap = new HashMap<String,List<Properties>>(); // map a requirement to a list of components that have it
Map<String,List<Properties>> providesMap = new HashMap<String,List<Properties>>(); // map a provided item to a list of components providing it
for (Properties oneP : allConfigs) {
// Build up dependency lists
String name = oneP.getProperty("name");
if (name == null) {
throw new NoSuchPropertyException("In config file `"+oneP.getProperty("configfile")+"': property `name' missing.");
}
addToMapList(providesMap, name, oneP);
String provides = oneP.getProperty("provides");
if (provides != null) {
StringTokenizer st = new StringTokenizer(provides);
while (st.hasMoreTokens()) {
addToMapList(providesMap, st.nextToken(), oneP);
}
}
String requires = oneP.getProperty("requires");
if (requires != null) {
StringTokenizer st = new StringTokenizer(requires);
while (st.hasMoreTokens()) {
addToMapList(requiresMap, st.nextToken(), oneP);
}
}
}
// Resolve dependencies
boolean allThere = true;
for (String requirement : requiresMap.keySet()) {
List<Properties> requirers = requiresMap.get(requirement);
for (Properties requirer : requirers) {
if (!providesMap.containsKey(requirement)) {
// Missing dependency
String component = tryToSolveDependencyProblem(requirement, requirer, "component is missing");
if (component != null) { // could solve one
// update classpath, in case a new jar file was installed
Mary.addJarsToClasspath();
// add new config file, re-check
File configFile = new File(maryBase+"/conf/"+component+".config");
assert configFile.exists();
allConfigs.addAll(readConfigFiles(new File[] {configFile}));
// recursive call
return checkDependencies(allConfigs);
} else { // failed, cannot solve
allThere = false;
}
} else { // Component is there
// Check version
String reqVersion = requirer.getProperty("requires."+requirement+".version");
List<Properties> providers = providesMap.get(requirement);
for (Properties provider : providers) {
if (reqVersion != null) {
String version = provider.getProperty(requirement+".version");
String problem = null;
if (version == null) { // bad configuration
problem = "no version number";
} else if (version.compareTo(reqVersion) < 0) { // version too small
problem = "version `"+version+"'";
} // else version OK
if (problem != null) {
String component = tryToSolveDependencyProblem(requirement, requirer,
"version number "+reqVersion+" is required, and component `"+provider.getProperty("name")+"' provides "+problem);
if (component != null) { // could solve one
// update classpath, in case a new jar file was installed
Mary.addJarsToClasspath();
// add new config file, re-check
File configFile = new File(maryBase+"/conf/"+component+".config");
assert configFile.exists();
allConfigs.addAll(readConfigFiles(new File[] {configFile}));
// recursive call
allThere = checkDependencies(allConfigs);
} else { // failed, cannot solve
allThere = false;
}
}
}
// Try to make sure that each provider is listed *before*
// the requirer in allConfigs -- this will affect the order
// in which modules are loaded.
int iProvider = allConfigs.indexOf(provider);
int iRequirer = allConfigs.indexOf(requirer);
assert iProvider >= 0;
assert iRequirer >= 0;
if (iProvider > iRequirer) {
allConfigs.remove(provider);
allConfigs.add(iRequirer, provider);
}
}
}
}
}
return allThere;
}
/**
* Helper to map one key to a list of values.
* @param map
* @param key
* @param listValue
*/
private static final void addToMapList(Map<String,List<Properties>> map, String key, Properties listValue)
{
List<Properties> list;
if (map.containsKey(key)) {
list = map.get(key);
} else {
list = new ArrayList<Properties>();
map.put(key, list);
}
list.add(listValue);
}
/**
* For a missing component, try to solve the dependency problem.
* @param missing name of the missing component
* @param reqProps properties of the requirer
* @param message description of the problem
* @return a String representing the new component name if the problem could be fixed, e.g. by
* installing the missing component; null on failure.
*/
private static final String tryToSolveDependencyProblem(String missing, Properties reqProps, String message)
{
String requirer = reqProps.getProperty("name");
String problem = "Component `"+missing+"' is required by `"+requirer+"',\n"+
"but "+message+".";
String component = reqProps.getProperty("requires."+missing+".download.package-name", missing).trim();
String download = reqProps.getProperty("requires."+missing+".download");
if (missing.contains("voice")) {
int answer = JOptionPane.showConfirmDialog(null,
problem+"\n"+
"Would you like to download `"+ component +"'\nusing the MARY Voice Installer?",
"Dependency problem",
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
// Try to install it via the voice installer
// run(), not start(), so that the code is executed in the current thread
new VoiceInstaller(component, false).run();
}
} else if (download != null) {
int answer = JOptionPane.showConfirmDialog(null,
problem+"\n"+
"Would you like to download `"+ component +"' from\n" + download + "?",
"Dependency problem",
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
System.getProperties().setProperty("licensepanel.title", "Installing "+component);
try {
// TODO: The AutomatedInstaller in IzPack calls System.exit(),
// so this does not return -- replace with own AutomatedInstaller?
//InstallationUtils.directRunInstaller(new URL(download), component);
InstallationUtils.downloadAndRunInstaller(new URL(download), component);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
if (new File(maryBase()+"/conf/"+component+".config").exists()) {
// apparently, the component has now been installed
return component;
}
}
} else {
// no download option, just inform.
JOptionPane.showMessageDialog(null,
problem,
"Dependency problem",
JOptionPane.ERROR_MESSAGE);
}
return null;
}
/**
* From a path entry in the properties, create an expanded form.
* Replace the string MARY_BASE with the value of property "mary.base";
* replace all "/" and "\\" with the platform-specific file separator.
*/
private static String expandPath(String path)
{
final String MARY_BASE = "MARY_BASE";
StringBuffer buf = null;
if (path.startsWith(MARY_BASE)) {
buf = new StringBuffer(maryBase);
buf.append(path.substring(MARY_BASE.length()));
} else {
buf = new StringBuffer(path);
}
if (File.separator.equals("/")) {
int i = -1;
while ((i = buf.indexOf("\\")) != -1)
buf.replace(i, i+1, "/");
} else if (File.separator.equals("\\")) {
int i = -1;
while ((i = buf.indexOf("/")) != -1)
buf.replace(i, i+1, "\\");
} else {
throw new Error("Unexpected File.separator: `" + File.separator + "'");
}
return buf.toString();
}
/**
* Get a property from the underlying properties.
* @param property the property requested
* @return the property value if found, null otherwise.
*/
public static String getProperty(String property)
{
return getProperty(property, null);
}
/**
* Get a boolean property from the underlying properties.
* @param property the property requested
* @return the boolean property value if found, false otherwise.
*/
public static boolean getBoolean(String property)
{
return getBoolean(property, false);
}
/**
* Get or infer a boolean property from the underlying properties.
* Apart from the values "true"and "false", a value "auto" is permitted;
* it will resolve to "true" in server mode and to "false" in non-server mode.
* @param property the property requested
* @return the boolean property value if found, false otherwise.
*/
public static boolean getAutoBoolean(String property)
{
return getAutoBoolean(property, false);
}
/**
* Get an integer property from the underlying properties.
* @param property the property requested
* @return the integer property value if found, -1 otherwise.
*/
public static int getInteger(String property)
{
return getInteger(property, -1);
}
/**
* Get a filename property from the underlying properties. The string MARY_BASE is
* replaced with the value of the property mary.base, and path separators are adapted
* to the current platform.
* @param property the property requested
* @return the filename corresponding to the property value if found, null otherwise.
*/
public static String getFilename(String property)
{
return getFilename(property, null);
}
/**
* Get a Class property from the underlying properties.
* @param property the property requested
* @return the Class property value if found and valid, null otherwise.
*/
public static Class getClass(String property)
{
return getClass(property, null);
}
/**
* Get a property from the underlying properties.
* @param property the property requested
* @param defaultValue the value to return if the property is not defined
* @return the property value if found, defaultValue otherwise.
*/
public static String getProperty(String property, String defaultValue)
{
if (p == null) return defaultValue;
return p.getProperty(property, defaultValue);
}
/**
* Get a boolean property from the underlying properties.
* @param property the property requested
* @param defaultValue the value to return if the property is not defined
* @return the boolean property value if found and valid, defaultValue otherwise.
*/
public static boolean getBoolean(String property, boolean defaultValue)
{
if (p == null) return defaultValue;
String value = p.getProperty(property);
if (value == null)
return defaultValue;
try {
boolean b = Boolean.valueOf(value).booleanValue();
return b;
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Get or infer a boolean property from the underlying properties.
* Apart from the values "true"and "false", a value "auto" is permitted;
* it will resolve to "true" in server mode and to "false" in non-server mode.
* @param property the property requested
* @param defaultValue the value to return if the property is not defined
* @return the boolean property value if found and valid, false otherwise.
*/
public static boolean getAutoBoolean(String property, boolean defaultValue)
{
if (p == null) return defaultValue;
String value = p.getProperty(property);
if (value == null)
return defaultValue;
if (value.equals("auto")) {
return ((getProperty("server").compareTo("commandline")==0) ? false:true);
} else {
return getBoolean(property, defaultValue);
}
}
/**
* Get a property from the underlying properties.
* @param property the property requested
* @param defaultValue the value to return if the property is not defined
* @return the integer property value if found and valid, defaultValue otherwise.
*/
public static int getInteger(String property, int defaultValue)
{
if (p == null) return defaultValue;
String value = p.getProperty(property);
if (value == null)
return defaultValue;
try {
int i = Integer.decode(value).intValue();
return i;
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Get a filename property from the underlying properties. The string MARY_BASE is
* replaced with the value of the property mary.base, and path separators are adapted
* to the current platform.
* @param property the property requested
* @param defaultValue the value to return if the property is not defined
* @return the filename corresponding to the property value if found, defaultValue otherwise.
*/
public static String getFilename(String property, String defaultValue)
{
if (p == null) return defaultValue;
String filename = p.getProperty(property);
if (filename == null)
return defaultValue;
return expandPath(filename);
}
/**
* Get a Class property from the underlying properties.
* @param property the property requested
* @param defaultValue the value to return if the property is not defined
* @return the property value if found, defaultValue otherwise.
*/
public static Class getClass(String property, Class defaultValue)
{
if (p == null) return defaultValue;
String value = p.getProperty(property);
if (value == null)
return defaultValue;
Class c = null;
try {
c = Class.forName(value);
} catch (ClassNotFoundException e) {
return defaultValue;
}
return c;
}
/**
* Get a property from the underlying properties, throwing an exception if
* it is not defined.
* @param property the property required
* @return the property value
* @throws NoSuchPropertyException if the property is not defined.
*/
public static String needProperty(String property) throws NoSuchPropertyException
{
String value = p.getProperty(property);
if (value == null)
throw new NoSuchPropertyException("Missing value `" + property + "' in configuration files");
return value;
}
/**
* Get a boolean property from the underlying properties, throwing an exception if
* it is not defined.
* @param property the property requested
* @return the boolean property value
* @throws NoSuchPropertyException if the property is not defined.
*/
public static boolean needBoolean(String property) throws NoSuchPropertyException
{
String value = p.getProperty(property);
if (value == null)
throw new NoSuchPropertyException("Missing property `" + property + "' in configuration files");
try {
boolean b = Boolean.valueOf(value).booleanValue();
return b;
} catch (NumberFormatException e) {
throw new NoSuchPropertyException("Boolean property `" + property + "' in configuration files has wrong value `" + value + "'");
}
}
/**
* Get or infer a boolean property from the underlying properties, throwing an exception if
* it is not defined.
* Apart from the values "true"and "false", a value "auto" is permitted;
* it will resolve to "true" in server mode and to "false" in non-server mode.
* @param property the property requested
* @return the boolean property value
* @throws NoSuchPropertyException if the property is not defined.
*/
public static boolean needAutoBoolean(String property)
throws NoSuchPropertyException
{
String value = p.getProperty(property);
if (value == null)
throw new NoSuchPropertyException("Missing property `" + property + "' in configuration files");
if (value.equals("auto")) {
return ((needProperty("server").compareTo("commandline")==0) ? false:true);
} else {
return needBoolean(property);
}
}
/**
* Get an integer property from the underlying properties, throwing an exception if
* it is not defined.
* @param property the property requested
* @return the integer property value
* @throws NoSuchPropertyException if the property is not defined.
*/
public static int needInteger(String property) throws NoSuchPropertyException
{
String value = p.getProperty(property);
if (value == null)
throw new NoSuchPropertyException("Missing property `" + property + "' in configuration files");
try {
int i = Integer.decode(value).intValue();
return i;
} catch (NumberFormatException e) {
throw new NoSuchPropertyException("Integer property `" + property + "' in configuration files has wrong value `" + value + "'");
}
}
/**
* Get a filename property from the underlying properties, throwing an exception if
* it is not defined. The string MARY_BASE is
* replaced with the value of the property mary.base, and path separators are adapted
* to the current platform.
* @param property the property requested
* @return the filename corresponding to the property value
* @throws NoSuchPropertyException if the property is not defined or the value is not a valid filename
*/
public static String needFilename(String property) throws NoSuchPropertyException
{
String filename = expandPath(needProperty(property));
if (!new File(filename).canRead()) {
throw new NoSuchPropertyException("Cannot read file `" + filename +
"'. Check property `" + property +
"' in configuration files");
}
return filename;
}
/**
* Get a Class property from the underlying properties, throwing an exception if
* it is not defined.
* @param property the property requested
* @return the Class corresponding to the property value
* @throws NoSuchPropertyException if the property is not defined or the value is not a valid class
*/
public static Class needClass(String property)
throws NoSuchPropertyException
{
String value = needProperty(property);
Class c = null;
try {
c = Class.forName(value);
} catch (ClassNotFoundException e) {
throw new NoSuchPropertyException("Cannot find class `" + value +
"'. Check property `" + property +
"' in configuration files");
}
return c;
}
/**
* Provide the config file prefix used for different locales in the
* config files. Will return "german" for Locale.GERMAN, "english" for
* Locale.US and Locale.ENGLISH, and "tibetan" for Locale("tib").
* For all other locales, return the string representation of the locale
* as produced by locale.toString(), e.g. "en_UK";
* if locale is null, return null.
* @param locale
* @return
*/
public static String localePrefix(Locale locale)
{
if (locale == null) return null;
if (locale2prefix.containsKey(locale)) {
return locale2prefix.get(locale);
}
for (Locale l : locale2prefix.keySet()) {
if (MaryUtils.subsumes(l, locale)) {
return locale2prefix.get(l);
}
}
return locale.toString();
}
}
| true | true | public static void readProperties()
throws Exception {
// Throws all sorts of exceptions, each of them should lead to
// a program halt: We cannot start up properly.
if (p != null) // we have done this already
return;
File confDir = new File(maryBase()+"/conf");
if (!confDir.exists()) {
throw new FileNotFoundException("Configuration directory not found: "+ confDir.getPath());
}
File[] configFiles = confDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".config");
}
});
assert configFiles != null;
if (configFiles.length == 0) {
throw new FileNotFoundException("No configuration files found in directory: "+ confDir.getPath());
}
List<Properties> allConfigs = readConfigFiles(configFiles);
boolean allThere = checkDependencies(allConfigs);
if (!allThere) System.exit(1);
// Add properties from individual config files to global properties:
// Global mary properties
p = new Properties();
for (Properties oneP : allConfigs) {
for (Iterator keyIt=oneP.keySet().iterator(); keyIt.hasNext(); ) {
String key = (String) keyIt.next();
// Ignore dependency-related properties:
if (key.equals("name") || key.equals("provides") || key.startsWith("requires")) {
continue;
}
String value = oneP.getProperty(key);
// Properties with keys ending in ".list" are to be appended in global properties.
if (key.endsWith(".list")) {
String prevValue = p.getProperty(key);
if (prevValue != null) {
value = prevValue + " " + value;
}
}
p.setProperty(key, value);
}
}
// Overwrite settings from config files with those set on the
// command line (System properties):
p.putAll(System.getProperties());
// Reciprocally, put all settings in p into the system properties
// (to allow for non-Mary config settings, e.g. for tritonus).
// If one day we find this to be too unflexible, we can also
// identify a subset of properties to put into the System properties,
// e.g. by prepending them with a "system." prefix. For now, this seems
// unnecessary.
System.getProperties().putAll(p);
// OK, now the individual settings
// If necessary, derive shprot.base from mary.base:
if (getProperty("shprot.base") == null) {
p.setProperty("shprot.base", maryBase + File.separator + "lib" +
File.separator + "modules" + File.separator + "shprot");
System.setProperty("shprot.base", getProperty("shprot.base"));
}
String helperString;
StringTokenizer st;
Set<String> ignoreModuleClasses = new HashSet<String>();
helperString = getProperty("ignore.modules.classes.list");
if (helperString != null) {
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, ", \t\n\r\f");
while (st.hasMoreTokens()) {
ignoreModuleClasses.add(st.nextToken());
}
}
helperString = needProperty("modules.classes.list");
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, " \t\n\r\f");
while (st.hasMoreTokens()) {
String className = st.nextToken();
if (!ignoreModuleClasses.contains(className))
moduleInitInfo.add(className);
}
helperString = needProperty("synthesizers.classes.list");
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, " \t\n\r\f");
while (st.hasMoreTokens()) {
synthClasses.add(st.nextToken());
}
String audioEffectClassName, audioEffectName, audioEffectParam, audioEffectSampleParam, audioEffectHelpText;
helperString = getProperty("audioeffects.classes.list");
if (helperString!=null)
{
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, " \t\n\r\f");
while (st.hasMoreTokens()) {
audioEffectClassName = st.nextToken();
audioEffectClasses.add(audioEffectClassName);
BaseAudioEffect ae = null;
try {
ae = (BaseAudioEffect)Class.forName(audioEffectClassName).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ae.setParams(ae.getExampleParameters());
audioEffectName = ae.getName();
audioEffectNames.add(audioEffectName);
audioEffectSampleParam = ae.getExampleParameters();
audioEffectSampleParams.add(audioEffectSampleParam);
audioEffectHelpText = ae.getHelpText();
audioEffectHelpTexts.add(audioEffectHelpText);
}
}
helperString = getProperty("schema.local");
if (helperString!=null)
{
st = new StringTokenizer(helperString);
Vector<File> v = new Vector<File>();
while (st.hasMoreTokens()) {
String schemaFilename = expandPath(st.nextToken());
File schemaFile = new File(schemaFilename);
if (!schemaFile.canRead())
throw new Exception("Cannot read Schema file: " + schemaFilename);
v.add(schemaFile);
}
localSchemas = v.toArray();
}
// Setup locale translation table:
locale2prefix.put(Locale.ENGLISH, "english");
locale2prefix.put(Locale.GERMAN, "german");
locale2prefix.put(new Locale("tib"), "tibetan");
}
| public static void readProperties()
throws Exception {
// Throws all sorts of exceptions, each of them should lead to
// a program halt: We cannot start up properly.
if (p != null) // we have done this already
return;
File confDir = new File(maryBase()+"/conf");
if (!confDir.exists()) {
throw new FileNotFoundException("Configuration directory not found: "+ confDir.getPath());
}
File[] configFiles = confDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".config");
}
});
assert configFiles != null;
if (configFiles.length == 0) {
throw new FileNotFoundException("No configuration files found in directory: "+ confDir.getPath());
}
List<Properties> allConfigs = readConfigFiles(configFiles);
boolean allThere = checkDependencies(allConfigs);
if (!allThere) System.exit(1);
// Add properties from individual config files to global properties:
// Global mary properties
p = new Properties();
for (Properties oneP : allConfigs) {
for (Iterator keyIt=oneP.keySet().iterator(); keyIt.hasNext(); ) {
String key = (String) keyIt.next();
// Ignore dependency-related properties:
if (key.equals("name") || key.equals("provides") || key.startsWith("requires")) {
continue;
}
String value = oneP.getProperty(key);
// Properties with keys ending in ".list" are to be appended in global properties.
if (key.endsWith(".list")) {
String prevValue = p.getProperty(key);
if (prevValue != null) {
value = prevValue + " " + value;
}
}
p.setProperty(key, value);
}
}
// Overwrite settings from config files with those set on the
// command line (System properties):
p.putAll(System.getProperties());
// Reciprocally, put all settings in p into the system properties
// (to allow for non-Mary config settings, e.g. for tritonus).
// If one day we find this to be too unflexible, we can also
// identify a subset of properties to put into the System properties,
// e.g. by prepending them with a "system." prefix. For now, this seems
// unnecessary.
System.getProperties().putAll(p);
// OK, now the individual settings
// If necessary, derive shprot.base from mary.base:
if (getProperty("shprot.base") == null) {
p.setProperty("shprot.base", maryBase + File.separator + "lib" +
File.separator + "modules" + File.separator + "shprot");
System.setProperty("shprot.base", getProperty("shprot.base"));
}
String helperString;
StringTokenizer st;
Set<String> ignoreModuleClasses = new HashSet<String>();
helperString = getProperty("ignore.modules.classes.list");
if (helperString != null) {
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, ", \t\n\r\f");
while (st.hasMoreTokens()) {
ignoreModuleClasses.add(st.nextToken());
}
}
helperString = needProperty("modules.classes.list");
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, " \t\n\r\f");
while (st.hasMoreTokens()) {
String className = st.nextToken();
if (!ignoreModuleClasses.contains(className))
moduleInitInfo.add(className);
}
helperString = needProperty("synthesizers.classes.list");
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, " \t\n\r\f");
while (st.hasMoreTokens()) {
synthClasses.add(st.nextToken());
}
String audioEffectClassName, audioEffectName, audioEffectParam, audioEffectSampleParam, audioEffectHelpText;
helperString = getProperty("audioeffects.classes.list");
if (helperString!=null)
{
// allow whitespace as list delimiters
st = new StringTokenizer(helperString, " \t\n\r\f");
while (st.hasMoreTokens()) {
audioEffectClassName = st.nextToken();
audioEffectClasses.add(audioEffectClassName);
BaseAudioEffect ae = null;
try {
ae = (BaseAudioEffect)Class.forName(audioEffectClassName).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ae.setParams(ae.getExampleParameters());
audioEffectName = ae.getName();
audioEffectNames.add(audioEffectName);
audioEffectSampleParam = ae.getExampleParameters();
audioEffectSampleParams.add(audioEffectSampleParam);
audioEffectHelpText = ae.getHelpText();
audioEffectHelpTexts.add(audioEffectHelpText);
}
}
helperString = getProperty("schema.local");
if (helperString!=null)
{
st = new StringTokenizer(helperString);
Vector<File> v = new Vector<File>();
while (st.hasMoreTokens()) {
String schemaFilename = expandPath(st.nextToken());
File schemaFile = new File(schemaFilename);
if (!schemaFile.canRead())
throw new Exception("Cannot read Schema file: " + schemaFilename);
v.add(schemaFile);
}
localSchemas = v.toArray();
}
// Setup locale translation table:
locale2prefix.put(Locale.US, "english");
locale2prefix.put(Locale.GERMAN, "german");
locale2prefix.put(new Locale("tib"), "tibetan");
}
|
diff --git a/prom6_patches/src-Patches/it/unipi/rupos/processmining/SampleMain.java b/prom6_patches/src-Patches/it/unipi/rupos/processmining/SampleMain.java
index b6e4bb8..4ec242c 100644
--- a/prom6_patches/src-Patches/it/unipi/rupos/processmining/SampleMain.java
+++ b/prom6_patches/src-Patches/it/unipi/rupos/processmining/SampleMain.java
@@ -1,100 +1,100 @@
package it.unipi.rupos.processmining;
import org.processmining.contexts.cli.ProMFactory;
import org.processmining.contexts.cli.ProMManager;
import org.deckfour.xes.model.XLog;
import org.deckfour.xes.model.XTrace;
import org.processmining.plugins.petrinet.replay.ReplayAction;
import org.processmining.plugins.petrinet.replayfitness.ReplayFitnessSetting;
import org.processmining.plugins.petrinet.replayfitness.TotalFitnessResult;
import org.processmining.plugins.petrinet.replayfitness.TotalPerformanceResult;
import org.processmining.plugins.petrinet.replayfitness.PerformanceVisualJS;
import org.processmining.plugins.petrinet.replayfitness.PNVisualizzeJS;
/**
* @author Dipartimento di Informatica - Rupos
*
*/
public class SampleMain {
public static void main(String [] args) throws Exception {
//String logFile = "../prom5_log_files/TracceRupos.mxml";
//String netFile = "../prom5_log_files/TracceRuposAlpha.pnml";
//String logFile = "../prom5_log_files/InviaFlusso.mxml";
//String netFile = "../prom5_log_files/InviaFlussoWoped.pnml";
//String logFile = "../prom5_log_files/InviaFlusso.mxml";
//String netFile = "../prom5_log_files/InviaFlussoWoped.pnml";
//String logFile = "../prom5_log_files/provepar.mxml";
//String netFile = "../prom5_log_files/provepar3xProm6.pnml";
- //String logFile = "../prom5_log_files/recursionprove3.mxml";
+ String logFile = "../prom5_log_files/recursionprove3.mxml";
String netFile = "../prom5_log_files/ReteAdHocRicorsionePerformacexProm6.pnml";
- String netFile = "../prom5_log_files/ReteAdHocRicorsionePerformace3xProm6.pnml";
+ //String netFile = "../prom5_log_files/ReteAdHocRicorsionePerformace3xProm6.pnml";
//String logFile = "../prom5_log_files/sequence.mxml";
//String netFile = "../prom5_log_files/seqAlphahiddenx6.pnml";
//String logFile = "../prom5_log_files/sequence.mxml";
//String netFile = "../prom5_log_files/sequence_prom6.pnml";
ProMManager manager = new ProMFactory().createManager();
PetriNetEngine engine = manager.createPetriNetEngine(netFile);
System.out.println(engine);
engine = manager.createPetriNetEngine(netFile);
System.out.println(engine);
XLog log = manager.openLog(logFile);
System.out.println("Log size: " + log.size());
ReplayFitnessSetting settings = engine.suggestSettings(log);
System.out.println("Settings: " + settings);
settings.setAction(ReplayAction.INSERT_ENABLED_MATCH, true);
settings.setAction(ReplayAction.INSERT_ENABLED_INVISIBLE, true);
settings.setAction(ReplayAction.REMOVE_HEAD, false);
settings.setAction(ReplayAction.INSERT_ENABLED_MISMATCH, false);
settings.setAction(ReplayAction.INSERT_DISABLED_MATCH, false);
settings.setAction(ReplayAction.INSERT_DISABLED_MISMATCH, false);
long startFitness = System.currentTimeMillis();
TotalFitnessResult fitness = engine.getFitness(log, settings);
// System.out.println("Fitness: " + fitness);
long endFitness = System.currentTimeMillis();
//visualizza i dati di conformance con nella pagina html
PNVisualizzeJS js = new PNVisualizzeJS();
js.generateJS("../javascrips/conformance.html", engine.net, fitness);
System.out.println("Fitness for a single TRACE");
long startFitness2 = System.currentTimeMillis();
fitness = engine.getFitness(log.get(0), settings);
System.out.println("Fitness: " + fitness);
long endFitness2 = System.currentTimeMillis();
System.out.println("Time fitness single call " + (endFitness - startFitness));
System.out.println("Time fitness multiple calls " + (endFitness2 - startFitness2));
long startPerformance= System.currentTimeMillis();
// TotalPerformanceResult performance = engine.getPerformance(log, settings);
// System.out.println(performance);
long endPerformance = System.currentTimeMillis();
long startPerformance2 = System.currentTimeMillis();
TotalPerformanceResult performance = engine.getPerformance(log.get(4), settings);
System.out.println("Fitness: " + performance);
long endPerformance2 = System.currentTimeMillis();
PerformanceVisualJS js2 = new PerformanceVisualJS();
js2.generateJS("../javascrips/Performance.html", engine.net, performance.getList().get(0));
System.out.println("Time Performance single call " + (endPerformance - startPerformance));
System.out.println("Time Performance multiple calls " + (endPerformance2 - startPerformance2));
manager.closeContext();
}
}
| false | true | public static void main(String [] args) throws Exception {
//String logFile = "../prom5_log_files/TracceRupos.mxml";
//String netFile = "../prom5_log_files/TracceRuposAlpha.pnml";
//String logFile = "../prom5_log_files/InviaFlusso.mxml";
//String netFile = "../prom5_log_files/InviaFlussoWoped.pnml";
//String logFile = "../prom5_log_files/InviaFlusso.mxml";
//String netFile = "../prom5_log_files/InviaFlussoWoped.pnml";
//String logFile = "../prom5_log_files/provepar.mxml";
//String netFile = "../prom5_log_files/provepar3xProm6.pnml";
//String logFile = "../prom5_log_files/recursionprove3.mxml";
String netFile = "../prom5_log_files/ReteAdHocRicorsionePerformacexProm6.pnml";
String netFile = "../prom5_log_files/ReteAdHocRicorsionePerformace3xProm6.pnml";
//String logFile = "../prom5_log_files/sequence.mxml";
//String netFile = "../prom5_log_files/seqAlphahiddenx6.pnml";
//String logFile = "../prom5_log_files/sequence.mxml";
//String netFile = "../prom5_log_files/sequence_prom6.pnml";
ProMManager manager = new ProMFactory().createManager();
PetriNetEngine engine = manager.createPetriNetEngine(netFile);
System.out.println(engine);
engine = manager.createPetriNetEngine(netFile);
System.out.println(engine);
XLog log = manager.openLog(logFile);
System.out.println("Log size: " + log.size());
ReplayFitnessSetting settings = engine.suggestSettings(log);
System.out.println("Settings: " + settings);
settings.setAction(ReplayAction.INSERT_ENABLED_MATCH, true);
settings.setAction(ReplayAction.INSERT_ENABLED_INVISIBLE, true);
settings.setAction(ReplayAction.REMOVE_HEAD, false);
settings.setAction(ReplayAction.INSERT_ENABLED_MISMATCH, false);
settings.setAction(ReplayAction.INSERT_DISABLED_MATCH, false);
settings.setAction(ReplayAction.INSERT_DISABLED_MISMATCH, false);
long startFitness = System.currentTimeMillis();
TotalFitnessResult fitness = engine.getFitness(log, settings);
// System.out.println("Fitness: " + fitness);
long endFitness = System.currentTimeMillis();
//visualizza i dati di conformance con nella pagina html
PNVisualizzeJS js = new PNVisualizzeJS();
js.generateJS("../javascrips/conformance.html", engine.net, fitness);
System.out.println("Fitness for a single TRACE");
long startFitness2 = System.currentTimeMillis();
fitness = engine.getFitness(log.get(0), settings);
System.out.println("Fitness: " + fitness);
long endFitness2 = System.currentTimeMillis();
System.out.println("Time fitness single call " + (endFitness - startFitness));
System.out.println("Time fitness multiple calls " + (endFitness2 - startFitness2));
long startPerformance= System.currentTimeMillis();
// TotalPerformanceResult performance = engine.getPerformance(log, settings);
// System.out.println(performance);
long endPerformance = System.currentTimeMillis();
long startPerformance2 = System.currentTimeMillis();
TotalPerformanceResult performance = engine.getPerformance(log.get(4), settings);
System.out.println("Fitness: " + performance);
long endPerformance2 = System.currentTimeMillis();
PerformanceVisualJS js2 = new PerformanceVisualJS();
js2.generateJS("../javascrips/Performance.html", engine.net, performance.getList().get(0));
System.out.println("Time Performance single call " + (endPerformance - startPerformance));
System.out.println("Time Performance multiple calls " + (endPerformance2 - startPerformance2));
manager.closeContext();
}
| public static void main(String [] args) throws Exception {
//String logFile = "../prom5_log_files/TracceRupos.mxml";
//String netFile = "../prom5_log_files/TracceRuposAlpha.pnml";
//String logFile = "../prom5_log_files/InviaFlusso.mxml";
//String netFile = "../prom5_log_files/InviaFlussoWoped.pnml";
//String logFile = "../prom5_log_files/InviaFlusso.mxml";
//String netFile = "../prom5_log_files/InviaFlussoWoped.pnml";
//String logFile = "../prom5_log_files/provepar.mxml";
//String netFile = "../prom5_log_files/provepar3xProm6.pnml";
String logFile = "../prom5_log_files/recursionprove3.mxml";
String netFile = "../prom5_log_files/ReteAdHocRicorsionePerformacexProm6.pnml";
//String netFile = "../prom5_log_files/ReteAdHocRicorsionePerformace3xProm6.pnml";
//String logFile = "../prom5_log_files/sequence.mxml";
//String netFile = "../prom5_log_files/seqAlphahiddenx6.pnml";
//String logFile = "../prom5_log_files/sequence.mxml";
//String netFile = "../prom5_log_files/sequence_prom6.pnml";
ProMManager manager = new ProMFactory().createManager();
PetriNetEngine engine = manager.createPetriNetEngine(netFile);
System.out.println(engine);
engine = manager.createPetriNetEngine(netFile);
System.out.println(engine);
XLog log = manager.openLog(logFile);
System.out.println("Log size: " + log.size());
ReplayFitnessSetting settings = engine.suggestSettings(log);
System.out.println("Settings: " + settings);
settings.setAction(ReplayAction.INSERT_ENABLED_MATCH, true);
settings.setAction(ReplayAction.INSERT_ENABLED_INVISIBLE, true);
settings.setAction(ReplayAction.REMOVE_HEAD, false);
settings.setAction(ReplayAction.INSERT_ENABLED_MISMATCH, false);
settings.setAction(ReplayAction.INSERT_DISABLED_MATCH, false);
settings.setAction(ReplayAction.INSERT_DISABLED_MISMATCH, false);
long startFitness = System.currentTimeMillis();
TotalFitnessResult fitness = engine.getFitness(log, settings);
// System.out.println("Fitness: " + fitness);
long endFitness = System.currentTimeMillis();
//visualizza i dati di conformance con nella pagina html
PNVisualizzeJS js = new PNVisualizzeJS();
js.generateJS("../javascrips/conformance.html", engine.net, fitness);
System.out.println("Fitness for a single TRACE");
long startFitness2 = System.currentTimeMillis();
fitness = engine.getFitness(log.get(0), settings);
System.out.println("Fitness: " + fitness);
long endFitness2 = System.currentTimeMillis();
System.out.println("Time fitness single call " + (endFitness - startFitness));
System.out.println("Time fitness multiple calls " + (endFitness2 - startFitness2));
long startPerformance= System.currentTimeMillis();
// TotalPerformanceResult performance = engine.getPerformance(log, settings);
// System.out.println(performance);
long endPerformance = System.currentTimeMillis();
long startPerformance2 = System.currentTimeMillis();
TotalPerformanceResult performance = engine.getPerformance(log.get(4), settings);
System.out.println("Fitness: " + performance);
long endPerformance2 = System.currentTimeMillis();
PerformanceVisualJS js2 = new PerformanceVisualJS();
js2.generateJS("../javascrips/Performance.html", engine.net, performance.getList().get(0));
System.out.println("Time Performance single call " + (endPerformance - startPerformance));
System.out.println("Time Performance multiple calls " + (endPerformance2 - startPerformance2));
manager.closeContext();
}
|
diff --git a/loci/plugins/browser/LociDataBrowser.java b/loci/plugins/browser/LociDataBrowser.java
index 8aacfdd05..f2cd022fb 100644
--- a/loci/plugins/browser/LociDataBrowser.java
+++ b/loci/plugins/browser/LociDataBrowser.java
@@ -1,316 +1,317 @@
//
// LociDataBrowser.java
//
/*
LOCI 4D Data Browser plugin for quick browsing of 4D datasets in ImageJ.
Copyright (C) 2005-@year@ Christopher Peterson, Francis Wong, Curtis Rueden
and Melissa Linkert.
This program 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 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 Library General Public License for more details.
You should have received a copy of the GNU Library 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 loci.plugins.browser;
import ij.*;
import ij.gui.GenericDialog;
import ij.gui.ImageCanvas;
import ij.io.FileInfo;
import loci.formats.*;
/**
* LociDataBrowser is a plugin for ImageJ that allows for browsing of 4D
* image data (stacks of image planes over time) with two-channel support.
*
* @author Francis Wong yutaiwong at wisc.edu
* @author Curtis Rueden ctrueden at wisc.edu
* @author Melissa Linkert linkert at cs.wisc.edu
*/
public class LociDataBrowser {
// -- Constants --
/** Debugging flag. */
protected static final boolean DEBUG = false;
// -- Fields --
/** Filename for each index. */
protected String[] names;
/** The file format reader used by the plugin. */
protected IFormatReader reader;
/** The file stitcher used by the reader.*/
protected FileStitcher fStitch;
/** The CustomWindow used to display data.*/
protected CustomWindow cw;
/** The current file name. */
protected String id;
/** Whether dataset has multiple Z, T and C positions. */
protected boolean hasZ, hasT, hasC;
/** Number of Z, T and C positions. */
protected int numZ, numT, numC;
/** Lengths of all dimensional axes; lengths[0] equals image depth. */
protected int[] lengths;
/** Indices into lengths array for Z, T and C. */
protected int zIndex, tIndex, cIndex;
/** Whether stack is accessed from disk as needed. */
protected boolean virtual;
/** Cache manager (if virtual stack is used). */
protected CacheManager manager;
/** Series to use in a multi-series file. */
protected int series;
private ImageStack stack;
// -- Constructor --
/** Constructs a new data browser. */
public LociDataBrowser() {
fStitch = new FileStitcher();
reader = new ChannelSeparator(fStitch);
}
// -- LociDataBrowser API methods --
/** Displays the given ImageJ image in a 4D browser window. */
public void show(ImagePlus imp) {
int stackSize = imp == null ? 0 : imp.getStackSize();
if (stackSize == 0) {
IJ.showMessage("Cannot show invalid image.");
return;
}
if (stackSize == 1 && !virtual) {
// show single image normally
imp.show();
return;
}
cw = new CustomWindow(this, imp, new ImageCanvas(imp));
}
/** Set the length of each dimensional axis and the dimension order. */
public void setDimensions(int sizeZ, int sizeC, int sizeT, int z,
int c, int t)
{
numZ = sizeZ;
numC = sizeC;
numT = sizeT;
hasZ = numZ > 1;
hasC = numC > 1;
hasT = numT > 1;
lengths = new int[3];
lengths[z] = numZ;
lengths[c] = numC;
lengths[t] = numT;
zIndex = z;
cIndex = c;
tIndex = t;
}
/** Reset all dimensional data in case they've switched.*/
public void setDimensions() {
String order = null;
try {
numZ = fStitch.getSizeZ(id);
numC = fStitch.getSizeC(id);
numT = fStitch.getSizeT(id);
order = fStitch.getDimensionOrder(id);
}
catch (Exception exc) {
if (DEBUG) exc.printStackTrace();
return;
}
hasZ = numZ > 1;
hasC = numC > 1;
hasT = numT > 1;
zIndex = order.indexOf("Z") - 2;
cIndex = order.indexOf("C") - 2;
tIndex = order.indexOf("T") - 2;
lengths[zIndex] = numZ;
lengths[tIndex] = numT;
lengths[cIndex] = numC;
}
/** Gets the slice number for the given Z, T and C indices. */
public int getIndex(int z, int t, int c) {
int result = -1;
synchronized(reader) {
try {
result = reader.getIndex(id,z,c,t);
}
catch (Exception exc) {if (DEBUG) exc.printStackTrace();}
}
return result;
}
/** Sets the series to open. */
public void setSeries(int num) {
// TODO : this isn't the prettiest way of prompting for a series
GenericDialog datasets =
new GenericDialog("4D Data Browser Series Chooser");
String[] values = new String[num];
for (int i=0; i<values.length; i++) values[i] = "" + i;
datasets.addChoice("Series ", values, "0");
if (num > 1) datasets.showDialog();
series = Integer.parseInt(datasets.getNextChoice());
}
public void run(String arg) {
LociOpener lociOpener = new LociOpener();
boolean done2 = false;
String directory = "";
String name = "";
boolean quiet = false;
// get file name and virtual stack option
stack = null;
while (!done2) {
try {
lociOpener.show();
directory = lociOpener.getDirectory();
name = lociOpener.getAbsolutePath();
virtual = lociOpener.getVirtual();
if (name == null || lociOpener.isCanceled()) return;
if (DEBUG) {
IJ.log("directory = " + directory);
IJ.log("name = " + name);
IJ.log("virtual = " + virtual);
}
ImagePlusWrapper ipw = null;
// process input
lengths = new int[3];
id = name;
if (DEBUG) System.err.println("id = " + id);
if (virtual) {
OMEXMLMetadataStore store = new OMEXMLMetadataStore();
synchronized (reader) {
reader.setMetadataStore(store);
store.createRoot();
reader.setSeries(id, series);
int num = reader.getImageCount(id);
manager = new CacheManager(0, 0, 0, 0, 0, 0, 20, 0, 0,
this, id, CacheManager.T_AXIS,
CacheManager.CROSS_MODE, CacheManager.FORWARD_FIRST);
try {
setDimensions();
// CTR: stack must not be null
int sizeX = reader.getSizeX(id);
int sizeY = reader.getSizeY(id);
stack = new ImageStack(sizeX, sizeY);
// CTR: must add at least one image to the stack
stack.addSlice(id + " : 1", manager.getSlice(0, 0, 0));
}
catch (OutOfMemoryError e) {
IJ.outOfMemory("LociDataBrowser");
if (stack != null) stack.trim();
}
}
if (stack == null || stack.getSize() == 0) {
IJ.error("Sorry, there was a problem creating the image stack.");
return;
}
ImagePlus imp = new ImagePlus(id, stack);
FileInfo fi = new FileInfo();
try {
fi.description = store.dumpXML();
}
catch (Exception exc) { exc.printStackTrace(); }
imp.setFileInfo(fi);
show(imp);
}
else {
ipw = new ImagePlusWrapper(id, reader, fStitch, true);
setDimensions();
- if (ipw.getImagePlus().getStackSize() != numZ * numT * numC) {
- System.err.println("Error, stack size mismatch with dimension
- sizes! StackSize = " + ipw.getImagePlus().getStackSize() +
- " numZ = " + numZ + " numT = " + numt + " numC = " + numC);
+ int stackSize = ipw.getImagePlus().getStackSize();
+ if (stackSize != numZ * numT * numC) {
+ System.err.println("Error, stack size mismatch with dimension " +
+ "sizes: stackSize=" + stackSize + ", numZ=" + numZ +
+ ", numT=" + numT + ", numC=" + numC);
}
FileInfo fi = ipw.getImagePlus().getOriginalFileInfo();
if (fi == null) fi = new FileInfo();
try {
fi.description = ((OMEXMLMetadataStore) ipw.store).dumpXML();
}
catch (Exception e) { }
ipw.getImagePlus().setFileInfo(fi);
show(ipw.getImagePlus());
}
done2 = true;
}
catch (Exception exc) {
exc.printStackTrace();
IJ.showStatus("");
if (!quiet) {
String msg = exc.getMessage();
IJ.showMessage("LOCI Bio-Formats", "Sorry, there was a problem " +
"reading the data" + (msg == null ? "." : (": " + msg)));
}
if (DEBUG) System.err.println("Read error");
done2 = false;
}
}
}
// -- Main method --
/** Main method, for testing. */
public static void main(String[] args) {
new ImageJ(null);
StringBuffer sb = new StringBuffer();
for (int i=0; i<args.length; i++) {
if (i > 0) sb.append(" ");
sb.append(args[i]);
}
new LociDataBrowser().run(sb.toString());
}
}
| true | true | public void run(String arg) {
LociOpener lociOpener = new LociOpener();
boolean done2 = false;
String directory = "";
String name = "";
boolean quiet = false;
// get file name and virtual stack option
stack = null;
while (!done2) {
try {
lociOpener.show();
directory = lociOpener.getDirectory();
name = lociOpener.getAbsolutePath();
virtual = lociOpener.getVirtual();
if (name == null || lociOpener.isCanceled()) return;
if (DEBUG) {
IJ.log("directory = " + directory);
IJ.log("name = " + name);
IJ.log("virtual = " + virtual);
}
ImagePlusWrapper ipw = null;
// process input
lengths = new int[3];
id = name;
if (DEBUG) System.err.println("id = " + id);
if (virtual) {
OMEXMLMetadataStore store = new OMEXMLMetadataStore();
synchronized (reader) {
reader.setMetadataStore(store);
store.createRoot();
reader.setSeries(id, series);
int num = reader.getImageCount(id);
manager = new CacheManager(0, 0, 0, 0, 0, 0, 20, 0, 0,
this, id, CacheManager.T_AXIS,
CacheManager.CROSS_MODE, CacheManager.FORWARD_FIRST);
try {
setDimensions();
// CTR: stack must not be null
int sizeX = reader.getSizeX(id);
int sizeY = reader.getSizeY(id);
stack = new ImageStack(sizeX, sizeY);
// CTR: must add at least one image to the stack
stack.addSlice(id + " : 1", manager.getSlice(0, 0, 0));
}
catch (OutOfMemoryError e) {
IJ.outOfMemory("LociDataBrowser");
if (stack != null) stack.trim();
}
}
if (stack == null || stack.getSize() == 0) {
IJ.error("Sorry, there was a problem creating the image stack.");
return;
}
ImagePlus imp = new ImagePlus(id, stack);
FileInfo fi = new FileInfo();
try {
fi.description = store.dumpXML();
}
catch (Exception exc) { exc.printStackTrace(); }
imp.setFileInfo(fi);
show(imp);
}
else {
ipw = new ImagePlusWrapper(id, reader, fStitch, true);
setDimensions();
if (ipw.getImagePlus().getStackSize() != numZ * numT * numC) {
System.err.println("Error, stack size mismatch with dimension
sizes! StackSize = " + ipw.getImagePlus().getStackSize() +
" numZ = " + numZ + " numT = " + numt + " numC = " + numC);
}
FileInfo fi = ipw.getImagePlus().getOriginalFileInfo();
if (fi == null) fi = new FileInfo();
try {
fi.description = ((OMEXMLMetadataStore) ipw.store).dumpXML();
}
catch (Exception e) { }
ipw.getImagePlus().setFileInfo(fi);
show(ipw.getImagePlus());
}
done2 = true;
}
catch (Exception exc) {
exc.printStackTrace();
IJ.showStatus("");
if (!quiet) {
String msg = exc.getMessage();
IJ.showMessage("LOCI Bio-Formats", "Sorry, there was a problem " +
"reading the data" + (msg == null ? "." : (": " + msg)));
}
if (DEBUG) System.err.println("Read error");
done2 = false;
}
}
}
| public void run(String arg) {
LociOpener lociOpener = new LociOpener();
boolean done2 = false;
String directory = "";
String name = "";
boolean quiet = false;
// get file name and virtual stack option
stack = null;
while (!done2) {
try {
lociOpener.show();
directory = lociOpener.getDirectory();
name = lociOpener.getAbsolutePath();
virtual = lociOpener.getVirtual();
if (name == null || lociOpener.isCanceled()) return;
if (DEBUG) {
IJ.log("directory = " + directory);
IJ.log("name = " + name);
IJ.log("virtual = " + virtual);
}
ImagePlusWrapper ipw = null;
// process input
lengths = new int[3];
id = name;
if (DEBUG) System.err.println("id = " + id);
if (virtual) {
OMEXMLMetadataStore store = new OMEXMLMetadataStore();
synchronized (reader) {
reader.setMetadataStore(store);
store.createRoot();
reader.setSeries(id, series);
int num = reader.getImageCount(id);
manager = new CacheManager(0, 0, 0, 0, 0, 0, 20, 0, 0,
this, id, CacheManager.T_AXIS,
CacheManager.CROSS_MODE, CacheManager.FORWARD_FIRST);
try {
setDimensions();
// CTR: stack must not be null
int sizeX = reader.getSizeX(id);
int sizeY = reader.getSizeY(id);
stack = new ImageStack(sizeX, sizeY);
// CTR: must add at least one image to the stack
stack.addSlice(id + " : 1", manager.getSlice(0, 0, 0));
}
catch (OutOfMemoryError e) {
IJ.outOfMemory("LociDataBrowser");
if (stack != null) stack.trim();
}
}
if (stack == null || stack.getSize() == 0) {
IJ.error("Sorry, there was a problem creating the image stack.");
return;
}
ImagePlus imp = new ImagePlus(id, stack);
FileInfo fi = new FileInfo();
try {
fi.description = store.dumpXML();
}
catch (Exception exc) { exc.printStackTrace(); }
imp.setFileInfo(fi);
show(imp);
}
else {
ipw = new ImagePlusWrapper(id, reader, fStitch, true);
setDimensions();
int stackSize = ipw.getImagePlus().getStackSize();
if (stackSize != numZ * numT * numC) {
System.err.println("Error, stack size mismatch with dimension " +
"sizes: stackSize=" + stackSize + ", numZ=" + numZ +
", numT=" + numT + ", numC=" + numC);
}
FileInfo fi = ipw.getImagePlus().getOriginalFileInfo();
if (fi == null) fi = new FileInfo();
try {
fi.description = ((OMEXMLMetadataStore) ipw.store).dumpXML();
}
catch (Exception e) { }
ipw.getImagePlus().setFileInfo(fi);
show(ipw.getImagePlus());
}
done2 = true;
}
catch (Exception exc) {
exc.printStackTrace();
IJ.showStatus("");
if (!quiet) {
String msg = exc.getMessage();
IJ.showMessage("LOCI Bio-Formats", "Sorry, there was a problem " +
"reading the data" + (msg == null ? "." : (": " + msg)));
}
if (DEBUG) System.err.println("Read error");
done2 = false;
}
}
}
|
diff --git a/plugins/SPIMAcquisition/spim/SPIMAcquisition.java b/plugins/SPIMAcquisition/spim/SPIMAcquisition.java
index 875db7e17..74ad9b535 100644
--- a/plugins/SPIMAcquisition/spim/SPIMAcquisition.java
+++ b/plugins/SPIMAcquisition/spim/SPIMAcquisition.java
@@ -1,870 +1,870 @@
package spim;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.gui.GenericDialog;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import mmcorej.CMMCore;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
public class SPIMAcquisition implements MMPlugin {
// TODO: read these from the properties
protected int motorMin = 1, motorMax = 8000,
twisterMin = -180, twisterMax = 180;
protected ScriptInterface app;
protected CMMCore mmc;
protected MMStudioMainFrame gui;
protected String xyStageLabel, zStageLabel, twisterLabel,
laserLabel, cameraLabel;
protected JFrame frame;
protected IntegerField xPosition, yPosition, zPosition, rotation,
zFrom, zTo, stepsPerRotation, degreesPerStep,
laserPower, exposure, settleTime;
protected MotorSlider xSlider, ySlider, zSlider, rotationSlider,
laserSlider, exposureSlider;
protected JCheckBox liveCheckbox, registrationCheckbox,
multipleAngleCheckbox, continuousCheckbox;
protected JButton speedControl, ohSnap;
protected boolean updateLiveImage, zStageHasVelocity;
// MMPlugin stuff
/**
* The menu name is stored in a static string, so Micro-Manager
* can obtain it without instantiating the plugin
*/
public static String menuName = "Acquire SPIM image";
/**
* The main app calls this method to remove the module window
*/
@Override
public void dispose() {
if (frame == null)
return;
frame.dispose();
frame = null;
runToX.interrupt();
runToY.interrupt();
runToZ.interrupt();
runToAngle.interrupt();
}
/**
* The main app passes its ScriptInterface to the module. This
* method is typically called after the module is instantiated.
* @param app - ScriptInterface implementation
*/
@Override
public void setApp(ScriptInterface app) {
this.app = app;
mmc = app.getMMCore();
gui = MMStudioMainFrame.getInstance();
}
/**
* Open the module window
*/
@Override
public void show() {
initUI();
configurationChanged();
frame.setVisible(true);
}
/**
* The main app calls this method when hardware settings change.
* This call signals to the module that it needs to update whatever
* information it needs from the MMCore.
*/
@Override
public void configurationChanged() {
zStageLabel = null;
xyStageLabel = null;
twisterLabel = null;
for (String label : mmc.getLoadedDevices().toArray()) try {
String driver = mmc.getDeviceNameInLibrary(label);
if (driver.equals("Picard Twister"))
twisterLabel = label;
else if (driver.equals("Picard Z Stage")) { // TODO: read this from the to-be-added property
zStageLabel = label;
zStageHasVelocity = mmc.hasProperty(zStageLabel, "Velocity");
}
else if (driver.equals("Picard XY Stage"))
xyStageLabel = label;
// testing
else if (driver.equals("DStage")) {
if (label.equals("DStage"))
zStageLabel = label;
else
twisterLabel = label;
}
else if (driver.equals("DXYStage"))
xyStageLabel = label;
} catch (Exception e) {
IJ.handleException(e);
}
cameraLabel = mmc.getCameraDevice();
updateUI();
}
/**
* Returns a very short (few words) description of the module.
*/
@Override
public String getDescription() {
return "Open Source SPIM acquisition";
}
/**
* Returns verbose information about the module.
* This may even include a short help instructions.
*/
@Override
public String getInfo() {
// TODO: be more verbose
return "See https://wiki.mpi-cbg.de/wiki/spiminabriefcase/";
}
/**
* Returns version string for the module.
* There is no specific required format for the version
*/
@Override
public String getVersion() {
return "0.01";
}
/**
* Returns copyright information
*/
@Override
public String getCopyright() {
return "Copyright Johannes Schindelin (2011)\n"
+ "GPLv2 or later";
}
// UI stuff
protected void initUI() {
if (frame != null)
return;
frame = new JFrame("OpenSPIM");
JPanel left = new JPanel();
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
left.setBorder(BorderFactory.createTitledBorder("Position/Angle"));
xSlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToX.run(value);
maybeUpdateImage();
}
};
ySlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToY.run(value);
maybeUpdateImage();
}
};
zSlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToZ.run(value);
maybeUpdateImage();
}
};
rotationSlider = new MotorSlider(twisterMin, twisterMax, 0) {
@Override
public void valueChanged(int value) {
runToAngle.run(value * 200 / 360);
maybeUpdateImage();
}
};
xPosition = new IntegerSliderField(xSlider);
yPosition = new IntegerSliderField(ySlider);
zPosition = new IntegerSliderField(zSlider);
rotation = new IntegerSliderField(rotationSlider);
zFrom = new IntegerField(1) {
@Override
public void valueChanged(int value) {
if (value < motorMin)
setText("" + motorMin);
else if (value > motorMax)
setText("" + motorMax);
}
};
zTo = new IntegerField(motorMax) {
@Override
public void valueChanged(int value) {
if (value < motorMin)
setText("" + motorMin);
else if (value > motorMax)
setText("" + motorMax);
}
};
stepsPerRotation = new IntegerField(4) {
@Override
public void valueChanged(int value) {
degreesPerStep.setText("" + (360 / value));
}
};
degreesPerStep = new IntegerField(90) {
@Override
public void valueChanged(int value) {
stepsPerRotation.setText("" + (360 / value));
}
};
addLine(left, Justification.LEFT, "x:", xPosition, "y:", yPosition, "z:", zPosition, "angle:", rotation);
addLine(left, Justification.STRETCH, "x:", xSlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", xSlider, 500, 2500));
addLine(left, Justification.STRETCH, "y:", ySlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", ySlider, 500, 2500));
addLine(left, Justification.STRETCH, "z:", zSlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", zSlider, 500, 2500));
addLine(left, Justification.RIGHT, "from z:", zFrom, "to z:", zTo);
addLine(left, Justification.STRETCH, "rotation:", rotationSlider);
addLine(left, Justification.RIGHT, "steps/rotation:", stepsPerRotation, "degrees/step:", degreesPerStep);
JPanel right = new JPanel();
right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
right.setBorder(BorderFactory.createTitledBorder("Acquisition"));
// TODO: find out correct values
laserSlider = new MotorSlider(0, 1000, 1000) {
@Override
public void valueChanged(int value) {
// TODO
}
};
// TODO: find out correct values
exposureSlider = new MotorSlider(10, 1000, 10) {
@Override
public void valueChanged(int value) {
try {
mmc.setExposure(value);
} catch (Exception e) {
IJ.handleException(e);
}
}
};
laserPower = new IntegerSliderField(laserSlider);
exposure = new IntegerSliderField(exposureSlider);
liveCheckbox = new JCheckBox("Update Live View");
- liveCheckbox.setSelected(gui.isLiveModeOn());
- updateLiveImage = true;
+ updateLiveImage = gui.isLiveModeOn();
+ liveCheckbox.setSelected(updateLiveImage);
liveCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
updateLiveImage = e.getStateChange() == ItemEvent.SELECTED;
if (updateLiveImage && !gui.isLiveModeOn())
gui.enableLiveMode(true);
}
});
registrationCheckbox = new JCheckBox("Perform SPIM registration");
registrationCheckbox.setSelected(false);
registrationCheckbox.setEnabled(false);
multipleAngleCheckbox = new JCheckBox("Multiple Rotation Angles");
multipleAngleCheckbox.setSelected(false);
multipleAngleCheckbox.setEnabled(false);
speedControl = new JButton("Set z-stage velocity");
speedControl.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread() {
public void run() {
setZStageVelocity();
}
}.start();
}
});
continuousCheckbox = new JCheckBox("Continuous z motion");
continuousCheckbox.setSelected(false);
continuousCheckbox.setEnabled(true);
settleTime = new IntegerField(0) {
@Override
public void valueChanged(int value) {
degreesPerStep.setText("" + (360 / value));
}
};
ohSnap = new JButton("Oh snap!");
ohSnap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final int zStart = zFrom.getValue();
final int zEnd = zTo.getValue();
final boolean isContinuous = continuousCheckbox.isSelected();
new Thread() {
@Override
public void run() {
try {
ImagePlus image = isContinuous ?
snapContinuousStack(zStart, zEnd) : snapStack(zStart, zEnd, settleTime.getValue());
image.show();
} catch (Exception e) {
IJ.handleException(e);
}
}
}.start();
}
});
addLine(right, Justification.RIGHT, "laser power:", laserPower, "exposure:", exposure);
addLine(right, Justification.STRETCH, "laser:", laserSlider);
addLine(right, Justification.STRETCH, "exposure:", exposureSlider);
addLine(right, Justification.RIGHT, liveCheckbox);
addLine(right, Justification.RIGHT, registrationCheckbox);
addLine(right, Justification.RIGHT, multipleAngleCheckbox);
addLine(right, Justification.RIGHT, speedControl);
//addLine(right, Justification.RIGHT, continuousCheckbox);
addLine(right, Justification.RIGHT, "Delay to let z-stage settle (ms)", settleTime);
addLine(right, Justification.RIGHT, ohSnap);
Container panel = frame.getContentPane();
panel.setLayout(new GridLayout(1, 2));
panel.add(left);
panel.add(right);
frame.pack();
}
protected void updateUI() {
xPosition.setEnabled(xyStageLabel != null);
yPosition.setEnabled(xyStageLabel != null);
zPosition.setEnabled(zStageLabel != null);
rotation.setEnabled(twisterLabel != null);
xSlider.setEnabled(xyStageLabel != null);
ySlider.setEnabled(xyStageLabel != null);
zSlider.setEnabled(zStageLabel != null);
zFrom.setEnabled(zStageLabel != null);
zTo.setEnabled(zStageLabel != null);
rotationSlider.setEnabled(twisterLabel != null);
stepsPerRotation.setEnabled(twisterLabel != null);
degreesPerStep.setEnabled(twisterLabel != null);
laserPower.setEnabled(laserLabel != null);
exposure.setEnabled(cameraLabel != null);
laserSlider.setEnabled(laserLabel != null);
exposureSlider.setEnabled(cameraLabel != null);
liveCheckbox.setEnabled(cameraLabel != null);
speedControl.setEnabled(zStageHasVelocity);
continuousCheckbox.setEnabled(zStageLabel != null && cameraLabel != null);
ohSnap.setEnabled(zStageLabel != null && cameraLabel != null);
if (xyStageLabel != null) try {
int x = (int)mmc.getXPosition(xyStageLabel);
int y = (int)mmc.getYPosition(xyStageLabel);
xPosition.setText("" + x);
yPosition.setText("" + y);
xSlider.setValue(x);
ySlider.setValue(y);
} catch (Exception e) {
IJ.handleException(e);
}
if (zStageLabel != null) try {
int z = (int)mmc.getPosition(zStageLabel);
zPosition.setText("" + z);
zSlider.setValue(z);
} catch (Exception e) {
IJ.handleException(e);
}
if (twisterLabel != null) try {
// TODO: how to handle 200 steps per 360 degrees?
int angle = (int)mmc.getPosition(twisterLabel);
rotation.setText("" + angle);
rotationSlider.setValue(angle);
} catch (Exception e) {
IJ.handleException(e);
}
if (laserLabel != null) try {
// TODO: get current laser power
} catch (Exception e) {
IJ.handleException(e);
}
if (cameraLabel != null) try {
// TODO: get current exposure
} catch (Exception e) {
IJ.handleException(e);
}
}
// UI helpers
protected enum Justification {
LEFT, STRETCH, RIGHT
};
protected static void addLine(Container container, Justification justification, Object... objects) {
JPanel panel = new JPanel();
if (justification == Justification.STRETCH)
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
else
panel.setLayout(new FlowLayout(justification == Justification.LEFT ? FlowLayout.LEADING : FlowLayout.TRAILING));
for (Object object : objects) {
Component component = (object instanceof String) ?
new JLabel((String)object) :
(Component)object;
panel.add(component);
}
container.add(panel);
}
protected static abstract class MotorSlider extends JSlider implements ChangeListener {
protected JTextField updating;
protected Color background;
public MotorSlider(int min, int max, int current) {
super(JSlider.HORIZONTAL, min, max, Math.min(max, Math.max(min, current)));
setMinorTickSpacing((int)((max - min) / 40));
setMajorTickSpacing((int)((max - min) / 5));
setPaintTrack(true);
setPaintTicks(true);
if (min == 1)
setLabelTable(makeLabelTable(min, max, 5));
setPaintLabels(true);
addChangeListener(this);
}
@Override
public void stateChanged(ChangeEvent e) {
final int value = getValue();
if (getValueIsAdjusting()) {
if (updating != null) {
if (background == null)
background = updating.getBackground();
updating.setBackground(Color.YELLOW);
updating.setText("" + value);
}
}
else
new Thread() {
@Override
public void run() {
if (updating != null)
updating.setBackground(background);
valueChanged(value);
}
}.start();
}
public abstract void valueChanged(int value);
}
protected static class LimitedRangeCheckbox extends JPanel implements ItemListener {
protected JTextField min, max;
protected JCheckBox checkbox;
protected MotorSlider slider;
protected Dictionary originalLabels, limitedLabels;
protected int originalMin, originalMax;
protected int limitedMin, limitedMax;
public LimitedRangeCheckbox(String label, MotorSlider slider, int min, int max) {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
checkbox = new JCheckBox(label);
add(checkbox);
this.min = new JTextField("" + min);
add(this.min);
add(new JLabel(" to "));
this.max = new JTextField("" + max);
add(this.max);
this.slider = slider;
originalLabels = slider.getLabelTable();
originalMin = slider.getMinimum();
originalMax = slider.getMaximum();
limitedMin = min;
limitedMax = max;
checkbox.setSelected(false);
checkbox.addItemListener(this);
}
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
limitedMin = getValue(min, limitedMin);
limitedMax = getValue(max, limitedMax);
limitedLabels = makeLabelTable(limitedMin, limitedMax, 5);
int current = slider.getValue();
if (current < limitedMin)
slider.setValue(limitedMin);
else if (current > limitedMax)
slider.setValue(limitedMax);
slider.setMinimum(limitedMin);
slider.setMaximum(limitedMax);
slider.setLabelTable(limitedLabels);
}
else {
slider.setMinimum(originalMin);
slider.setMaximum(originalMax);
slider.setLabelTable(originalLabels);
}
}
protected static int getValue(JTextField text, int defaultValue) {
try {
return Integer.parseInt(text.getText());
} catch (Exception e) {
return defaultValue;
}
}
}
protected static Dictionary makeLabelTable(int min, int max, int count) {
int spacing = (int)((max - min) / count);
spacing = 100 * ((spacing + 50) / 100); // round to nearest 100
Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
table.put(min, new JLabel("" + min));
for (int i = max; i > min; i -= spacing)
table.put(i, new JLabel("" + i));
return table;
}
protected static abstract class IntegerField extends JTextField {
public IntegerField(int value) {
this(value, 4);
}
public IntegerField(int value, int columns) {
super(columns);
setText("" + value);
addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_ENTER)
return;
valueChanged(getValue());
}
});
addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
valueChanged(getValue());
}
});
}
public int getValue() {
String typed = getText();
if(!typed.matches("\\d+"))
return 0;
return Integer.parseInt(typed);
}
public abstract void valueChanged(int value);
}
protected static class IntegerSliderField extends IntegerField {
protected JSlider slider;
public IntegerSliderField(JSlider slider) {
super(slider.getValue());
this.slider = slider;
if (slider instanceof MotorSlider)
((MotorSlider)slider).updating = this;
}
@Override
public void valueChanged(int value) {
if (slider != null)
slider.setValue(value);
}
}
protected void setZStageVelocity() {
try {
String[] allowedValues = mmc.getAllowedPropertyValues(zStageLabel, "Velocity").toArray();
String currentValue = mmc.getProperty(zStageLabel, "Velocity");
GenericDialog gd = new GenericDialog("z-stage velocity");
gd.addChoice("velocity", allowedValues, currentValue);
gd.showDialog();
if (gd.wasCanceled())
return;
int newValue = (int)Integer.parseInt(gd.getNextChoice());
mmc.setProperty(zStageLabel, "Velocity", newValue);
} catch (Exception e) {
IJ.handleException(e);
}
}
// Accessing the devices
protected void maybeUpdateImage() {
if (cameraLabel != null && updateLiveImage)
gui.updateImage();
}
protected abstract static class RunTo extends Thread {
protected int goal, current = Integer.MAX_VALUE;
@Override
public void run() {
for (;;) try {
if (goal != current) synchronized (this) {
if (get() == goal) {
current = goal;
done();
notifyAll();
}
}
Thread.currentThread().sleep(50);
} catch (Exception e) {
return;
}
}
public void run(int value) {
synchronized (this) {
if (goal == value) {
done();
return;
}
goal = value;
try {
set(goal);
} catch (Exception e) {
return;
}
synchronized (this) {
if (!isAlive())
start();
try {
wait();
} catch (InterruptedException e) {
return;
}
}
}
}
public abstract int get() throws Exception ;
public abstract void set(int value) throws Exception;
public abstract void done();
}
protected RunTo runToX = new RunTo() {
@Override
public int get() throws Exception {
return (int)mmc.getXPosition(xyStageLabel);
}
@Override
public void set(int value) throws Exception {
mmc.setXYPosition(xyStageLabel, value, mmc.getYPosition(xyStageLabel));
}
@Override
public void done() {
xPosition.setText("" + goal);
}
};
protected RunTo runToY = new RunTo() {
@Override
public int get() throws Exception {
return (int)mmc.getYPosition(xyStageLabel);
}
@Override
public void set(int value) throws Exception {
mmc.setXYPosition(xyStageLabel, mmc.getXPosition(xyStageLabel), value);
}
@Override
public void done() {
yPosition.setText("" + goal);
}
};
protected RunTo runToZ = new RunTo() {
@Override
public int get() throws Exception {
return (int)mmc.getPosition(zStageLabel);
}
@Override
public void set(int value) throws Exception {
mmc.setPosition(zStageLabel, value);
}
@Override
public void done() {
zPosition.setText("" + goal);
}
};
protected RunTo runToAngle = new RunTo() {
@Override
public int get() throws Exception {
return (int)mmc.getPosition(twisterLabel);
}
@Override
public void set(int value) throws Exception {
mmc.setPosition(twisterLabel, value);
}
@Override
public void done() {
rotation.setText("" + (goal * 360 / 200));
}
};
protected ImageProcessor snapSlice() throws Exception {
mmc.snapImage();
int width = (int)mmc.getImageWidth();
int height = (int)mmc.getImageHeight();
if (mmc.getBytesPerPixel() == 1) {
byte[] pixels = (byte[])mmc.getImage();
return new ByteProcessor(width, height, pixels, null);
} else if (mmc.getBytesPerPixel() == 2){
short[] pixels = (short[])mmc.getImage();
return new ShortProcessor(width, height, pixels, null);
} else
return null;
}
protected void snapAndShowContinuousStack(final int zStart, final int zEnd) throws Exception {
// Cannot run this on the EDT
if (SwingUtilities.isEventDispatchThread()) {
new Thread() {
public void run() {
try {
snapAndShowContinuousStack(zStart, zEnd);
} catch (Exception e) {
IJ.handleException(e);
}
}
}.start();
return;
}
snapContinuousStack(zStart, zEnd).show();
}
protected ImagePlus snapContinuousStack(int zStart, int zEnd) throws Exception {
String meta = getMetaData();
ImageStack stack = null;
zSlider.setValue(zStart);
runToZ.run(zStart);
IJ.wait(50); // wait 50 milliseconds for the state to settle
zSlider.setValue(zEnd);
int zStep = (zStart < zEnd ? +1 : -1);
IJ.log("from " + zStart + " to " + zEnd + ", step: " + zStep);
for (int z = zStart; z * zStep <= zEnd * zStep; z = z + zStep) {
IJ.log("Waiting for " + z + " (" + (z * zStep) + " < " + ((int)mmc.getPosition(zStageLabel) * zStep) + ")");
while (z * zStep > (int)mmc.getPosition(zStageLabel) * zStep)
Thread.yield();
IJ.log("Got " + mmc.getPosition(zStageLabel));
ImageProcessor ip = snapSlice();
z = (int)mmc.getPosition(zStageLabel);
IJ.log("Updated z to " + z);
if (stack == null)
stack = new ImageStack(ip.getWidth(), ip.getHeight());
stack.addSlice("z: " + z, ip);
}
IJ.log("Finished taking " + (zStep * (zEnd - zStart)) + " slices (really got " + (stack == null ? "0" : stack.getSize() + ")"));
ImagePlus result = new ImagePlus("SPIM!", stack);
result.setProperty("Info", meta);
return result;
}
protected ImagePlus snapStack(int zStart, int zEnd, int delayMs) throws Exception {
String meta = getMetaData();
ImageStack stack = null;
int zStep = (zStart < zEnd ? +1 : -1);
for (int z = zStart; z * zStep <= zEnd * zStep; z = z + zStep) {
zSlider.setValue(z);
runToZ.run(z);
if (delayMs > 0)
IJ.wait(delayMs);
ImageProcessor ip = snapSlice();
if (stack == null)
stack = new ImageStack(ip.getWidth(), ip.getHeight());
stack.addSlice("z: " + z, ip);
}
ImagePlus result = new ImagePlus("SPIM!", stack);
result.setProperty("Info", meta);
return result;
}
protected String getMetaData() throws Exception {
String meta = "";
if (xyStageLabel != "")
meta += "x motor position: " + mmc.getXPosition(xyStageLabel) + "\n"
+ "y motor position: " + mmc.getYPosition(xyStageLabel) + "\n";
if (zStageLabel != "")
meta += "z motor position: " + mmc.getPosition(zStageLabel) + "\n";
if (twisterLabel != "")
meta += "twister position: " + mmc.getPosition(twisterLabel) + "\n"
+ "twister angle: " + (360.0 / 200.0 * mmc.getPosition(twisterLabel)) + "\n";
return meta;
}
}
| true | true | protected void initUI() {
if (frame != null)
return;
frame = new JFrame("OpenSPIM");
JPanel left = new JPanel();
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
left.setBorder(BorderFactory.createTitledBorder("Position/Angle"));
xSlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToX.run(value);
maybeUpdateImage();
}
};
ySlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToY.run(value);
maybeUpdateImage();
}
};
zSlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToZ.run(value);
maybeUpdateImage();
}
};
rotationSlider = new MotorSlider(twisterMin, twisterMax, 0) {
@Override
public void valueChanged(int value) {
runToAngle.run(value * 200 / 360);
maybeUpdateImage();
}
};
xPosition = new IntegerSliderField(xSlider);
yPosition = new IntegerSliderField(ySlider);
zPosition = new IntegerSliderField(zSlider);
rotation = new IntegerSliderField(rotationSlider);
zFrom = new IntegerField(1) {
@Override
public void valueChanged(int value) {
if (value < motorMin)
setText("" + motorMin);
else if (value > motorMax)
setText("" + motorMax);
}
};
zTo = new IntegerField(motorMax) {
@Override
public void valueChanged(int value) {
if (value < motorMin)
setText("" + motorMin);
else if (value > motorMax)
setText("" + motorMax);
}
};
stepsPerRotation = new IntegerField(4) {
@Override
public void valueChanged(int value) {
degreesPerStep.setText("" + (360 / value));
}
};
degreesPerStep = new IntegerField(90) {
@Override
public void valueChanged(int value) {
stepsPerRotation.setText("" + (360 / value));
}
};
addLine(left, Justification.LEFT, "x:", xPosition, "y:", yPosition, "z:", zPosition, "angle:", rotation);
addLine(left, Justification.STRETCH, "x:", xSlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", xSlider, 500, 2500));
addLine(left, Justification.STRETCH, "y:", ySlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", ySlider, 500, 2500));
addLine(left, Justification.STRETCH, "z:", zSlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", zSlider, 500, 2500));
addLine(left, Justification.RIGHT, "from z:", zFrom, "to z:", zTo);
addLine(left, Justification.STRETCH, "rotation:", rotationSlider);
addLine(left, Justification.RIGHT, "steps/rotation:", stepsPerRotation, "degrees/step:", degreesPerStep);
JPanel right = new JPanel();
right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
right.setBorder(BorderFactory.createTitledBorder("Acquisition"));
// TODO: find out correct values
laserSlider = new MotorSlider(0, 1000, 1000) {
@Override
public void valueChanged(int value) {
// TODO
}
};
// TODO: find out correct values
exposureSlider = new MotorSlider(10, 1000, 10) {
@Override
public void valueChanged(int value) {
try {
mmc.setExposure(value);
} catch (Exception e) {
IJ.handleException(e);
}
}
};
laserPower = new IntegerSliderField(laserSlider);
exposure = new IntegerSliderField(exposureSlider);
liveCheckbox = new JCheckBox("Update Live View");
liveCheckbox.setSelected(gui.isLiveModeOn());
updateLiveImage = true;
liveCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
updateLiveImage = e.getStateChange() == ItemEvent.SELECTED;
if (updateLiveImage && !gui.isLiveModeOn())
gui.enableLiveMode(true);
}
});
registrationCheckbox = new JCheckBox("Perform SPIM registration");
registrationCheckbox.setSelected(false);
registrationCheckbox.setEnabled(false);
multipleAngleCheckbox = new JCheckBox("Multiple Rotation Angles");
multipleAngleCheckbox.setSelected(false);
multipleAngleCheckbox.setEnabled(false);
speedControl = new JButton("Set z-stage velocity");
speedControl.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread() {
public void run() {
setZStageVelocity();
}
}.start();
}
});
continuousCheckbox = new JCheckBox("Continuous z motion");
continuousCheckbox.setSelected(false);
continuousCheckbox.setEnabled(true);
settleTime = new IntegerField(0) {
@Override
public void valueChanged(int value) {
degreesPerStep.setText("" + (360 / value));
}
};
ohSnap = new JButton("Oh snap!");
ohSnap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final int zStart = zFrom.getValue();
final int zEnd = zTo.getValue();
final boolean isContinuous = continuousCheckbox.isSelected();
new Thread() {
@Override
public void run() {
try {
ImagePlus image = isContinuous ?
snapContinuousStack(zStart, zEnd) : snapStack(zStart, zEnd, settleTime.getValue());
image.show();
} catch (Exception e) {
IJ.handleException(e);
}
}
}.start();
}
});
addLine(right, Justification.RIGHT, "laser power:", laserPower, "exposure:", exposure);
addLine(right, Justification.STRETCH, "laser:", laserSlider);
addLine(right, Justification.STRETCH, "exposure:", exposureSlider);
addLine(right, Justification.RIGHT, liveCheckbox);
addLine(right, Justification.RIGHT, registrationCheckbox);
addLine(right, Justification.RIGHT, multipleAngleCheckbox);
addLine(right, Justification.RIGHT, speedControl);
//addLine(right, Justification.RIGHT, continuousCheckbox);
addLine(right, Justification.RIGHT, "Delay to let z-stage settle (ms)", settleTime);
addLine(right, Justification.RIGHT, ohSnap);
Container panel = frame.getContentPane();
panel.setLayout(new GridLayout(1, 2));
panel.add(left);
panel.add(right);
frame.pack();
}
| protected void initUI() {
if (frame != null)
return;
frame = new JFrame("OpenSPIM");
JPanel left = new JPanel();
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
left.setBorder(BorderFactory.createTitledBorder("Position/Angle"));
xSlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToX.run(value);
maybeUpdateImage();
}
};
ySlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToY.run(value);
maybeUpdateImage();
}
};
zSlider = new MotorSlider(motorMin, motorMax, 1) {
@Override
public void valueChanged(int value) {
runToZ.run(value);
maybeUpdateImage();
}
};
rotationSlider = new MotorSlider(twisterMin, twisterMax, 0) {
@Override
public void valueChanged(int value) {
runToAngle.run(value * 200 / 360);
maybeUpdateImage();
}
};
xPosition = new IntegerSliderField(xSlider);
yPosition = new IntegerSliderField(ySlider);
zPosition = new IntegerSliderField(zSlider);
rotation = new IntegerSliderField(rotationSlider);
zFrom = new IntegerField(1) {
@Override
public void valueChanged(int value) {
if (value < motorMin)
setText("" + motorMin);
else if (value > motorMax)
setText("" + motorMax);
}
};
zTo = new IntegerField(motorMax) {
@Override
public void valueChanged(int value) {
if (value < motorMin)
setText("" + motorMin);
else if (value > motorMax)
setText("" + motorMax);
}
};
stepsPerRotation = new IntegerField(4) {
@Override
public void valueChanged(int value) {
degreesPerStep.setText("" + (360 / value));
}
};
degreesPerStep = new IntegerField(90) {
@Override
public void valueChanged(int value) {
stepsPerRotation.setText("" + (360 / value));
}
};
addLine(left, Justification.LEFT, "x:", xPosition, "y:", yPosition, "z:", zPosition, "angle:", rotation);
addLine(left, Justification.STRETCH, "x:", xSlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", xSlider, 500, 2500));
addLine(left, Justification.STRETCH, "y:", ySlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", ySlider, 500, 2500));
addLine(left, Justification.STRETCH, "z:", zSlider);
addLine(left, Justification.RIGHT, new LimitedRangeCheckbox("Limit range", zSlider, 500, 2500));
addLine(left, Justification.RIGHT, "from z:", zFrom, "to z:", zTo);
addLine(left, Justification.STRETCH, "rotation:", rotationSlider);
addLine(left, Justification.RIGHT, "steps/rotation:", stepsPerRotation, "degrees/step:", degreesPerStep);
JPanel right = new JPanel();
right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
right.setBorder(BorderFactory.createTitledBorder("Acquisition"));
// TODO: find out correct values
laserSlider = new MotorSlider(0, 1000, 1000) {
@Override
public void valueChanged(int value) {
// TODO
}
};
// TODO: find out correct values
exposureSlider = new MotorSlider(10, 1000, 10) {
@Override
public void valueChanged(int value) {
try {
mmc.setExposure(value);
} catch (Exception e) {
IJ.handleException(e);
}
}
};
laserPower = new IntegerSliderField(laserSlider);
exposure = new IntegerSliderField(exposureSlider);
liveCheckbox = new JCheckBox("Update Live View");
updateLiveImage = gui.isLiveModeOn();
liveCheckbox.setSelected(updateLiveImage);
liveCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
updateLiveImage = e.getStateChange() == ItemEvent.SELECTED;
if (updateLiveImage && !gui.isLiveModeOn())
gui.enableLiveMode(true);
}
});
registrationCheckbox = new JCheckBox("Perform SPIM registration");
registrationCheckbox.setSelected(false);
registrationCheckbox.setEnabled(false);
multipleAngleCheckbox = new JCheckBox("Multiple Rotation Angles");
multipleAngleCheckbox.setSelected(false);
multipleAngleCheckbox.setEnabled(false);
speedControl = new JButton("Set z-stage velocity");
speedControl.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread() {
public void run() {
setZStageVelocity();
}
}.start();
}
});
continuousCheckbox = new JCheckBox("Continuous z motion");
continuousCheckbox.setSelected(false);
continuousCheckbox.setEnabled(true);
settleTime = new IntegerField(0) {
@Override
public void valueChanged(int value) {
degreesPerStep.setText("" + (360 / value));
}
};
ohSnap = new JButton("Oh snap!");
ohSnap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final int zStart = zFrom.getValue();
final int zEnd = zTo.getValue();
final boolean isContinuous = continuousCheckbox.isSelected();
new Thread() {
@Override
public void run() {
try {
ImagePlus image = isContinuous ?
snapContinuousStack(zStart, zEnd) : snapStack(zStart, zEnd, settleTime.getValue());
image.show();
} catch (Exception e) {
IJ.handleException(e);
}
}
}.start();
}
});
addLine(right, Justification.RIGHT, "laser power:", laserPower, "exposure:", exposure);
addLine(right, Justification.STRETCH, "laser:", laserSlider);
addLine(right, Justification.STRETCH, "exposure:", exposureSlider);
addLine(right, Justification.RIGHT, liveCheckbox);
addLine(right, Justification.RIGHT, registrationCheckbox);
addLine(right, Justification.RIGHT, multipleAngleCheckbox);
addLine(right, Justification.RIGHT, speedControl);
//addLine(right, Justification.RIGHT, continuousCheckbox);
addLine(right, Justification.RIGHT, "Delay to let z-stage settle (ms)", settleTime);
addLine(right, Justification.RIGHT, ohSnap);
Container panel = frame.getContentPane();
panel.setLayout(new GridLayout(1, 2));
panel.add(left);
panel.add(right);
frame.pack();
}
|
diff --git a/source/RMG/jing/rxn/TemplateReactionGenerator.java b/source/RMG/jing/rxn/TemplateReactionGenerator.java
index c21b059e..18491080 100644
--- a/source/RMG/jing/rxn/TemplateReactionGenerator.java
+++ b/source/RMG/jing/rxn/TemplateReactionGenerator.java
@@ -1,320 +1,317 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// 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 jing.rxn;
import jing.chem.*;
import java.util.*;
import jing.chem.Species;
import jing.param.Global;
import jing.param.Temperature;
//## package jing::rxn
//----------------------------------------------------------------------------
// jing\rxn\TemplateReactionGenerator.java
//----------------------------------------------------------------------------
//## class TemplateReactionGenerator
public class TemplateReactionGenerator implements ReactionGenerator {
protected ReactionTemplateLibrary reactionTemplateLibrary;
// Constructors
//## operation TemplateReactionGenerator()
public TemplateReactionGenerator() {
//#[ operation TemplateReactionGenerator()
reactionTemplateLibrary = ReactionTemplateLibrary.getINSTANCE();
//#]
}
/**
Requires:
Effects: Check all the pass-in species to see if there is a match between the species and any reaction template's reactant's pattern, if there is a match, generate the new reaction, find out the kinetics from first kinetics library, then kineticstemplatelibrary, then add the new reaction
into the reaction set. keep doing this until there is no more new match. return the final reaction set.
Modifies:
*/
// Argument HashSetp_speciesSeed :
/**
the set of species in the reaction system.
*/
//## operation react(HashSet)
public LinkedHashSet react(LinkedHashSet p_speciesSeed) {
LinkedHashSet allReactions = new LinkedHashSet();
LinkedHashSet allSpecies = new LinkedHashSet();
// Iterate over all species in the LinkedHashSet
for (Iterator speciesIter = p_speciesSeed.iterator(); speciesIter.hasNext();) {
// Grab the current species, add it to the "core", and react it against the "core"
Species currentSpecies = (Species)speciesIter.next();
allSpecies.add(currentSpecies);
allReactions.addAll(react(allSpecies,currentSpecies,"All"));
}
return allReactions;
}
public LinkedHashSet generatePdepReactions(Species p_species){
Iterator template_iter = reactionTemplateLibrary.getReactionTemplate();
LinkedHashSet pdepReactionSet = new LinkedHashSet();
while (template_iter.hasNext()) {
ReactionTemplate current_template = (ReactionTemplate)template_iter.next();
// the reaction template has only one reactant, we only need to loop over the whole species seed set to find a match
double startTime = System.currentTimeMillis();
if (current_template.hasOneReactant()) {
/*
* Added by MRH on 15-Jun-2009
* Display more information to the user:
* This println command informs the user which rxn family template
* the species is reacting against
*/
System.out.println("Generating pressure dependent network for " + p_species.getChemkinName() + ": " + current_template.name);
LinkedHashSet current_reactions = current_template.reactOneReactant(p_species);
pdepReactionSet.addAll(current_reactions);
}
}
Runtime runTime = Runtime.getRuntime();
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
if (runTime.freeMemory() < runTime.totalMemory()/3) {
runTime.gc();
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
}
return pdepReactionSet;
}
//## operation react(HashSet,Species)
public LinkedHashSet react(LinkedHashSet p_speciesSet, Species newCoreSpecies, String specificRxnFamily) {
// double pT = System.currentTimeMillis();
//#[ operation react(HashSet,Species)
LinkedHashSet reaction_set = new LinkedHashSet();
if (!newCoreSpecies.isReactive()){
return reaction_set;
}
if (p_speciesSet.size() == 0 && newCoreSpecies == null) {
return reaction_set;
}
double singleReaction = 0, doubleReaction = 0;
double longestTime = 0;
String longestTemplate = "";
StringBuffer HAbs = new StringBuffer();//"H_Abstraction");
HashSet pdepReactionSet = new HashSet();
// add here the algorithm to generate reaction
// loop over all the reaction template to find any possible match between the species seed set and the reaction template library
Iterator template_iter = reactionTemplateLibrary.getReactionTemplate();
while (template_iter.hasNext()) {
ReactionTemplate current_template = (ReactionTemplate)template_iter.next();
if (specificRxnFamily.equals("All") || specificRxnFamily.equals(current_template.name)) {
/*
* Added by MRH on 12-Jun-2009
* Display more information to the user:
* This println command informs the user which rxn family template
* the new core species is reacting against
*/
System.out.println("Reacting " + newCoreSpecies.getChemkinName() + " with the core: " + current_template.name);
// the reaction template has only one reactant, we only need to loop over the whole species seed set to find a match
double startTime = System.currentTimeMillis();
if (current_template.hasOneReactant()) {
LinkedHashSet current_reactions = current_template.reactOneReactant(newCoreSpecies);
- for (Iterator currentRxnIter = current_reactions.iterator(); currentRxnIter.hasNext();) {
- Reaction r = (Reaction)currentRxnIter.next();
- reaction_set = sm.updateReactionList(r, reaction_set, false);
- }
+ reaction_set.addAll(current_reactions);
singleReaction = singleReaction + ((System.currentTimeMillis()-startTime)/1000/60);
}
// the reaction template has two reactants, we need to check all the possible combination of two species
else if (current_template.hasTwoReactants()) {
// LinkedHashSet current_reactions = new LinkedHashSet();
StructureTemplate structTemp = current_template.structureTemplate;
LinkedHashSet site1_reactiveSites_sp1 = new LinkedHashSet();
LinkedHashSet site2_reactiveSites_sp1 = new LinkedHashSet();
LinkedHashSet site1_reactiveSites_sp2 = new LinkedHashSet();
LinkedHashSet site2_reactiveSites_sp2 = new LinkedHashSet();
if (!newCoreSpecies.hasResonanceIsomers()) {
ChemGraph newCoreCG = newCoreSpecies.getChemGraph();
site1_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,1);
site2_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,2);
Iterator coreSpeciesIter = p_speciesSet.iterator();
while (coreSpeciesIter.hasNext()) {
Species coreSpecies = (Species)coreSpeciesIter.next();
if (coreSpecies.isReactive()) {
if (!coreSpecies.hasResonanceIsomers()) {
ChemGraph tempCG = coreSpecies.getChemGraph();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
} else {
Iterator coreSpeciesCGIter = coreSpecies.getResonanceIsomers();
while (coreSpeciesCGIter.hasNext()) {
ChemGraph tempCG = (ChemGraph)coreSpeciesCGIter.next();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
}
}
}
}
} else {
Iterator newSpeciesCGIter = newCoreSpecies.getResonanceIsomers();
while (newSpeciesCGIter.hasNext()) {
ChemGraph newCoreCG = (ChemGraph)newSpeciesCGIter.next();
site1_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,1);
site2_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,2);
Iterator coreSpeciesIter = p_speciesSet.iterator();
while (coreSpeciesIter.hasNext()) {
Species coreSpecies = (Species)coreSpeciesIter.next();
if (coreSpecies.isReactive()) {
if (!coreSpecies.hasResonanceIsomers()) {
ChemGraph tempCG = coreSpecies.getChemGraph();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
} else {
Iterator coreSpeciesCGIter = coreSpecies.getResonanceIsomers();
while (coreSpeciesCGIter.hasNext()) {
ChemGraph tempCG = (ChemGraph)coreSpeciesCGIter.next();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
}
}
}
}
}
}
}
doubleReaction += ((System.currentTimeMillis()-startTime)/1000/60);
double thisDoubleReaction = ((System.currentTimeMillis()-startTime)/1000/60);
if (thisDoubleReaction >= longestTime){
longestTime = thisDoubleReaction;
longestTemplate = current_template.name;
}
}
}
newCoreSpecies.addPdepPaths(pdepReactionSet);
Global.enlargerInfo.append(newCoreSpecies.getChemkinName() + "\t" + singleReaction + "\t" + doubleReaction + "\t" + longestTime +"\t" + longestTemplate + "\t" + HAbs.toString() + "\n");
//PDepNetwork.completeNetwork(p_species);
Runtime runTime = Runtime.getRuntime();
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
if (runTime.freeMemory() < runTime.totalMemory()/3) {
runTime.gc();
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
}
// double t = (System.currentTimeMillis()-pT)/1000/60;
// Global.RT_reactTwoReactants += t;
return reaction_set;
//#]
}
public ChemGraph generateCGcopyIfNecessary(ChemGraph cg1, ChemGraph cg2) {
ChemGraph cg_copy = null;
if (cg1 == cg2) {
try {
cg_copy = ChemGraph.copy(cg2);
} catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure encountered in react(): " + e.toString());
}
} else return cg1;
return cg_copy;
}
public ReactionTemplateLibrary getReactionTemplateLibrary() {
return reactionTemplateLibrary;
}
public void setReactionTemplateLibrary(ReactionTemplateLibrary p_ReactionTemplateLibrary) {
reactionTemplateLibrary = p_ReactionTemplateLibrary;
}
}
/*********************************************************************
File Path : RMG\RMG\jing\rxn\TemplateReactionGenerator.java
*********************************************************************/
| true | true | public LinkedHashSet react(LinkedHashSet p_speciesSet, Species newCoreSpecies, String specificRxnFamily) {
// double pT = System.currentTimeMillis();
//#[ operation react(HashSet,Species)
LinkedHashSet reaction_set = new LinkedHashSet();
if (!newCoreSpecies.isReactive()){
return reaction_set;
}
if (p_speciesSet.size() == 0 && newCoreSpecies == null) {
return reaction_set;
}
double singleReaction = 0, doubleReaction = 0;
double longestTime = 0;
String longestTemplate = "";
StringBuffer HAbs = new StringBuffer();//"H_Abstraction");
HashSet pdepReactionSet = new HashSet();
// add here the algorithm to generate reaction
// loop over all the reaction template to find any possible match between the species seed set and the reaction template library
Iterator template_iter = reactionTemplateLibrary.getReactionTemplate();
while (template_iter.hasNext()) {
ReactionTemplate current_template = (ReactionTemplate)template_iter.next();
if (specificRxnFamily.equals("All") || specificRxnFamily.equals(current_template.name)) {
/*
* Added by MRH on 12-Jun-2009
* Display more information to the user:
* This println command informs the user which rxn family template
* the new core species is reacting against
*/
System.out.println("Reacting " + newCoreSpecies.getChemkinName() + " with the core: " + current_template.name);
// the reaction template has only one reactant, we only need to loop over the whole species seed set to find a match
double startTime = System.currentTimeMillis();
if (current_template.hasOneReactant()) {
LinkedHashSet current_reactions = current_template.reactOneReactant(newCoreSpecies);
for (Iterator currentRxnIter = current_reactions.iterator(); currentRxnIter.hasNext();) {
Reaction r = (Reaction)currentRxnIter.next();
reaction_set = sm.updateReactionList(r, reaction_set, false);
}
singleReaction = singleReaction + ((System.currentTimeMillis()-startTime)/1000/60);
}
// the reaction template has two reactants, we need to check all the possible combination of two species
else if (current_template.hasTwoReactants()) {
// LinkedHashSet current_reactions = new LinkedHashSet();
StructureTemplate structTemp = current_template.structureTemplate;
LinkedHashSet site1_reactiveSites_sp1 = new LinkedHashSet();
LinkedHashSet site2_reactiveSites_sp1 = new LinkedHashSet();
LinkedHashSet site1_reactiveSites_sp2 = new LinkedHashSet();
LinkedHashSet site2_reactiveSites_sp2 = new LinkedHashSet();
if (!newCoreSpecies.hasResonanceIsomers()) {
ChemGraph newCoreCG = newCoreSpecies.getChemGraph();
site1_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,1);
site2_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,2);
Iterator coreSpeciesIter = p_speciesSet.iterator();
while (coreSpeciesIter.hasNext()) {
Species coreSpecies = (Species)coreSpeciesIter.next();
if (coreSpecies.isReactive()) {
if (!coreSpecies.hasResonanceIsomers()) {
ChemGraph tempCG = coreSpecies.getChemGraph();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
} else {
Iterator coreSpeciesCGIter = coreSpecies.getResonanceIsomers();
while (coreSpeciesCGIter.hasNext()) {
ChemGraph tempCG = (ChemGraph)coreSpeciesCGIter.next();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
}
}
}
}
} else {
Iterator newSpeciesCGIter = newCoreSpecies.getResonanceIsomers();
while (newSpeciesCGIter.hasNext()) {
ChemGraph newCoreCG = (ChemGraph)newSpeciesCGIter.next();
site1_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,1);
site2_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,2);
Iterator coreSpeciesIter = p_speciesSet.iterator();
while (coreSpeciesIter.hasNext()) {
Species coreSpecies = (Species)coreSpeciesIter.next();
if (coreSpecies.isReactive()) {
if (!coreSpecies.hasResonanceIsomers()) {
ChemGraph tempCG = coreSpecies.getChemGraph();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
} else {
Iterator coreSpeciesCGIter = coreSpecies.getResonanceIsomers();
while (coreSpeciesCGIter.hasNext()) {
ChemGraph tempCG = (ChemGraph)coreSpeciesCGIter.next();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
}
}
}
}
}
}
}
doubleReaction += ((System.currentTimeMillis()-startTime)/1000/60);
double thisDoubleReaction = ((System.currentTimeMillis()-startTime)/1000/60);
if (thisDoubleReaction >= longestTime){
longestTime = thisDoubleReaction;
longestTemplate = current_template.name;
}
}
}
newCoreSpecies.addPdepPaths(pdepReactionSet);
Global.enlargerInfo.append(newCoreSpecies.getChemkinName() + "\t" + singleReaction + "\t" + doubleReaction + "\t" + longestTime +"\t" + longestTemplate + "\t" + HAbs.toString() + "\n");
//PDepNetwork.completeNetwork(p_species);
Runtime runTime = Runtime.getRuntime();
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
if (runTime.freeMemory() < runTime.totalMemory()/3) {
runTime.gc();
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
}
// double t = (System.currentTimeMillis()-pT)/1000/60;
// Global.RT_reactTwoReactants += t;
return reaction_set;
//#]
}
| public LinkedHashSet react(LinkedHashSet p_speciesSet, Species newCoreSpecies, String specificRxnFamily) {
// double pT = System.currentTimeMillis();
//#[ operation react(HashSet,Species)
LinkedHashSet reaction_set = new LinkedHashSet();
if (!newCoreSpecies.isReactive()){
return reaction_set;
}
if (p_speciesSet.size() == 0 && newCoreSpecies == null) {
return reaction_set;
}
double singleReaction = 0, doubleReaction = 0;
double longestTime = 0;
String longestTemplate = "";
StringBuffer HAbs = new StringBuffer();//"H_Abstraction");
HashSet pdepReactionSet = new HashSet();
// add here the algorithm to generate reaction
// loop over all the reaction template to find any possible match between the species seed set and the reaction template library
Iterator template_iter = reactionTemplateLibrary.getReactionTemplate();
while (template_iter.hasNext()) {
ReactionTemplate current_template = (ReactionTemplate)template_iter.next();
if (specificRxnFamily.equals("All") || specificRxnFamily.equals(current_template.name)) {
/*
* Added by MRH on 12-Jun-2009
* Display more information to the user:
* This println command informs the user which rxn family template
* the new core species is reacting against
*/
System.out.println("Reacting " + newCoreSpecies.getChemkinName() + " with the core: " + current_template.name);
// the reaction template has only one reactant, we only need to loop over the whole species seed set to find a match
double startTime = System.currentTimeMillis();
if (current_template.hasOneReactant()) {
LinkedHashSet current_reactions = current_template.reactOneReactant(newCoreSpecies);
reaction_set.addAll(current_reactions);
singleReaction = singleReaction + ((System.currentTimeMillis()-startTime)/1000/60);
}
// the reaction template has two reactants, we need to check all the possible combination of two species
else if (current_template.hasTwoReactants()) {
// LinkedHashSet current_reactions = new LinkedHashSet();
StructureTemplate structTemp = current_template.structureTemplate;
LinkedHashSet site1_reactiveSites_sp1 = new LinkedHashSet();
LinkedHashSet site2_reactiveSites_sp1 = new LinkedHashSet();
LinkedHashSet site1_reactiveSites_sp2 = new LinkedHashSet();
LinkedHashSet site2_reactiveSites_sp2 = new LinkedHashSet();
if (!newCoreSpecies.hasResonanceIsomers()) {
ChemGraph newCoreCG = newCoreSpecies.getChemGraph();
site1_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,1);
site2_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,2);
Iterator coreSpeciesIter = p_speciesSet.iterator();
while (coreSpeciesIter.hasNext()) {
Species coreSpecies = (Species)coreSpeciesIter.next();
if (coreSpecies.isReactive()) {
if (!coreSpecies.hasResonanceIsomers()) {
ChemGraph tempCG = coreSpecies.getChemGraph();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
} else {
Iterator coreSpeciesCGIter = coreSpecies.getResonanceIsomers();
while (coreSpeciesCGIter.hasNext()) {
ChemGraph tempCG = (ChemGraph)coreSpeciesCGIter.next();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
}
}
}
}
} else {
Iterator newSpeciesCGIter = newCoreSpecies.getResonanceIsomers();
while (newSpeciesCGIter.hasNext()) {
ChemGraph newCoreCG = (ChemGraph)newSpeciesCGIter.next();
site1_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,1);
site2_reactiveSites_sp1 = structTemp.identifyReactedSites(newCoreCG,2);
Iterator coreSpeciesIter = p_speciesSet.iterator();
while (coreSpeciesIter.hasNext()) {
Species coreSpecies = (Species)coreSpeciesIter.next();
if (coreSpecies.isReactive()) {
if (!coreSpecies.hasResonanceIsomers()) {
ChemGraph tempCG = coreSpecies.getChemGraph();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
} else {
Iterator coreSpeciesCGIter = coreSpecies.getResonanceIsomers();
while (coreSpeciesCGIter.hasNext()) {
ChemGraph tempCG = (ChemGraph)coreSpeciesCGIter.next();
ChemGraph oldCoreCG = generateCGcopyIfNecessary(tempCG,newCoreCG);
if (!site1_reactiveSites_sp1.isEmpty()) site2_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,2);
if (!site2_reactiveSites_sp1.isEmpty()) site1_reactiveSites_sp2 = structTemp.identifyReactedSites(oldCoreCG,1);
// React A + B
LinkedHashSet current_reactions = current_template.reactTwoReactants(newCoreCG,site1_reactiveSites_sp1,oldCoreCG,site2_reactiveSites_sp2);
reaction_set.addAll(current_reactions);
// React B + A
current_reactions = current_template.reactTwoReactants(oldCoreCG,site1_reactiveSites_sp2,newCoreCG,site2_reactiveSites_sp1);
reaction_set.addAll(current_reactions);
}
}
}
}
}
}
}
doubleReaction += ((System.currentTimeMillis()-startTime)/1000/60);
double thisDoubleReaction = ((System.currentTimeMillis()-startTime)/1000/60);
if (thisDoubleReaction >= longestTime){
longestTime = thisDoubleReaction;
longestTemplate = current_template.name;
}
}
}
newCoreSpecies.addPdepPaths(pdepReactionSet);
Global.enlargerInfo.append(newCoreSpecies.getChemkinName() + "\t" + singleReaction + "\t" + doubleReaction + "\t" + longestTime +"\t" + longestTemplate + "\t" + HAbs.toString() + "\n");
//PDepNetwork.completeNetwork(p_species);
Runtime runTime = Runtime.getRuntime();
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
if (runTime.freeMemory() < runTime.totalMemory()/3) {
runTime.gc();
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
}
// double t = (System.currentTimeMillis()-pT)/1000/60;
// Global.RT_reactTwoReactants += t;
return reaction_set;
//#]
}
|
diff --git a/src/java/com/stackframe/sarariman/Sarariman.java b/src/java/com/stackframe/sarariman/Sarariman.java
index 55e52b9..6bf01ed 100644
--- a/src/java/com/stackframe/sarariman/Sarariman.java
+++ b/src/java/com/stackframe/sarariman/Sarariman.java
@@ -1,519 +1,520 @@
/*
* Copyright (C) 2009-2013 StackFrame, LLC
* This code is licensed under GPLv2.
*/
package com.stackframe.sarariman;
import static com.google.common.base.Preconditions.*;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.stackframe.reflect.ReflectionUtils;
import com.stackframe.sarariman.accesslog.AccessLog;
import com.stackframe.sarariman.accesslog.AccessLogImpl;
import com.stackframe.sarariman.clients.Clients;
import com.stackframe.sarariman.clients.ClientsImpl;
import com.stackframe.sarariman.contacts.Contacts;
import com.stackframe.sarariman.contacts.ContactsImpl;
import com.stackframe.sarariman.errors.Errors;
import com.stackframe.sarariman.errors.ErrorsImpl;
import com.stackframe.sarariman.events.Events;
import com.stackframe.sarariman.events.EventsImpl;
import com.stackframe.sarariman.holidays.Holidays;
import com.stackframe.sarariman.holidays.HolidaysImpl;
import com.stackframe.sarariman.locationlog.LocationLog;
import com.stackframe.sarariman.locationlog.LocationLogImpl;
import com.stackframe.sarariman.logincookies.LoginCookies;
import com.stackframe.sarariman.outofoffice.OutOfOfficeEntries;
import com.stackframe.sarariman.outofoffice.OutOfOfficeEntriesImpl;
import com.stackframe.sarariman.projects.LaborProjections;
import com.stackframe.sarariman.projects.LaborProjectionsImpl;
import com.stackframe.sarariman.projects.Projects;
import com.stackframe.sarariman.projects.ProjectsImpl;
import com.stackframe.sarariman.taskassignments.DefaultTaskAssignments;
import com.stackframe.sarariman.taskassignments.DefaultTaskAssignmentsImpl;
import com.stackframe.sarariman.taskassignments.TaskAssignments;
import com.stackframe.sarariman.taskassignments.TaskAssignmentsImpl;
import com.stackframe.sarariman.tasks.Tasks;
import com.stackframe.sarariman.tasks.TasksImpl;
import com.stackframe.sarariman.telephony.SMSGateway;
import com.stackframe.sarariman.telephony.twilio.TwilioSMSGatewayImpl;
import com.stackframe.sarariman.tickets.Tickets;
import com.stackframe.sarariman.tickets.TicketsImpl;
import com.stackframe.sarariman.timesheets.Timesheets;
import com.stackframe.sarariman.timesheets.TimesheetsImpl;
import com.stackframe.sarariman.vacation.Vacations;
import com.stackframe.sarariman.vacation.VacationsImpl;
import com.stackframe.sarariman.xmpp.XMPPServer;
import com.stackframe.sarariman.xmpp.XMPPServerImpl;
import com.twilio.sdk.TwilioRestClient;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
/**
*
* @author mcculley
*/
public class Sarariman implements ServletContextListener {
// This ExecutorService is used for background jobs which do not require synchronous completion with regard to an HTTP request.
private final ExecutorService backgroundExecutor = Executors.newFixedThreadPool(1);
// This ExecutorService is used for background jobs which write to the database and do not require synchronous completion with
// regard to an HTTP request.
private final ExecutorService backgroundDatabaseWriteExecutor = Executors.newFixedThreadPool(1);
private final Collection<Employee> approvers = new EmployeeTable(this, "approvers");
private final Collection<Employee> invoiceManagers = new EmployeeTable(this, "invoice_managers");
private final Collection<Employee> timesheetManagers = new EmployeeTable(this, "timesheet_managers");
private final Collection<LaborCategoryAssignment> projectBillRates = new LaborCategoryAssignmentTable(this);
private final Collection<LaborCategory> laborCategories = new LaborCategoryTable(this);
private final Collection<Extension> extensions = new ArrayList<Extension>();
private final Holidays holidays = new HolidaysImpl(getDataSource());
private final DirectorySynchronizer directorySynchronizer = new DirectorySynchronizerImpl();
private OrganizationHierarchy organizationHierarchy;
private LDAPDirectory directory;
private EmailDispatcher emailDispatcher;
private CronJobs cronJobs;
private String logoURL;
private String mountPoint;
private TimesheetEntries timesheetEntries;
private Projects projects;
private Tasks tasks;
private Clients clients;
private Tickets tickets;
private Events events;
private Vacations vacations;
private OutOfOfficeEntries outOfOffice;
private Contacts contacts;
private Timesheets timesheets;
private Errors errors;
private AccessLog accessLog;
private Workdays workdays;
private PaidTimeOff paidTimeOff;
private LaborProjections laborProjections;
private TaskAssignments taskAssignments;
private DefaultTaskAssignments defaultTaskAssignments;
private LoginCookies loginCookies;
private LocationLog locationLog;
private final Timer timer = new Timer("Sarariman");
private SMSGateway SMS;
private XMPPServer xmpp;
public String getVersion() {
return Version.version;
}
private static Properties lookupDirectoryProperties(Context envContext) throws NamingException {
Properties props = new Properties();
String[] propNames = new String[]{Context.INITIAL_CONTEXT_FACTORY, Context.PROVIDER_URL, Context.SECURITY_AUTHENTICATION,
Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS};
for (String s : propNames) {
props.put(s, envContext.lookup(s));
}
return props;
}
private static Properties lookupMailProperties(Context envContext) throws NamingException {
Properties props = new Properties();
String[] propNames = new String[]{"mail.from", "mail.smtp.host", "mail.smtp.port"};
for (String s : propNames) {
props.put(s, envContext.lookup(s));
}
return props;
}
public DataSource getDataSource() {
try {
return (DataSource)new InitialContext().lookup("java:comp/env/jdbc/sarariman");
} catch (NamingException namingException) {
throw new RuntimeException(namingException);
}
}
public Connection openConnection() {
try {
return getDataSource().getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Directory getDirectory() {
return directory;
}
public EmailDispatcher getEmailDispatcher() {
return emailDispatcher;
}
public Collection<Employee> getApprovers() {
return approvers;
}
public Collection<Employee> getInvoiceManagers() {
return invoiceManagers;
}
public Collection<Employee> getTimesheetManagers() {
return timesheetManagers;
}
public Timesheets getTimesheets() {
return timesheets;
}
public Clients getClients() {
return clients;
}
private Collection<Employee> getAdministrators() {
Predicate<Employee> isAdministrator = ReflectionUtils.predicateForProperty(Employee.class, "administrator");
return Collections2.filter(directory.getByUserName().values(), isAdministrator);
}
public String getLogoURL() {
return logoURL;
}
public String getMountPoint() {
return mountPoint;
}
public Collection<LaborCategoryAssignment> getProjectBillRates() {
return projectBillRates;
}
public Map<Long, LaborCategory> getLaborCategories() {
Map<Long, LaborCategory> result = new LinkedHashMap<Long, LaborCategory>();
for (LaborCategory lc : laborCategories) {
result.put(lc.getId(), lc);
}
return result;
}
public Collection<Extension> getExtensions() {
return extensions;
}
public AccessLog getAccessLog() {
return accessLog;
}
public OrganizationHierarchy getOrganizationHierarchy() {
return organizationHierarchy;
}
public TaskAssignments getTaskAssignments() {
return taskAssignments;
}
public Collection<Employee> employees(Collection<Integer> ids) {
Collection<Employee> result = new ArrayList<Employee>();
for (int id : ids) {
result.add(directory.getByNumber().get(id));
}
return result;
}
public Holidays getHolidays() {
return holidays;
}
public Vacations getVacations() {
return vacations;
}
public LaborProjections getLaborProjections() {
return laborProjections;
}
public DefaultTaskAssignments getDefaultTaskAssignments() {
return defaultTaskAssignments;
}
public LoginCookies getLoginCookies() {
return loginCookies;
}
public LocationLog getLocationLog() {
return locationLog;
}
public Collection<Audit> getGlobalAudits() {
Collection<Audit> c = new ArrayList<Audit>();
c.add(new OrgChartGlobalAudit(this));
c.add(new TimesheetAudit(this, directory));
c.add(new ContactsGlobalAudit(getDataSource(), contacts));
c.add(new ProjectAdministrativeAssistantGlobalAudit(getDataSource(), projects));
c.add(new ProjectManagerGlobalAudit(getDataSource(), projects));
c.add(new ProjectCostManagerGlobalAudit(getDataSource(), projects));
c.add(new DirectRateAudit(directory));
c.add(new TaskAssignmentsGlobalAudit(getDataSource(), directory, tasks, taskAssignments));
return c;
}
public static boolean isBoss(OrganizationHierarchy organizationHierarchy, Employee employee) throws SQLException {
Collection<Integer> bossIDs = organizationHierarchy.getBosses();
return bossIDs.contains(employee.getNumber());
}
public boolean isBoss(Employee employee) throws SQLException {
return isBoss(organizationHierarchy, employee);
}
public static boolean isBoss(Sarariman sarariman, Employee employee) throws SQLException {
return sarariman.isBoss(employee);
}
/**
* Make contains visible to the tag library.
*
* @param coll
* @param o
* @return whether or not coll contains o
*/
public static boolean contains(Collection<?> coll, Object o) {
checkNotNull(coll);
return coll.contains(o);
}
DirectorySynchronizer getDirectorySynchronizer() {
return directorySynchronizer;
}
public Timer getTimer() {
return timer;
}
public TimesheetEntries getTimesheetEntries() {
return timesheetEntries;
}
public Projects getProjects() {
return projects;
}
public Tasks getTasks() {
return tasks;
}
public Tickets getTickets() {
return tickets;
}
public Events getEvents() {
return events;
}
public Errors getErrors() {
return errors;
}
public OutOfOfficeEntries getOutOfOfficeEntries() {
return outOfOffice;
}
public Contacts getContacts() {
return contacts;
}
public Workdays getWorkdays() {
return workdays;
}
public PaidTimeOff getPaidTimeOff() {
return paidTimeOff;
}
public Executor getBackgroundDatabaseWriteExecutor() {
return backgroundDatabaseWriteExecutor;
}
public SMSGateway getSMSGateway() {
return SMS;
}
public Collection<UIResource> getNavbarLinks() {
return ImmutableList.<UIResource>of(new UIResourceImpl(getMountPoint(), "Home", "icon-home"),
new UIResourceImpl(getMountPoint() + "tools", "Tools", "icon-wrench"),
new UIResourceImpl(getMountPoint() + "holidays/upcoming.jsp", "Holidays",
"icon-calendar"));
}
public void contextInitialized(ServletContextEvent sce) {
extensions.add(new SAICExtension());
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:comp/env");
Properties directoryProperties = lookupDirectoryProperties(envContext);
directory = new LDAPDirectory(new InitialDirContext(directoryProperties), this);
try {
directorySynchronizer.synchronize(directory, getDataSource());
} catch (Exception e) {
// FIXME: log
System.err.println("Trouble synchronizing directory with database: " + e);
}
initContext.rebind("sarariman.directory", directory);
organizationHierarchy = new OrganizationHierarchyImpl(getDataSource(), directory);
boolean inhibitEmail = (Boolean)envContext.lookup("inhibitEmail");
String twilioAccountSID = (String)envContext.lookup("twilioAccountSID");
String twilioAuthToken = (String)envContext.lookup("twilioAuthToken");
TwilioRestClient twilioClient = new TwilioRestClient(twilioAccountSID, twilioAuthToken);
boolean inhibitSMS = (Boolean)envContext.lookup("inhibitSMS");
String SMSFrom = (String)envContext.lookup("SMSFrom");
try {
SMS = new TwilioSMSGatewayImpl(twilioClient, PhoneNumberUtil.getInstance().parse(SMSFrom, "US"), inhibitSMS,
backgroundDatabaseWriteExecutor, getDataSource());
} catch (NumberParseException pe) {
throw new RuntimeException(pe);
}
emailDispatcher = new EmailDispatcher(lookupMailProperties(envContext), inhibitEmail, backgroundExecutor);
logoURL = (String)envContext.lookup("logoURL");
mountPoint = (String)envContext.lookup("mountPoint");
clients = new ClientsImpl(getDataSource(), mountPoint);
projects = new ProjectsImpl(getDataSource(), organizationHierarchy, directory, this);
tasks = new TasksImpl(getDataSource(), getMountPoint(), projects);
timesheetEntries = new TimesheetEntriesImpl(getDataSource(), directory, tasks, mountPoint);
tickets = new TicketsImpl(getDataSource(), mountPoint);
events = new EventsImpl(getDataSource(), mountPoint);
vacations = new VacationsImpl(getDataSource(), directory);
outOfOffice = new OutOfOfficeEntriesImpl(getDataSource(), directory);
contacts = new ContactsImpl(getDataSource(), mountPoint);
timesheets = new TimesheetsImpl(this, mountPoint);
errors = new ErrorsImpl(getDataSource(), mountPoint, directory);
accessLog = new AccessLogImpl(getDataSource(), directory);
workdays = new WorkdaysImpl(holidays);
paidTimeOff = new PaidTimeOff(tasks);
laborProjections = new LaborProjectionsImpl(getDataSource(), directory, tasks, mountPoint);
taskAssignments = new TaskAssignmentsImpl(directory, getDataSource(), mountPoint);
defaultTaskAssignments = new DefaultTaskAssignmentsImpl(getDataSource(), tasks);
loginCookies = new LoginCookies(getDataSource(), timer);
locationLog = new LocationLogImpl(getDataSource(), directory, backgroundDatabaseWriteExecutor);
String keyStorePath = (String)envContext.lookup("keyStorePath");
String keyStorePassword = (String)envContext.lookup("keyStorePassword");
try {
System.err.println("starting XMPP server");
xmpp = new XMPPServerImpl(directory, new File(keyStorePath), keyStorePassword);
+ xmpp.start();
} catch (Exception e) {
System.err.println("trouble starting XMPP server");
e.printStackTrace();
}
} catch (NamingException ne) {
throw new RuntimeException(ne); // FIXME: Is this the best thing to throw here?
}
cronJobs = new CronJobs(timer, this, directory, emailDispatcher);
ServletContext servletContext = sce.getServletContext();
servletContext.setAttribute("sarariman", this);
servletContext.setAttribute("directory", directory);
cronJobs.start();
final String hostname = getHostname();
Runnable sendStartupEmailNotification = new Runnable() {
public void run() {
try {
for (Employee employee : getAdministrators()) {
String message = String.format("Sarariman version %s has been started on %s at %s.", getVersion(), hostname,
mountPoint);
emailDispatcher.send(employee.getEmail(), null, "sarariman started", message);
SMS.send(employee.getMobile(), "Sarariman has been started.");
}
} catch (Exception e) {
e.printStackTrace();
// FIXME: log
}
}
};
backgroundExecutor.execute(sendStartupEmailNotification);
}
private static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException uhe) {
return "unknown host";
}
}
public void contextDestroyed(ServletContextEvent sce) {
// FIXME: Should we worry about email that has been queued but not yet sent?
timer.cancel();
backgroundExecutor.shutdown();
try {
xmpp.stop();
} catch (Exception e) {
System.err.println("trouble stopping XMPP server");
e.printStackTrace();
}
}
}
| true | true | public void contextInitialized(ServletContextEvent sce) {
extensions.add(new SAICExtension());
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:comp/env");
Properties directoryProperties = lookupDirectoryProperties(envContext);
directory = new LDAPDirectory(new InitialDirContext(directoryProperties), this);
try {
directorySynchronizer.synchronize(directory, getDataSource());
} catch (Exception e) {
// FIXME: log
System.err.println("Trouble synchronizing directory with database: " + e);
}
initContext.rebind("sarariman.directory", directory);
organizationHierarchy = new OrganizationHierarchyImpl(getDataSource(), directory);
boolean inhibitEmail = (Boolean)envContext.lookup("inhibitEmail");
String twilioAccountSID = (String)envContext.lookup("twilioAccountSID");
String twilioAuthToken = (String)envContext.lookup("twilioAuthToken");
TwilioRestClient twilioClient = new TwilioRestClient(twilioAccountSID, twilioAuthToken);
boolean inhibitSMS = (Boolean)envContext.lookup("inhibitSMS");
String SMSFrom = (String)envContext.lookup("SMSFrom");
try {
SMS = new TwilioSMSGatewayImpl(twilioClient, PhoneNumberUtil.getInstance().parse(SMSFrom, "US"), inhibitSMS,
backgroundDatabaseWriteExecutor, getDataSource());
} catch (NumberParseException pe) {
throw new RuntimeException(pe);
}
emailDispatcher = new EmailDispatcher(lookupMailProperties(envContext), inhibitEmail, backgroundExecutor);
logoURL = (String)envContext.lookup("logoURL");
mountPoint = (String)envContext.lookup("mountPoint");
clients = new ClientsImpl(getDataSource(), mountPoint);
projects = new ProjectsImpl(getDataSource(), organizationHierarchy, directory, this);
tasks = new TasksImpl(getDataSource(), getMountPoint(), projects);
timesheetEntries = new TimesheetEntriesImpl(getDataSource(), directory, tasks, mountPoint);
tickets = new TicketsImpl(getDataSource(), mountPoint);
events = new EventsImpl(getDataSource(), mountPoint);
vacations = new VacationsImpl(getDataSource(), directory);
outOfOffice = new OutOfOfficeEntriesImpl(getDataSource(), directory);
contacts = new ContactsImpl(getDataSource(), mountPoint);
timesheets = new TimesheetsImpl(this, mountPoint);
errors = new ErrorsImpl(getDataSource(), mountPoint, directory);
accessLog = new AccessLogImpl(getDataSource(), directory);
workdays = new WorkdaysImpl(holidays);
paidTimeOff = new PaidTimeOff(tasks);
laborProjections = new LaborProjectionsImpl(getDataSource(), directory, tasks, mountPoint);
taskAssignments = new TaskAssignmentsImpl(directory, getDataSource(), mountPoint);
defaultTaskAssignments = new DefaultTaskAssignmentsImpl(getDataSource(), tasks);
loginCookies = new LoginCookies(getDataSource(), timer);
locationLog = new LocationLogImpl(getDataSource(), directory, backgroundDatabaseWriteExecutor);
String keyStorePath = (String)envContext.lookup("keyStorePath");
String keyStorePassword = (String)envContext.lookup("keyStorePassword");
try {
System.err.println("starting XMPP server");
xmpp = new XMPPServerImpl(directory, new File(keyStorePath), keyStorePassword);
} catch (Exception e) {
System.err.println("trouble starting XMPP server");
e.printStackTrace();
}
} catch (NamingException ne) {
throw new RuntimeException(ne); // FIXME: Is this the best thing to throw here?
}
cronJobs = new CronJobs(timer, this, directory, emailDispatcher);
ServletContext servletContext = sce.getServletContext();
servletContext.setAttribute("sarariman", this);
servletContext.setAttribute("directory", directory);
cronJobs.start();
final String hostname = getHostname();
Runnable sendStartupEmailNotification = new Runnable() {
public void run() {
try {
for (Employee employee : getAdministrators()) {
String message = String.format("Sarariman version %s has been started on %s at %s.", getVersion(), hostname,
mountPoint);
emailDispatcher.send(employee.getEmail(), null, "sarariman started", message);
SMS.send(employee.getMobile(), "Sarariman has been started.");
}
} catch (Exception e) {
e.printStackTrace();
// FIXME: log
}
}
};
backgroundExecutor.execute(sendStartupEmailNotification);
}
| public void contextInitialized(ServletContextEvent sce) {
extensions.add(new SAICExtension());
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:comp/env");
Properties directoryProperties = lookupDirectoryProperties(envContext);
directory = new LDAPDirectory(new InitialDirContext(directoryProperties), this);
try {
directorySynchronizer.synchronize(directory, getDataSource());
} catch (Exception e) {
// FIXME: log
System.err.println("Trouble synchronizing directory with database: " + e);
}
initContext.rebind("sarariman.directory", directory);
organizationHierarchy = new OrganizationHierarchyImpl(getDataSource(), directory);
boolean inhibitEmail = (Boolean)envContext.lookup("inhibitEmail");
String twilioAccountSID = (String)envContext.lookup("twilioAccountSID");
String twilioAuthToken = (String)envContext.lookup("twilioAuthToken");
TwilioRestClient twilioClient = new TwilioRestClient(twilioAccountSID, twilioAuthToken);
boolean inhibitSMS = (Boolean)envContext.lookup("inhibitSMS");
String SMSFrom = (String)envContext.lookup("SMSFrom");
try {
SMS = new TwilioSMSGatewayImpl(twilioClient, PhoneNumberUtil.getInstance().parse(SMSFrom, "US"), inhibitSMS,
backgroundDatabaseWriteExecutor, getDataSource());
} catch (NumberParseException pe) {
throw new RuntimeException(pe);
}
emailDispatcher = new EmailDispatcher(lookupMailProperties(envContext), inhibitEmail, backgroundExecutor);
logoURL = (String)envContext.lookup("logoURL");
mountPoint = (String)envContext.lookup("mountPoint");
clients = new ClientsImpl(getDataSource(), mountPoint);
projects = new ProjectsImpl(getDataSource(), organizationHierarchy, directory, this);
tasks = new TasksImpl(getDataSource(), getMountPoint(), projects);
timesheetEntries = new TimesheetEntriesImpl(getDataSource(), directory, tasks, mountPoint);
tickets = new TicketsImpl(getDataSource(), mountPoint);
events = new EventsImpl(getDataSource(), mountPoint);
vacations = new VacationsImpl(getDataSource(), directory);
outOfOffice = new OutOfOfficeEntriesImpl(getDataSource(), directory);
contacts = new ContactsImpl(getDataSource(), mountPoint);
timesheets = new TimesheetsImpl(this, mountPoint);
errors = new ErrorsImpl(getDataSource(), mountPoint, directory);
accessLog = new AccessLogImpl(getDataSource(), directory);
workdays = new WorkdaysImpl(holidays);
paidTimeOff = new PaidTimeOff(tasks);
laborProjections = new LaborProjectionsImpl(getDataSource(), directory, tasks, mountPoint);
taskAssignments = new TaskAssignmentsImpl(directory, getDataSource(), mountPoint);
defaultTaskAssignments = new DefaultTaskAssignmentsImpl(getDataSource(), tasks);
loginCookies = new LoginCookies(getDataSource(), timer);
locationLog = new LocationLogImpl(getDataSource(), directory, backgroundDatabaseWriteExecutor);
String keyStorePath = (String)envContext.lookup("keyStorePath");
String keyStorePassword = (String)envContext.lookup("keyStorePassword");
try {
System.err.println("starting XMPP server");
xmpp = new XMPPServerImpl(directory, new File(keyStorePath), keyStorePassword);
xmpp.start();
} catch (Exception e) {
System.err.println("trouble starting XMPP server");
e.printStackTrace();
}
} catch (NamingException ne) {
throw new RuntimeException(ne); // FIXME: Is this the best thing to throw here?
}
cronJobs = new CronJobs(timer, this, directory, emailDispatcher);
ServletContext servletContext = sce.getServletContext();
servletContext.setAttribute("sarariman", this);
servletContext.setAttribute("directory", directory);
cronJobs.start();
final String hostname = getHostname();
Runnable sendStartupEmailNotification = new Runnable() {
public void run() {
try {
for (Employee employee : getAdministrators()) {
String message = String.format("Sarariman version %s has been started on %s at %s.", getVersion(), hostname,
mountPoint);
emailDispatcher.send(employee.getEmail(), null, "sarariman started", message);
SMS.send(employee.getMobile(), "Sarariman has been started.");
}
} catch (Exception e) {
e.printStackTrace();
// FIXME: log
}
}
};
backgroundExecutor.execute(sendStartupEmailNotification);
}
|
diff --git a/NPlayer/src/main/java/fr/ribesg/bukkit/nplayer/NPlayer.java b/NPlayer/src/main/java/fr/ribesg/bukkit/nplayer/NPlayer.java
index e338c5a6..b5e0a4a9 100644
--- a/NPlayer/src/main/java/fr/ribesg/bukkit/nplayer/NPlayer.java
+++ b/NPlayer/src/main/java/fr/ribesg/bukkit/nplayer/NPlayer.java
@@ -1,186 +1,187 @@
package fr.ribesg.bukkit.nplayer;
import fr.ribesg.bukkit.ncore.node.player.PlayerNode;
import fr.ribesg.bukkit.nplayer.lang.Messages;
import fr.ribesg.bukkit.nplayer.punishment.PunishmentDb;
import fr.ribesg.bukkit.nplayer.punishment.PunishmentListener;
import fr.ribesg.bukkit.nplayer.user.LoggedOutUserHandler;
import fr.ribesg.bukkit.nplayer.user.UserDb;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.plugin.PluginManager;
import org.mcstats.Metrics;
import java.io.IOException;
public class NPlayer extends PlayerNode {
// Configs
private Messages messages;
private Config pluginConfig;
// Useful Nodes
// // None
// Plugin Data
private UserDb userDb;
private LoggedOutUserHandler loggedOutUserHandler;
private PunishmentDb punishmentDb;
@Override
protected String getMinCoreVersion() {
return "0.4.0";
}
@Override
public boolean onNodeEnable() {
// Messages first !
try {
if (!getDataFolder().isDirectory()) {
getDataFolder().mkdir();
}
messages = new Messages();
messages.loadMessages(this);
} catch (final IOException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load messages.yml");
return false;
}
// Config
try {
pluginConfig = new Config(this);
pluginConfig.loadConfig();
} catch (final IOException | InvalidConfigurationException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load config.yml");
return false;
}
loggedOutUserHandler = new LoggedOutUserHandler(this);
userDb = new UserDb(this);
try {
userDb.loadConfig();
} catch (IOException | InvalidConfigurationException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load userDB.yml");
return false;
}
punishmentDb = new PunishmentDb(this);
try {
punishmentDb.loadConfig();
} catch (IOException | InvalidConfigurationException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load punishmentDB.yml");
return false;
}
// Listener
final PluginManager pm = getServer().getPluginManager();
pm.registerEvents(loggedOutUserHandler, this);
pm.registerEvents(new PunishmentListener(this), this);
// Commands
final PlayerCommandHandler playerCommandHandler = new PlayerCommandHandler(this);
getCommand("login").setExecutor(playerCommandHandler);
getCommand("register").setExecutor(playerCommandHandler);
getCommand("logout").setExecutor(playerCommandHandler);
// TODO getCommand("info").setExecutor(playerCommandHandler);
getCommand("home").setExecutor(playerCommandHandler);
getCommand("sethome").setExecutor(playerCommandHandler);
+ getCommand("forcelogin").setExecutor(playerCommandHandler);
final PunishmentCommandHandler punishmentCommandHandler = new PunishmentCommandHandler(this);
getCommand("ban").setExecutor(punishmentCommandHandler);
getCommand("banip").setExecutor(punishmentCommandHandler);
getCommand("mute").setExecutor(punishmentCommandHandler);
getCommand("jail").setExecutor(punishmentCommandHandler);
getCommand("unban").setExecutor(punishmentCommandHandler);
getCommand("unbanip").setExecutor(punishmentCommandHandler);
getCommand("unmute").setExecutor(punishmentCommandHandler);
getCommand("unjail").setExecutor(punishmentCommandHandler);
getCommand("kick").setExecutor(punishmentCommandHandler);
// CommandHandler's Listeners
pm.registerEvents(playerCommandHandler, this);
// Metrics
final Metrics.Graph g = getMetrics().createGraph("Amount of Players");
g.addPlotter(new Metrics.Plotter("Registered") {
@Override
public int getValue() {
return getUserDb().size();
}
});
g.addPlotter(new Metrics.Plotter("Played in the last 2 weeks") {
@Override
public int getValue() {
return getUserDb().recurrentSize();
}
});
return true;
}
@Override
public void onNodeDisable() {
try {
getPluginConfig().writeConfig();
} catch (final IOException e) {
e.printStackTrace();
}
try {
userDb.saveConfig();
} catch (IOException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to save userDB.yml");
}
try {
punishmentDb.saveConfig();
} catch (IOException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to save punishmentDB.yml");
}
}
@Override
protected void linkCore() {
getCore().setPlayerNode(this);
}
/** @see fr.ribesg.bukkit.ncore.node.NPlugin#handleOtherNodes() */
@Override
protected void handleOtherNodes() {
// Nothing to do here for now
}
@Override
public Messages getMessages() {
return messages;
}
public Config getPluginConfig() {
return pluginConfig;
}
public UserDb getUserDb() {
return userDb;
}
public LoggedOutUserHandler getLoggedOutUserHandler() {
return loggedOutUserHandler;
}
public PunishmentDb getPunishmentDb() {
return punishmentDb;
}
}
| true | true | public boolean onNodeEnable() {
// Messages first !
try {
if (!getDataFolder().isDirectory()) {
getDataFolder().mkdir();
}
messages = new Messages();
messages.loadMessages(this);
} catch (final IOException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load messages.yml");
return false;
}
// Config
try {
pluginConfig = new Config(this);
pluginConfig.loadConfig();
} catch (final IOException | InvalidConfigurationException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load config.yml");
return false;
}
loggedOutUserHandler = new LoggedOutUserHandler(this);
userDb = new UserDb(this);
try {
userDb.loadConfig();
} catch (IOException | InvalidConfigurationException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load userDB.yml");
return false;
}
punishmentDb = new PunishmentDb(this);
try {
punishmentDb.loadConfig();
} catch (IOException | InvalidConfigurationException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load punishmentDB.yml");
return false;
}
// Listener
final PluginManager pm = getServer().getPluginManager();
pm.registerEvents(loggedOutUserHandler, this);
pm.registerEvents(new PunishmentListener(this), this);
// Commands
final PlayerCommandHandler playerCommandHandler = new PlayerCommandHandler(this);
getCommand("login").setExecutor(playerCommandHandler);
getCommand("register").setExecutor(playerCommandHandler);
getCommand("logout").setExecutor(playerCommandHandler);
// TODO getCommand("info").setExecutor(playerCommandHandler);
getCommand("home").setExecutor(playerCommandHandler);
getCommand("sethome").setExecutor(playerCommandHandler);
final PunishmentCommandHandler punishmentCommandHandler = new PunishmentCommandHandler(this);
getCommand("ban").setExecutor(punishmentCommandHandler);
getCommand("banip").setExecutor(punishmentCommandHandler);
getCommand("mute").setExecutor(punishmentCommandHandler);
getCommand("jail").setExecutor(punishmentCommandHandler);
getCommand("unban").setExecutor(punishmentCommandHandler);
getCommand("unbanip").setExecutor(punishmentCommandHandler);
getCommand("unmute").setExecutor(punishmentCommandHandler);
getCommand("unjail").setExecutor(punishmentCommandHandler);
getCommand("kick").setExecutor(punishmentCommandHandler);
// CommandHandler's Listeners
pm.registerEvents(playerCommandHandler, this);
// Metrics
final Metrics.Graph g = getMetrics().createGraph("Amount of Players");
g.addPlotter(new Metrics.Plotter("Registered") {
@Override
public int getValue() {
return getUserDb().size();
}
});
g.addPlotter(new Metrics.Plotter("Played in the last 2 weeks") {
@Override
public int getValue() {
return getUserDb().recurrentSize();
}
});
return true;
}
| public boolean onNodeEnable() {
// Messages first !
try {
if (!getDataFolder().isDirectory()) {
getDataFolder().mkdir();
}
messages = new Messages();
messages.loadMessages(this);
} catch (final IOException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load messages.yml");
return false;
}
// Config
try {
pluginConfig = new Config(this);
pluginConfig.loadConfig();
} catch (final IOException | InvalidConfigurationException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load config.yml");
return false;
}
loggedOutUserHandler = new LoggedOutUserHandler(this);
userDb = new UserDb(this);
try {
userDb.loadConfig();
} catch (IOException | InvalidConfigurationException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load userDB.yml");
return false;
}
punishmentDb = new PunishmentDb(this);
try {
punishmentDb.loadConfig();
} catch (IOException | InvalidConfigurationException e) {
getLogger().severe("An error occured, stacktrace follows:");
e.printStackTrace();
getLogger().severe("This error occured when NPlayer tried to load punishmentDB.yml");
return false;
}
// Listener
final PluginManager pm = getServer().getPluginManager();
pm.registerEvents(loggedOutUserHandler, this);
pm.registerEvents(new PunishmentListener(this), this);
// Commands
final PlayerCommandHandler playerCommandHandler = new PlayerCommandHandler(this);
getCommand("login").setExecutor(playerCommandHandler);
getCommand("register").setExecutor(playerCommandHandler);
getCommand("logout").setExecutor(playerCommandHandler);
// TODO getCommand("info").setExecutor(playerCommandHandler);
getCommand("home").setExecutor(playerCommandHandler);
getCommand("sethome").setExecutor(playerCommandHandler);
getCommand("forcelogin").setExecutor(playerCommandHandler);
final PunishmentCommandHandler punishmentCommandHandler = new PunishmentCommandHandler(this);
getCommand("ban").setExecutor(punishmentCommandHandler);
getCommand("banip").setExecutor(punishmentCommandHandler);
getCommand("mute").setExecutor(punishmentCommandHandler);
getCommand("jail").setExecutor(punishmentCommandHandler);
getCommand("unban").setExecutor(punishmentCommandHandler);
getCommand("unbanip").setExecutor(punishmentCommandHandler);
getCommand("unmute").setExecutor(punishmentCommandHandler);
getCommand("unjail").setExecutor(punishmentCommandHandler);
getCommand("kick").setExecutor(punishmentCommandHandler);
// CommandHandler's Listeners
pm.registerEvents(playerCommandHandler, this);
// Metrics
final Metrics.Graph g = getMetrics().createGraph("Amount of Players");
g.addPlotter(new Metrics.Plotter("Registered") {
@Override
public int getValue() {
return getUserDb().size();
}
});
g.addPlotter(new Metrics.Plotter("Played in the last 2 weeks") {
@Override
public int getValue() {
return getUserDb().recurrentSize();
}
});
return true;
}
|
diff --git a/XPathTestRunner/src/test/java/org/omg/bpmn/miwg/xpath/XPathTest.java b/XPathTestRunner/src/test/java/org/omg/bpmn/miwg/xpath/XPathTest.java
index f3c5f6da..670071e1 100644
--- a/XPathTestRunner/src/test/java/org/omg/bpmn/miwg/xpath/XPathTest.java
+++ b/XPathTestRunner/src/test/java/org/omg/bpmn/miwg/xpath/XPathTest.java
@@ -1,158 +1,158 @@
/**
* The MIT License (MIT)
* Copyright (c) 2013 OMG BPMN Model Interchange Working Group
*
*
* 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 org.omg.bpmn.miwg.xpath;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.omg.bpmn.miwg.xpathTestRunner.base.TestInfo;
import org.omg.bpmn.miwg.xpathTestRunner.base.TestOutput;
import org.omg.bpmn.miwg.xpathTestRunner.tests.B_1_0_Test;
import org.omg.bpmn.miwg.xpathTestRunner.tests.B_2_0_Test;
import org.omg.bpmn.miwg.xpathTestRunner.tests.ValidatorTest;
/**
*
* @author Tim Stephenson
*
*/
public class XPathTest {
private static final String S = File.separator;
private static final String RESOURCE_BASE_DIR = ".." + S + ".." + S
+ "bpmn-miwg-test-suite" + S;
private static final String A_DIR = "A - Fixed Digrams with Variations of Attributes";
private static final String B_DIR = "B - Validate that tool covers conformance class set";
private static final String RPT_DIR = "target" + S + "surefire-reports";
private static File baseDir;
private static File testADir;
private static File testBDir;
private static List<String> tools;
@BeforeClass
public static void setUp() throws Exception {
baseDir = new File(RESOURCE_BASE_DIR);
System.out.println("Looking for MIWG resources in: "
+ baseDir.getAbsolutePath());
testADir = new File(baseDir, A_DIR);
assertTrue("Dir does not exist at " + testADir.getAbsolutePath()
+ ", please ensure you have checked out the MIWG resources.",
testADir.exists());
testBDir = new File(baseDir, B_DIR);
assertTrue("Dir does not exist at " + testBDir.getAbsolutePath()
+ ", please ensure you have checked out the MIWG resources.",
testBDir.exists());
tools = new ArrayList<String>();
for (String dir : testADir.list()) {
if (!dir.equals("Reference") && !dir.startsWith(".")) {
tools.add(dir);
}
}
new File(RPT_DIR).mkdirs();
}
@Test
public void testSchemaValid() {
doTest(new ValidatorTest(), "B.1.0");
doTest(new ValidatorTest(), "B.2.0");
}
@Test
public void testB10() {
doTest(new B_1_0_Test(), "B.1.0");
}
@Test
public void testB20() {
doTest(new B_2_0_Test(), "B.2.0");
}
private void doTest(org.omg.bpmn.miwg.xpathTestRunner.testBase.Test test, String baseFileName) {
for (String tool : tools) {
- TestInfo info = new TestInfo(baseDir.getAbsolutePath()
- + testBDir.getName() + S, tool, baseFileName
+ TestInfo info = new TestInfo(baseDir.getAbsolutePath() + S
+ + testBDir.getName(), tool, baseFileName
+ "-roundtrip.bpmn");
TestOutput out = null;
try {
out = new TestOutput(test, info, RPT_DIR);
out.println("Running Tests for " + test.getName() + ":");
int numOK = 0;
int numIssue = 0;
if (test.isApplicable(info.getFile().getName())) {
out.println("> TEST " + test.getName());
try {
test.init(out);
test.execute(info.getFile().getAbsolutePath());
} catch (FileNotFoundException e) {
// Most likely this is because this tool has not
// provided a test file
out.println(e.getMessage());
} catch (Exception e) {
out.println("Exception during test execution of "
+ test.getName());
e.printStackTrace();
fail(e.getMessage());
} catch (Throwable e) {
e.printStackTrace();
fail(e.getMessage());
}
out.println();
out.println(" TEST " + test.getName() + " results:");
out.println(" * OK : " + test.ResultsOK());
out.println(" * ISSUES: " + test.ResultsIssue());
out.println();
numOK += test.ResultsOK();
numIssue += test.ResultsIssue();
} else {
fail("File to test is not applicable: "
+ info.getFile().getName());
}
} catch (IOException e) {
fail(e.getMessage());
} finally {
out.close();
}
}
}
}
| true | true | private void doTest(org.omg.bpmn.miwg.xpathTestRunner.testBase.Test test, String baseFileName) {
for (String tool : tools) {
TestInfo info = new TestInfo(baseDir.getAbsolutePath()
+ testBDir.getName() + S, tool, baseFileName
+ "-roundtrip.bpmn");
TestOutput out = null;
try {
out = new TestOutput(test, info, RPT_DIR);
out.println("Running Tests for " + test.getName() + ":");
int numOK = 0;
int numIssue = 0;
if (test.isApplicable(info.getFile().getName())) {
out.println("> TEST " + test.getName());
try {
test.init(out);
test.execute(info.getFile().getAbsolutePath());
} catch (FileNotFoundException e) {
// Most likely this is because this tool has not
// provided a test file
out.println(e.getMessage());
} catch (Exception e) {
out.println("Exception during test execution of "
+ test.getName());
e.printStackTrace();
fail(e.getMessage());
} catch (Throwable e) {
e.printStackTrace();
fail(e.getMessage());
}
out.println();
out.println(" TEST " + test.getName() + " results:");
out.println(" * OK : " + test.ResultsOK());
out.println(" * ISSUES: " + test.ResultsIssue());
out.println();
numOK += test.ResultsOK();
numIssue += test.ResultsIssue();
} else {
fail("File to test is not applicable: "
+ info.getFile().getName());
}
} catch (IOException e) {
fail(e.getMessage());
} finally {
out.close();
}
}
}
| private void doTest(org.omg.bpmn.miwg.xpathTestRunner.testBase.Test test, String baseFileName) {
for (String tool : tools) {
TestInfo info = new TestInfo(baseDir.getAbsolutePath() + S
+ testBDir.getName(), tool, baseFileName
+ "-roundtrip.bpmn");
TestOutput out = null;
try {
out = new TestOutput(test, info, RPT_DIR);
out.println("Running Tests for " + test.getName() + ":");
int numOK = 0;
int numIssue = 0;
if (test.isApplicable(info.getFile().getName())) {
out.println("> TEST " + test.getName());
try {
test.init(out);
test.execute(info.getFile().getAbsolutePath());
} catch (FileNotFoundException e) {
// Most likely this is because this tool has not
// provided a test file
out.println(e.getMessage());
} catch (Exception e) {
out.println("Exception during test execution of "
+ test.getName());
e.printStackTrace();
fail(e.getMessage());
} catch (Throwable e) {
e.printStackTrace();
fail(e.getMessage());
}
out.println();
out.println(" TEST " + test.getName() + " results:");
out.println(" * OK : " + test.ResultsOK());
out.println(" * ISSUES: " + test.ResultsIssue());
out.println();
numOK += test.ResultsOK();
numIssue += test.ResultsIssue();
} else {
fail("File to test is not applicable: "
+ info.getFile().getName());
}
} catch (IOException e) {
fail(e.getMessage());
} finally {
out.close();
}
}
}
|
diff --git a/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java b/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java
index e36d345ec..d7ebc2fd1 100644
--- a/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java
+++ b/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java
@@ -1,1001 +1,1000 @@
//
// ZeissLSMReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.*;
import java.util.*;
import loci.formats.*;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
/**
* ZeissLSMReader is the file format reader for Zeiss LSM files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java">SVN</a></dd></dl>
*
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert linkert at wisc.edu
* @author Curtis Rueden ctrueden at wisc.edu
*/
public class ZeissLSMReader extends BaseTiffReader {
// -- Constants --
public static final String[] MDB_SUFFIX = {"mdb"};
/** Tag identifying a Zeiss LSM file. */
private static final int ZEISS_ID = 34412;
/** Data types. */
private static final int TYPE_SUBBLOCK = 0;
private static final int TYPE_ASCII = 2;
private static final int TYPE_LONG = 4;
private static final int TYPE_RATIONAL = 5;
/** Subblock types. */
private static final int SUBBLOCK_RECORDING = 0x10000000;
private static final int SUBBLOCK_LASERS = 0x30000000;
private static final int SUBBLOCK_LASER = 0x50000000;
private static final int SUBBLOCK_TRACKS = 0x20000000;
private static final int SUBBLOCK_TRACK = 0x40000000;
private static final int SUBBLOCK_DETECTION_CHANNELS = 0x60000000;
private static final int SUBBLOCK_DETECTION_CHANNEL = 0x70000000;
private static final int SUBBLOCK_ILLUMINATION_CHANNELS = 0x80000000;
private static final int SUBBLOCK_ILLUMINATION_CHANNEL = 0x90000000;
private static final int SUBBLOCK_BEAM_SPLITTERS = 0xa0000000;
private static final int SUBBLOCK_BEAM_SPLITTER = 0xb0000000;
private static final int SUBBLOCK_DATA_CHANNELS = 0xc0000000;
private static final int SUBBLOCK_DATA_CHANNEL = 0xd0000000;
private static final int SUBBLOCK_TIMERS = 0x11000000;
private static final int SUBBLOCK_TIMER = 0x12000000;
private static final int SUBBLOCK_MARKERS = 0x13000000;
private static final int SUBBLOCK_MARKER = 0x14000000;
private static final int SUBBLOCK_END = (int) 0xffffffff;
private static final int SUBBLOCK_GAMMA = 1;
private static final int SUBBLOCK_BRIGHTNESS = 2;
private static final int SUBBLOCK_CONTRAST = 3;
private static final int SUBBLOCK_RAMP = 4;
private static final int SUBBLOCK_KNOTS = 5;
private static final int SUBBLOCK_PALETTE = 6;
/** Data types. */
private static final int RECORDING_ENTRY_DESCRIPTION = 0x10000002;
private static final int RECORDING_ENTRY_OBJECTIVE = 0x10000004;
private static final int TRACK_ENTRY_TIME_BETWEEN_STACKS = 0x4000000b;
private static final int LASER_ENTRY_NAME = 0x50000001;
private static final int CHANNEL_ENTRY_DETECTOR_GAIN = 0x70000003;
private static final int CHANNEL_ENTRY_PINHOLE_DIAMETER = 0x70000009;
private static final int CHANNEL_ENTRY_SPI_WAVELENGTH_START = 0x70000022;
private static final int CHANNEL_ENTRY_SPI_WAVELENGTH_END = 0x70000023;
private static final int ILLUM_CHANNEL_WAVELENGTH = 0x90000003;
private static final int START_TIME = 0x10000036;
private static final int DATA_CHANNEL_NAME = 0xd0000001;
// -- Static fields --
private static Hashtable metadataKeys = createKeys();
// -- Fields --
private double pixelSizeX, pixelSizeY, pixelSizeZ;
private boolean thumbnailsRemoved = false;
private byte[] lut = null;
private Vector timestamps;
private int validChannels;
private String mdbFilename;
// -- Constructor --
/** Constructs a new Zeiss LSM reader. */
public ZeissLSMReader() { super("Zeiss Laser-Scanning Microscopy", "lsm"); }
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
super.close();
pixelSizeX = pixelSizeY = pixelSizeZ = 0f;
lut = null;
thumbnailsRemoved = false;
timestamps = null;
validChannels = 0;
mdbFilename = null;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#getUsedFiles() */
public String[] getUsedFiles() {
FormatTools.assertId(currentId, true, 1);
if (mdbFilename == null) return super.getUsedFiles();
return new String[] {currentId, mdbFilename};
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (lut == null || getPixelType() != FormatTools.UINT8) return null;
byte[][] b = new byte[3][256];
for (int i=2; i>=3-validChannels; i--) {
for (int j=0; j<256; j++) {
b[i][j] = (byte) j;
}
}
return b;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (lut == null || getPixelType() != FormatTools.UINT16) return null;
short[][] s = new short[3][65536];
for (int i=2; i>=3-validChannels; i--) {
for (int j=0; j<s[i].length; j++) {
s[i][j] = (short) j;
}
}
return s;
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initMetadata() */
protected void initMetadata() {
if (!thumbnailsRemoved) return;
Hashtable ifd = ifds[0];
status("Reading LSM metadata");
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
try {
super.initStandardMetadata();
// get TIF_CZ_LSMINFO structure
short[] s = TiffTools.getIFDShortArray(ifd, ZEISS_ID, true);
byte[] cz = new byte[s.length];
for (int i=0; i<s.length; i++) {
cz[i] = (byte) s[i];
- if (cz[i] < 0) cz[i]++; // account for byte->short conversion
}
RandomAccessStream ras = new RandomAccessStream(cz);
ras.order(isLittleEndian());
put("MagicNumber", ras.readInt());
put("StructureSize", ras.readInt());
put("DimensionX", ras.readInt());
put("DimensionY", ras.readInt());
core[0].sizeZ = ras.readInt();
ras.skipBytes(4);
core[0].sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
put("DataType", "12 bit unsigned integer");
break;
case 5:
put("DataType", "32 bit float");
break;
case 0:
put("DataType", "varying data types");
break;
default:
put("DataType", "8 bit unsigned integer");
}
put("ThumbnailX", ras.readInt());
put("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
put("VoxelSizeX", new Double(pixelSizeX));
put("VoxelSizeY", new Double(pixelSizeY));
put("VoxelSizeZ", new Double(pixelSizeZ));
put("OriginX", ras.readDouble());
put("OriginY", ras.readDouble());
put("OriginZ", ras.readDouble());
int scanType = ras.readShort();
switch (scanType) {
case 0:
put("ScanType", "x-y-z scan");
core[0].dimensionOrder = "XYZCT";
break;
case 1:
put("ScanType", "z scan (x-z plane)");
core[0].dimensionOrder = "XYZCT";
break;
case 2:
put("ScanType", "line scan");
core[0].dimensionOrder = "XYZCT";
break;
case 3:
put("ScanType", "time series x-y");
core[0].dimensionOrder = "XYTCZ";
break;
case 4:
put("ScanType", "time series x-z");
core[0].dimensionOrder = "XYZTC";
break;
case 5:
put("ScanType", "time series 'Mean of ROIs'");
core[0].dimensionOrder = "XYTCZ";
break;
case 6:
put("ScanType", "time series x-y-z");
core[0].dimensionOrder = "XYZTC";
break;
case 7:
put("ScanType", "spline scan");
core[0].dimensionOrder = "XYCTZ";
break;
case 8:
put("ScanType", "spline scan x-z");
core[0].dimensionOrder = "XYCZT";
break;
case 9:
put("ScanType", "time series spline plane x-z");
core[0].dimensionOrder = "XYTCZ";
break;
case 10:
put("ScanType", "point mode");
core[0].dimensionOrder = "XYZCT";
break;
default:
put("ScanType", "x-y-z scan");
core[0].dimensionOrder = "XYZCT";
}
store.setImageName("", 0);
MetadataTools.setDefaultCreationDate(store, getCurrentFile(), 0);
int spectralScan = ras.readShort();
if (spectralScan != 1) put("SpectralScan", "no spectral scan");
else put("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
put("DataType2", "calculated data");
break;
case 2:
put("DataType2", "animation");
break;
default:
put("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
long channelColorsOffset = ras.readInt();
put("TimeInterval", ras.readDouble());
ras.skipBytes(4);
long scanInformationOffset = ras.readInt();
ras.skipBytes(4);
long timeStampOffset = ras.readInt();
long eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
put("DisplayAspectX", ras.readDouble());
put("DisplayAspectY", ras.readDouble());
put("DisplayAspectZ", ras.readDouble());
put("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(overlayOffsets[i], overlayKeys[i]);
}
put("ToolbarFlags", ras.readInt());
ras.close();
// read referenced structures
core[0].indexed = lut != null && getSizeC() == 1;
if (isIndexed()) {
core[0].sizeC = 1;
core[0].rgb = false;
}
if (getSizeC() == 0) core[0].sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
core[0].dimensionOrder = getDimensionOrder().replaceAll("C", "");
core[0].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
put("DimensionZ", getSizeZ());
put("DimensionChannels", getSizeC());
if (channelColorsOffset != 0) {
- in.seek(channelColorsOffset + 12);
+ in.seek(channelColorsOffset + 16);
int namesOffset = in.readInt();
// read in the intensity value for each color
if (namesOffset > 0) {
in.skipBytes(namesOffset - 16);
for (int i=0; i<getSizeC(); i++) {
if (in.getFilePointer() >= in.length() - 1) break;
// we want to read until we find a null char
String name = in.readCString();
if (name.length() <= 128) put("ChannelName" + i, name);
}
}
}
if (timeStampOffset != 0) {
if ((timeStampOffset % 2) == 1) in.seek(timeStampOffset + 7);
else in.seek(timeStampOffset - 248);
for (int i=0; i<getSizeT(); i++) {
double stamp = in.readDouble();
put("TimeStamp" + i, stamp);
timestamps.add(new Double(stamp));
}
}
if (eventListOffset != 0) {
in.seek(eventListOffset + 4);
int numEvents = in.readInt();
in.seek(in.getFilePointer() - 4);
in.order(!in.isLittleEndian());
int tmpEvents = in.readInt();
if (numEvents < 0) numEvents = tmpEvents;
else numEvents = (int) Math.min(numEvents, tmpEvents);
in.order(!in.isLittleEndian());
if (numEvents > 65535) numEvents = 0;
for (int i=0; i<numEvents; i++) {
if (in.getFilePointer() + 16 <= in.length()) {
int size = in.readInt();
double eventTime = in.readDouble();
int eventType = in.readInt();
put("Event" + i + " Time", eventTime);
put("Event" + i + " Type", eventType);
long fp = in.getFilePointer();
int len = size - 16;
if (len > 65536) len = 65536;
if (len < 0) len = 0;
put("Event" + i + " Description", in.readString(len));
in.seek(fp + size - 16);
if (in.getFilePointer() < 0) break;
}
}
}
if (scanInformationOffset != 0) {
in.seek(scanInformationOffset);
Stack prefix = new Stack();
int count = 1;
Object value = null;
boolean done = false;
int nextLaserMedium = 0, nextLaserType = 0, nextGain = 0;
int nextPinhole = 0, nextEmWave = 0, nextExWave = 0;
int nextChannelName = 0;
while (!done) {
int entry = in.readInt();
int blockType = in.readInt();
int dataSize = in.readInt();
switch (blockType) {
case TYPE_SUBBLOCK:
switch (entry) {
case SUBBLOCK_RECORDING:
prefix.push("Recording");
break;
case SUBBLOCK_LASERS:
prefix.push("Lasers");
break;
case SUBBLOCK_LASER:
prefix.push("Laser " + count);
count++;
break;
case SUBBLOCK_TRACKS:
prefix.push("Tracks");
break;
case SUBBLOCK_TRACK:
prefix.push("Track " + count);
count++;
break;
case SUBBLOCK_DETECTION_CHANNELS:
prefix.push("Detection Channels");
break;
case SUBBLOCK_DETECTION_CHANNEL:
prefix.push("Detection Channel " + count);
count++;
validChannels = count;
break;
case SUBBLOCK_ILLUMINATION_CHANNELS:
prefix.push("Illumination Channels");
break;
case SUBBLOCK_ILLUMINATION_CHANNEL:
prefix.push("Illumination Channel " + count);
count++;
break;
case SUBBLOCK_BEAM_SPLITTERS:
prefix.push("Beam Splitters");
break;
case SUBBLOCK_BEAM_SPLITTER:
prefix.push("Beam Splitter " + count);
count++;
break;
case SUBBLOCK_DATA_CHANNELS:
prefix.push("Data Channels");
break;
case SUBBLOCK_DATA_CHANNEL:
prefix.push("Data Channel " + count);
count++;
break;
case SUBBLOCK_TIMERS:
prefix.push("Timers");
break;
case SUBBLOCK_TIMER:
prefix.push("Timer " + count);
count++;
break;
case SUBBLOCK_MARKERS:
prefix.push("Markers");
break;
case SUBBLOCK_MARKER:
prefix.push("Marker " + count);
count++;
break;
case SUBBLOCK_END:
count = 1;
if (prefix.size() > 0) prefix.pop();
if (prefix.size() == 0) done = true;
break;
}
break;
case TYPE_LONG:
value = new Long(in.readInt());
break;
case TYPE_RATIONAL:
value = new Double(in.readDouble());
break;
case TYPE_ASCII:
value = in.readString(dataSize);
break;
}
String key = getKey(prefix, entry).trim();
if (value instanceof String) value = ((String) value).trim();
if (key != null) addMeta(key, value);
switch (entry) {
case RECORDING_ENTRY_DESCRIPTION:
store.setImageDescription(value.toString(), 0);
break;
case RECORDING_ENTRY_OBJECTIVE:
store.setObjectiveModel(value.toString(), 0, 0);
break;
case TRACK_ENTRY_TIME_BETWEEN_STACKS:
store.setDimensionsTimeIncrement(
new Float(value.toString()), 0, 0);
break;
case LASER_ENTRY_NAME:
String medium = value.toString();
String laserType = null;
if (medium.startsWith("HeNe")) {
medium = "HeNe";
laserType = "Gas";
}
else if (medium.startsWith("Argon")) {
medium = "Ar";
laserType = "Gas";
}
else if (medium.equals("Titanium:Sapphire") ||
medium.equals("Mai Tai"))
{
medium = "TiSapphire";
laserType = "SolidState";
}
else if (medium.equals("YAG")) {
medium = null;
laserType = "SolidState";
}
else if (medium.equals("Ar/Kr")) {
medium = null;
laserType = "Gas";
}
else if (medium.equals("Enterprise")) medium = null;
if (medium != null && laserType != null) {
store.setLaserLaserMedium(medium, 0, nextLaserMedium++);
store.setLaserType(laserType, 0, nextLaserType++);
}
break;
//case LASER_POWER:
// TODO: this is a setting, not a fixed value
// store.setLaserPower(new Float(value.toString()), 0, count - 1);
// break;
case CHANNEL_ENTRY_DETECTOR_GAIN:
//store.setDetectorSettingsGain(
// new Float(value.toString()), 0, nextGain++);
break;
case CHANNEL_ENTRY_PINHOLE_DIAMETER:
int n = (int) Float.parseFloat(value.toString());
if (n > 0 && nextPinhole < getSizeC()) {
store.setLogicalChannelPinholeSize(new Integer(n), 0,
nextPinhole++);
}
break;
case CHANNEL_ENTRY_SPI_WAVELENGTH_START:
n = (int) Float.parseFloat(value.toString());
store.setLogicalChannelEmWave(new Integer(n), 0,
(nextEmWave % getSizeC()));
nextEmWave++;
break;
case CHANNEL_ENTRY_SPI_WAVELENGTH_END:
n = (int) Float.parseFloat(value.toString());
store.setLogicalChannelExWave(new Integer(n), 0,
(nextExWave % getSizeC()));
nextExWave++;
break;
case ILLUM_CHANNEL_WAVELENGTH:
n = (int) Float.parseFloat(value.toString());
store.setLogicalChannelEmWave(new Integer(n), 0,
(nextEmWave % getSizeC()));
store.setLogicalChannelExWave(new Integer(n), 0,
(nextExWave % getSizeC()));
nextEmWave++;
nextExWave++;
break;
case START_TIME:
// date/time on which the first pixel was acquired, in days
// since 30 December 1899
double time = Double.parseDouble(value.toString());
store.setImageCreationDate(DataTools.convertDate(
(long) (time * 86400000), DataTools.MICROSOFT), 0);
break;
case DATA_CHANNEL_NAME:
store.setLogicalChannelName(value.toString(),
0, nextChannelName++);
break;
}
if (!done) done = in.getFilePointer() >= in.length() - 12;
}
}
}
catch (FormatException exc) {
if (debug) trace(exc);
}
catch (IOException exc) {
if (debug) trace(exc);
}
if (isIndexed()) core[0].rgb = false;
if (getEffectiveSizeC() == 0) core[0].imageCount = getSizeZ() * getSizeT();
else core[0].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
if (getImageCount() != ifds.length) {
int diff = getImageCount() - ifds.length;
core[0].imageCount = ifds.length;
if (diff % getSizeZ() == 0) {
core[0].sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
core[0].sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
core[0].sizeZ = ifds.length;
core[0].sizeT = 1;
}
else if (getSizeT() > 1) {
core[0].sizeT = ifds.length;
core[0].sizeZ = 1;
}
}
if (getSizeZ() == 0) core[0].sizeZ = getImageCount();
if (getSizeT() == 0) core[0].sizeT = getImageCount() / getSizeZ();
MetadataTools.populatePixels(store, this);
Float pixX = new Float((float) pixelSizeX);
Float pixY = new Float((float) pixelSizeY);
Float pixZ = new Float((float) pixelSizeZ);
store.setDimensionsPhysicalSizeX(pixX, 0, 0);
store.setDimensionsPhysicalSizeY(pixY, 0, 0);
store.setDimensionsPhysicalSizeZ(pixZ, 0, 0);
float firstStamp =
timestamps.size() == 0 ? 0f : ((Double) timestamps.get(0)).floatValue();
for (int i=0; i<getImageCount(); i++) {
int[] zct = FormatTools.getZCTCoords(this, i);
if (zct[2] < timestamps.size()) {
float thisStamp = ((Double) timestamps.get(zct[2])).floatValue();
store.setPlaneTimingDeltaT(new Float(thisStamp - firstStamp), 0, 0, i);
float nextStamp = i < getSizeT() - 1 ?
((Double) timestamps.get(zct[2] + 1)).floatValue() : thisStamp;
if (i == getSizeT() - 1 && zct[2] > 0) {
thisStamp = ((Double) timestamps.get(zct[2] - 1)).floatValue();
}
store.setPlaneTimingExposureTime(new Float(nextStamp - thisStamp),
0, 0, i);
}
}
// see if we have an associated MDB file
Location dir = new Location(currentId).getAbsoluteFile().getParentFile();
String[] dirList = dir.list();
for (int i=0; i<dirList.length; i++) {
if (checkSuffix(dirList[i], MDB_SUFFIX)) {
try {
Location file = new Location(dir.getPath(), dirList[i]);
if (!file.isDirectory()) {
mdbFilename = file.getAbsolutePath();
Vector[] tables = MDBParser.parseDatabase(mdbFilename);
for (int table=0; table<tables.length; table++) {
String[] columnNames = (String[]) tables[table].get(0);
for (int row=1; row<tables[table].size(); row++) {
String[] tableRow = (String[]) tables[table].get(row);
String baseKey = columnNames[0] + " ";
for (int col=0; col<tableRow.length; col++) {
addMeta(baseKey + columnNames[col + 1] + " " + row,
tableRow[col]);
}
}
}
}
}
catch (Exception exc) {
if (debug) trace(exc);
}
i = dirList.length;
}
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("ZeissLSMReader.initFile(" + id + ")");
thumbnailsRemoved = false;
super.initFile(id);
timestamps = new Vector();
// go through the IFD hashtable array and
// remove anything with NEW_SUBFILE_TYPE = 1
// NEW_SUBFILE_TYPE = 1 indicates that the IFD
// contains a thumbnail image
status("Removing thumbnails");
Vector newIFDs = new Vector();
for (int i=0; i<ifds.length; i++) {
long subFileType = TiffTools.getIFDLongValue(ifds[i],
TiffTools.NEW_SUBFILE_TYPE, true, 0);
if (subFileType == 0) {
// check that predictor is set to 1 if anything other
// than LZW compression is used
if (TiffTools.getCompression(ifds[i]) != TiffTools.LZW) {
ifds[i].put(new Integer(TiffTools.PREDICTOR), new Integer(1));
}
newIFDs.add(ifds[i]);
}
}
// reset numImages and ifds
ifds = (Hashtable[]) newIFDs.toArray(new Hashtable[0]);
thumbnailsRemoved = true;
initMetadata();
core[0].littleEndian = !isLittleEndian();
}
// -- Helper methods --
/** Parses overlay-related fields. */
protected void parseOverlays(long data, String suffix) throws IOException {
if (data == 0) return;
in.seek(data);
int nde = in.readInt();
put("NumberDrawingElements-" + suffix, nde);
int size = in.readInt();
int idata = in.readInt();
put("LineWidth-" + suffix, idata);
idata = in.readInt();
put("Measure-" + suffix, idata);
in.skipBytes(8);
put("ColorRed-" + suffix, in.read());
put("ColorGreen-" + suffix, in.read());
put("ColorBlue-" + suffix, in.read());
in.skipBytes(1);
put("Valid-" + suffix, in.readInt());
put("KnotWidth-" + suffix, in.readInt());
put("CatchArea-" + suffix, in.readInt());
// some fields describing the font
put("FontHeight-" + suffix, in.readInt());
put("FontWidth-" + suffix, in.readInt());
put("FontEscapement-" + suffix, in.readInt());
put("FontOrientation-" + suffix, in.readInt());
put("FontWeight-" + suffix, in.readInt());
put("FontItalic-" + suffix, in.readInt());
put("FontUnderline-" + suffix, in.readInt());
put("FontStrikeOut-" + suffix, in.readInt());
put("FontCharSet-" + suffix, in.readInt());
put("FontOutPrecision-" + suffix, in.readInt());
put("FontClipPrecision-" + suffix, in.readInt());
put("FontQuality-" + suffix, in.readInt());
put("FontPitchAndFamily-" + suffix, in.readInt());
put("FontFaceName-" + suffix, in.readString(64));
// some flags for measuring values of different drawing element types
put("ClosedPolyline-" + suffix, in.read());
put("OpenPolyline-" + suffix, in.read());
put("ClosedBezierCurve-" + suffix, in.read());
put("OpenBezierCurve-" + suffix, in.read());
put("ArrowWithClosedTip-" + suffix, in.read());
put("ArrowWithOpenTip-" + suffix, in.read());
put("Ellipse-" + suffix, in.read());
put("Circle-" + suffix, in.read());
put("Rectangle-" + suffix, in.read());
put("Line-" + suffix, in.read());
/*
try {
int drawingEl = (size - 194) / nde;
if (drawingEl <= 0) return;
if (DataTools.swap(nde) < nde) nde = DataTools.swap(nde);
for (int i=0; i<nde; i++) {
put("DrawingElement" + i + "-" + suffix, in.readString(drawingEl));
}
}
catch (ArithmeticException exc) {
if (debug) trace(exc);
}
*/
}
/** Construct a metadata key from the given stack. */
private String getKey(Stack stack, int entry) {
StringBuffer sb = new StringBuffer();
for (int i=0; i<stack.size(); i++) {
sb.append((String) stack.get(i));
sb.append("/");
}
sb.append(" - ");
sb.append(metadataKeys.get(new Integer(entry)));
return sb.toString();
}
private static Hashtable createKeys() {
Hashtable h = new Hashtable();
h.put(new Integer(0x10000001), "Name");
h.put(new Integer(0x4000000c), "Name");
h.put(new Integer(0x50000001), "Name");
h.put(new Integer(0x90000001), "Name");
h.put(new Integer(0x90000005), "Name");
h.put(new Integer(0xb0000003), "Name");
h.put(new Integer(0xd0000001), "Name");
h.put(new Integer(0x12000001), "Name");
h.put(new Integer(0x14000001), "Name");
h.put(new Integer(0x10000002), "Description");
h.put(new Integer(0x14000002), "Description");
h.put(new Integer(0x10000003), "Notes");
h.put(new Integer(0x10000004), "Objective");
h.put(new Integer(0x10000005), "Processing Summary");
h.put(new Integer(0x10000006), "Special Scan Mode");
h.put(new Integer(0x10000007), "Scan Type");
h.put(new Integer(0x10000008), "Scan Mode");
h.put(new Integer(0x10000009), "Number of Stacks");
h.put(new Integer(0x1000000a), "Lines Per Plane");
h.put(new Integer(0x1000000b), "Samples Per Line");
h.put(new Integer(0x1000000c), "Planes Per Volume");
h.put(new Integer(0x1000000d), "Images Width");
h.put(new Integer(0x1000000e), "Images Height");
h.put(new Integer(0x1000000f), "Number of Planes");
h.put(new Integer(0x10000010), "Number of Stacks");
h.put(new Integer(0x10000011), "Number of Channels");
h.put(new Integer(0x10000012), "Linescan XY Size");
h.put(new Integer(0x10000013), "Scan Direction");
h.put(new Integer(0x10000014), "Time Series");
h.put(new Integer(0x10000015), "Original Scan Data");
h.put(new Integer(0x10000016), "Zoom X");
h.put(new Integer(0x10000017), "Zoom Y");
h.put(new Integer(0x10000018), "Zoom Z");
h.put(new Integer(0x10000019), "Sample 0X");
h.put(new Integer(0x1000001a), "Sample 0Y");
h.put(new Integer(0x1000001b), "Sample 0Z");
h.put(new Integer(0x1000001c), "Sample Spacing");
h.put(new Integer(0x1000001d), "Line Spacing");
h.put(new Integer(0x1000001e), "Plane Spacing");
h.put(new Integer(0x1000001f), "Plane Width");
h.put(new Integer(0x10000020), "Plane Height");
h.put(new Integer(0x10000021), "Volume Depth");
h.put(new Integer(0x10000034), "Rotation");
h.put(new Integer(0x10000035), "Precession");
h.put(new Integer(0x10000036), "Sample 0Time");
h.put(new Integer(0x10000037), "Start Scan Trigger In");
h.put(new Integer(0x10000038), "Start Scan Trigger Out");
h.put(new Integer(0x10000039), "Start Scan Event");
h.put(new Integer(0x10000040), "Start Scan Time");
h.put(new Integer(0x10000041), "Stop Scan Trigger In");
h.put(new Integer(0x10000042), "Stop Scan Trigger Out");
h.put(new Integer(0x10000043), "Stop Scan Event");
h.put(new Integer(0x10000044), "Stop Scan Time");
h.put(new Integer(0x10000045), "Use ROIs");
h.put(new Integer(0x10000046), "Use Reduced Memory ROIs");
h.put(new Integer(0x10000047), "User");
h.put(new Integer(0x10000048), "Use B/C Correction");
h.put(new Integer(0x10000049), "Position B/C Contrast 1");
h.put(new Integer(0x10000050), "Position B/C Contrast 2");
h.put(new Integer(0x10000051), "Interpolation Y");
h.put(new Integer(0x10000052), "Camera Binning");
h.put(new Integer(0x10000053), "Camera Supersampling");
h.put(new Integer(0x10000054), "Camera Frame Width");
h.put(new Integer(0x10000055), "Camera Frame Height");
h.put(new Integer(0x10000056), "Camera Offset X");
h.put(new Integer(0x10000057), "Camera Offset Y");
h.put(new Integer(0x40000001), "Multiplex Type");
h.put(new Integer(0x40000002), "Multiplex Order");
h.put(new Integer(0x40000003), "Sampling Mode");
h.put(new Integer(0x40000004), "Sampling Method");
h.put(new Integer(0x40000005), "Sampling Number");
h.put(new Integer(0x40000006), "Acquire");
h.put(new Integer(0x50000002), "Acquire");
h.put(new Integer(0x7000000b), "Acquire");
h.put(new Integer(0x90000004), "Acquire");
h.put(new Integer(0xd0000017), "Acquire");
h.put(new Integer(0x40000007), "Sample Observation Time");
h.put(new Integer(0x40000008), "Time Between Stacks");
h.put(new Integer(0x4000000d), "Collimator 1 Name");
h.put(new Integer(0x4000000e), "Collimator 1 Position");
h.put(new Integer(0x4000000f), "Collimator 2 Name");
h.put(new Integer(0x40000010), "Collimator 2 Position");
h.put(new Integer(0x40000011), "Is Bleach Track");
h.put(new Integer(0x40000012), "Bleach After Scan Number");
h.put(new Integer(0x40000013), "Bleach Scan Number");
h.put(new Integer(0x40000014), "Trigger In");
h.put(new Integer(0x12000004), "Trigger In");
h.put(new Integer(0x14000003), "Trigger In");
h.put(new Integer(0x40000015), "Trigger Out");
h.put(new Integer(0x12000005), "Trigger Out");
h.put(new Integer(0x14000004), "Trigger Out");
h.put(new Integer(0x40000016), "Is Ratio Track");
h.put(new Integer(0x40000017), "Bleach Count");
h.put(new Integer(0x40000018), "SPI Center Wavelength");
h.put(new Integer(0x40000019), "Pixel Time");
h.put(new Integer(0x40000020), "ID Condensor Frontlens");
h.put(new Integer(0x40000021), "Condensor Frontlens");
h.put(new Integer(0x40000022), "ID Field Stop");
h.put(new Integer(0x40000023), "Field Stop Value");
h.put(new Integer(0x40000024), "ID Condensor Aperture");
h.put(new Integer(0x40000025), "Condensor Aperture");
h.put(new Integer(0x40000026), "ID Condensor Revolver");
h.put(new Integer(0x40000027), "Condensor Revolver");
h.put(new Integer(0x40000028), "ID Transmission Filter 1");
h.put(new Integer(0x40000029), "ID Transmission 1");
h.put(new Integer(0x40000030), "ID Transmission Filter 2");
h.put(new Integer(0x40000031), "ID Transmission 2");
h.put(new Integer(0x40000032), "Repeat Bleach");
h.put(new Integer(0x40000033), "Enable Spot Bleach Pos");
h.put(new Integer(0x40000034), "Spot Bleach Position X");
h.put(new Integer(0x40000035), "Spot Bleach Position Y");
h.put(new Integer(0x40000036), "Bleach Position Z");
h.put(new Integer(0x50000003), "Power");
h.put(new Integer(0x90000002), "Power");
h.put(new Integer(0x70000003), "Detector Gain");
h.put(new Integer(0x70000005), "Amplifier Gain");
h.put(new Integer(0x70000007), "Amplifier Offset");
h.put(new Integer(0x70000009), "Pinhole Diameter");
h.put(new Integer(0x7000000c), "Detector Name");
h.put(new Integer(0x7000000d), "Amplifier Name");
h.put(new Integer(0x7000000e), "Pinhole Name");
h.put(new Integer(0x7000000f), "Filter Set Name");
h.put(new Integer(0x70000010), "Filter Name");
h.put(new Integer(0x70000013), "Integrator Name");
h.put(new Integer(0x70000014), "Detection Channel Name");
h.put(new Integer(0x70000015), "Detector Gain B/C 1");
h.put(new Integer(0x70000016), "Detector Gain B/C 2");
h.put(new Integer(0x70000017), "Amplifier Gain B/C 1");
h.put(new Integer(0x70000018), "Amplifier Gain B/C 2");
h.put(new Integer(0x70000019), "Amplifier Offset B/C 1");
h.put(new Integer(0x70000020), "Amplifier Offset B/C 2");
h.put(new Integer(0x70000021), "Spectral Scan Channels");
h.put(new Integer(0x70000022), "SPI Wavelength Start");
h.put(new Integer(0x70000023), "SPI Wavelength End");
h.put(new Integer(0x70000026), "Dye Name");
h.put(new Integer(0xd0000014), "Dye Name");
h.put(new Integer(0x70000027), "Dye Folder");
h.put(new Integer(0xd0000015), "Dye Folder");
h.put(new Integer(0x90000003), "Wavelength");
h.put(new Integer(0x90000006), "Power B/C 1");
h.put(new Integer(0x90000007), "Power B/C 2");
h.put(new Integer(0xb0000001), "Filter Set");
h.put(new Integer(0xb0000002), "Filter");
h.put(new Integer(0xd0000004), "Color");
h.put(new Integer(0xd0000005), "Sample Type");
h.put(new Integer(0xd0000006), "Bits Per Sample");
h.put(new Integer(0xd0000007), "Ratio Type");
h.put(new Integer(0xd0000008), "Ratio Track 1");
h.put(new Integer(0xd0000009), "Ratio Track 2");
h.put(new Integer(0xd000000a), "Ratio Channel 1");
h.put(new Integer(0xd000000b), "Ratio Channel 2");
h.put(new Integer(0xd000000c), "Ratio Const. 1");
h.put(new Integer(0xd000000d), "Ratio Const. 2");
h.put(new Integer(0xd000000e), "Ratio Const. 3");
h.put(new Integer(0xd000000f), "Ratio Const. 4");
h.put(new Integer(0xd0000010), "Ratio Const. 5");
h.put(new Integer(0xd0000011), "Ratio Const. 6");
h.put(new Integer(0xd0000012), "Ratio First Images 1");
h.put(new Integer(0xd0000013), "Ratio First Images 2");
h.put(new Integer(0xd0000016), "Spectrum");
h.put(new Integer(0x12000003), "Interval");
return h;
}
}
| false | true | protected void initMetadata() {
if (!thumbnailsRemoved) return;
Hashtable ifd = ifds[0];
status("Reading LSM metadata");
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
try {
super.initStandardMetadata();
// get TIF_CZ_LSMINFO structure
short[] s = TiffTools.getIFDShortArray(ifd, ZEISS_ID, true);
byte[] cz = new byte[s.length];
for (int i=0; i<s.length; i++) {
cz[i] = (byte) s[i];
if (cz[i] < 0) cz[i]++; // account for byte->short conversion
}
RandomAccessStream ras = new RandomAccessStream(cz);
ras.order(isLittleEndian());
put("MagicNumber", ras.readInt());
put("StructureSize", ras.readInt());
put("DimensionX", ras.readInt());
put("DimensionY", ras.readInt());
core[0].sizeZ = ras.readInt();
ras.skipBytes(4);
core[0].sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
put("DataType", "12 bit unsigned integer");
break;
case 5:
put("DataType", "32 bit float");
break;
case 0:
put("DataType", "varying data types");
break;
default:
put("DataType", "8 bit unsigned integer");
}
put("ThumbnailX", ras.readInt());
put("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
put("VoxelSizeX", new Double(pixelSizeX));
put("VoxelSizeY", new Double(pixelSizeY));
put("VoxelSizeZ", new Double(pixelSizeZ));
put("OriginX", ras.readDouble());
put("OriginY", ras.readDouble());
put("OriginZ", ras.readDouble());
int scanType = ras.readShort();
switch (scanType) {
case 0:
put("ScanType", "x-y-z scan");
core[0].dimensionOrder = "XYZCT";
break;
case 1:
put("ScanType", "z scan (x-z plane)");
core[0].dimensionOrder = "XYZCT";
break;
case 2:
put("ScanType", "line scan");
core[0].dimensionOrder = "XYZCT";
break;
case 3:
put("ScanType", "time series x-y");
core[0].dimensionOrder = "XYTCZ";
break;
case 4:
put("ScanType", "time series x-z");
core[0].dimensionOrder = "XYZTC";
break;
case 5:
put("ScanType", "time series 'Mean of ROIs'");
core[0].dimensionOrder = "XYTCZ";
break;
case 6:
put("ScanType", "time series x-y-z");
core[0].dimensionOrder = "XYZTC";
break;
case 7:
put("ScanType", "spline scan");
core[0].dimensionOrder = "XYCTZ";
break;
case 8:
put("ScanType", "spline scan x-z");
core[0].dimensionOrder = "XYCZT";
break;
case 9:
put("ScanType", "time series spline plane x-z");
core[0].dimensionOrder = "XYTCZ";
break;
case 10:
put("ScanType", "point mode");
core[0].dimensionOrder = "XYZCT";
break;
default:
put("ScanType", "x-y-z scan");
core[0].dimensionOrder = "XYZCT";
}
store.setImageName("", 0);
MetadataTools.setDefaultCreationDate(store, getCurrentFile(), 0);
int spectralScan = ras.readShort();
if (spectralScan != 1) put("SpectralScan", "no spectral scan");
else put("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
put("DataType2", "calculated data");
break;
case 2:
put("DataType2", "animation");
break;
default:
put("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
long channelColorsOffset = ras.readInt();
put("TimeInterval", ras.readDouble());
ras.skipBytes(4);
long scanInformationOffset = ras.readInt();
ras.skipBytes(4);
long timeStampOffset = ras.readInt();
long eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
put("DisplayAspectX", ras.readDouble());
put("DisplayAspectY", ras.readDouble());
put("DisplayAspectZ", ras.readDouble());
put("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(overlayOffsets[i], overlayKeys[i]);
}
put("ToolbarFlags", ras.readInt());
ras.close();
// read referenced structures
core[0].indexed = lut != null && getSizeC() == 1;
if (isIndexed()) {
core[0].sizeC = 1;
core[0].rgb = false;
}
if (getSizeC() == 0) core[0].sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
core[0].dimensionOrder = getDimensionOrder().replaceAll("C", "");
core[0].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
put("DimensionZ", getSizeZ());
put("DimensionChannels", getSizeC());
if (channelColorsOffset != 0) {
in.seek(channelColorsOffset + 12);
int namesOffset = in.readInt();
// read in the intensity value for each color
if (namesOffset > 0) {
in.skipBytes(namesOffset - 16);
for (int i=0; i<getSizeC(); i++) {
if (in.getFilePointer() >= in.length() - 1) break;
// we want to read until we find a null char
String name = in.readCString();
if (name.length() <= 128) put("ChannelName" + i, name);
}
}
}
if (timeStampOffset != 0) {
if ((timeStampOffset % 2) == 1) in.seek(timeStampOffset + 7);
else in.seek(timeStampOffset - 248);
for (int i=0; i<getSizeT(); i++) {
double stamp = in.readDouble();
put("TimeStamp" + i, stamp);
timestamps.add(new Double(stamp));
}
}
if (eventListOffset != 0) {
in.seek(eventListOffset + 4);
int numEvents = in.readInt();
in.seek(in.getFilePointer() - 4);
in.order(!in.isLittleEndian());
int tmpEvents = in.readInt();
if (numEvents < 0) numEvents = tmpEvents;
else numEvents = (int) Math.min(numEvents, tmpEvents);
in.order(!in.isLittleEndian());
if (numEvents > 65535) numEvents = 0;
for (int i=0; i<numEvents; i++) {
if (in.getFilePointer() + 16 <= in.length()) {
int size = in.readInt();
double eventTime = in.readDouble();
int eventType = in.readInt();
put("Event" + i + " Time", eventTime);
put("Event" + i + " Type", eventType);
long fp = in.getFilePointer();
int len = size - 16;
if (len > 65536) len = 65536;
if (len < 0) len = 0;
put("Event" + i + " Description", in.readString(len));
in.seek(fp + size - 16);
if (in.getFilePointer() < 0) break;
}
}
}
if (scanInformationOffset != 0) {
in.seek(scanInformationOffset);
Stack prefix = new Stack();
int count = 1;
Object value = null;
boolean done = false;
int nextLaserMedium = 0, nextLaserType = 0, nextGain = 0;
int nextPinhole = 0, nextEmWave = 0, nextExWave = 0;
int nextChannelName = 0;
while (!done) {
int entry = in.readInt();
int blockType = in.readInt();
int dataSize = in.readInt();
switch (blockType) {
case TYPE_SUBBLOCK:
switch (entry) {
case SUBBLOCK_RECORDING:
prefix.push("Recording");
break;
case SUBBLOCK_LASERS:
prefix.push("Lasers");
break;
case SUBBLOCK_LASER:
prefix.push("Laser " + count);
count++;
break;
case SUBBLOCK_TRACKS:
prefix.push("Tracks");
break;
case SUBBLOCK_TRACK:
prefix.push("Track " + count);
count++;
break;
case SUBBLOCK_DETECTION_CHANNELS:
prefix.push("Detection Channels");
break;
case SUBBLOCK_DETECTION_CHANNEL:
prefix.push("Detection Channel " + count);
count++;
validChannels = count;
break;
case SUBBLOCK_ILLUMINATION_CHANNELS:
prefix.push("Illumination Channels");
break;
case SUBBLOCK_ILLUMINATION_CHANNEL:
prefix.push("Illumination Channel " + count);
count++;
break;
case SUBBLOCK_BEAM_SPLITTERS:
prefix.push("Beam Splitters");
break;
case SUBBLOCK_BEAM_SPLITTER:
prefix.push("Beam Splitter " + count);
count++;
break;
case SUBBLOCK_DATA_CHANNELS:
prefix.push("Data Channels");
break;
case SUBBLOCK_DATA_CHANNEL:
prefix.push("Data Channel " + count);
count++;
break;
case SUBBLOCK_TIMERS:
prefix.push("Timers");
break;
case SUBBLOCK_TIMER:
prefix.push("Timer " + count);
count++;
break;
case SUBBLOCK_MARKERS:
prefix.push("Markers");
break;
case SUBBLOCK_MARKER:
prefix.push("Marker " + count);
count++;
break;
case SUBBLOCK_END:
count = 1;
if (prefix.size() > 0) prefix.pop();
if (prefix.size() == 0) done = true;
break;
}
break;
case TYPE_LONG:
value = new Long(in.readInt());
break;
case TYPE_RATIONAL:
value = new Double(in.readDouble());
break;
case TYPE_ASCII:
value = in.readString(dataSize);
break;
}
String key = getKey(prefix, entry).trim();
if (value instanceof String) value = ((String) value).trim();
if (key != null) addMeta(key, value);
switch (entry) {
case RECORDING_ENTRY_DESCRIPTION:
store.setImageDescription(value.toString(), 0);
break;
case RECORDING_ENTRY_OBJECTIVE:
store.setObjectiveModel(value.toString(), 0, 0);
break;
case TRACK_ENTRY_TIME_BETWEEN_STACKS:
store.setDimensionsTimeIncrement(
new Float(value.toString()), 0, 0);
break;
case LASER_ENTRY_NAME:
String medium = value.toString();
String laserType = null;
if (medium.startsWith("HeNe")) {
medium = "HeNe";
laserType = "Gas";
}
else if (medium.startsWith("Argon")) {
medium = "Ar";
laserType = "Gas";
}
else if (medium.equals("Titanium:Sapphire") ||
medium.equals("Mai Tai"))
{
medium = "TiSapphire";
laserType = "SolidState";
}
else if (medium.equals("YAG")) {
medium = null;
laserType = "SolidState";
}
else if (medium.equals("Ar/Kr")) {
medium = null;
laserType = "Gas";
}
else if (medium.equals("Enterprise")) medium = null;
if (medium != null && laserType != null) {
store.setLaserLaserMedium(medium, 0, nextLaserMedium++);
store.setLaserType(laserType, 0, nextLaserType++);
}
break;
//case LASER_POWER:
// TODO: this is a setting, not a fixed value
// store.setLaserPower(new Float(value.toString()), 0, count - 1);
// break;
case CHANNEL_ENTRY_DETECTOR_GAIN:
//store.setDetectorSettingsGain(
// new Float(value.toString()), 0, nextGain++);
break;
case CHANNEL_ENTRY_PINHOLE_DIAMETER:
int n = (int) Float.parseFloat(value.toString());
if (n > 0 && nextPinhole < getSizeC()) {
store.setLogicalChannelPinholeSize(new Integer(n), 0,
nextPinhole++);
}
break;
case CHANNEL_ENTRY_SPI_WAVELENGTH_START:
n = (int) Float.parseFloat(value.toString());
store.setLogicalChannelEmWave(new Integer(n), 0,
(nextEmWave % getSizeC()));
nextEmWave++;
break;
case CHANNEL_ENTRY_SPI_WAVELENGTH_END:
n = (int) Float.parseFloat(value.toString());
store.setLogicalChannelExWave(new Integer(n), 0,
(nextExWave % getSizeC()));
nextExWave++;
break;
case ILLUM_CHANNEL_WAVELENGTH:
n = (int) Float.parseFloat(value.toString());
store.setLogicalChannelEmWave(new Integer(n), 0,
(nextEmWave % getSizeC()));
store.setLogicalChannelExWave(new Integer(n), 0,
(nextExWave % getSizeC()));
nextEmWave++;
nextExWave++;
break;
case START_TIME:
// date/time on which the first pixel was acquired, in days
// since 30 December 1899
double time = Double.parseDouble(value.toString());
store.setImageCreationDate(DataTools.convertDate(
(long) (time * 86400000), DataTools.MICROSOFT), 0);
break;
case DATA_CHANNEL_NAME:
store.setLogicalChannelName(value.toString(),
0, nextChannelName++);
break;
}
if (!done) done = in.getFilePointer() >= in.length() - 12;
}
}
}
catch (FormatException exc) {
if (debug) trace(exc);
}
catch (IOException exc) {
if (debug) trace(exc);
}
if (isIndexed()) core[0].rgb = false;
if (getEffectiveSizeC() == 0) core[0].imageCount = getSizeZ() * getSizeT();
else core[0].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
if (getImageCount() != ifds.length) {
int diff = getImageCount() - ifds.length;
core[0].imageCount = ifds.length;
if (diff % getSizeZ() == 0) {
core[0].sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
core[0].sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
core[0].sizeZ = ifds.length;
core[0].sizeT = 1;
}
else if (getSizeT() > 1) {
core[0].sizeT = ifds.length;
core[0].sizeZ = 1;
}
}
if (getSizeZ() == 0) core[0].sizeZ = getImageCount();
if (getSizeT() == 0) core[0].sizeT = getImageCount() / getSizeZ();
MetadataTools.populatePixels(store, this);
Float pixX = new Float((float) pixelSizeX);
Float pixY = new Float((float) pixelSizeY);
Float pixZ = new Float((float) pixelSizeZ);
store.setDimensionsPhysicalSizeX(pixX, 0, 0);
store.setDimensionsPhysicalSizeY(pixY, 0, 0);
store.setDimensionsPhysicalSizeZ(pixZ, 0, 0);
float firstStamp =
timestamps.size() == 0 ? 0f : ((Double) timestamps.get(0)).floatValue();
for (int i=0; i<getImageCount(); i++) {
int[] zct = FormatTools.getZCTCoords(this, i);
if (zct[2] < timestamps.size()) {
float thisStamp = ((Double) timestamps.get(zct[2])).floatValue();
store.setPlaneTimingDeltaT(new Float(thisStamp - firstStamp), 0, 0, i);
float nextStamp = i < getSizeT() - 1 ?
((Double) timestamps.get(zct[2] + 1)).floatValue() : thisStamp;
if (i == getSizeT() - 1 && zct[2] > 0) {
thisStamp = ((Double) timestamps.get(zct[2] - 1)).floatValue();
}
store.setPlaneTimingExposureTime(new Float(nextStamp - thisStamp),
0, 0, i);
}
}
// see if we have an associated MDB file
Location dir = new Location(currentId).getAbsoluteFile().getParentFile();
String[] dirList = dir.list();
for (int i=0; i<dirList.length; i++) {
if (checkSuffix(dirList[i], MDB_SUFFIX)) {
try {
Location file = new Location(dir.getPath(), dirList[i]);
if (!file.isDirectory()) {
mdbFilename = file.getAbsolutePath();
Vector[] tables = MDBParser.parseDatabase(mdbFilename);
for (int table=0; table<tables.length; table++) {
String[] columnNames = (String[]) tables[table].get(0);
for (int row=1; row<tables[table].size(); row++) {
String[] tableRow = (String[]) tables[table].get(row);
String baseKey = columnNames[0] + " ";
for (int col=0; col<tableRow.length; col++) {
addMeta(baseKey + columnNames[col + 1] + " " + row,
tableRow[col]);
}
}
}
}
}
catch (Exception exc) {
if (debug) trace(exc);
}
i = dirList.length;
}
}
}
| protected void initMetadata() {
if (!thumbnailsRemoved) return;
Hashtable ifd = ifds[0];
status("Reading LSM metadata");
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
try {
super.initStandardMetadata();
// get TIF_CZ_LSMINFO structure
short[] s = TiffTools.getIFDShortArray(ifd, ZEISS_ID, true);
byte[] cz = new byte[s.length];
for (int i=0; i<s.length; i++) {
cz[i] = (byte) s[i];
}
RandomAccessStream ras = new RandomAccessStream(cz);
ras.order(isLittleEndian());
put("MagicNumber", ras.readInt());
put("StructureSize", ras.readInt());
put("DimensionX", ras.readInt());
put("DimensionY", ras.readInt());
core[0].sizeZ = ras.readInt();
ras.skipBytes(4);
core[0].sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
put("DataType", "12 bit unsigned integer");
break;
case 5:
put("DataType", "32 bit float");
break;
case 0:
put("DataType", "varying data types");
break;
default:
put("DataType", "8 bit unsigned integer");
}
put("ThumbnailX", ras.readInt());
put("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
put("VoxelSizeX", new Double(pixelSizeX));
put("VoxelSizeY", new Double(pixelSizeY));
put("VoxelSizeZ", new Double(pixelSizeZ));
put("OriginX", ras.readDouble());
put("OriginY", ras.readDouble());
put("OriginZ", ras.readDouble());
int scanType = ras.readShort();
switch (scanType) {
case 0:
put("ScanType", "x-y-z scan");
core[0].dimensionOrder = "XYZCT";
break;
case 1:
put("ScanType", "z scan (x-z plane)");
core[0].dimensionOrder = "XYZCT";
break;
case 2:
put("ScanType", "line scan");
core[0].dimensionOrder = "XYZCT";
break;
case 3:
put("ScanType", "time series x-y");
core[0].dimensionOrder = "XYTCZ";
break;
case 4:
put("ScanType", "time series x-z");
core[0].dimensionOrder = "XYZTC";
break;
case 5:
put("ScanType", "time series 'Mean of ROIs'");
core[0].dimensionOrder = "XYTCZ";
break;
case 6:
put("ScanType", "time series x-y-z");
core[0].dimensionOrder = "XYZTC";
break;
case 7:
put("ScanType", "spline scan");
core[0].dimensionOrder = "XYCTZ";
break;
case 8:
put("ScanType", "spline scan x-z");
core[0].dimensionOrder = "XYCZT";
break;
case 9:
put("ScanType", "time series spline plane x-z");
core[0].dimensionOrder = "XYTCZ";
break;
case 10:
put("ScanType", "point mode");
core[0].dimensionOrder = "XYZCT";
break;
default:
put("ScanType", "x-y-z scan");
core[0].dimensionOrder = "XYZCT";
}
store.setImageName("", 0);
MetadataTools.setDefaultCreationDate(store, getCurrentFile(), 0);
int spectralScan = ras.readShort();
if (spectralScan != 1) put("SpectralScan", "no spectral scan");
else put("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
put("DataType2", "calculated data");
break;
case 2:
put("DataType2", "animation");
break;
default:
put("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
long channelColorsOffset = ras.readInt();
put("TimeInterval", ras.readDouble());
ras.skipBytes(4);
long scanInformationOffset = ras.readInt();
ras.skipBytes(4);
long timeStampOffset = ras.readInt();
long eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
put("DisplayAspectX", ras.readDouble());
put("DisplayAspectY", ras.readDouble());
put("DisplayAspectZ", ras.readDouble());
put("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(overlayOffsets[i], overlayKeys[i]);
}
put("ToolbarFlags", ras.readInt());
ras.close();
// read referenced structures
core[0].indexed = lut != null && getSizeC() == 1;
if (isIndexed()) {
core[0].sizeC = 1;
core[0].rgb = false;
}
if (getSizeC() == 0) core[0].sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
core[0].dimensionOrder = getDimensionOrder().replaceAll("C", "");
core[0].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
put("DimensionZ", getSizeZ());
put("DimensionChannels", getSizeC());
if (channelColorsOffset != 0) {
in.seek(channelColorsOffset + 16);
int namesOffset = in.readInt();
// read in the intensity value for each color
if (namesOffset > 0) {
in.skipBytes(namesOffset - 16);
for (int i=0; i<getSizeC(); i++) {
if (in.getFilePointer() >= in.length() - 1) break;
// we want to read until we find a null char
String name = in.readCString();
if (name.length() <= 128) put("ChannelName" + i, name);
}
}
}
if (timeStampOffset != 0) {
if ((timeStampOffset % 2) == 1) in.seek(timeStampOffset + 7);
else in.seek(timeStampOffset - 248);
for (int i=0; i<getSizeT(); i++) {
double stamp = in.readDouble();
put("TimeStamp" + i, stamp);
timestamps.add(new Double(stamp));
}
}
if (eventListOffset != 0) {
in.seek(eventListOffset + 4);
int numEvents = in.readInt();
in.seek(in.getFilePointer() - 4);
in.order(!in.isLittleEndian());
int tmpEvents = in.readInt();
if (numEvents < 0) numEvents = tmpEvents;
else numEvents = (int) Math.min(numEvents, tmpEvents);
in.order(!in.isLittleEndian());
if (numEvents > 65535) numEvents = 0;
for (int i=0; i<numEvents; i++) {
if (in.getFilePointer() + 16 <= in.length()) {
int size = in.readInt();
double eventTime = in.readDouble();
int eventType = in.readInt();
put("Event" + i + " Time", eventTime);
put("Event" + i + " Type", eventType);
long fp = in.getFilePointer();
int len = size - 16;
if (len > 65536) len = 65536;
if (len < 0) len = 0;
put("Event" + i + " Description", in.readString(len));
in.seek(fp + size - 16);
if (in.getFilePointer() < 0) break;
}
}
}
if (scanInformationOffset != 0) {
in.seek(scanInformationOffset);
Stack prefix = new Stack();
int count = 1;
Object value = null;
boolean done = false;
int nextLaserMedium = 0, nextLaserType = 0, nextGain = 0;
int nextPinhole = 0, nextEmWave = 0, nextExWave = 0;
int nextChannelName = 0;
while (!done) {
int entry = in.readInt();
int blockType = in.readInt();
int dataSize = in.readInt();
switch (blockType) {
case TYPE_SUBBLOCK:
switch (entry) {
case SUBBLOCK_RECORDING:
prefix.push("Recording");
break;
case SUBBLOCK_LASERS:
prefix.push("Lasers");
break;
case SUBBLOCK_LASER:
prefix.push("Laser " + count);
count++;
break;
case SUBBLOCK_TRACKS:
prefix.push("Tracks");
break;
case SUBBLOCK_TRACK:
prefix.push("Track " + count);
count++;
break;
case SUBBLOCK_DETECTION_CHANNELS:
prefix.push("Detection Channels");
break;
case SUBBLOCK_DETECTION_CHANNEL:
prefix.push("Detection Channel " + count);
count++;
validChannels = count;
break;
case SUBBLOCK_ILLUMINATION_CHANNELS:
prefix.push("Illumination Channels");
break;
case SUBBLOCK_ILLUMINATION_CHANNEL:
prefix.push("Illumination Channel " + count);
count++;
break;
case SUBBLOCK_BEAM_SPLITTERS:
prefix.push("Beam Splitters");
break;
case SUBBLOCK_BEAM_SPLITTER:
prefix.push("Beam Splitter " + count);
count++;
break;
case SUBBLOCK_DATA_CHANNELS:
prefix.push("Data Channels");
break;
case SUBBLOCK_DATA_CHANNEL:
prefix.push("Data Channel " + count);
count++;
break;
case SUBBLOCK_TIMERS:
prefix.push("Timers");
break;
case SUBBLOCK_TIMER:
prefix.push("Timer " + count);
count++;
break;
case SUBBLOCK_MARKERS:
prefix.push("Markers");
break;
case SUBBLOCK_MARKER:
prefix.push("Marker " + count);
count++;
break;
case SUBBLOCK_END:
count = 1;
if (prefix.size() > 0) prefix.pop();
if (prefix.size() == 0) done = true;
break;
}
break;
case TYPE_LONG:
value = new Long(in.readInt());
break;
case TYPE_RATIONAL:
value = new Double(in.readDouble());
break;
case TYPE_ASCII:
value = in.readString(dataSize);
break;
}
String key = getKey(prefix, entry).trim();
if (value instanceof String) value = ((String) value).trim();
if (key != null) addMeta(key, value);
switch (entry) {
case RECORDING_ENTRY_DESCRIPTION:
store.setImageDescription(value.toString(), 0);
break;
case RECORDING_ENTRY_OBJECTIVE:
store.setObjectiveModel(value.toString(), 0, 0);
break;
case TRACK_ENTRY_TIME_BETWEEN_STACKS:
store.setDimensionsTimeIncrement(
new Float(value.toString()), 0, 0);
break;
case LASER_ENTRY_NAME:
String medium = value.toString();
String laserType = null;
if (medium.startsWith("HeNe")) {
medium = "HeNe";
laserType = "Gas";
}
else if (medium.startsWith("Argon")) {
medium = "Ar";
laserType = "Gas";
}
else if (medium.equals("Titanium:Sapphire") ||
medium.equals("Mai Tai"))
{
medium = "TiSapphire";
laserType = "SolidState";
}
else if (medium.equals("YAG")) {
medium = null;
laserType = "SolidState";
}
else if (medium.equals("Ar/Kr")) {
medium = null;
laserType = "Gas";
}
else if (medium.equals("Enterprise")) medium = null;
if (medium != null && laserType != null) {
store.setLaserLaserMedium(medium, 0, nextLaserMedium++);
store.setLaserType(laserType, 0, nextLaserType++);
}
break;
//case LASER_POWER:
// TODO: this is a setting, not a fixed value
// store.setLaserPower(new Float(value.toString()), 0, count - 1);
// break;
case CHANNEL_ENTRY_DETECTOR_GAIN:
//store.setDetectorSettingsGain(
// new Float(value.toString()), 0, nextGain++);
break;
case CHANNEL_ENTRY_PINHOLE_DIAMETER:
int n = (int) Float.parseFloat(value.toString());
if (n > 0 && nextPinhole < getSizeC()) {
store.setLogicalChannelPinholeSize(new Integer(n), 0,
nextPinhole++);
}
break;
case CHANNEL_ENTRY_SPI_WAVELENGTH_START:
n = (int) Float.parseFloat(value.toString());
store.setLogicalChannelEmWave(new Integer(n), 0,
(nextEmWave % getSizeC()));
nextEmWave++;
break;
case CHANNEL_ENTRY_SPI_WAVELENGTH_END:
n = (int) Float.parseFloat(value.toString());
store.setLogicalChannelExWave(new Integer(n), 0,
(nextExWave % getSizeC()));
nextExWave++;
break;
case ILLUM_CHANNEL_WAVELENGTH:
n = (int) Float.parseFloat(value.toString());
store.setLogicalChannelEmWave(new Integer(n), 0,
(nextEmWave % getSizeC()));
store.setLogicalChannelExWave(new Integer(n), 0,
(nextExWave % getSizeC()));
nextEmWave++;
nextExWave++;
break;
case START_TIME:
// date/time on which the first pixel was acquired, in days
// since 30 December 1899
double time = Double.parseDouble(value.toString());
store.setImageCreationDate(DataTools.convertDate(
(long) (time * 86400000), DataTools.MICROSOFT), 0);
break;
case DATA_CHANNEL_NAME:
store.setLogicalChannelName(value.toString(),
0, nextChannelName++);
break;
}
if (!done) done = in.getFilePointer() >= in.length() - 12;
}
}
}
catch (FormatException exc) {
if (debug) trace(exc);
}
catch (IOException exc) {
if (debug) trace(exc);
}
if (isIndexed()) core[0].rgb = false;
if (getEffectiveSizeC() == 0) core[0].imageCount = getSizeZ() * getSizeT();
else core[0].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
if (getImageCount() != ifds.length) {
int diff = getImageCount() - ifds.length;
core[0].imageCount = ifds.length;
if (diff % getSizeZ() == 0) {
core[0].sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
core[0].sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
core[0].sizeZ = ifds.length;
core[0].sizeT = 1;
}
else if (getSizeT() > 1) {
core[0].sizeT = ifds.length;
core[0].sizeZ = 1;
}
}
if (getSizeZ() == 0) core[0].sizeZ = getImageCount();
if (getSizeT() == 0) core[0].sizeT = getImageCount() / getSizeZ();
MetadataTools.populatePixels(store, this);
Float pixX = new Float((float) pixelSizeX);
Float pixY = new Float((float) pixelSizeY);
Float pixZ = new Float((float) pixelSizeZ);
store.setDimensionsPhysicalSizeX(pixX, 0, 0);
store.setDimensionsPhysicalSizeY(pixY, 0, 0);
store.setDimensionsPhysicalSizeZ(pixZ, 0, 0);
float firstStamp =
timestamps.size() == 0 ? 0f : ((Double) timestamps.get(0)).floatValue();
for (int i=0; i<getImageCount(); i++) {
int[] zct = FormatTools.getZCTCoords(this, i);
if (zct[2] < timestamps.size()) {
float thisStamp = ((Double) timestamps.get(zct[2])).floatValue();
store.setPlaneTimingDeltaT(new Float(thisStamp - firstStamp), 0, 0, i);
float nextStamp = i < getSizeT() - 1 ?
((Double) timestamps.get(zct[2] + 1)).floatValue() : thisStamp;
if (i == getSizeT() - 1 && zct[2] > 0) {
thisStamp = ((Double) timestamps.get(zct[2] - 1)).floatValue();
}
store.setPlaneTimingExposureTime(new Float(nextStamp - thisStamp),
0, 0, i);
}
}
// see if we have an associated MDB file
Location dir = new Location(currentId).getAbsoluteFile().getParentFile();
String[] dirList = dir.list();
for (int i=0; i<dirList.length; i++) {
if (checkSuffix(dirList[i], MDB_SUFFIX)) {
try {
Location file = new Location(dir.getPath(), dirList[i]);
if (!file.isDirectory()) {
mdbFilename = file.getAbsolutePath();
Vector[] tables = MDBParser.parseDatabase(mdbFilename);
for (int table=0; table<tables.length; table++) {
String[] columnNames = (String[]) tables[table].get(0);
for (int row=1; row<tables[table].size(); row++) {
String[] tableRow = (String[]) tables[table].get(row);
String baseKey = columnNames[0] + " ";
for (int col=0; col<tableRow.length; col++) {
addMeta(baseKey + columnNames[col + 1] + " " + row,
tableRow[col]);
}
}
}
}
}
catch (Exception exc) {
if (debug) trace(exc);
}
i = dirList.length;
}
}
}
|
diff --git a/src/java/com/idega/block/cal/presentation/CalendarView.java b/src/java/com/idega/block/cal/presentation/CalendarView.java
index 9cf384f..0a1f214 100644
--- a/src/java/com/idega/block/cal/presentation/CalendarView.java
+++ b/src/java/com/idega/block/cal/presentation/CalendarView.java
@@ -1,1315 +1,1315 @@
/*
* Created on Jan 16, 2004
*/
package com.idega.block.cal.presentation;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import com.idega.block.cal.business.CalBusiness;
import com.idega.block.cal.data.CalendarEntry;
import com.idega.block.cal.data.CalendarLedger;
import com.idega.idegaweb.IWApplicationContext;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.idegaweb.presentation.CalendarParameters;
import com.idega.idegaweb.presentation.SmallCalendar;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.Image;
import com.idega.presentation.Layer;
import com.idega.presentation.Page;
import com.idega.presentation.Table;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.GenericButton;
import com.idega.presentation.ui.StyledButton;
import com.idega.user.business.UserBusiness;
import com.idega.user.data.Group;
import com.idega.user.data.User;
import com.idega.util.IWCalendar;
import com.idega.util.IWTimestamp;
/**
* Description: <br>
* Copyright: Idega Software 2004 <br>
* Company: Idega Software <br>
* @author <a href="mailto:[email protected]">Birna Iris Jonsdottir</a>
*/
public class CalendarView extends Block{
private final static String IW_BUNDLE_IDENTIFIER = "com.idega.block.cal";
private int view = CalendarParameters.MONTH;
private final static String PARAMETER_ISI_GROUP_ID = "group_id";
private IWTimestamp now = null;
private IWTimestamp timeStamp = null;
private IWCalendar cal = null;
private int beginHour = 6;
private int endHour = 24;
private String borderWhiteTableStyle = "borderAllWhite";
private String mainTableStyle = "main";
private String menuTableStyle = "menu";
private String borderLeftTopRight = "borderLeftTopRight";
private String styledLink = "styledLink";
private String entryLink = "entryLink";
private String entryLinkActive = "entryLinkActive";
private String bold = "bold";
private String headline ="headline";
private String ledgerListStyle = "ledgerList";
public static String ACTION = "action";
public static String OPEN = "open";
public static String CLOSE = "close";
private String action = null;
private CalBusiness calBiz;
private int userID = -1;
private int groupID = -2;
private boolean isPrintable = false;
public boolean adminOnTop = true;
public CalendarView() {
}
public String getCategoryType() {
return "";
}
public boolean getMultible() {
return true;
}
/**
* draws the day view of the CalendarView
* By default the day view varies from 8:00 until 17:00
* but can be changed via setBeginHour(int hour) and setEndHour(int hour)
*/
private Table dayView(IWContext iwc, IWTimestamp stamp) {
//row is 2 because in the first row info on the day (name etc. are printed)
int row = 1;
now = new IWTimestamp();
Table backTable = new Table();
backTable.setColor("#cccccc");
backTable.setCellspacing(1);
backTable.setCellpadding(0);
backTable.setWidth(Table.HUNDRED_PERCENT);//500
backTable.setHeight(400);
/* backTable.mergeCells(1,1,2,1);
backTable.add(headTable,1,1);
*/
//the outer for-loop goes through the hours and prints out
//the style for each cell,
//the entrylist for each hour
for(int i=beginHour;i<=endHour;i++) {
backTable.setHeight(1,row,40);
backTable.setHeight(2,row,40);
backTable.setWidth(1,row,40);
Table dayTable = new Table();
dayTable.setCellspacing(0);
dayTable.setCellpadding(0);
dayTable.setWidth(Table.HUNDRED_PERCENT);
dayTable.setHeight(Table.HUNDRED_PERCENT);
Table entryTable = new Table();
entryTable.setCellspacing(0);
entryTable.setCellpadding(0);
entryTable.setWidth(Table.HUNDRED_PERCENT);
entryTable.setHeight(Table.HUNDRED_PERCENT);
entryTable.setColor(1,1,"#ffffff");
entryTable.setColor(1,2,"#f9f9f9");
entryTable.setStyleClass(1,2,"borderTop");
entryTable.setHeight(1,1,18);
entryTable.setHeight(1,2,18);
now.setTime(i,0,0);
Text timeText = new Text(now.getDateString("HH:mm",iwc.getCurrentLocale()));
timeText.setBold();
dayTable.add(timeText,1,1);
dayTable.setAlignment(1,1,Table.HORIZONTAL_ALIGN_CENTER);
dayTable.setColor(1,1,"#ffffff");
backTable.add(dayTable,1,row);
Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
fromStamp.setHours(beginHour);
fromStamp.setMinutes(0);
fromStamp.setNanos(0);
Timestamp toStamp =Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
toStamp.setHours(endHour);
toStamp.setMinutes(0);
toStamp.setNanos(0);
List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp);
User user = null;
Integer userID = null;
if(iwc.isLoggedOn()) {
user = iwc.getCurrentUser();
userID = (Integer) user.getPrimaryKey();
}
//the inner for-loop goes through the list of entries and prints them out as a link
//the link opens the view for the entry
int numberOfEntries = listOfEntries.size();
for(int j=0; j<numberOfEntries; j++) {
CalendarEntry entry = (CalendarEntry) listOfEntries.get(j);
if(entry==null) {
//fucked up check
continue;
}
CalendarLedger ledger = null;
int groupIDInLedger = -1;
boolean isInGroup = false;
//get a collection of groups the current user may view
Collection viewGroups = null;
if(user != null) {
try {
viewGroups = getUserBusiness(iwc).getUserGroups(user);
}catch(Exception e) {
e.printStackTrace();
}
}
if(entry.getLedgerID() != -1) {
ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID());
if(ledger != null) {
groupIDInLedger = ledger.getGroupID();
}
}
else {
groupIDInLedger = -1;
}
if(viewGroups != null) {
Iterator viewGroupsIter = viewGroups.iterator();
//goes through the groups the user may view and prints out the entry if
//the group connected to the entry is the same as the group the user may view
while(viewGroupsIter.hasNext()) {
Group group =(Group) viewGroupsIter.next();
Integer groupID = (Integer) group.getPrimaryKey();
if(entry.getGroupID() == groupID.intValue()
|| groupIDInLedger == groupID.intValue()) {
isInGroup = true;
}
}
}
if(groupIDInLedger == getViewGroupID()) {
isInGroup = true;
}
if(isInGroup || iwc.isSuperAdmin() ||
getViewGroupID() == entry.getGroupID() ||
(userID!=null && userID.intValue() == entry.getUserID())) {
Timestamp fStamp = entry.getDate();
Timestamp tStamp = entry.getEndDate();
//i is the current hour
if(i <= tStamp.getHours() && i >= fStamp.getHours()) {
entry.getGroupID();
String headline = getEntryHeadline(entry);
Link headlineLink = new Link(headline);
headlineLink.addParameter(ACTION,OPEN);
headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view);
headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear());
headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth());
headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay());
headlineLink.addParameter("entryID", entry.getPrimaryKey().toString());
if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc) || isPrintable) {
headlineLink.setWindowToOpen(EntryInfoWindow.class);
}
headlineLink.setStyleClass(entryLink);
if(i == fStamp.getHours()) {
if(fStamp.getMinutes() >= 30) {
entryTable.add(headlineLink,1,2);
}
else {
entryTable.add(headlineLink,1,1);
entryTable.add(headlineLink,1,2);
}
}
else if(i == tStamp.getHours()) {
if(tStamp.getMinutes() >= 30) {
entryTable.add(headlineLink,1,1);
entryTable.add(headlineLink,1,2);
}
else {
entryTable.add(headlineLink,1,1);
}
}
else {
entryTable.add(headlineLink,1,1);
entryTable.add(headlineLink,1,2);
}
entryTable.add(Text.BREAK,1,1);
entryTable.add(Text.BREAK,1,2);
}
}
}
backTable.add(entryTable,2,row);
row++;
}
return backTable;
}
/**
* draws the week view of the CalendarView
* By default the week view varies from 8:00 until 17:00
* but can be changed via setBeginHour(int hour) and setEndHour(int hour)
*/
private Table weekView(IWContext iwc,IWTimestamp stamp) {
int row = 1;
int column = 1;
int day = 0;
/*
* now holds the current time
*/
now = new IWTimestamp();
Table backTable = new Table();
backTable.setColor("#cccccc");
backTable.setCellspacing(1);
backTable.setCellpadding(0);
backTable.setWidth(500);
backTable.setHeight(400);
/*
* timeStamp is used to traverse trough the week
*/
// IWTimestamp tStamp = new IWTimestamp();
cal = new IWCalendar();
Text nameOfDay = new Text();
/* backTable.mergeCells(1,1,8,1);
backTable.add(headTable,1,1);
*/ int weekdays = 8;
int weekday = cal.getDayOfWeek(now.getYear(),now.getMonth(),now.getDay());
int today = stamp.getDay();
/*
* The outer for-loop runs through the columns of the weekTable
* the weekdays
*/
for(int i=0;i<weekdays; i++) {
row = 2;
/*
* The inner for-loop runs through the rows of the weekTable
* the hours
*/
for(int j=beginHour;j<=endHour;j++) {
Table weekTable = new Table();
weekTable.setWidth("100%");
weekTable.setHeight("100%");
weekTable.setColor("#ffffff");
weekTable.setCellpadding(1);
weekTable.setCellspacing(0);
if(column == 1 && row != 2) {
stamp.setTime(j,0,0);
weekTable.add(stamp.getTime().toString(),1,1);
backTable.add(weekTable,column,row);
}
else if(row == 2 && column != 1) {
if(i==weekday) {
weekTable.setColor("#e9e9e9");
}
nameOfDay = new Text(cal.getDayName(i, iwc.getCurrentLocale(), IWCalendar.LONG).toString());
if(i < weekday) {
if(today == 1) {
int lengthOfPreviousMonth = 0;
if(stamp.getMonth() == 1) {
/*
* if January the lengthOfPreviousMonth is the length of Desember the year before
*/
lengthOfPreviousMonth = cal.getLengthOfMonth(12,stamp.getYear()-1);
}
else {
/*
* else lengthOfPreviousMonth is the length of the month before in the current year
*/
lengthOfPreviousMonth = cal.getLengthOfMonth(stamp.getMonth()-1,stamp.getYear());
}
day = (today + lengthOfPreviousMonth) - (weekday - i);
}
else {
day = today - (weekday - i);
}
stamp.setDay(day);
}// end if
weekTable.add(nameOfDay,1,1);
weekTable.add("-" + stamp.getDateString("dd.MM"),1,1);
backTable.add(weekTable,column,row);
stamp.addDays(1);
}// end else if
else {
// weekTable.setStyleClass(column,row,borderWhiteTableStyle);
Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
fromStamp.setHours(beginHour);
fromStamp.setMinutes(0);
fromStamp.setNanos(0);
Timestamp toStamp =Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
toStamp.setHours(endHour);
toStamp.setMinutes(0);
toStamp.setNanos(0);
List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp);
User user = null;
Integer userID = null;
if(iwc.isLoggedOn()) {
user = iwc.getCurrentUser();
userID = (Integer) user.getPrimaryKey();
}
for(int h=0; h<listOfEntries.size(); h++) {
CalendarEntry entry = (CalendarEntry) listOfEntries.get(h);
Collection viewGroups = null;
CalendarLedger ledger = null;
boolean isInGroup = false;
int groupIDInLedger = -1;
if(user != null) {
try {
viewGroups = getUserBusiness(iwc).getUserGroups(user);
}catch(Exception e) {
e.printStackTrace();
}
}
if(entry.getLedgerID() != -1) {
ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID());
if(ledger != null) {
groupIDInLedger = ledger.getGroupID();
}
}
else {
groupIDInLedger = 1;
}
if(viewGroups != null) {
Iterator viewGroupsIter = viewGroups.iterator();
//goes through the groups the user may view and prints out the entry if
//the group connected to the entry is the same as the group the user may view
while(viewGroupsIter.hasNext()) {
Group group =(Group) viewGroupsIter.next();
Integer groupID = (Integer) group.getPrimaryKey();
if(entry.getGroupID() == groupID.intValue()
|| groupIDInLedger == groupID.intValue()) {
isInGroup = true;
}
}
}
if(groupIDInLedger == getViewGroupID()) {
isInGroup = true;
}
if(isInGroup || iwc.isSuperAdmin() ||
getViewGroupID() == entry.getGroupID() ||
(userID!=null && userID.intValue() == entry.getUserID()) ) {
Timestamp fStamp = entry.getDate();
Timestamp ttStamp = entry.getEndDate();
if(j <= ttStamp.getHours() && j >= fStamp.getHours()) {
String headline = getEntryHeadline(entry);
Link headlineLink = new Link(headline);
headlineLink.addParameter(ACTION,OPEN);
headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear());
headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth());
headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay());
headlineLink.addParameter("entryID", entry.getPrimaryKey().toString());
if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc) || isPrintable) {
headlineLink.setWindowToOpen(EntryInfoWindow.class);
}
headlineLink.setStyleClass(entryLink);
headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view);
weekTable.add(headlineLink,1,1);
weekTable.add("<br>",1,1);
// backTable.add(weekTable,column,row);
}
}
} //end for
backTable.setHeight(column,row,"40");
backTable.add(weekTable,column,row);
}
row++;
} //end inner for
column++;
}//end outer for
return backTable;
}
/**
*
* @return a table displaying the days of the current month
*/
private Table monthView(IWContext iwc, IWTimestamp stamp) {
now = IWTimestamp.RightNow();
cal = new IWCalendar();
cal.setLocale(iwc.getCurrentLocale());
Text nameOfDay = new Text();
Text t = new Text();
int weekdays = 8;
int daycount = cal.getLengthOfMonth(stamp.getMonth(),stamp.getYear());
- int firstWeekDayOfMonth = cal.getDayOfWeek(stamp.getYear(),stamp.getMonth(),2);
+ int firstWeekDayOfMonth = cal.getDayOfWeek(stamp.getYear(),stamp.getMonth(),7);
// int dayOfMonth = cal.getDay();
int row = 1;
int column = firstWeekDayOfMonth;
int n = 1;
Table table = new Table();
table.setCellpadding(0);
table.setCellspacing(0);
Table topTable = new Table();
topTable.setCellpadding(0);
topTable.setCellspacing(0);
topTable.setWidth(Table.HUNDRED_PERCENT);
Table backTable = new Table();
backTable.setColor("#cccccc");
backTable.setCellspacing(1);
backTable.setCellpadding(0);
backTable.setWidth(Table.HUNDRED_PERCENT);//700
backTable.setHeight(270);
/* backTable.mergeCells(1,1,7,1);
backTable.add(headTable,1,1);
*/
int weekday = 1;
for(int i=1; i<weekdays; i++) {
weekday = i % 7;
if (weekday == 0)
weekday = 7;
nameOfDay = new Text(cal.getDayName(weekday, iwc.getCurrentLocale(), IWCalendar.SHORT).toString().toLowerCase());
nameOfDay.setBold();
Table nameOfDayTable = new Table();
nameOfDayTable.setCellspacing(0);
nameOfDayTable.setCellpadding(0);
nameOfDayTable.setWidth(Table.HUNDRED_PERCENT);
nameOfDayTable.setHeight(Table.HUNDRED_PERCENT);
nameOfDayTable.setColor("#f8f8f8");
nameOfDayTable.setStyleAttribute("border-top: 1px solid #cccccc");
nameOfDayTable.setAlignment(1,1,Table.HORIZONTAL_ALIGN_CENTER);
nameOfDayTable.setVerticalAlignment(1,1,Table.VERTICAL_ALIGN_BOTTOM);
nameOfDayTable.add(nameOfDay,1,1);
topTable.setHeight(i,1,"30");
topTable.setHeight(i,2,"5");
topTable.add(nameOfDayTable,i,1);
// backTable.setWidth(i,2,"200");
}
User user = null;
Integer userID = null;
if(iwc.isLoggedOn()) {
user = iwc.getCurrentUser();
userID = (Integer) user.getPrimaryKey();
}
else {
userID = new Integer(-2);
}
Collection viewGroups = null;
if(user != null) {
try {
viewGroups = getUserBusiness(iwc).getUserGroups(user);
}catch(Exception e) {
e.printStackTrace();
}
}
while (n <= daycount) {
Table dayCell = new Table();
dayCell.setCellspacing(0);
dayCell.setCellpadding(0);
dayCell.setWidth(Table.HUNDRED_PERCENT);
dayCell.setHeight(Table.HUNDRED_PERCENT);
dayCell.setVerticalAlignment(1,1,Table.VERTICAL_ALIGN_TOP);
t = new Text(String.valueOf(n));
int cellRow = 2;
backTable.setWidth(column,row,"100");
backTable.setHeight(column,row,"95");
if(n == now.getDay()) {
dayCell.setColor("#e9e9e9");
}
else {
dayCell.setColor("#ffffff");
}
Link dayLink = new Link(t);
dayLink.setStyleClass(styledLink);
dayLink.addParameter(CalendarParameters.PARAMETER_VIEW,CalendarParameters.DAY);
dayLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear());
dayLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth());
dayLink.addParameter(CalendarParameters.PARAMETER_DAY, n);
if(groupID != -2) {
dayLink.addParameter(PARAMETER_ISI_GROUP_ID,groupID);
}
dayCell.add(dayLink,1,1);
dayCell.setHeight(1,1,12);
dayCell.add(Text.BREAK,1,1);
dayCell.setAlignment(1,1,Table.HORIZONTAL_ALIGN_RIGHT);
Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
fromStamp.setDate(n);
fromStamp.setHours(0);
fromStamp.setMinutes(0);
fromStamp.setNanos(0);
Timestamp toStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
toStamp.setDate(n);
toStamp.setHours(23);
toStamp.setMinutes(59);
toStamp.setNanos(0);
List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp);
Collections.sort(listOfEntries,new Comparator() {
public int compare(Object arg0, Object arg1) {
return ((CalendarEntry) arg0).getDate().compareTo(((CalendarEntry) arg1).getDate());
}
});
for(int h=0; h<listOfEntries.size(); h++) {
CalendarEntry entry = (CalendarEntry) listOfEntries.get(h);
CalendarLedger ledger = null;
int groupIDInLedger = 0;
int coachGroupIDInLedger = 0;
boolean isInGroup = false;
if(entry.getLedgerID() != -1) {
ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID());
if(ledger != null) {
groupIDInLedger = ledger.getGroupID();
coachGroupIDInLedger = ledger.getCoachGroupID();
}
}
else {
groupIDInLedger = -1;
coachGroupIDInLedger = -1;
}
if(viewGroups != null) {
Iterator viewGroupsIter = viewGroups.iterator();
//goes through the groups the user may view and prints out the entry if
//the group connected to the entry is the same as the group the user may view
while(viewGroupsIter.hasNext()) {
Group group =(Group) viewGroupsIter.next();
Integer groupID = (Integer) group.getPrimaryKey();
if(entry.getGroupID() == groupID.intValue()
|| groupIDInLedger == groupID.intValue()){
isInGroup = true;
}
}
}
if(groupIDInLedger == getViewGroupID()) {
isInGroup = true;
}
if(coachGroupIDInLedger == getViewGroupID()) {
isInGroup = true;
}
if(isInGroup || iwc.isSuperAdmin() ||
getViewGroupID() == entry.getGroupID() ||
(userID!=null && userID.intValue() == entry.getUserID())) {
String headline = getEntryHeadline(entry);
Link headlineLink = new Link(headline);
headlineLink.addParameter(ACTION,OPEN);
headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view);
headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear());
headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth());
headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay());
headlineLink.addParameter(CalendarEntryCreator.entryIDParameterName, entry.getPrimaryKey().toString());
if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc) || isPrintable) {
headlineLink.setWindowToOpen(EntryInfoWindow.class);
}
headlineLink.setStyleClass(entryLink);
String e = iwc.getParameter(CalendarEntryCreator.entryIDParameterName);
CalendarEntry ent = null;
if(e == null || e.equals("")) {
e = "";
}
else {
try {
ent = getCalBusiness(iwc).getEntry(Integer.parseInt(e));
}catch(Exception ex) {
ent = null;
}
}
if(ent != null) {
if(ent.getPrimaryKey().equals(entry.getPrimaryKey())) {
headlineLink.setStyleClass(entryLinkActive);
}
}
dayCell.add(headlineLink,1,cellRow);
dayCell.setVerticalAlignment(1,cellRow,"top");
dayCell.add("<br>",1,cellRow++);
}
}
backTable.add(dayCell,column,row);
backTable.setColor(column,row,"#ffffff");
backTable.add(Text.NON_BREAKING_SPACE,column,row);
backTable.setVerticalAlignment(column,row,"top");
column = column % 7 + 1;
if (column == 1)
row++;
n++;
}
table.add(topTable,1,1);
table.add(backTable,1,2);
return table;
}
/**
* The display of the entry in the calendar is in the form:
* "fromtime - totime nameOfEntry, locationOfEntry"
* @param entry
* @return headline - the display string of the calendar entry
*/
private String getEntryHeadline(CalendarEntry entry) {
Timestamp startDate = entry.getDate();
int startHours = startDate.getHours();
int startMinutes = startDate.getMinutes();
Timestamp endDate = entry.getEndDate();
int endHours = endDate.getHours();
int endMinutes = endDate.getMinutes();
String name = entry.getName();
String location = entry.getLocation();
String headline = getTimeString(startHours,startMinutes) +
"-" + getTimeString(endHours,endMinutes);
if(name != null && !name.equals("")) {
headline = headline + " " + name;
}
if(location != null && !location.equals("")) {
headline = headline + ", " + location;
}
return headline;
}
/**
*
* @param hours
* @param minutes
* @return
*/
private String getTimeString(int hours, int minutes) {
String timeString;
String mi;
if(minutes<10) {
mi = "0"+minutes;
}
else {
mi = ""+minutes;
}
timeString = hours + ":" + mi;
return timeString;
}
private Table yearView(IWContext iwc, IWTimestamp stamp) {
now = new IWTimestamp();
Table yearTable = new Table();
IWTimestamp yearStamp = null;
SmallCalendar smallCalendar = null;
int row = 2;
int column = 1;
for (int a = 1; a <= 12; a++) {
yearStamp = new IWTimestamp(stamp.getDay(), a, stamp.getYear());
smallCalendar = new SmallCalendar(yearStamp);
smallCalendar.setDaysAsLink(true);
smallCalendar.addParameterToLink(CalendarParameters.PARAMETER_VIEW,CalendarParameters.DAY);
yearTable.add(smallCalendar,column, row);
yearTable.setStyleClass(column,row,borderWhiteTableStyle);
yearTable.setRowVerticalAlignment(row, "top");
yearTable.setAlignment("center");
column = column % 4 + 1;
if (column == 1)
row++;
}
return yearTable;
}
private Table getTopTable(int view, IWTimestamp stamp, IWContext iwc) {
Link right = getRightLink(iwc);
Link left = getLeftLink(iwc);
Text dateString = null;
switch (view) {
case CalendarParameters.DAY :
addNextDayPrm(right,timeStamp);
addLastDayPrm(left,timeStamp);
dateString = new Text(stamp.getDateString("dd MMMMMMMM, yyyy",iwc.getCurrentLocale()));
break;
case CalendarParameters.WEEK :
addNextWeekPrm(right,timeStamp);
addLastWeekPrm(left,timeStamp);
dateString = new Text(getResourceBundle(iwc).getLocalizedString("calView.week_of_year","Week of the year") + " " + stamp.getWeekOfYear() + "<br>" + stamp.getDateString("yyyy"));
break;
case CalendarParameters.MONTH :
addNextMonthPrm(right, timeStamp);
addLastMonthPrm(left, timeStamp);
dateString = new Text(stamp.getDateString("MMMMMMMM yyyy",iwc.getCurrentLocale()));
break;
case CalendarParameters.YEAR :
addNextYearPrm(right,timeStamp);
addLastYearPrm(left,timeStamp);
dateString = new Text(stamp.getDateString("yyyy"));
break;
}
if(dateString != null) {
dateString.setStyleClass(headline);
dateString.setBold();
}
Table headTable = new Table();
headTable.setCellspacing(0);
headTable.setCellpadding(0);
headTable.setStyleAttribute("border-top: 1px solid #cccccc");
headTable.setColor("#f3f3f3");
headTable.setWidth(Table.HUNDRED_PERCENT);
headTable.setHeight(Table.HUNDRED_PERCENT);
Table navTable = new Table();
navTable.add(left,1,1);
navTable.add(dateString,2,1);
navTable.add(right,3,1);
headTable.setAlignment(1,1,Table.HORIZONTAL_ALIGN_LEFT);
headTable.add(navTable,1,1);
headTable.setAlignment(2,1,Table.HORIZONTAL_ALIGN_RIGHT);
headTable.add(getIconTable(iwc),2,1);
return headTable;
}
private Table getIconTable(IWContext iwc) {
Table iconTable = new Table();
/*
* dayView, weekView, monthView and yearView trigger a change of the calendar view
*/
IWBundle iwb = getBundle(iwc);
Image day_on = iwb.getImage("day_on_blue.gif");
Link dayView = new Link();
addLinkParameters(dayView,CalendarParameters.DAY,timeStamp);
dayView.setImage(day_on);
/* Image week_on = iwb.getImage("week_on_blue.gif");
Link weekView = new Link();
addLinkParameters(weekView,CalendarParameters.WEEK,timeStamp);
weekView.setImage(week_on);
*/
Image month_on = iwb.getImage("month_on_blue.gif");
Link monthView = new Link();
addLinkParameters(monthView,CalendarParameters.MONTH,timeStamp);
monthView.setImage(month_on);
Image year_on = iwb.getImage("year_on_blue.gif");
Link yearView = new Link();
addLinkParameters(yearView,CalendarParameters.YEAR,timeStamp);
yearView.setImage(year_on);
iconTable.add(dayView,1,1);
// iconTable.add(weekView,2,1);
iconTable.add(monthView,2,1);
iconTable.add(yearView,3,1);
return iconTable;
}
private Table getAdminTable(IWContext iwc, CalendarEntryCreator creator) {
IWResourceBundle iwrb = getResourceBundle(iwc);
Table adminTable = new Table();
adminTable.setWidth(Table.HUNDRED_PERCENT);
adminTable.setHeight(Table.HUNDRED_PERCENT);
adminTable.setCellpadding(0);
adminTable.setStyleAttribute("border-top: 1px solid #cccccc");
if(adminOnTop) {
adminTable.setStyleClass(1,1,"borderRight");
}
Table ledgerListTable = new Table();
ledgerListTable.setCellpadding(5);
ledgerListTable.setCellspacing(0);
ledgerListTable.setWidth(Table.HUNDRED_PERCENT);
Table creatorTable = new Table();
creatorTable.setCellpadding(5);
creatorTable.setCellspacing(0);
creatorTable.setWidth(Table.HUNDRED_PERCENT);
Table headlineLedgerTable = new Table();
headlineLedgerTable.setCellpadding(0);
headlineLedgerTable.setCellspacing(0);
headlineLedgerTable.setStyleAttribute("border-bottom:1px dotted #cccccc;");
headlineLedgerTable.setWidth(Table.HUNDRED_PERCENT);
Text ledgerText = new Text(iwrb.getLocalizedString("calendarView.ledgers", "Ledgers"));
// ledgerText.setStyleClass(headline);
ledgerText.setBold();
ledgerText.setFontColor("#5f5f5f");
headlineLedgerTable.add(ledgerText,1,1);
headlineLedgerTable.setHeight(1,2,3);
Table headlineCreatorTable = new Table();
headlineCreatorTable.setCellpadding(0);
headlineCreatorTable.setCellspacing(0);
headlineCreatorTable.setStyleAttribute("border-bottom:1px dotted #cccccc;");
headlineCreatorTable.setWidth(Table.HUNDRED_PERCENT);
Text creatorText = null;
String entryID = iwc.getParameter("entryID");
if(entryID != null && !entryID.equals("")) {
creatorText = new Text(iwrb.getLocalizedString("calendarEntry.change_entry", "Change entry"));
}
else {
creatorText = new Text(iwrb.getLocalizedString("calendarEntry.create_new", "Create new entry"));
}
// creatorText.setStyleClass(headline);
creatorText.setBold();
creatorText.setFontColor("#5f5f5f");
headlineCreatorTable.add(creatorText,1,1);
headlineCreatorTable.setHeight(1,2,3);
int row = 2;
Table ledgerTable = new Table();
ledgerTable.setCellpadding(2);
ledgerTable.setCellspacing(0);
ledgerTable.setWidth(Table.HUNDRED_PERCENT);
String linkText = iwrb.getLocalizedString("calendarwindow.new_ledger","New Ledger");
GenericButton newLedgerButton = new GenericButton(linkText);
newLedgerButton.setWindowToOpen(CreateLedgerWindow.class);
StyledButton styledNewLedgerButton = new StyledButton(newLedgerButton);
ledgerTable.setAlignment(1,1,Table.HORIZONTAL_ALIGN_RIGHT);
ledgerTable.add(styledNewLedgerButton,1,1);
User user = null;
if(iwc.isLoggedOn()) {
user = iwc.getCurrentUser();
}
Iterator ledgerIter = getCalBusiness(iwc).getAllLedgers().iterator();
while(ledgerIter.hasNext()) {
CalendarLedger ledger = (CalendarLedger) ledgerIter.next();
Link ledgerLink =new Link(ledger.getName());
ledgerLink.setStyleClass(styledLink);
ledgerLink.addParameter(LedgerWindow.LEDGER,ledger.getPrimaryKey().toString());
ledgerLink.addParameter(CalendarParameters.PARAMETER_DAY,timeStamp.getDay());
ledgerLink.addParameter(CalendarParameters.PARAMETER_MONTH,timeStamp.getMonth());
ledgerLink.addParameter(CalendarParameters.PARAMETER_YEAR,timeStamp.getYear());
ledgerLink.setWindowToOpen(LedgerWindow.class);
if(user != null) {
if(((Integer) user.getPrimaryKey()).intValue() == ledger.getCoachID() || user.getPrimaryGroupID() == ledger.getCoachGroupID()) {
ledgerTable.add(" • ",1,row);
ledgerTable.add(ledgerLink,1,row++);
}
}
}
Layer layer = new Layer(Layer.DIV);
layer.setOverflow("auto");
if(adminOnTop) {
layer.setWidth("220px");
layer.setHeight("260px");
}
else {
layer.setWidth("240px");
layer.setHeight("200px");
ledgerListTable.setStyleAttribute("border-bottom: 1px solid #cccccc");
}
// layer.setStyleClass(ledgerListStyle);
layer.add(ledgerTable);
adminTable.setVerticalAlignment(1,1,Table.VERTICAL_ALIGN_TOP);
adminTable.setVerticalAlignment(1,2,Table.VERTICAL_ALIGN_TOP);
ledgerListTable.add(headlineLedgerTable,1,1);
ledgerListTable.add(layer,1,2);
creatorTable.add(headlineCreatorTable,1,1);
creatorTable.add(creator,1,2);
adminTable.add(ledgerListTable,1,1);
if(adminOnTop) {
adminTable.add(creatorTable,2,1);
}
else {
adminTable.add(creatorTable,1,3);
}
return adminTable;
}
private Link getRightLink(IWContext iwc) {
IWBundle iwb = getBundle(iwc);
Image rightArrow = iwb.getImage("right_arrow.gif");
Link right = new Link();
right.setImage(rightArrow);
right.addParameter(CalendarParameters.PARAMETER_VIEW,view);
return right;
}
private Link getLeftLink(IWContext iwc) {
IWBundle iwb = getBundle(iwc);
Image leftArrow = iwb.getImage("left_arrow.gif");
Link left = new Link();
left.setImage(leftArrow);
left.addParameter(CalendarParameters.PARAMETER_VIEW,view);
return left;
}
public void main(IWContext iwc) throws Exception{
IWResourceBundle iwrb = getResourceBundle(iwc);
Page parentPage = this.getParentPage();
String styleSrc = iwc.getIWMainApplication().getBundle(getBundleIdentifier()).getResourcesURL();
String styleSheetName = "CalStyle.css";
styleSrc = styleSrc + "/" + styleSheetName;
if(parentPage != null) {
parentPage.addStyleSheetURL(styleSrc);
}
if (timeStamp == null) {
String day = iwc.getParameter(CalendarParameters.PARAMETER_DAY);
String month = iwc.getParameter(CalendarParameters.PARAMETER_MONTH);
String year = iwc.getParameter(CalendarParameters.PARAMETER_YEAR);
if(month != null && !month.equals("") &&
day != null && !day.equals("") &&
year != null && !year.equals("")) {
timeStamp = getTimestamp(day,month,year);
}
else {
timeStamp = IWTimestamp.RightNow();
}
}
CalendarEntryCreator creator = new CalendarEntryCreator();
String save = iwc.getParameter(creator.saveButtonParameterName);
if(save != null) {
creator.saveEntry(iwc,parentPage);
}
/*
* view is set to the current view
*/
String viewString = iwc.getParameter(CalendarParameters.PARAMETER_VIEW);
if (viewString != null && !viewString.equals("")) {
view = Integer.parseInt(viewString);
}
Table table = new Table();
table.setCellspacing(0);
table.setCellpadding(0);
table.setColor("#f8f8f8");
table.setHeight(Table.HUNDRED_PERCENT);
table.setVerticalAlignment(2,2,Table.VERTICAL_ALIGN_TOP);
table.setVerticalAlignment(1,2,Table.VERTICAL_ALIGN_TOP);
table.setVerticalAlignment(1,1,Table.VERTICAL_ALIGN_TOP);
Table viewTable = new Table();
switch (view) {
case CalendarParameters.DAY :
viewTable = dayView(iwc, timeStamp);
break;
case CalendarParameters.WEEK :
viewTable = weekView(iwc,timeStamp);
break;
case CalendarParameters.MONTH :
viewTable = monthView(iwc,timeStamp);
break;
case CalendarParameters.YEAR :
viewTable = yearView(iwc,timeStamp);
break;
}
table.add(getTopTable(view,timeStamp,iwc),1,1);
if(adminOnTop) {
table.setWidth(620);
table.add(viewTable,1,3);
}
else {
table.mergeCells(1,1,2,1);
table.setWidth(880);
table.add(viewTable,1,2);
}
if(iwc.getAccessController().hasRole("cal_view_entry_creator",iwc) && !isPrintable) {
if(adminOnTop) {
table.add(getAdminTable(iwc,creator),1,2);
}
else {
table.add(getAdminTable(iwc,creator),2,2);
}
}
if(!isPrintable) {
Link printLink = new Link(iwrb.getLocalizedString("calendarwindow.printable_cal","Printerfriendly Calendar"));
printLink.setWindowToOpen(PrintableCalendarView.class);
printLink.addParameter("group_id", getViewGroupID());
printLink.addParameter("user_id", getViewUserID());
printLink.addParameter(CalendarParameters.PARAMETER_VIEW,view);
printLink.setStyleClass(styledLink);
table.add(printLink,1,3);
}
add(table);
}
/**
*
* @param l
* @param viewValue
* @param stamp
*/
public void addLinkParameters(Link l, int viewValue, IWTimestamp stamp) {
if(groupID != -2) {
l.addParameter("group_id",groupID);
}
l.addParameter(CalendarParameters.PARAMETER_VIEW, viewValue);
l.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear());
l.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth());
l.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay());
l.addParameter(ACTION,action);
}
/**
*
* @param hour - the time of day when the CalenderView - day- or weekView, starts
*/
public void setBeginHour(int hour) {
beginHour = hour;
}
/**
*
* @param hour - the time of day when the CalendarView - day- or weekView, ends
*/
public void setEndHour(int hour) {
endHour = hour;
}
public void setViewInGroupID(int id) {
groupID = id;
}
public void setViewInUserID(int id) {
userID = id;
}
public int getViewGroupID() {
return groupID;
}
public int getViewUserID() {
return userID;
}
public void setPrintableVersion(boolean isPrintable) {
this.isPrintable = isPrintable;
}
/**
* Adds parameters for the next day to the next day link
* @param L
* @param idts
*/
public void addNextDayPrm(Link L, IWTimestamp idts) {
if(groupID != -2) {
L.addParameter(PARAMETER_ISI_GROUP_ID,groupID);
}
IWCalendar cal = new IWCalendar();
int lastDayOfMonth = cal.getLengthOfMonth(idts.getMonth(),idts.getYear());
if(idts.getDay() == lastDayOfMonth) {
if(idts.getMonth() == 12) {
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() + 1));
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(1));
}
else {
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear()));
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth() + 1));
}
L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(1));
}
else {
L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(idts.getDay() + 1));
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth()));
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear()));
}
}
/**
*
* @param L
* @param idts
*/
public void addLastDayPrm(Link L, IWTimestamp idts) {
if(groupID != -2) {
L.addParameter(PARAMETER_ISI_GROUP_ID,groupID);
}
IWCalendar cal = new IWCalendar();
int lastDayOfPreviousMonthThisYear = cal.getLengthOfMonth(idts.getMonth() - 1,idts.getYear());
int lastDayOfPreviousMonthLastYear = cal.getLengthOfMonth(idts.getMonth() - 1,idts.getYear() - 1);
if(idts.getDay() == 1) {
if(idts.getMonth() == 1) {
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() - 1));
L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(lastDayOfPreviousMonthLastYear));
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(12));
}
else {
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear()));
L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(lastDayOfPreviousMonthThisYear));
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth() - 1));
}
}
else {
L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(idts.getDay() - 1));
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth()));
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear()));
}
}
public void addNextWeekPrm(Link L, IWTimestamp idts) {
GregorianCalendar calendar = new GregorianCalendar(idts.getYear(),idts.getMonth(),idts.getDay());
Timestamp ts = idts.getTimestamp();
calendar.add(calendar.DAY_OF_MONTH,6);
if(calendar.get(calendar.DAY_OF_MONTH) < idts.getDay()) {
calendar.add(calendar.MONTH,1);
if(calendar.get(calendar.MONTH) < idts.getMonth()) {
calendar.add(calendar.YEAR,1);
}
}
Date sd = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.S");
String f = format.format(sd);
ts = Timestamp.valueOf(f);
// int year = sd.getYear() + 1900;
// ts.setYear(year);
idts = new IWTimestamp(ts);
L.addParameter(CalendarParameters.PARAMETER_DAY,String.valueOf(idts.getDay()));
L.addParameter(CalendarParameters.PARAMETER_MONTH,String.valueOf(idts.getMonth()));
L.addParameter(CalendarParameters.PARAMETER_YEAR,String.valueOf(idts.getYear()));
}
public void addLastWeekPrm(Link L, IWTimestamp idts) {
}
/**
* The same method as in SmallCalendar.java
* @param L
* @param idts
*/
public void addNextMonthPrm(Link L, IWTimestamp idts) {
if(groupID != -2) {
L.addParameter(PARAMETER_ISI_GROUP_ID,groupID);
}
if (idts.getMonth() == 12) {
L.addParameter(CalendarParameters.PARAMETER_DAY, idts.getDay());
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(1));
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() + 1));
}
else {
L.addParameter(CalendarParameters.PARAMETER_DAY, idts.getDay());
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth() + 1));
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear()));
}
}
/**
* The same method as in SmallCalendar.java
* @param L
* @param idts
*/
public void addLastMonthPrm(Link L, IWTimestamp idts) {
if(groupID != -2) {
L.addParameter(PARAMETER_ISI_GROUP_ID,groupID);
}
if (idts.getMonth() == 1) {
L.addParameter(CalendarParameters.PARAMETER_DAY,idts.getDay());
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(12));
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() - 1));
}
else {
L.addParameter(CalendarParameters.PARAMETER_DAY,idts.getDay());
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth() - 1));
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear()));
}
}
public void addNextYearPrm(Link L, IWTimestamp idts) {
L.addParameter(CalendarParameters.PARAMETER_DAY, idts.getDay());
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth()));
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() + 1));
}
public void addLastYearPrm(Link L, IWTimestamp idts) {
L.addParameter(CalendarParameters.PARAMETER_DAY,idts.getDay());
L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth()));
L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() - 1));
}
public static IWTimestamp getTimestamp(String day, String month, String year) {
IWTimestamp stamp = new IWTimestamp();
if (day != null) {
stamp.setDay(Integer.parseInt(day));
}
// removed dubius behavior A
/*else {
stamp.setDay(1);
}
*/
if (month != null) {
stamp.setMonth(Integer.parseInt(month));
}
if (year != null) {
stamp.setYear(Integer.parseInt(year));
}
stamp.setHour(0);
stamp.setMinute(0);
stamp.setSecond(0);
return stamp;
}
public void setAdminOnTop(boolean adminOnTop) {
this.adminOnTop = adminOnTop;
}
public String getBundleIdentifier() {
return IW_BUNDLE_IDENTIFIER;
}
public CalBusiness getCalBusiness(IWApplicationContext iwc) {
if (calBiz == null) {
try {
calBiz = (CalBusiness) com.idega.business.IBOLookup.getServiceInstance(iwc, CalBusiness.class);
}
catch (java.rmi.RemoteException rme) {
throw new RuntimeException(rme.getMessage());
}
}
return calBiz;
}
protected UserBusiness getUserBusiness(IWApplicationContext iwc) {
UserBusiness userBusiness = null;
if (userBusiness == null) {
try {
userBusiness = (UserBusiness) com.idega.business.IBOLookup.getServiceInstance(iwc, UserBusiness.class);
}
catch (java.rmi.RemoteException rme) {
throw new RuntimeException(rme.getMessage());
}
}
return userBusiness;
}
}
| true | true | private Table monthView(IWContext iwc, IWTimestamp stamp) {
now = IWTimestamp.RightNow();
cal = new IWCalendar();
cal.setLocale(iwc.getCurrentLocale());
Text nameOfDay = new Text();
Text t = new Text();
int weekdays = 8;
int daycount = cal.getLengthOfMonth(stamp.getMonth(),stamp.getYear());
int firstWeekDayOfMonth = cal.getDayOfWeek(stamp.getYear(),stamp.getMonth(),2);
// int dayOfMonth = cal.getDay();
int row = 1;
int column = firstWeekDayOfMonth;
int n = 1;
Table table = new Table();
table.setCellpadding(0);
table.setCellspacing(0);
Table topTable = new Table();
topTable.setCellpadding(0);
topTable.setCellspacing(0);
topTable.setWidth(Table.HUNDRED_PERCENT);
Table backTable = new Table();
backTable.setColor("#cccccc");
backTable.setCellspacing(1);
backTable.setCellpadding(0);
backTable.setWidth(Table.HUNDRED_PERCENT);//700
backTable.setHeight(270);
/* backTable.mergeCells(1,1,7,1);
backTable.add(headTable,1,1);
*/
int weekday = 1;
for(int i=1; i<weekdays; i++) {
weekday = i % 7;
if (weekday == 0)
weekday = 7;
nameOfDay = new Text(cal.getDayName(weekday, iwc.getCurrentLocale(), IWCalendar.SHORT).toString().toLowerCase());
nameOfDay.setBold();
Table nameOfDayTable = new Table();
nameOfDayTable.setCellspacing(0);
nameOfDayTable.setCellpadding(0);
nameOfDayTable.setWidth(Table.HUNDRED_PERCENT);
nameOfDayTable.setHeight(Table.HUNDRED_PERCENT);
nameOfDayTable.setColor("#f8f8f8");
nameOfDayTable.setStyleAttribute("border-top: 1px solid #cccccc");
nameOfDayTable.setAlignment(1,1,Table.HORIZONTAL_ALIGN_CENTER);
nameOfDayTable.setVerticalAlignment(1,1,Table.VERTICAL_ALIGN_BOTTOM);
nameOfDayTable.add(nameOfDay,1,1);
topTable.setHeight(i,1,"30");
topTable.setHeight(i,2,"5");
topTable.add(nameOfDayTable,i,1);
// backTable.setWidth(i,2,"200");
}
User user = null;
Integer userID = null;
if(iwc.isLoggedOn()) {
user = iwc.getCurrentUser();
userID = (Integer) user.getPrimaryKey();
}
else {
userID = new Integer(-2);
}
Collection viewGroups = null;
if(user != null) {
try {
viewGroups = getUserBusiness(iwc).getUserGroups(user);
}catch(Exception e) {
e.printStackTrace();
}
}
while (n <= daycount) {
Table dayCell = new Table();
dayCell.setCellspacing(0);
dayCell.setCellpadding(0);
dayCell.setWidth(Table.HUNDRED_PERCENT);
dayCell.setHeight(Table.HUNDRED_PERCENT);
dayCell.setVerticalAlignment(1,1,Table.VERTICAL_ALIGN_TOP);
t = new Text(String.valueOf(n));
int cellRow = 2;
backTable.setWidth(column,row,"100");
backTable.setHeight(column,row,"95");
if(n == now.getDay()) {
dayCell.setColor("#e9e9e9");
}
else {
dayCell.setColor("#ffffff");
}
Link dayLink = new Link(t);
dayLink.setStyleClass(styledLink);
dayLink.addParameter(CalendarParameters.PARAMETER_VIEW,CalendarParameters.DAY);
dayLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear());
dayLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth());
dayLink.addParameter(CalendarParameters.PARAMETER_DAY, n);
if(groupID != -2) {
dayLink.addParameter(PARAMETER_ISI_GROUP_ID,groupID);
}
dayCell.add(dayLink,1,1);
dayCell.setHeight(1,1,12);
dayCell.add(Text.BREAK,1,1);
dayCell.setAlignment(1,1,Table.HORIZONTAL_ALIGN_RIGHT);
Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
fromStamp.setDate(n);
fromStamp.setHours(0);
fromStamp.setMinutes(0);
fromStamp.setNanos(0);
Timestamp toStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
toStamp.setDate(n);
toStamp.setHours(23);
toStamp.setMinutes(59);
toStamp.setNanos(0);
List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp);
Collections.sort(listOfEntries,new Comparator() {
public int compare(Object arg0, Object arg1) {
return ((CalendarEntry) arg0).getDate().compareTo(((CalendarEntry) arg1).getDate());
}
});
for(int h=0; h<listOfEntries.size(); h++) {
CalendarEntry entry = (CalendarEntry) listOfEntries.get(h);
CalendarLedger ledger = null;
int groupIDInLedger = 0;
int coachGroupIDInLedger = 0;
boolean isInGroup = false;
if(entry.getLedgerID() != -1) {
ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID());
if(ledger != null) {
groupIDInLedger = ledger.getGroupID();
coachGroupIDInLedger = ledger.getCoachGroupID();
}
}
else {
groupIDInLedger = -1;
coachGroupIDInLedger = -1;
}
if(viewGroups != null) {
Iterator viewGroupsIter = viewGroups.iterator();
//goes through the groups the user may view and prints out the entry if
//the group connected to the entry is the same as the group the user may view
while(viewGroupsIter.hasNext()) {
Group group =(Group) viewGroupsIter.next();
Integer groupID = (Integer) group.getPrimaryKey();
if(entry.getGroupID() == groupID.intValue()
|| groupIDInLedger == groupID.intValue()){
isInGroup = true;
}
}
}
if(groupIDInLedger == getViewGroupID()) {
isInGroup = true;
}
if(coachGroupIDInLedger == getViewGroupID()) {
isInGroup = true;
}
if(isInGroup || iwc.isSuperAdmin() ||
getViewGroupID() == entry.getGroupID() ||
(userID!=null && userID.intValue() == entry.getUserID())) {
String headline = getEntryHeadline(entry);
Link headlineLink = new Link(headline);
headlineLink.addParameter(ACTION,OPEN);
headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view);
headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear());
headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth());
headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay());
headlineLink.addParameter(CalendarEntryCreator.entryIDParameterName, entry.getPrimaryKey().toString());
if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc) || isPrintable) {
headlineLink.setWindowToOpen(EntryInfoWindow.class);
}
headlineLink.setStyleClass(entryLink);
String e = iwc.getParameter(CalendarEntryCreator.entryIDParameterName);
CalendarEntry ent = null;
if(e == null || e.equals("")) {
e = "";
}
else {
try {
ent = getCalBusiness(iwc).getEntry(Integer.parseInt(e));
}catch(Exception ex) {
ent = null;
}
}
if(ent != null) {
if(ent.getPrimaryKey().equals(entry.getPrimaryKey())) {
headlineLink.setStyleClass(entryLinkActive);
}
}
dayCell.add(headlineLink,1,cellRow);
dayCell.setVerticalAlignment(1,cellRow,"top");
dayCell.add("<br>",1,cellRow++);
}
}
backTable.add(dayCell,column,row);
backTable.setColor(column,row,"#ffffff");
backTable.add(Text.NON_BREAKING_SPACE,column,row);
backTable.setVerticalAlignment(column,row,"top");
column = column % 7 + 1;
if (column == 1)
row++;
n++;
}
table.add(topTable,1,1);
table.add(backTable,1,2);
return table;
}
| private Table monthView(IWContext iwc, IWTimestamp stamp) {
now = IWTimestamp.RightNow();
cal = new IWCalendar();
cal.setLocale(iwc.getCurrentLocale());
Text nameOfDay = new Text();
Text t = new Text();
int weekdays = 8;
int daycount = cal.getLengthOfMonth(stamp.getMonth(),stamp.getYear());
int firstWeekDayOfMonth = cal.getDayOfWeek(stamp.getYear(),stamp.getMonth(),7);
// int dayOfMonth = cal.getDay();
int row = 1;
int column = firstWeekDayOfMonth;
int n = 1;
Table table = new Table();
table.setCellpadding(0);
table.setCellspacing(0);
Table topTable = new Table();
topTable.setCellpadding(0);
topTable.setCellspacing(0);
topTable.setWidth(Table.HUNDRED_PERCENT);
Table backTable = new Table();
backTable.setColor("#cccccc");
backTable.setCellspacing(1);
backTable.setCellpadding(0);
backTable.setWidth(Table.HUNDRED_PERCENT);//700
backTable.setHeight(270);
/* backTable.mergeCells(1,1,7,1);
backTable.add(headTable,1,1);
*/
int weekday = 1;
for(int i=1; i<weekdays; i++) {
weekday = i % 7;
if (weekday == 0)
weekday = 7;
nameOfDay = new Text(cal.getDayName(weekday, iwc.getCurrentLocale(), IWCalendar.SHORT).toString().toLowerCase());
nameOfDay.setBold();
Table nameOfDayTable = new Table();
nameOfDayTable.setCellspacing(0);
nameOfDayTable.setCellpadding(0);
nameOfDayTable.setWidth(Table.HUNDRED_PERCENT);
nameOfDayTable.setHeight(Table.HUNDRED_PERCENT);
nameOfDayTable.setColor("#f8f8f8");
nameOfDayTable.setStyleAttribute("border-top: 1px solid #cccccc");
nameOfDayTable.setAlignment(1,1,Table.HORIZONTAL_ALIGN_CENTER);
nameOfDayTable.setVerticalAlignment(1,1,Table.VERTICAL_ALIGN_BOTTOM);
nameOfDayTable.add(nameOfDay,1,1);
topTable.setHeight(i,1,"30");
topTable.setHeight(i,2,"5");
topTable.add(nameOfDayTable,i,1);
// backTable.setWidth(i,2,"200");
}
User user = null;
Integer userID = null;
if(iwc.isLoggedOn()) {
user = iwc.getCurrentUser();
userID = (Integer) user.getPrimaryKey();
}
else {
userID = new Integer(-2);
}
Collection viewGroups = null;
if(user != null) {
try {
viewGroups = getUserBusiness(iwc).getUserGroups(user);
}catch(Exception e) {
e.printStackTrace();
}
}
while (n <= daycount) {
Table dayCell = new Table();
dayCell.setCellspacing(0);
dayCell.setCellpadding(0);
dayCell.setWidth(Table.HUNDRED_PERCENT);
dayCell.setHeight(Table.HUNDRED_PERCENT);
dayCell.setVerticalAlignment(1,1,Table.VERTICAL_ALIGN_TOP);
t = new Text(String.valueOf(n));
int cellRow = 2;
backTable.setWidth(column,row,"100");
backTable.setHeight(column,row,"95");
if(n == now.getDay()) {
dayCell.setColor("#e9e9e9");
}
else {
dayCell.setColor("#ffffff");
}
Link dayLink = new Link(t);
dayLink.setStyleClass(styledLink);
dayLink.addParameter(CalendarParameters.PARAMETER_VIEW,CalendarParameters.DAY);
dayLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear());
dayLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth());
dayLink.addParameter(CalendarParameters.PARAMETER_DAY, n);
if(groupID != -2) {
dayLink.addParameter(PARAMETER_ISI_GROUP_ID,groupID);
}
dayCell.add(dayLink,1,1);
dayCell.setHeight(1,1,12);
dayCell.add(Text.BREAK,1,1);
dayCell.setAlignment(1,1,Table.HORIZONTAL_ALIGN_RIGHT);
Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
fromStamp.setDate(n);
fromStamp.setHours(0);
fromStamp.setMinutes(0);
fromStamp.setNanos(0);
Timestamp toStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S"));
toStamp.setDate(n);
toStamp.setHours(23);
toStamp.setMinutes(59);
toStamp.setNanos(0);
List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp);
Collections.sort(listOfEntries,new Comparator() {
public int compare(Object arg0, Object arg1) {
return ((CalendarEntry) arg0).getDate().compareTo(((CalendarEntry) arg1).getDate());
}
});
for(int h=0; h<listOfEntries.size(); h++) {
CalendarEntry entry = (CalendarEntry) listOfEntries.get(h);
CalendarLedger ledger = null;
int groupIDInLedger = 0;
int coachGroupIDInLedger = 0;
boolean isInGroup = false;
if(entry.getLedgerID() != -1) {
ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID());
if(ledger != null) {
groupIDInLedger = ledger.getGroupID();
coachGroupIDInLedger = ledger.getCoachGroupID();
}
}
else {
groupIDInLedger = -1;
coachGroupIDInLedger = -1;
}
if(viewGroups != null) {
Iterator viewGroupsIter = viewGroups.iterator();
//goes through the groups the user may view and prints out the entry if
//the group connected to the entry is the same as the group the user may view
while(viewGroupsIter.hasNext()) {
Group group =(Group) viewGroupsIter.next();
Integer groupID = (Integer) group.getPrimaryKey();
if(entry.getGroupID() == groupID.intValue()
|| groupIDInLedger == groupID.intValue()){
isInGroup = true;
}
}
}
if(groupIDInLedger == getViewGroupID()) {
isInGroup = true;
}
if(coachGroupIDInLedger == getViewGroupID()) {
isInGroup = true;
}
if(isInGroup || iwc.isSuperAdmin() ||
getViewGroupID() == entry.getGroupID() ||
(userID!=null && userID.intValue() == entry.getUserID())) {
String headline = getEntryHeadline(entry);
Link headlineLink = new Link(headline);
headlineLink.addParameter(ACTION,OPEN);
headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view);
headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear());
headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth());
headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay());
headlineLink.addParameter(CalendarEntryCreator.entryIDParameterName, entry.getPrimaryKey().toString());
if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc) || isPrintable) {
headlineLink.setWindowToOpen(EntryInfoWindow.class);
}
headlineLink.setStyleClass(entryLink);
String e = iwc.getParameter(CalendarEntryCreator.entryIDParameterName);
CalendarEntry ent = null;
if(e == null || e.equals("")) {
e = "";
}
else {
try {
ent = getCalBusiness(iwc).getEntry(Integer.parseInt(e));
}catch(Exception ex) {
ent = null;
}
}
if(ent != null) {
if(ent.getPrimaryKey().equals(entry.getPrimaryKey())) {
headlineLink.setStyleClass(entryLinkActive);
}
}
dayCell.add(headlineLink,1,cellRow);
dayCell.setVerticalAlignment(1,cellRow,"top");
dayCell.add("<br>",1,cellRow++);
}
}
backTable.add(dayCell,column,row);
backTable.setColor(column,row,"#ffffff");
backTable.add(Text.NON_BREAKING_SPACE,column,row);
backTable.setVerticalAlignment(column,row,"top");
column = column % 7 + 1;
if (column == 1)
row++;
n++;
}
table.add(topTable,1,1);
table.add(backTable,1,2);
return table;
}
|
diff --git a/src/com/zrd/zr/letuwb/WeiboPage.java b/src/com/zrd/zr/letuwb/WeiboPage.java
index 62867af..530d492 100644
--- a/src/com/zrd/zr/letuwb/WeiboPage.java
+++ b/src/com/zrd/zr/letuwb/WeiboPage.java
@@ -1,1593 +1,1593 @@
package com.zrd.zr.letuwb;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weibo4android.Comment;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.WeiboException;
import weibo4android.org.json.JSONArray;
import weibo4android.org.json.JSONException;
import weibo4android.org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import com.weibo.sdk.android.api.FriendshipsAPI;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.api.WeiboAPI.FEATURE;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.custom.Responds;
import com.weibo.sdk.android.custom.Status2;
import com.weibo.sdk.android.custom.User2;
import com.zrd.zr.pnj.ThreadPNJDealer;
import com.zrd.zr.protos.WeibousersProtos.UCMappings;
import com.zrd.zr.weiboes.Sina;
import com.zrd.zr.weiboes.ThreadSinaDealer;
public class WeiboPage {
private EntranceActivity parent;
private int mReferer = -1;
protected static final int COUNT_PERPAGE_TIMELINE = 20;
protected static final int COUNT_PERPAGE_COMMENTS = 20;
private TextView mTextScreenName;
private ImageView mImageVerified;
private TextView mTextCreatedAt;
private TextView mTextLocation;
private ImageButton mBtnDescription;
private TextView mTextCounts;
private ListView mListStatus;
private ProgressBar mProgressStatusLoading;
private TextView mTextPossess;
private TextView mTextFriendship;
private TextView mTextAtSomeone;
private ImageView mBtnTinyProfileImage;
private AlertDialog mDlgRepost;
private EditText mEditRepost;
private AlertDialog mDlgComment;
private EditText mEditComment;
private AlertDialog mDlgUpdateStatus;
private EditText mEditUpdateStatus;
private Button mBtnMoreTimelines;
private Button mBtnMoreComments;
private Dialog mDlgComments;
private Dialog mDlgMore;
private Long mUid = null;
private Long mId = null;
private User2 mLastUser = null;
private List<Sina.XStatus> mLastUserTimeline = new ArrayList<Sina.XStatus>();
private int mIndexOfSelectedStatus = -1;
private List<Comment> mLastComments = new ArrayList<Comment>();
//private AlphaAnimation mAnimFadein = new AlphaAnimation(0.1f, 1.0f);
//private AlphaAnimation mAnimFadeout = new AlphaAnimation(1.0f, 0.1f);
/*
* Handler for showing all kinds of SINA_weibo data from background thread.
*/
Handler mHandler = new Handler() {
@SuppressWarnings("unchecked")
public void handleMessage(Message msg) {
Sina sina = (Sina)msg.getData().getSerializable(ThreadSinaDealer.KEY_SINA);
if (sina == null) {
sina = mSina;
} else {
setSina(sina);
}
weibo4android.WeiboException wexp = (weibo4android.WeiboException)msg.getData().getSerializable(ThreadSinaDealer.KEY_WEIBO_ERR);
User user;
Status status;
Comment comment;
Responds resp;
Bundle bundle = msg.getData();
switch (msg.what) {
case ThreadPNJDealer.GET_POSSESSIONS:
UCMappings mappings = (UCMappings)msg.getData().getSerializable(ThreadPNJDealer.KEY_DATA);
if (mappings != null) {
if (mappings.getFlag() == 1) {
Toast.makeText(
parent,
R.string.tips_alreadypossessed,
Toast.LENGTH_LONG
).show();
} else if (mappings.getFlag() == 2) {
Toast.makeText(
parent,
R.string.tips_possessed,
Toast.LENGTH_LONG
).show();
} else {
Toast.makeText(
parent,
R.string.tips_failedtopossess,
Toast.LENGTH_LONG
).show();
}
} else {
//deal with failing to possess
}
break;
case ThreadSinaDealer.SHOW_USER:
//mLastUser = (User)msg.getData().getSerializable(ThreadSinaDealer.KEY_DATA);
case Responds.USERS_SHOW:
resp = (Responds) bundle.getSerializable(Responds.KEY_DATA);
switch (resp.getRespType()) {
case Responds.TYPE_COMPLETE:
try {
mLastUser = new User2(new JSONObject(resp.getRespOnComplete()));
} catch (WeiboException e) {
// TODO Auto-generated catch block
mLastUser = null;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
mLastUser = null;
e.printStackTrace();
} catch (NullPointerException e) {
mLastUser = null;
e.printStackTrace();
}
break;
case Responds.TYPE_ERROR:
case Responds.TYPE_IO_ERROR:
mLastUser = null;
break;
}
if (mLastUser != null) {
/*
* show the profile-image
*/
AsyncImageLoader ail = new AsyncImageLoader(
parent,
R.id.btnTinyProfileImage,
R.drawable.person
);
ail.execute(mLastUser.getProfileImageURL());
/*
* show the screen name
*/
mTextScreenName.setText(mLastUser.getScreenName());
/*
* show "v" if verified
*/
if (mLastUser.isVerified()) {
mImageVerified.setVisibility(ImageView.VISIBLE);
} else {
mImageVerified.setVisibility(ImageView.GONE);
}
/*
* show when was the user created
*/
Date dtCreatedAt = mLastUser.getCreatedAt();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
mTextCreatedAt.setText(sdf.format(dtCreatedAt));
/*
* show the location and the description
*/
mTextLocation.setText(
" [" + mLastUser.getLocation() + "]"
);
String description = mLastUser.getDescription();
if (!description.equals("")) {
mBtnDescription.setVisibility(ImageButton.VISIBLE);
mBtnDescription.setTag(description);
} else {
mBtnDescription.setVisibility(ImageButton.GONE);
mBtnDescription.setTag(null);
}
/*
* show all kinds of the counts
*/
String sCounts = parent.getString(R.string.label_weibos) + ":" + mLastUser.getStatusesCount()
+ " "
+ parent.getString(R.string.label_favorites) + ":" + mLastUser.getFavouritesCount()
+ " "
+ parent.getString(R.string.label_followers) + ":" + mLastUser.getFollowersCount()
+ " "
+ parent.getString(R.string.label_friends) + ":" + mLastUser.getFriendsCount();
mTextCounts.setText(sCounts);
parent.getBrowPage().getTextCounts_brow().setText(sCounts);
/*
* alter the label of "@" button according to the gender of the user
*/
if (mLastUser.getGender().equals("f")) {
mTextAtSomeone.setText(parent.getString(R.string.label_atsomeone) + parent.getString(R.string.label_her));
parent.getBrowPage().getBtnAtSomeone().setText(parent.getString(R.string.label_atsomeone) + parent.getString(R.string.label_her));
} else if (mLastUser.getGender().equals("m")){
mTextAtSomeone.setText(parent.getString(R.string.label_atsomeone) + parent.getString(R.string.label_him));
parent.getBrowPage().getBtnAtSomeone().setText(parent.getString(R.string.label_atsomeone) + parent.getString(R.string.label_him));
} else {
mTextAtSomeone.setText(parent.getString(R.string.label_atsomeone) + parent.getString(R.string.label_her) + "/" + parent.getString(R.string.label_him));
parent.getBrowPage().getBtnAtSomeone().setText(parent.getString(R.string.label_atsomeone) + parent.getString(R.string.label_her) + "/" + parent.getString(R.string.label_him));
}
} else {
mTextAtSomeone.setText(R.string.label_atsomeone);
parent.getBrowPage().getBtnAtSomeone().setText(R.string.label_atsomeone);
/*
* clear all kinds of the counts
*/
String sCounts = parent.getString(R.string.label_weibos) + ":-"
+ " "
+ parent.getString(R.string.label_favorites) + ":-"
+ " "
+ parent.getString(R.string.label_followers) + ":-"
+ " "
+ parent.getString(R.string.label_friends) + ":-";
mTextCounts.setText(sCounts);
parent.getBrowPage().getTextCounts_brow().setText(sCounts);
if (wexp != null) {
Toast.makeText(
parent,
//wexp.toString(),
R.string.tips_getweiboinfofailed,
Toast.LENGTH_LONG
).show();
}
}
break;
case ThreadSinaDealer.GET_USER_TIMELINE:
//ArrayList<Sina.XStatus> xstatuses = (ArrayList<Sina.XStatus>)msg.getData().getSerializable(ThreadSinaDealer.KEY_DATA);
case Responds.STATUSES_USERTIMELINE:
final ArrayList<Sina.XStatus> xstatuses = new ArrayList<Sina.XStatus>();
resp = (Responds) bundle.getSerializable(Responds.KEY_DATA);
switch (resp.getRespType()) {
case Responds.TYPE_COMPLETE:
JSONObject json;
try {
json = new JSONObject(resp.getRespOnComplete());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
json = null;
Toast.makeText(parent, "~~4debug~~00", Toast.LENGTH_LONG).show();
break;
}
JSONArray statuses;
ArrayList<String> ids = new ArrayList<String>();
try {
statuses = json.getJSONArray("statuses");
for (int i = 0; i < statuses.length(); i++) {
Sina.XStatus xstatus = mSina.getXStatus();
xstatus.setStatus(new Status2(statuses.getJSONObject(i)));
xstatuses.add(xstatus);
ids.add(statuses.getJSONObject(i).getString("id"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
statuses = null;
Toast.makeText(parent, "~~4debug~~11", Toast.LENGTH_LONG).show();
break;
}
//List<Status> tlist = mSina.getWeibo().getUserTimeline(mParams[0], paging);
catch (WeiboException e) {
// TODO Auto-generated catch block
e.printStackTrace();
statuses = null;
Toast.makeText(parent, "~~4debug~~22", Toast.LENGTH_LONG).show();
break;
} catch (NullPointerException e) {
e.printStackTrace();
statuses = null;
Toast.makeText(parent, "~~4debug~~33", Toast.LENGTH_LONG).show();
break;
}
if (ids.size() != 0) {
StatusesAPI api = new StatusesAPI(parent.getAccessToken());
String[] _ids = new String[ids.size()];
for (int i = 0; i < ids.size(); i++) {
_ids[i] = ids.get(i);
}
api.count(_ids,
new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
JSONArray counts;
try {
counts = new JSONArray(response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
counts = null;
}
for (int i = 0; counts != null && i < counts.length(); i++) {
for (int j = 0; j < xstatuses.size(); j++) {
try {
if (xstatuses.get(j).getStatus().getId()
== counts.getJSONObject(i).getLong("id")) {
xstatuses.get(j).setComments(counts.getJSONObject(i).getInt("comments"));
xstatuses.get(j).setReposts(counts.getJSONObject(i).getInt("reposts"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
}
});
}
break;
case Responds.TYPE_ERROR:
case Responds.TYPE_IO_ERROR:
break;
}
for (int i = 0; i < xstatuses.size(); i++) {
mLastUserTimeline.add(xstatuses.get(i));
}
/*
* show the user time_line
*/
WeiboStatusListAdapter adapter = new WeiboStatusListAdapter(
parent,
//getStatusData(ThreadSinaDealer.GET_USER_TIMELINE)
getStatusData(Responds.STATUSES_USERTIMELINE)
);
mListStatus.setAdapter(adapter);
mListStatus.setSelection(
(getLastUserTimelineTotalPage() - 1) * COUNT_PERPAGE_TIMELINE
);
turnDealing(false);
break;
/*
case ThreadSinaDealer.CREATE_FRIENDSHIP:
user = (User)msg.getData().getSerializable(ThreadSinaDealer.KEY_DATA);
if (user != null) {
if (!user.equals(mSina.getLoggedInUser())) {
Toast.makeText(
parent,
R.string.tips_friendsmade,
Toast.LENGTH_LONG
).show();
} else {
Toast.makeText(
parent,
R.string.tips_friendsalready,
Toast.LENGTH_LONG
).show();
}
} else {
//deal with failing to make friends
if (wexp != null) {
Toast.makeText(
parent,
//wexp.toString(),
R.string.tips_getweiboinfofailed,
Toast.LENGTH_LONG
).show();
}
}
turnDealing(false);
break;
*/
case Responds.FRIENDSHIPS_CREATE:
int fsc = msg.getData().getInt(Responds.KEY_DATA);
switch (fsc) {
case 0:
Toast.makeText(
parent,
R.string.tips_friendsalready,
Toast.LENGTH_LONG
).show();
break;
case 1:
Toast.makeText(
parent,
R.string.tips_friendsmade,
Toast.LENGTH_LONG
).show();
break;
case -1:
Toast.makeText(
parent,
R.string.tips_getweiboinfofailed,
Toast.LENGTH_LONG
).show();
default:
Toast.makeText(
parent,
R.string.tips_getweiboinfofailed,
Toast.LENGTH_SHORT
).show();
break;
}
turnDealing(false);
break;
case ThreadSinaDealer.CREATE_FAVORITE:
status = (Status)msg.getData().getSerializable(ThreadSinaDealer.KEY_DATA);
if (status != null) {
Toast.makeText(
parent,
R.string.tips_favoritemade,
Toast.LENGTH_LONG
).show();
} else {
//deal with failing to make favorite
if (wexp != null) {
Toast.makeText(
parent,
//wexp.toString(),
R.string.tips_getweiboinfofailed,
Toast.LENGTH_LONG
).show();
}
}
turnDealing(false);
break;
case ThreadSinaDealer.REPOST:
status = (Status)msg.getData().getSerializable(ThreadSinaDealer.KEY_DATA);
if (status != null) {
Toast.makeText(
parent,
R.string.tips_reposted,
Toast.LENGTH_LONG
).show();
} else {
//deal with failing to make favorite
if (wexp != null) {
Toast.makeText(
parent,
//wexp.toString(),
R.string.tips_getweiboinfofailed,
Toast.LENGTH_LONG
).show();
}
}
turnDealing(false);
break;
case ThreadSinaDealer.GET_COMMENTS:
ArrayList<Comment> comments = (ArrayList<Comment>)msg.getData().getSerializable(ThreadSinaDealer.KEY_DATA);
if (comments != null) {
if (comments.size() != 0) {
for (int i = 0; i < comments.size(); i++) {
mLastComments.add(comments.get(i));
}
if (mLastComments.size() != 0) {
ListView lv = (ListView)mDlgComments.findViewById(R.id.lvCustomList);
lv.removeFooterView(mBtnMoreComments);
lv.addFooterView(mBtnMoreComments);
ArrayList<String> contents = new ArrayList<String>();
WeiboStatusListAdapter _tmp =
new WeiboStatusListAdapter(parent, null);
for (int i = 0; i < mLastComments.size(); i++) {
user = mLastComments.get(i).getUser();
contents.add(
"[" + (i + 1) + "] "
+ (user != null ? user.getScreenName() : "")
+ "(" + _tmp.getSpecialDateText(mLastComments.get(i).getCreatedAt(), 0) + "):\n"
+ mLastComments.get(i).getText()
);
}
lv.setAdapter(
new ArrayAdapter<String>(
parent,
R.layout.item_custom_dialog_list,
contents
)
);
lv.setSelection(
(getLastCommentsTotalPage() - 1) * COUNT_PERPAGE_COMMENTS
);
} else {
Toast.makeText(
parent,
R.string.tips_nocomments,
Toast.LENGTH_LONG
).show();
}
} else {
Toast.makeText(
parent,
R.string.tips_nomorecomments,
Toast.LENGTH_LONG
).show();
mBtnMoreComments.setTag(2);
mBtnMoreComments.setEnabled(false);
}
} else {
//deal with failing to get comments
Integer flag = (Integer)mBtnMoreComments.getTag();
if (flag != null && flag != 0) {
//if mBtnMoreComments was clicked, then do something here
mDlgComments.dismiss();
} else {
//if mBtnMoreComments was not clicked, do something here
}
if (wexp != null) {
Toast.makeText(
parent,
//wexp.toString(),
R.string.tips_getweiboinfofailed,
Toast.LENGTH_LONG
).show();
}
}
turnDealing(false);
break;
case ThreadSinaDealer.UPDATE_COMMENT:
comment = (Comment)msg.getData().getSerializable(ThreadSinaDealer.KEY_DATA);
if (comment != null) {
Toast.makeText(
parent,
R.string.tips_commented,
Toast.LENGTH_LONG
).show();
} else {
//deal with failing to make favorite
if (wexp != null) {
Toast.makeText(
parent,
//wexp.toString(),
R.string.tips_getweiboinfofailed,
Toast.LENGTH_LONG
).show();
}
}
turnDealing(false);
break;
case ThreadSinaDealer.UPDATE_STATUS:
status = (Status)msg.getData().getSerializable(ThreadSinaDealer.KEY_DATA);
if (status != null) {
Toast.makeText(
parent,
R.string.tips_statusupdated,
Toast.LENGTH_LONG
).show();
} else {
//deal with failing to make favorite
if (wexp != null) {
Toast.makeText(
parent,
//wexp.toString(),
R.string.tips_getweiboinfofailed,
Toast.LENGTH_LONG
).show();
}
}
turnDealing(false);
break;
case Sina.REFRESH_USERBAR:
ImageView iv = (ImageView)parent.findViewById(R.id.ivTitleIcon);
TextView tv = (TextView)parent.findViewById(R.id.tvTitleName);
if (iv != null && tv != null && getSina().getLoggedInUser() != null) {
AsyncImageLoader loader = new AsyncImageLoader(parent,
iv, R.drawable.person);
loader.execute(getSina().getLoggedInUser().getProfileImageURL());
tv.setText(getSina().getLoggedInUser().getScreenName());
}
break;
}
}
};
private Sina mSina = new Sina(mHandler);
WeiboPage(EntranceActivity activity) {
this.parent = activity;
mTextScreenName = (TextView)parent.findViewById(R.id.tvScreenName);
mImageVerified = (ImageView)parent.findViewById(R.id.ivVerified);
mTextCreatedAt = (TextView)parent.findViewById(R.id.tvCreatedAt);
mTextLocation = (TextView)parent.findViewById(R.id.tvLocation);
mBtnDescription = (ImageButton)parent.findViewById(R.id.btnDescription);
mTextCounts = (TextView)parent.findViewById(R.id.tvCounts);
mListStatus = (ListView)parent.findViewById(R.id.lvStatus);
mProgressStatusLoading = (ProgressBar)parent.findViewById(R.id.pbStatusLoading);
mTextPossess = (TextView)parent.findViewById(R.id.tvPossess);
mTextFriendship = (TextView)parent.findViewById(R.id.tvFriendship);
mTextAtSomeone = (TextView)parent.findViewById(R.id.tvAtSomeone);
mEditRepost = new EditText(parent);
mEditComment = new EditText(parent);
mBtnTinyProfileImage = (ImageButton)parent.findViewById(R.id.btnTinyProfileImage);
mEditUpdateStatus = new EditText(parent);
mImageVerified.setVisibility(ImageView.GONE);
mBtnDescription.setVisibility(ImageButton.GONE);
mBtnMoreTimelines = new Button(parent);
mBtnMoreTimelines.setText(R.string.label_getmore);
mBtnMoreTimelines.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.GET_USER_TIMELINE,
new String[] {
getUid().toString(),
"" + (getLastUserTimelineTotalPage() + 1),
"" + COUNT_PERPAGE_TIMELINE
},
mHandler
)
).start();
*/
StatusesAPI api = new StatusesAPI(parent.getAccessToken());
api.userTimeline(getUid(), 0, 0,
COUNT_PERPAGE_TIMELINE/*how many lines*/,
(getLastUserTimelineTotalPage() + 1),
false, FEATURE.ALL, false,
new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, response);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, e);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, e);
}
});
turnDealing(true);
}
});
mListStatus.addFooterView(mBtnMoreTimelines);
mBtnMoreComments = new Button(parent);
mBtnMoreComments.setText(R.string.label_getmore);
/*
* 0 means not clicked
* 1 means clicked
* 2 means should not be clicked till next comments showing up
*/
mBtnMoreComments.setTag(0);
mBtnMoreComments.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.GET_COMMENTS,
new String[] {
"" + sid,
"" + (getLastCommentsTotalPage() + 1),
"" + COUNT_PERPAGE_COMMENTS
},
mHandler
)
).start();
turnDealing(true);
mBtnMoreComments.setTag(1);
}
});
mBtnTinyProfileImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*
Intent intent = new Intent();
intent.setClass(WeiboShowActivity.this, PicbrowActivity.class);
intent.putExtra("id", mId);
startActivity(intent);
*/
parent.getBrowPage().setReferer(R.layout.main);
//parent.switchPage(R.layout.brow, mId);
parent.switchPage(R.layout.brow);
}
});
mDlgRepost = new AlertDialog.Builder(parent)
.setTitle(R.string.title_repost)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(mEditRepost)
.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
/*
* This is the place it handles reposting
*/
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.REPOST,
new String[] {"" + sid, mEditRepost.getText().toString()},
mHandler
)
).start();
turnDealing(true);
}
})
.setNegativeButton(R.string.label_cancel, null)
.create();
mDlgComment = new AlertDialog.Builder(parent)
.setTitle(R.string.title_comment)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(mEditComment)
.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
/*
* This is the place it handles comment
*/
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.UPDATE_COMMENT,
new String[] {mEditComment.getText().toString(), "" + sid, null},
mHandler
)
).start();
turnDealing(true);
}
})
.setNegativeButton(R.string.label_cancel, null)
.create();
mDlgUpdateStatus = new AlertDialog.Builder(parent)
.setTitle(R.string.title_updatestatus)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(mEditUpdateStatus)
.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
/*
* This is the place it handles comment
*/
Toast.makeText(
parent,
R.string.tips_statusupdating,
Toast.LENGTH_LONG
).show();
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.UPDATE_STATUS,
new String[] {mEditUpdateStatus.getText().toString()},
mHandler
)
).start();
turnDealing(true);
}
})
.setNegativeButton(R.string.label_cancel, null)
.create();
mDlgComments = new Dialog(parent, R.style.Dialog_Clean);
mDlgComments.setContentView(R.layout.custom_dialog_list);
ListView lvComments = (ListView)mDlgComments.findViewById(R.id.lvCustomList);
lvComments.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
mDlgComments.dismiss();
}
});
/*
* deal actions for components
*/
mListStatus.setTag((long)0);
mListStatus.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
/*
* make the selected item different with others
*/
int position = arg2;
/*
HeaderViewListAdapter ha = (HeaderViewListAdapter)parent.getAdapter();
WeiboStatusListAdapter adapter = (WeiboStatusListAdapter)ha.getWrappedAdapter();
adapter.setSelectedItem(position);
adapter.notifyDataSetInvalidated();
*/
mIndexOfSelectedStatus = position;
/*
* pop up the "more" list
*/
mDlgMore.show();
long lastClickTime;
/*
* check if it's double click
*/
lastClickTime = (Long)mListStatus.getTag();
if (Math.abs(lastClickTime-System.currentTimeMillis()) < 2000) {
mListStatus.setTag((long)0);
//to do some double click stuff here
showComments();
turnDealing(true);
} else {
mListStatus.setTag(System.currentTimeMillis());
}
}
});
mListStatus.setOnScrollListener(new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
//when it's not scrolling
if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){
//if it's already to the bottom
if(view.getLastVisiblePosition()==(view.getCount()-1)){
Toast.makeText(
parent,
R.string.tips_alreadylastone,
Toast.LENGTH_LONG
).show();
}
}
}
});
mBtnDescription.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
parent.popupDescription((String) mBtnDescription.getTag());
}
});
mTextPossess.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(
new ThreadPNJDealer(
ThreadPNJDealer.GET_POSSESSIONS,
EntranceActivity.URL_SITE
+ "updpzs.php?"
+ "clientkey=" + EntranceActivity.getClientKey()
+ "&channelid=0"
+ "&uid=" + getUid(),
mHandler
)
).start();
}
});
mTextFriendship.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mSina != null && mSina.isLoggedIn()) {
/*
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.CREATE_FRIENDSHIP,
new String[] {getUid().toString()},
mHandler
)
).start();
*/
turnDealing(true);
FriendshipsAPI api = new FriendshipsAPI(parent.getAccessToken());
//step 1, judge if already friends
//step 2, if not yet, create it
User2 usr = getSina().getLoggedInUser();
api.show(usr.getId(), getUid(), new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
FriendshipsAPI api = new FriendshipsAPI(parent.getAccessToken());
try {
JSONObject json = new JSONObject(response);
JSONObject target = new JSONObject(json.getString("target"));
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
if (target.getBoolean("followed_by")) {
/**
* 0 means "already friends"
* 1 means "friendships created"
* -1 means "friendships failed to be created"
* <-1 means other errors
*/
bundle.putInt(Responds.KEY_DATA , 0);
msg.setData(bundle);
mHandler.sendMessage(msg);
} else {
api.create(getUid(), null, new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
try {
JSONObject json = new JSONObject(response);
if (json.has("id")) {
bundle.putInt(Responds.KEY_DATA, 1);
} else {
bundle.putInt(Responds.KEY_DATA, -1);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
bundle.putInt(Responds.KEY_DATA, -2);
}
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -3);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -4);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -5);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -6);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -7);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
});
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
}
});
mTextAtSomeone.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mLastUser == null) {
Toast.makeText(
parent,
R.string.tips_waitforgettinguser,
Toast.LENGTH_LONG
).show();
} else {
mEditUpdateStatus.setText(
"@" + mLastUser.getScreenName() + ":"
- + parent.getString(R.string.tips_routinehello)
+ + String.format(parent.getString(R.string.tips_routinehello), parent.getString(R.string.app_name))
+ " \"" + parent.getString(R.string.app_name)
+ "\":" + EntranceActivity.URL_UPDATE + "letuwb.apk"
);
mDlgUpdateStatus.show();
}
}
});
mDlgMore = new Dialog(parent, R.style.Dialog_Clean);
mDlgMore.setContentView(R.layout.custom_dialog_list);
ListView lvMore = (ListView)mDlgMore.findViewById(R.id.lvCustomList);
ArrayList<String> mlist = new ArrayList<String>();
mlist.add(parent.getString(R.string.label_weibo_favorite));
mlist.add(parent.getString(R.string.label_comment));
mlist.add(parent.getString(R.string.label_weibo_repost));
mlist.add(parent.getString(R.string.label_comments));
mlist.add(parent.getString(R.string.label_seebiggerimage0));
mlist.add(parent.getString(R.string.label_seebiggerimage1));
mlist.add(parent.getString(R.string.label_reload));
lvMore.setAdapter(
new ArrayAdapter<String> (
parent,
R.layout.item_custom_dialog_list,
mlist
)
);
lvMore.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> av, View view,
int position, long id) {
// TODO Auto-generated method stub
String originalPic;
switch (position) {
case 0:
if (mSina != null && mSina.isLoggedIn()) {
if (mIndexOfSelectedStatus != -1) {
/*
* make it favorite
*/
if (mLastUserTimeline == null) {
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.CREATE_FAVORITE,
new String[] {"" + mLastUser.getStatus().getId()},
mHandler
)
).start();
} else {
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.CREATE_FAVORITE,
new String[] {"" + mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId()},
mHandler
)
).start();
}
turnDealing(true);
} else {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
}
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
break;
case 1:
if (mSina != null && mSina.isLoggedIn()) {
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
return;
}
mDlgComment.show();
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
break;
case 2:
if (mSina != null && mSina.isLoggedIn()) {
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
return;
}
mDlgRepost.show();
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
break;
case 3:
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
} else {
showComments();
turnDealing(true);
}
break;
case 4:
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
} else {
originalPic = mLastUserTimeline
.get(mIndexOfSelectedStatus)
.getStatus()
.getOriginal_pic();
if (originalPic != null && !originalPic.trim().equals("")) {
showOriginalImage(originalPic);
} else {
Toast.makeText(
parent,
R.string.tips_nooriginalimage0,
Toast.LENGTH_LONG
).show();
}
}
break;
case 5:
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
} else {
Status2 retweeted = mLastUserTimeline
.get(mIndexOfSelectedStatus)
.getStatus()
.getRetweeted_status();
if (retweeted != null) {
originalPic = retweeted.getOriginal_pic();
} else {
originalPic = null;
}
if (originalPic != null && !originalPic.trim().equals("")) {
showOriginalImage(originalPic);
} else {
Toast.makeText(
parent,
R.string.tips_nooriginalimage1,
Toast.LENGTH_LONG
).show();
}
}
break;
case 6:
reloadAll();
turnDealing(true);
break;
}
mDlgMore.dismiss();
}
});
}
protected void showComments() {
// TODO Auto-generated method stub
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
mLastComments.clear();
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.GET_COMMENTS,
new String[] {
"" + sid,
"" + getLastCommentsTotalPage(),
"" + COUNT_PERPAGE_COMMENTS
},
mHandler
)
).start();
ListView lvComments = (ListView)mDlgComments.findViewById(R.id.lvCustomList);
ArrayList<String> lstWaiting = new ArrayList<String>();
lstWaiting.add(parent.getString(R.string.tips_waitasecond));
lvComments.removeFooterView(mBtnMoreComments);
mBtnMoreComments.setTag(0);
mBtnMoreComments.setEnabled(true);
lvComments.setAdapter(
new ArrayAdapter<String>(
parent,
R.layout.item_custom_dialog_list,
lstWaiting
)
);
mDlgComments.show();
}
public void reloadLastUser(Long uid) {
mLastUser = null;
mIndexOfSelectedStatus = -1;
/*
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.SHOW_USER,
new String[] {uid.toString()},
mHandler
)
).start();
*/
UsersAPI api = new UsersAPI(parent.getAccessToken());
api.show(uid,
new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
fireToUI(Responds.USERS_SHOW, response);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
fireToUI(Responds.USERS_SHOW, e);
}
@Override
public void onError(com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
fireToUI(Responds.USERS_SHOW, e);
}
});
}
protected void reloadAll() {
// TODO Auto-generated method stub
if (mLastUser == null) {
reloadLastUser(getUid());
}
mLastUserTimeline.clear();
/*
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.GET_USER_TIMELINE,
new String[] {getUid().toString(), "" + getLastUserTimelineTotalPage(), "" + COUNT_PERPAGE_TIMELINE},
mHandler
)
).start();
*/
StatusesAPI api = new StatusesAPI(parent.getAccessToken());
api.userTimeline(getUid(), 0, 0,
COUNT_PERPAGE_TIMELINE/*how many lines*/,
(getLastUserTimelineTotalPage() + 1),
false, FEATURE.ALL, false,
new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, response);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, e);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, e);
}
});
}
protected int getLastUserTimelineTotalPage() {
// TODO Auto-generated method stub
if (mLastUserTimeline == null) return 1;
int size = mLastUserTimeline.size();
if (size == 0) return 1;
if (size % COUNT_PERPAGE_TIMELINE != 0) return size / COUNT_PERPAGE_TIMELINE + 1;
else return size / COUNT_PERPAGE_TIMELINE;
}
protected int getLastCommentsTotalPage() {
if (mLastComments == null) return 1;
int size = mLastComments.size();
if (size == 0) return 1;
if (size % COUNT_PERPAGE_COMMENTS != 0) return size / COUNT_PERPAGE_COMMENTS + 1;
else return size / COUNT_PERPAGE_COMMENTS;
}
public Sina getSina() {
return mSina;
}
public void setSina(Sina sina) {
mSina = sina;
}
public int getPrivilege() {
return mSina.getLoggedInUser() == null ? 1 : 0;
}
private List<Map<String, Object>> getStatusData(int type) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map;
Sina.XStatus xstatus;
switch (type) {
case ThreadSinaDealer.SHOW_USER:
if (mLastUser != null) {
xstatus = mSina.getXStatus();
xstatus.setStatus(mLastUser.getStatus());
if (xstatus != null) {
map = new HashMap<String, Object>();
map.put("xstatus", xstatus);
list.add(map);
}
}
break;
case ThreadSinaDealer.GET_USER_TIMELINE:
case Responds.STATUSES_USERTIMELINE:
if (mLastUserTimeline != null) {
for (int i = 0; i < mLastUserTimeline.size(); i++) {
xstatus = mLastUserTimeline.get(i);
map = new HashMap<String, Object>();
map.put("xstatus", xstatus);
list.add(map);
}
}
break;
}
return list;
}
/*
* change the status for the components when dealing with SINA_weibo data
*/
public void turnDealing(boolean on) {
if (on == true) {
mTextPossess.setEnabled(false);
mBtnMoreTimelines.setEnabled(false);
mBtnMoreComments.setEnabled(false);
mProgressStatusLoading.setVisibility(ProgressBar.VISIBLE);
} else {
mTextPossess.setEnabled(true);
mBtnMoreTimelines.setEnabled(true);
Integer flag = (Integer)mBtnMoreComments.getTag();
if (flag != null && flag == 2) {
} else {
mBtnMoreComments.setEnabled(true);
}
mProgressStatusLoading.setVisibility(ProgressBar.GONE);
}
}
/*
* try to show pictures from weibo in a dialog
* with given uri
*/
protected void showOriginalImage(String sUrl) {
Intent intent = new Intent();
intent.putExtra("url", sUrl);
intent.setClass(parent, ImageActivity.class);
parent.startActivity(intent);
}
private void fireToUI(int act, String arg) {
if (mHandler == null) return;
Message msg = new Message();
msg.what = act;
Responds resp = new Responds(msg.what);
resp.setRespOnComplete(arg);
Bundle bundle = new Bundle();
bundle.putSerializable(Responds.KEY_DATA, resp);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
private void fireToUI(int act, com.weibo.sdk.android.WeiboException arg) {
if (mHandler == null) return;
Message msg = new Message();
msg.what = act;
Responds resp = new Responds(msg.what);
resp.setRespOnError(arg);
Bundle bundle = new Bundle();
bundle.putSerializable(Responds.KEY_DATA, resp);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
private void fireToUI(int act, IOException arg) {
if (mHandler == null) return;
Message msg = new Message();
msg.what = act;
Responds resp = new Responds(msg.what);
resp.setRespOnIOError(arg);
Bundle bundle = new Bundle();
bundle.putSerializable(Responds.KEY_DATA, resp);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
public Long getUid() {
return mUid;
}
public void setUid(Long mUid) {
this.mUid = mUid;
}
public int getReferer() {
return mReferer;
}
public void setReferer(int mReferer) {
this.mReferer = mReferer;
}
public Long getId() {
return mId;
}
public void setId(Long mId) {
this.mId = mId;
}
public User2 getLastUser() {
return this.mLastUser;
}
public TextView getTextAtSomeone() {
return this.mTextAtSomeone;
}
public void friendshipClick() {
mTextFriendship.performClick();
}
}
| true | true | WeiboPage(EntranceActivity activity) {
this.parent = activity;
mTextScreenName = (TextView)parent.findViewById(R.id.tvScreenName);
mImageVerified = (ImageView)parent.findViewById(R.id.ivVerified);
mTextCreatedAt = (TextView)parent.findViewById(R.id.tvCreatedAt);
mTextLocation = (TextView)parent.findViewById(R.id.tvLocation);
mBtnDescription = (ImageButton)parent.findViewById(R.id.btnDescription);
mTextCounts = (TextView)parent.findViewById(R.id.tvCounts);
mListStatus = (ListView)parent.findViewById(R.id.lvStatus);
mProgressStatusLoading = (ProgressBar)parent.findViewById(R.id.pbStatusLoading);
mTextPossess = (TextView)parent.findViewById(R.id.tvPossess);
mTextFriendship = (TextView)parent.findViewById(R.id.tvFriendship);
mTextAtSomeone = (TextView)parent.findViewById(R.id.tvAtSomeone);
mEditRepost = new EditText(parent);
mEditComment = new EditText(parent);
mBtnTinyProfileImage = (ImageButton)parent.findViewById(R.id.btnTinyProfileImage);
mEditUpdateStatus = new EditText(parent);
mImageVerified.setVisibility(ImageView.GONE);
mBtnDescription.setVisibility(ImageButton.GONE);
mBtnMoreTimelines = new Button(parent);
mBtnMoreTimelines.setText(R.string.label_getmore);
mBtnMoreTimelines.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.GET_USER_TIMELINE,
new String[] {
getUid().toString(),
"" + (getLastUserTimelineTotalPage() + 1),
"" + COUNT_PERPAGE_TIMELINE
},
mHandler
)
).start();
*/
StatusesAPI api = new StatusesAPI(parent.getAccessToken());
api.userTimeline(getUid(), 0, 0,
COUNT_PERPAGE_TIMELINE/*how many lines*/,
(getLastUserTimelineTotalPage() + 1),
false, FEATURE.ALL, false,
new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, response);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, e);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, e);
}
});
turnDealing(true);
}
});
mListStatus.addFooterView(mBtnMoreTimelines);
mBtnMoreComments = new Button(parent);
mBtnMoreComments.setText(R.string.label_getmore);
/*
* 0 means not clicked
* 1 means clicked
* 2 means should not be clicked till next comments showing up
*/
mBtnMoreComments.setTag(0);
mBtnMoreComments.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.GET_COMMENTS,
new String[] {
"" + sid,
"" + (getLastCommentsTotalPage() + 1),
"" + COUNT_PERPAGE_COMMENTS
},
mHandler
)
).start();
turnDealing(true);
mBtnMoreComments.setTag(1);
}
});
mBtnTinyProfileImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*
Intent intent = new Intent();
intent.setClass(WeiboShowActivity.this, PicbrowActivity.class);
intent.putExtra("id", mId);
startActivity(intent);
*/
parent.getBrowPage().setReferer(R.layout.main);
//parent.switchPage(R.layout.brow, mId);
parent.switchPage(R.layout.brow);
}
});
mDlgRepost = new AlertDialog.Builder(parent)
.setTitle(R.string.title_repost)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(mEditRepost)
.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
/*
* This is the place it handles reposting
*/
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.REPOST,
new String[] {"" + sid, mEditRepost.getText().toString()},
mHandler
)
).start();
turnDealing(true);
}
})
.setNegativeButton(R.string.label_cancel, null)
.create();
mDlgComment = new AlertDialog.Builder(parent)
.setTitle(R.string.title_comment)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(mEditComment)
.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
/*
* This is the place it handles comment
*/
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.UPDATE_COMMENT,
new String[] {mEditComment.getText().toString(), "" + sid, null},
mHandler
)
).start();
turnDealing(true);
}
})
.setNegativeButton(R.string.label_cancel, null)
.create();
mDlgUpdateStatus = new AlertDialog.Builder(parent)
.setTitle(R.string.title_updatestatus)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(mEditUpdateStatus)
.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
/*
* This is the place it handles comment
*/
Toast.makeText(
parent,
R.string.tips_statusupdating,
Toast.LENGTH_LONG
).show();
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.UPDATE_STATUS,
new String[] {mEditUpdateStatus.getText().toString()},
mHandler
)
).start();
turnDealing(true);
}
})
.setNegativeButton(R.string.label_cancel, null)
.create();
mDlgComments = new Dialog(parent, R.style.Dialog_Clean);
mDlgComments.setContentView(R.layout.custom_dialog_list);
ListView lvComments = (ListView)mDlgComments.findViewById(R.id.lvCustomList);
lvComments.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
mDlgComments.dismiss();
}
});
/*
* deal actions for components
*/
mListStatus.setTag((long)0);
mListStatus.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
/*
* make the selected item different with others
*/
int position = arg2;
/*
HeaderViewListAdapter ha = (HeaderViewListAdapter)parent.getAdapter();
WeiboStatusListAdapter adapter = (WeiboStatusListAdapter)ha.getWrappedAdapter();
adapter.setSelectedItem(position);
adapter.notifyDataSetInvalidated();
*/
mIndexOfSelectedStatus = position;
/*
* pop up the "more" list
*/
mDlgMore.show();
long lastClickTime;
/*
* check if it's double click
*/
lastClickTime = (Long)mListStatus.getTag();
if (Math.abs(lastClickTime-System.currentTimeMillis()) < 2000) {
mListStatus.setTag((long)0);
//to do some double click stuff here
showComments();
turnDealing(true);
} else {
mListStatus.setTag(System.currentTimeMillis());
}
}
});
mListStatus.setOnScrollListener(new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
//when it's not scrolling
if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){
//if it's already to the bottom
if(view.getLastVisiblePosition()==(view.getCount()-1)){
Toast.makeText(
parent,
R.string.tips_alreadylastone,
Toast.LENGTH_LONG
).show();
}
}
}
});
mBtnDescription.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
parent.popupDescription((String) mBtnDescription.getTag());
}
});
mTextPossess.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(
new ThreadPNJDealer(
ThreadPNJDealer.GET_POSSESSIONS,
EntranceActivity.URL_SITE
+ "updpzs.php?"
+ "clientkey=" + EntranceActivity.getClientKey()
+ "&channelid=0"
+ "&uid=" + getUid(),
mHandler
)
).start();
}
});
mTextFriendship.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mSina != null && mSina.isLoggedIn()) {
/*
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.CREATE_FRIENDSHIP,
new String[] {getUid().toString()},
mHandler
)
).start();
*/
turnDealing(true);
FriendshipsAPI api = new FriendshipsAPI(parent.getAccessToken());
//step 1, judge if already friends
//step 2, if not yet, create it
User2 usr = getSina().getLoggedInUser();
api.show(usr.getId(), getUid(), new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
FriendshipsAPI api = new FriendshipsAPI(parent.getAccessToken());
try {
JSONObject json = new JSONObject(response);
JSONObject target = new JSONObject(json.getString("target"));
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
if (target.getBoolean("followed_by")) {
/**
* 0 means "already friends"
* 1 means "friendships created"
* -1 means "friendships failed to be created"
* <-1 means other errors
*/
bundle.putInt(Responds.KEY_DATA , 0);
msg.setData(bundle);
mHandler.sendMessage(msg);
} else {
api.create(getUid(), null, new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
try {
JSONObject json = new JSONObject(response);
if (json.has("id")) {
bundle.putInt(Responds.KEY_DATA, 1);
} else {
bundle.putInt(Responds.KEY_DATA, -1);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
bundle.putInt(Responds.KEY_DATA, -2);
}
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -3);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -4);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -5);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -6);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -7);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
});
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
}
});
mTextAtSomeone.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mLastUser == null) {
Toast.makeText(
parent,
R.string.tips_waitforgettinguser,
Toast.LENGTH_LONG
).show();
} else {
mEditUpdateStatus.setText(
"@" + mLastUser.getScreenName() + ":"
+ parent.getString(R.string.tips_routinehello)
+ " \"" + parent.getString(R.string.app_name)
+ "\":" + EntranceActivity.URL_UPDATE + "letuwb.apk"
);
mDlgUpdateStatus.show();
}
}
});
mDlgMore = new Dialog(parent, R.style.Dialog_Clean);
mDlgMore.setContentView(R.layout.custom_dialog_list);
ListView lvMore = (ListView)mDlgMore.findViewById(R.id.lvCustomList);
ArrayList<String> mlist = new ArrayList<String>();
mlist.add(parent.getString(R.string.label_weibo_favorite));
mlist.add(parent.getString(R.string.label_comment));
mlist.add(parent.getString(R.string.label_weibo_repost));
mlist.add(parent.getString(R.string.label_comments));
mlist.add(parent.getString(R.string.label_seebiggerimage0));
mlist.add(parent.getString(R.string.label_seebiggerimage1));
mlist.add(parent.getString(R.string.label_reload));
lvMore.setAdapter(
new ArrayAdapter<String> (
parent,
R.layout.item_custom_dialog_list,
mlist
)
);
lvMore.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> av, View view,
int position, long id) {
// TODO Auto-generated method stub
String originalPic;
switch (position) {
case 0:
if (mSina != null && mSina.isLoggedIn()) {
if (mIndexOfSelectedStatus != -1) {
/*
* make it favorite
*/
if (mLastUserTimeline == null) {
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.CREATE_FAVORITE,
new String[] {"" + mLastUser.getStatus().getId()},
mHandler
)
).start();
} else {
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.CREATE_FAVORITE,
new String[] {"" + mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId()},
mHandler
)
).start();
}
turnDealing(true);
} else {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
}
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
break;
case 1:
if (mSina != null && mSina.isLoggedIn()) {
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
return;
}
mDlgComment.show();
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
break;
case 2:
if (mSina != null && mSina.isLoggedIn()) {
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
return;
}
mDlgRepost.show();
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
break;
case 3:
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
} else {
showComments();
turnDealing(true);
}
break;
case 4:
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
} else {
originalPic = mLastUserTimeline
.get(mIndexOfSelectedStatus)
.getStatus()
.getOriginal_pic();
if (originalPic != null && !originalPic.trim().equals("")) {
showOriginalImage(originalPic);
} else {
Toast.makeText(
parent,
R.string.tips_nooriginalimage0,
Toast.LENGTH_LONG
).show();
}
}
break;
case 5:
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
} else {
Status2 retweeted = mLastUserTimeline
.get(mIndexOfSelectedStatus)
.getStatus()
.getRetweeted_status();
if (retweeted != null) {
originalPic = retweeted.getOriginal_pic();
} else {
originalPic = null;
}
if (originalPic != null && !originalPic.trim().equals("")) {
showOriginalImage(originalPic);
} else {
Toast.makeText(
parent,
R.string.tips_nooriginalimage1,
Toast.LENGTH_LONG
).show();
}
}
break;
case 6:
reloadAll();
turnDealing(true);
break;
}
mDlgMore.dismiss();
}
});
}
| WeiboPage(EntranceActivity activity) {
this.parent = activity;
mTextScreenName = (TextView)parent.findViewById(R.id.tvScreenName);
mImageVerified = (ImageView)parent.findViewById(R.id.ivVerified);
mTextCreatedAt = (TextView)parent.findViewById(R.id.tvCreatedAt);
mTextLocation = (TextView)parent.findViewById(R.id.tvLocation);
mBtnDescription = (ImageButton)parent.findViewById(R.id.btnDescription);
mTextCounts = (TextView)parent.findViewById(R.id.tvCounts);
mListStatus = (ListView)parent.findViewById(R.id.lvStatus);
mProgressStatusLoading = (ProgressBar)parent.findViewById(R.id.pbStatusLoading);
mTextPossess = (TextView)parent.findViewById(R.id.tvPossess);
mTextFriendship = (TextView)parent.findViewById(R.id.tvFriendship);
mTextAtSomeone = (TextView)parent.findViewById(R.id.tvAtSomeone);
mEditRepost = new EditText(parent);
mEditComment = new EditText(parent);
mBtnTinyProfileImage = (ImageButton)parent.findViewById(R.id.btnTinyProfileImage);
mEditUpdateStatus = new EditText(parent);
mImageVerified.setVisibility(ImageView.GONE);
mBtnDescription.setVisibility(ImageButton.GONE);
mBtnMoreTimelines = new Button(parent);
mBtnMoreTimelines.setText(R.string.label_getmore);
mBtnMoreTimelines.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.GET_USER_TIMELINE,
new String[] {
getUid().toString(),
"" + (getLastUserTimelineTotalPage() + 1),
"" + COUNT_PERPAGE_TIMELINE
},
mHandler
)
).start();
*/
StatusesAPI api = new StatusesAPI(parent.getAccessToken());
api.userTimeline(getUid(), 0, 0,
COUNT_PERPAGE_TIMELINE/*how many lines*/,
(getLastUserTimelineTotalPage() + 1),
false, FEATURE.ALL, false,
new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, response);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, e);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
fireToUI(Responds.STATUSES_USERTIMELINE, e);
}
});
turnDealing(true);
}
});
mListStatus.addFooterView(mBtnMoreTimelines);
mBtnMoreComments = new Button(parent);
mBtnMoreComments.setText(R.string.label_getmore);
/*
* 0 means not clicked
* 1 means clicked
* 2 means should not be clicked till next comments showing up
*/
mBtnMoreComments.setTag(0);
mBtnMoreComments.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.GET_COMMENTS,
new String[] {
"" + sid,
"" + (getLastCommentsTotalPage() + 1),
"" + COUNT_PERPAGE_COMMENTS
},
mHandler
)
).start();
turnDealing(true);
mBtnMoreComments.setTag(1);
}
});
mBtnTinyProfileImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*
Intent intent = new Intent();
intent.setClass(WeiboShowActivity.this, PicbrowActivity.class);
intent.putExtra("id", mId);
startActivity(intent);
*/
parent.getBrowPage().setReferer(R.layout.main);
//parent.switchPage(R.layout.brow, mId);
parent.switchPage(R.layout.brow);
}
});
mDlgRepost = new AlertDialog.Builder(parent)
.setTitle(R.string.title_repost)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(mEditRepost)
.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
/*
* This is the place it handles reposting
*/
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.REPOST,
new String[] {"" + sid, mEditRepost.getText().toString()},
mHandler
)
).start();
turnDealing(true);
}
})
.setNegativeButton(R.string.label_cancel, null)
.create();
mDlgComment = new AlertDialog.Builder(parent)
.setTitle(R.string.title_comment)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(mEditComment)
.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
/*
* This is the place it handles comment
*/
long sid;
if (mLastUserTimeline == null) {
sid = mLastUser.getStatus().getId();
} else {
sid = mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId();
}
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.UPDATE_COMMENT,
new String[] {mEditComment.getText().toString(), "" + sid, null},
mHandler
)
).start();
turnDealing(true);
}
})
.setNegativeButton(R.string.label_cancel, null)
.create();
mDlgUpdateStatus = new AlertDialog.Builder(parent)
.setTitle(R.string.title_updatestatus)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(mEditUpdateStatus)
.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
/*
* This is the place it handles comment
*/
Toast.makeText(
parent,
R.string.tips_statusupdating,
Toast.LENGTH_LONG
).show();
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.UPDATE_STATUS,
new String[] {mEditUpdateStatus.getText().toString()},
mHandler
)
).start();
turnDealing(true);
}
})
.setNegativeButton(R.string.label_cancel, null)
.create();
mDlgComments = new Dialog(parent, R.style.Dialog_Clean);
mDlgComments.setContentView(R.layout.custom_dialog_list);
ListView lvComments = (ListView)mDlgComments.findViewById(R.id.lvCustomList);
lvComments.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
mDlgComments.dismiss();
}
});
/*
* deal actions for components
*/
mListStatus.setTag((long)0);
mListStatus.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
/*
* make the selected item different with others
*/
int position = arg2;
/*
HeaderViewListAdapter ha = (HeaderViewListAdapter)parent.getAdapter();
WeiboStatusListAdapter adapter = (WeiboStatusListAdapter)ha.getWrappedAdapter();
adapter.setSelectedItem(position);
adapter.notifyDataSetInvalidated();
*/
mIndexOfSelectedStatus = position;
/*
* pop up the "more" list
*/
mDlgMore.show();
long lastClickTime;
/*
* check if it's double click
*/
lastClickTime = (Long)mListStatus.getTag();
if (Math.abs(lastClickTime-System.currentTimeMillis()) < 2000) {
mListStatus.setTag((long)0);
//to do some double click stuff here
showComments();
turnDealing(true);
} else {
mListStatus.setTag(System.currentTimeMillis());
}
}
});
mListStatus.setOnScrollListener(new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
//when it's not scrolling
if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){
//if it's already to the bottom
if(view.getLastVisiblePosition()==(view.getCount()-1)){
Toast.makeText(
parent,
R.string.tips_alreadylastone,
Toast.LENGTH_LONG
).show();
}
}
}
});
mBtnDescription.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
parent.popupDescription((String) mBtnDescription.getTag());
}
});
mTextPossess.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(
new ThreadPNJDealer(
ThreadPNJDealer.GET_POSSESSIONS,
EntranceActivity.URL_SITE
+ "updpzs.php?"
+ "clientkey=" + EntranceActivity.getClientKey()
+ "&channelid=0"
+ "&uid=" + getUid(),
mHandler
)
).start();
}
});
mTextFriendship.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mSina != null && mSina.isLoggedIn()) {
/*
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.CREATE_FRIENDSHIP,
new String[] {getUid().toString()},
mHandler
)
).start();
*/
turnDealing(true);
FriendshipsAPI api = new FriendshipsAPI(parent.getAccessToken());
//step 1, judge if already friends
//step 2, if not yet, create it
User2 usr = getSina().getLoggedInUser();
api.show(usr.getId(), getUid(), new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
FriendshipsAPI api = new FriendshipsAPI(parent.getAccessToken());
try {
JSONObject json = new JSONObject(response);
JSONObject target = new JSONObject(json.getString("target"));
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
if (target.getBoolean("followed_by")) {
/**
* 0 means "already friends"
* 1 means "friendships created"
* -1 means "friendships failed to be created"
* <-1 means other errors
*/
bundle.putInt(Responds.KEY_DATA , 0);
msg.setData(bundle);
mHandler.sendMessage(msg);
} else {
api.create(getUid(), null, new RequestListener() {
@Override
public void onComplete(String response) {
// TODO Auto-generated method stub
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
try {
JSONObject json = new JSONObject(response);
if (json.has("id")) {
bundle.putInt(Responds.KEY_DATA, 1);
} else {
bundle.putInt(Responds.KEY_DATA, -1);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
bundle.putInt(Responds.KEY_DATA, -2);
}
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -3);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -4);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -5);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
}
@Override
public void onIOException(IOException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -6);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onError(
com.weibo.sdk.android.WeiboException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Message msg = new Message();
msg.what = Responds.FRIENDSHIPS_CREATE;
Bundle bundle = new Bundle();
bundle.putInt(Responds.KEY_DATA, -7);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
});
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
}
});
mTextAtSomeone.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mLastUser == null) {
Toast.makeText(
parent,
R.string.tips_waitforgettinguser,
Toast.LENGTH_LONG
).show();
} else {
mEditUpdateStatus.setText(
"@" + mLastUser.getScreenName() + ":"
+ String.format(parent.getString(R.string.tips_routinehello), parent.getString(R.string.app_name))
+ " \"" + parent.getString(R.string.app_name)
+ "\":" + EntranceActivity.URL_UPDATE + "letuwb.apk"
);
mDlgUpdateStatus.show();
}
}
});
mDlgMore = new Dialog(parent, R.style.Dialog_Clean);
mDlgMore.setContentView(R.layout.custom_dialog_list);
ListView lvMore = (ListView)mDlgMore.findViewById(R.id.lvCustomList);
ArrayList<String> mlist = new ArrayList<String>();
mlist.add(parent.getString(R.string.label_weibo_favorite));
mlist.add(parent.getString(R.string.label_comment));
mlist.add(parent.getString(R.string.label_weibo_repost));
mlist.add(parent.getString(R.string.label_comments));
mlist.add(parent.getString(R.string.label_seebiggerimage0));
mlist.add(parent.getString(R.string.label_seebiggerimage1));
mlist.add(parent.getString(R.string.label_reload));
lvMore.setAdapter(
new ArrayAdapter<String> (
parent,
R.layout.item_custom_dialog_list,
mlist
)
);
lvMore.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> av, View view,
int position, long id) {
// TODO Auto-generated method stub
String originalPic;
switch (position) {
case 0:
if (mSina != null && mSina.isLoggedIn()) {
if (mIndexOfSelectedStatus != -1) {
/*
* make it favorite
*/
if (mLastUserTimeline == null) {
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.CREATE_FAVORITE,
new String[] {"" + mLastUser.getStatus().getId()},
mHandler
)
).start();
} else {
new Thread(
new ThreadSinaDealer(
mSina,
ThreadSinaDealer.CREATE_FAVORITE,
new String[] {"" + mLastUserTimeline.get(mIndexOfSelectedStatus).getStatus().getId()},
mHandler
)
).start();
}
turnDealing(true);
} else {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
}
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
break;
case 1:
if (mSina != null && mSina.isLoggedIn()) {
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
return;
}
mDlgComment.show();
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
break;
case 2:
if (mSina != null && mSina.isLoggedIn()) {
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
return;
}
mDlgRepost.show();
} else {
RegLoginActivity.shallWeLogin(R.string.title_loginfirst, parent);
}
break;
case 3:
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
} else {
showComments();
turnDealing(true);
}
break;
case 4:
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
} else {
originalPic = mLastUserTimeline
.get(mIndexOfSelectedStatus)
.getStatus()
.getOriginal_pic();
if (originalPic != null && !originalPic.trim().equals("")) {
showOriginalImage(originalPic);
} else {
Toast.makeText(
parent,
R.string.tips_nooriginalimage0,
Toast.LENGTH_LONG
).show();
}
}
break;
case 5:
if (mIndexOfSelectedStatus == -1) {
Toast.makeText(
parent,
R.string.tips_noitemselected,
Toast.LENGTH_LONG
).show();
} else {
Status2 retweeted = mLastUserTimeline
.get(mIndexOfSelectedStatus)
.getStatus()
.getRetweeted_status();
if (retweeted != null) {
originalPic = retweeted.getOriginal_pic();
} else {
originalPic = null;
}
if (originalPic != null && !originalPic.trim().equals("")) {
showOriginalImage(originalPic);
} else {
Toast.makeText(
parent,
R.string.tips_nooriginalimage1,
Toast.LENGTH_LONG
).show();
}
}
break;
case 6:
reloadAll();
turnDealing(true);
break;
}
mDlgMore.dismiss();
}
});
}
|
diff --git a/rhogen-wizard/src/rhogenwizard/debugger/DebugProtocol.java b/rhogen-wizard/src/rhogenwizard/debugger/DebugProtocol.java
index 8dbc536..db3836b 100644
--- a/rhogen-wizard/src/rhogenwizard/debugger/DebugProtocol.java
+++ b/rhogen-wizard/src/rhogenwizard/debugger/DebugProtocol.java
@@ -1,59 +1,58 @@
package rhogenwizard.debugger;
public class DebugProtocol {
private DebugServer debugServer;
private IDebugCallback debugCallback;
private DebugState state;
public DebugProtocol (DebugServer server, IDebugCallback callback) {
this.debugServer = server;
this.debugCallback = callback;
this.state = DebugState.NOTCONNECTED;
}
public DebugState getState() {
return this.state;
}
protected void processCommand(String cmd) {
if(cmd.endsWith("\n"))
cmd = cmd.substring(0, cmd.length()-1);
if (cmd.compareTo("CONNECT")==0) {
this.state = DebugState.CONNECTED;
debugServer.send("CONNECTED");
debugCallback.connected();
// not yet implemented in debugger.rb:
//} else if (cmd.compareTo("QUIT")==0) {
// this.state = DebugState.EXITED;
// debugServer.stop();
// debugCallback.exited();
} else if (cmd.startsWith("BP:")) {
this.state = DebugState.STOPPED;
String[] bp = cmd.split(":");
debugCallback.breakpoint(bp[1].replace('|', ':').replace('\\', '/'), Integer.parseInt(bp[2]));
} else if (cmd.startsWith("EV:")) {
- String[] bp = cmd.split(":");
- debugCallback.evaluation(bp[1].replace("\\n", "\n"));
+ debugCallback.evaluation(cmd.substring(3).replace("\\n", "\n"));
} else {
debugCallback.unknown(cmd);
}
}
public void step() {
this.state = DebugState.RUNNING;
debugServer.send("STEP");
}
public void resume() {
this.state = DebugState.RUNNING;
debugServer.send("CONT");
}
public void setBreakpoint(String file, int line) {
debugServer.send("BP:"+file+":"+line);
}
public void evaluate(String expression) {
debugServer.send("EV:"+expression);
}
}
| true | true | protected void processCommand(String cmd) {
if(cmd.endsWith("\n"))
cmd = cmd.substring(0, cmd.length()-1);
if (cmd.compareTo("CONNECT")==0) {
this.state = DebugState.CONNECTED;
debugServer.send("CONNECTED");
debugCallback.connected();
// not yet implemented in debugger.rb:
//} else if (cmd.compareTo("QUIT")==0) {
// this.state = DebugState.EXITED;
// debugServer.stop();
// debugCallback.exited();
} else if (cmd.startsWith("BP:")) {
this.state = DebugState.STOPPED;
String[] bp = cmd.split(":");
debugCallback.breakpoint(bp[1].replace('|', ':').replace('\\', '/'), Integer.parseInt(bp[2]));
} else if (cmd.startsWith("EV:")) {
String[] bp = cmd.split(":");
debugCallback.evaluation(bp[1].replace("\\n", "\n"));
} else {
debugCallback.unknown(cmd);
}
}
| protected void processCommand(String cmd) {
if(cmd.endsWith("\n"))
cmd = cmd.substring(0, cmd.length()-1);
if (cmd.compareTo("CONNECT")==0) {
this.state = DebugState.CONNECTED;
debugServer.send("CONNECTED");
debugCallback.connected();
// not yet implemented in debugger.rb:
//} else if (cmd.compareTo("QUIT")==0) {
// this.state = DebugState.EXITED;
// debugServer.stop();
// debugCallback.exited();
} else if (cmd.startsWith("BP:")) {
this.state = DebugState.STOPPED;
String[] bp = cmd.split(":");
debugCallback.breakpoint(bp[1].replace('|', ':').replace('\\', '/'), Integer.parseInt(bp[2]));
} else if (cmd.startsWith("EV:")) {
debugCallback.evaluation(cmd.substring(3).replace("\\n", "\n"));
} else {
debugCallback.unknown(cmd);
}
}
|
diff --git a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/TeachingHoursCDRManagement.java b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/TeachingHoursCDRManagement.java
index d4472074..ec85514c 100644
--- a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/TeachingHoursCDRManagement.java
+++ b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/TeachingHoursCDRManagement.java
@@ -1,332 +1,334 @@
package gr.sch.ira.minoas.seam.components.management;
import gr.sch.ira.minoas.model.core.SchoolYear;
import gr.sch.ira.minoas.model.core.Unit;
import gr.sch.ira.minoas.model.employee.Employee;
import gr.sch.ira.minoas.model.employement.Disposal;
import gr.sch.ira.minoas.model.employement.Employment;
import gr.sch.ira.minoas.model.employement.EmploymentType;
import gr.sch.ira.minoas.model.employement.Leave;
import gr.sch.ira.minoas.model.employement.Secondment;
import gr.sch.ira.minoas.model.employement.ServiceAllocation;
import gr.sch.ira.minoas.model.employement.TeachingHourCDR;
import gr.sch.ira.minoas.model.employement.TeachingHourCDRType;
import gr.sch.ira.minoas.seam.components.BaseDatabaseAwareSeamComponent;
import gr.sch.ira.minoas.seam.components.CoreSearching;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import javax.persistence.EntityManager;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
@Name(value = "teachingHoursCDRManagement")
@Scope(ScopeType.CONVERSATION)
public class TeachingHoursCDRManagement extends BaseDatabaseAwareSeamComponent {
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 1L;
@In(required = true, create = true)
private CoreSearching coreSearching;
@Transactional
public void doCalculateCurrentCDRs() {
long started = System.currentTimeMillis();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
EntityManager em = getEntityManager();
SchoolYear currentSchoolYear = coreSearching.getActiveSchoolYear(em);
info("generating teaching hours CDR for current school year #0", currentSchoolYear);
int totalCDRsCreated = 0;
/* first fetch all current CDRs and remove them */
Collection<TeachingHourCDR> oldCRDs = coreSearching.getTeachingHoursCDRs(em, currentSchoolYear);
int cdrsDeleted = 0;
for (TeachingHourCDR cdr : oldCRDs) {
entityManager.remove(cdr);
cdrsDeleted++;
}
info("successfully deleted totally #0 old CRD(s).", cdrsDeleted);
/* fetch all regular employments */
Collection<Employment> regularEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.REGULAR,
currentSchoolYear);
for (Employment employment : regularEmployments) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT);
StringBuffer sb = new StringBuffer();
sb.append("Οργανική θέση στην μονάδα απο τις ");
sb.append(df.format(employment.getEstablished()));
sb.append(" με υποχρεωτικό ωράριο ");
sb.append(employment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(employment.getEmployee());
cdr.setEmployment(employment);
cdr.setHours(employment.getFinalWorkingHours());
cdr.setUnit(employment.getSchool());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* fetch all deputy employments */
Collection<Employment> deputyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.DEPUTY,
currentSchoolYear);
for (Employment employment : deputyEmployments) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT);
StringBuffer sb = new StringBuffer();
sb.append("Τοποθέτηση αναπληρωτή στην μονάδα απο τις ");
sb.append(df.format(employment.getEstablished()));
sb.append(" για ");
sb.append(employment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(employment.getEmployee());
cdr.setEmployment(employment);
cdr.setHours(employment.getFinalWorkingHours());
cdr.setUnit(employment.getSchool());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* fetch all hourly employments */
Collection<Employment> hourlyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.HOURLYBASED,
currentSchoolYear);
for (Employment employment : hourlyEmployments) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT);
StringBuffer sb = new StringBuffer();
sb.append("Τοποθέτηση ωρομίσθιου στην μονάδα απο τις ");
sb.append(df.format(employment.getEstablished()));
sb.append(" για ");
sb.append(employment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(employment.getEmployee());
cdr.setEmployment(employment);
cdr.setHours(employment.getFinalWorkingHours());
cdr.setUnit(employment.getSchool());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* handle secodnments */
Collection<Secondment> secondments = coreSearching.getActiveSecondments(em, currentSchoolYear);
for (Secondment secondment : secondments) {
/* hack for secondments */
if (secondment.getFinalWorkingHours() != null && secondment.getMandatoryWorkingHours() != null &&
secondment.getFinalWorkingHours().intValue() == secondment.getMandatoryWorkingHours().intValue()) {
/* if final working hour is equal to mandatory working hours then it means
* that the valus were copied from the employment
*/
Integer workingHours = secondment.getFinalWorkingHours();
Employment employment = secondment.getAffectedEmployment();
if (employment != null) {
if (employment.getMandatoryWorkingHours().intValue() != workingHours.intValue()) {
secondment.setFinalWorkingHours(employment.getMandatoryWorkingHours());
secondment.setMandatoryWorkingHours(employment.getMandatoryWorkingHours());
}
}
}
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SECONDMENT);
StringBuffer sb = new StringBuffer();
sb.append("Αποσπασμένος απο την μονάδα ");
sb.append(secondment.getSourceUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(secondment.getEstablished()));
sb.append(" για ");
sb.append(secondment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(secondment.getEmployee());
cdr.setSecondment(secondment);
cdr.setHours(secondment.getFinalWorkingHours());
cdr.setUnit(secondment.getTargetUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
/* apply on source unit */
cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SECONDMENT);
sb = new StringBuffer();
sb.append("Αποσπασμένος στην μονάδα ");
sb.append(secondment.getTargetUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(secondment.getEstablished()));
sb.append(" για ");
sb.append(secondment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(secondment.getEmployee());
cdr.setSecondment(secondment);
cdr.setHours((-1) * secondment.getFinalWorkingHours());
cdr.setUnit(secondment.getSourceUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* handle disposal */
Collection<Disposal> disposals = coreSearching.getActiveDisposal(em, currentSchoolYear);
for (Disposal disposal : disposals) {
Unit sourceUnit = null;
try {
sourceUnit = disposal.getAffectedEmployment() != null ? disposal.getAffectedEmployment().getSchool()
: disposal.getAffectedSecondment().getTargetUnit();
} catch (Exception ex) {
error("unhandled exception with disposal #0. Exception #1", disposal, ex);
continue;
}
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.DISPOSAL);
StringBuffer sb = new StringBuffer();
sb.append("Διάθεση απο την μονάδα ");
sb.append(sourceUnit.getTitle());
sb.append(" απο τις ");
sb.append(df.format(disposal.getEstablished()));
sb.append(" για ");
sb.append(disposal.getHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(disposal.getEmployee());
cdr.setDisposal(disposal);
cdr.setHours(disposal.getHours());
cdr.setUnit(disposal.getDisposalUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
/* apply on source unit */
cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.DISPOSAL);
sb = new StringBuffer();
sb.append("Διάθεση στην μονάδα ");
sb.append(disposal.getDisposalUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(disposal.getEstablished()));
sb.append(" για ");
sb.append(disposal.getHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(disposal.getEmployee());
cdr.setDisposal(disposal);
cdr.setHours((-1) * disposal.getHours());
cdr.setUnit(sourceUnit);
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* handle service allocation */
Collection<ServiceAllocation> serviceAllocations = coreSearching.getActiveServiceAllocations(em);
info("found #0 totally active service allocations.", serviceAllocations.size());
for(ServiceAllocation serviceAllocation : serviceAllocations) {
if(serviceAllocation.getSourceUnit()==null) {
/* this should never happen */
warn("service allocation #0 has no source unit !!!!!!", serviceAllocation);
break;
}
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION);
StringBuffer sb = new StringBuffer();
sb.append("Θητεία απο την μονάδα ");
sb.append(serviceAllocation.getSourceUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(serviceAllocation.getEstablished()));
sb.append(" για ");
sb.append(serviceAllocation.getWorkingHoursOnServicingPosition());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(serviceAllocation.getEmployee());
cdr.setServiceAllocation(serviceAllocation);
cdr.setHours(serviceAllocation.getWorkingHoursOnServicingPosition());
cdr.setUnit(serviceAllocation.getServiceUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
/* apply on source unit */
cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION);
sb = new StringBuffer();
sb.append("Θητεία στην μονάδα ");
sb.append(serviceAllocation.getServiceUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(serviceAllocation.getEstablished()));
sb.append(" για ");
sb.append(serviceAllocation.getWorkingHoursOnServicingPosition());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(serviceAllocation.getEmployee());
cdr.setServiceAllocation(serviceAllocation);
cdr.setHours((-1) * serviceAllocation.getWorkingHoursOnServicingPosition());
cdr.setUnit(serviceAllocation.getSourceUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* WE NEED TO ADD LEAVES */
Collection<Leave> activeLeaves = coreSearching.getActiveLeaves(em);
info("found #0 totally active leaves.", activeLeaves.size());
for(Leave activeLeave : activeLeaves) {
Employee employeeWithLeave = activeLeave.getEmployee();
/* fix the common leave message */
StringBuffer sb = new StringBuffer();
sb.append("Άδεια τύπου ");
sb.append(activeLeave.getLeaveType());
sb.append(" απο τις ");
sb.append(df.format(activeLeave.getEstablished()));
sb.append(" μέχρι και ");
sb.append(df.format(activeLeave.getDueTo()));
Collection<TeachingHourCDR> employeeCDRs = coreSearching.getEmployeeTeachingHoursCDRs(em, currentSchoolYear, employeeWithLeave);
for(TeachingHourCDR employeeCDR : employeeCDRs) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.LEAVE);
cdr.setComment(sb.toString());
cdr.setEmployee(employeeWithLeave);
cdr.setHours(0);
cdr.setSchoolYear(currentSchoolYear);
cdr.setUnit(employeeCDR.getUnit());
cdr.setLeave(activeLeave);
+ entityManager.persist(cdr);
+ totalCDRsCreated++;
}
}
em.flush();
long finished = System.currentTimeMillis();
info("generated total CDRs #0 after #1 [ms]", totalCDRsCreated, (finished - started));
}
}
| true | true | public void doCalculateCurrentCDRs() {
long started = System.currentTimeMillis();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
EntityManager em = getEntityManager();
SchoolYear currentSchoolYear = coreSearching.getActiveSchoolYear(em);
info("generating teaching hours CDR for current school year #0", currentSchoolYear);
int totalCDRsCreated = 0;
/* first fetch all current CDRs and remove them */
Collection<TeachingHourCDR> oldCRDs = coreSearching.getTeachingHoursCDRs(em, currentSchoolYear);
int cdrsDeleted = 0;
for (TeachingHourCDR cdr : oldCRDs) {
entityManager.remove(cdr);
cdrsDeleted++;
}
info("successfully deleted totally #0 old CRD(s).", cdrsDeleted);
/* fetch all regular employments */
Collection<Employment> regularEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.REGULAR,
currentSchoolYear);
for (Employment employment : regularEmployments) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT);
StringBuffer sb = new StringBuffer();
sb.append("Οργανική θέση στην μονάδα απο τις ");
sb.append(df.format(employment.getEstablished()));
sb.append(" με υποχρεωτικό ωράριο ");
sb.append(employment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(employment.getEmployee());
cdr.setEmployment(employment);
cdr.setHours(employment.getFinalWorkingHours());
cdr.setUnit(employment.getSchool());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* fetch all deputy employments */
Collection<Employment> deputyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.DEPUTY,
currentSchoolYear);
for (Employment employment : deputyEmployments) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT);
StringBuffer sb = new StringBuffer();
sb.append("Τοποθέτηση αναπληρωτή στην μονάδα απο τις ");
sb.append(df.format(employment.getEstablished()));
sb.append(" για ");
sb.append(employment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(employment.getEmployee());
cdr.setEmployment(employment);
cdr.setHours(employment.getFinalWorkingHours());
cdr.setUnit(employment.getSchool());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* fetch all hourly employments */
Collection<Employment> hourlyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.HOURLYBASED,
currentSchoolYear);
for (Employment employment : hourlyEmployments) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT);
StringBuffer sb = new StringBuffer();
sb.append("Τοποθέτηση ωρομίσθιου στην μονάδα απο τις ");
sb.append(df.format(employment.getEstablished()));
sb.append(" για ");
sb.append(employment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(employment.getEmployee());
cdr.setEmployment(employment);
cdr.setHours(employment.getFinalWorkingHours());
cdr.setUnit(employment.getSchool());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* handle secodnments */
Collection<Secondment> secondments = coreSearching.getActiveSecondments(em, currentSchoolYear);
for (Secondment secondment : secondments) {
/* hack for secondments */
if (secondment.getFinalWorkingHours() != null && secondment.getMandatoryWorkingHours() != null &&
secondment.getFinalWorkingHours().intValue() == secondment.getMandatoryWorkingHours().intValue()) {
/* if final working hour is equal to mandatory working hours then it means
* that the valus were copied from the employment
*/
Integer workingHours = secondment.getFinalWorkingHours();
Employment employment = secondment.getAffectedEmployment();
if (employment != null) {
if (employment.getMandatoryWorkingHours().intValue() != workingHours.intValue()) {
secondment.setFinalWorkingHours(employment.getMandatoryWorkingHours());
secondment.setMandatoryWorkingHours(employment.getMandatoryWorkingHours());
}
}
}
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SECONDMENT);
StringBuffer sb = new StringBuffer();
sb.append("Αποσπασμένος απο την μονάδα ");
sb.append(secondment.getSourceUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(secondment.getEstablished()));
sb.append(" για ");
sb.append(secondment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(secondment.getEmployee());
cdr.setSecondment(secondment);
cdr.setHours(secondment.getFinalWorkingHours());
cdr.setUnit(secondment.getTargetUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
/* apply on source unit */
cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SECONDMENT);
sb = new StringBuffer();
sb.append("Αποσπασμένος στην μονάδα ");
sb.append(secondment.getTargetUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(secondment.getEstablished()));
sb.append(" για ");
sb.append(secondment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(secondment.getEmployee());
cdr.setSecondment(secondment);
cdr.setHours((-1) * secondment.getFinalWorkingHours());
cdr.setUnit(secondment.getSourceUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* handle disposal */
Collection<Disposal> disposals = coreSearching.getActiveDisposal(em, currentSchoolYear);
for (Disposal disposal : disposals) {
Unit sourceUnit = null;
try {
sourceUnit = disposal.getAffectedEmployment() != null ? disposal.getAffectedEmployment().getSchool()
: disposal.getAffectedSecondment().getTargetUnit();
} catch (Exception ex) {
error("unhandled exception with disposal #0. Exception #1", disposal, ex);
continue;
}
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.DISPOSAL);
StringBuffer sb = new StringBuffer();
sb.append("Διάθεση απο την μονάδα ");
sb.append(sourceUnit.getTitle());
sb.append(" απο τις ");
sb.append(df.format(disposal.getEstablished()));
sb.append(" για ");
sb.append(disposal.getHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(disposal.getEmployee());
cdr.setDisposal(disposal);
cdr.setHours(disposal.getHours());
cdr.setUnit(disposal.getDisposalUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
/* apply on source unit */
cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.DISPOSAL);
sb = new StringBuffer();
sb.append("Διάθεση στην μονάδα ");
sb.append(disposal.getDisposalUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(disposal.getEstablished()));
sb.append(" για ");
sb.append(disposal.getHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(disposal.getEmployee());
cdr.setDisposal(disposal);
cdr.setHours((-1) * disposal.getHours());
cdr.setUnit(sourceUnit);
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* handle service allocation */
Collection<ServiceAllocation> serviceAllocations = coreSearching.getActiveServiceAllocations(em);
info("found #0 totally active service allocations.", serviceAllocations.size());
for(ServiceAllocation serviceAllocation : serviceAllocations) {
if(serviceAllocation.getSourceUnit()==null) {
/* this should never happen */
warn("service allocation #0 has no source unit !!!!!!", serviceAllocation);
break;
}
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION);
StringBuffer sb = new StringBuffer();
sb.append("Θητεία απο την μονάδα ");
sb.append(serviceAllocation.getSourceUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(serviceAllocation.getEstablished()));
sb.append(" για ");
sb.append(serviceAllocation.getWorkingHoursOnServicingPosition());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(serviceAllocation.getEmployee());
cdr.setServiceAllocation(serviceAllocation);
cdr.setHours(serviceAllocation.getWorkingHoursOnServicingPosition());
cdr.setUnit(serviceAllocation.getServiceUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
/* apply on source unit */
cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION);
sb = new StringBuffer();
sb.append("Θητεία στην μονάδα ");
sb.append(serviceAllocation.getServiceUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(serviceAllocation.getEstablished()));
sb.append(" για ");
sb.append(serviceAllocation.getWorkingHoursOnServicingPosition());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(serviceAllocation.getEmployee());
cdr.setServiceAllocation(serviceAllocation);
cdr.setHours((-1) * serviceAllocation.getWorkingHoursOnServicingPosition());
cdr.setUnit(serviceAllocation.getSourceUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* WE NEED TO ADD LEAVES */
Collection<Leave> activeLeaves = coreSearching.getActiveLeaves(em);
info("found #0 totally active leaves.", activeLeaves.size());
for(Leave activeLeave : activeLeaves) {
Employee employeeWithLeave = activeLeave.getEmployee();
/* fix the common leave message */
StringBuffer sb = new StringBuffer();
sb.append("Άδεια τύπου ");
sb.append(activeLeave.getLeaveType());
sb.append(" απο τις ");
sb.append(df.format(activeLeave.getEstablished()));
sb.append(" μέχρι και ");
sb.append(df.format(activeLeave.getDueTo()));
Collection<TeachingHourCDR> employeeCDRs = coreSearching.getEmployeeTeachingHoursCDRs(em, currentSchoolYear, employeeWithLeave);
for(TeachingHourCDR employeeCDR : employeeCDRs) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.LEAVE);
cdr.setComment(sb.toString());
cdr.setEmployee(employeeWithLeave);
cdr.setHours(0);
cdr.setSchoolYear(currentSchoolYear);
cdr.setUnit(employeeCDR.getUnit());
cdr.setLeave(activeLeave);
}
}
em.flush();
long finished = System.currentTimeMillis();
info("generated total CDRs #0 after #1 [ms]", totalCDRsCreated, (finished - started));
}
| public void doCalculateCurrentCDRs() {
long started = System.currentTimeMillis();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
EntityManager em = getEntityManager();
SchoolYear currentSchoolYear = coreSearching.getActiveSchoolYear(em);
info("generating teaching hours CDR for current school year #0", currentSchoolYear);
int totalCDRsCreated = 0;
/* first fetch all current CDRs and remove them */
Collection<TeachingHourCDR> oldCRDs = coreSearching.getTeachingHoursCDRs(em, currentSchoolYear);
int cdrsDeleted = 0;
for (TeachingHourCDR cdr : oldCRDs) {
entityManager.remove(cdr);
cdrsDeleted++;
}
info("successfully deleted totally #0 old CRD(s).", cdrsDeleted);
/* fetch all regular employments */
Collection<Employment> regularEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.REGULAR,
currentSchoolYear);
for (Employment employment : regularEmployments) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT);
StringBuffer sb = new StringBuffer();
sb.append("Οργανική θέση στην μονάδα απο τις ");
sb.append(df.format(employment.getEstablished()));
sb.append(" με υποχρεωτικό ωράριο ");
sb.append(employment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(employment.getEmployee());
cdr.setEmployment(employment);
cdr.setHours(employment.getFinalWorkingHours());
cdr.setUnit(employment.getSchool());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* fetch all deputy employments */
Collection<Employment> deputyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.DEPUTY,
currentSchoolYear);
for (Employment employment : deputyEmployments) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT);
StringBuffer sb = new StringBuffer();
sb.append("Τοποθέτηση αναπληρωτή στην μονάδα απο τις ");
sb.append(df.format(employment.getEstablished()));
sb.append(" για ");
sb.append(employment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(employment.getEmployee());
cdr.setEmployment(employment);
cdr.setHours(employment.getFinalWorkingHours());
cdr.setUnit(employment.getSchool());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* fetch all hourly employments */
Collection<Employment> hourlyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.HOURLYBASED,
currentSchoolYear);
for (Employment employment : hourlyEmployments) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT);
StringBuffer sb = new StringBuffer();
sb.append("Τοποθέτηση ωρομίσθιου στην μονάδα απο τις ");
sb.append(df.format(employment.getEstablished()));
sb.append(" για ");
sb.append(employment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(employment.getEmployee());
cdr.setEmployment(employment);
cdr.setHours(employment.getFinalWorkingHours());
cdr.setUnit(employment.getSchool());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* handle secodnments */
Collection<Secondment> secondments = coreSearching.getActiveSecondments(em, currentSchoolYear);
for (Secondment secondment : secondments) {
/* hack for secondments */
if (secondment.getFinalWorkingHours() != null && secondment.getMandatoryWorkingHours() != null &&
secondment.getFinalWorkingHours().intValue() == secondment.getMandatoryWorkingHours().intValue()) {
/* if final working hour is equal to mandatory working hours then it means
* that the valus were copied from the employment
*/
Integer workingHours = secondment.getFinalWorkingHours();
Employment employment = secondment.getAffectedEmployment();
if (employment != null) {
if (employment.getMandatoryWorkingHours().intValue() != workingHours.intValue()) {
secondment.setFinalWorkingHours(employment.getMandatoryWorkingHours());
secondment.setMandatoryWorkingHours(employment.getMandatoryWorkingHours());
}
}
}
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SECONDMENT);
StringBuffer sb = new StringBuffer();
sb.append("Αποσπασμένος απο την μονάδα ");
sb.append(secondment.getSourceUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(secondment.getEstablished()));
sb.append(" για ");
sb.append(secondment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(secondment.getEmployee());
cdr.setSecondment(secondment);
cdr.setHours(secondment.getFinalWorkingHours());
cdr.setUnit(secondment.getTargetUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
/* apply on source unit */
cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SECONDMENT);
sb = new StringBuffer();
sb.append("Αποσπασμένος στην μονάδα ");
sb.append(secondment.getTargetUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(secondment.getEstablished()));
sb.append(" για ");
sb.append(secondment.getFinalWorkingHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(secondment.getEmployee());
cdr.setSecondment(secondment);
cdr.setHours((-1) * secondment.getFinalWorkingHours());
cdr.setUnit(secondment.getSourceUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* handle disposal */
Collection<Disposal> disposals = coreSearching.getActiveDisposal(em, currentSchoolYear);
for (Disposal disposal : disposals) {
Unit sourceUnit = null;
try {
sourceUnit = disposal.getAffectedEmployment() != null ? disposal.getAffectedEmployment().getSchool()
: disposal.getAffectedSecondment().getTargetUnit();
} catch (Exception ex) {
error("unhandled exception with disposal #0. Exception #1", disposal, ex);
continue;
}
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.DISPOSAL);
StringBuffer sb = new StringBuffer();
sb.append("Διάθεση απο την μονάδα ");
sb.append(sourceUnit.getTitle());
sb.append(" απο τις ");
sb.append(df.format(disposal.getEstablished()));
sb.append(" για ");
sb.append(disposal.getHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(disposal.getEmployee());
cdr.setDisposal(disposal);
cdr.setHours(disposal.getHours());
cdr.setUnit(disposal.getDisposalUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
/* apply on source unit */
cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.DISPOSAL);
sb = new StringBuffer();
sb.append("Διάθεση στην μονάδα ");
sb.append(disposal.getDisposalUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(disposal.getEstablished()));
sb.append(" για ");
sb.append(disposal.getHours());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(disposal.getEmployee());
cdr.setDisposal(disposal);
cdr.setHours((-1) * disposal.getHours());
cdr.setUnit(sourceUnit);
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* handle service allocation */
Collection<ServiceAllocation> serviceAllocations = coreSearching.getActiveServiceAllocations(em);
info("found #0 totally active service allocations.", serviceAllocations.size());
for(ServiceAllocation serviceAllocation : serviceAllocations) {
if(serviceAllocation.getSourceUnit()==null) {
/* this should never happen */
warn("service allocation #0 has no source unit !!!!!!", serviceAllocation);
break;
}
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION);
StringBuffer sb = new StringBuffer();
sb.append("Θητεία απο την μονάδα ");
sb.append(serviceAllocation.getSourceUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(serviceAllocation.getEstablished()));
sb.append(" για ");
sb.append(serviceAllocation.getWorkingHoursOnServicingPosition());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(serviceAllocation.getEmployee());
cdr.setServiceAllocation(serviceAllocation);
cdr.setHours(serviceAllocation.getWorkingHoursOnServicingPosition());
cdr.setUnit(serviceAllocation.getServiceUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
/* apply on source unit */
cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION);
sb = new StringBuffer();
sb.append("Θητεία στην μονάδα ");
sb.append(serviceAllocation.getServiceUnit().getTitle());
sb.append(" απο τις ");
sb.append(df.format(serviceAllocation.getEstablished()));
sb.append(" για ");
sb.append(serviceAllocation.getWorkingHoursOnServicingPosition());
sb.append(" ώρες.");
cdr.setComment(sb.toString());
cdr.setEmployee(serviceAllocation.getEmployee());
cdr.setServiceAllocation(serviceAllocation);
cdr.setHours((-1) * serviceAllocation.getWorkingHoursOnServicingPosition());
cdr.setUnit(serviceAllocation.getSourceUnit());
cdr.setSchoolYear(currentSchoolYear);
entityManager.persist(cdr);
totalCDRsCreated++;
}
/* WE NEED TO ADD LEAVES */
Collection<Leave> activeLeaves = coreSearching.getActiveLeaves(em);
info("found #0 totally active leaves.", activeLeaves.size());
for(Leave activeLeave : activeLeaves) {
Employee employeeWithLeave = activeLeave.getEmployee();
/* fix the common leave message */
StringBuffer sb = new StringBuffer();
sb.append("Άδεια τύπου ");
sb.append(activeLeave.getLeaveType());
sb.append(" απο τις ");
sb.append(df.format(activeLeave.getEstablished()));
sb.append(" μέχρι και ");
sb.append(df.format(activeLeave.getDueTo()));
Collection<TeachingHourCDR> employeeCDRs = coreSearching.getEmployeeTeachingHoursCDRs(em, currentSchoolYear, employeeWithLeave);
for(TeachingHourCDR employeeCDR : employeeCDRs) {
TeachingHourCDR cdr = new TeachingHourCDR();
cdr.setCdrType(TeachingHourCDRType.LEAVE);
cdr.setComment(sb.toString());
cdr.setEmployee(employeeWithLeave);
cdr.setHours(0);
cdr.setSchoolYear(currentSchoolYear);
cdr.setUnit(employeeCDR.getUnit());
cdr.setLeave(activeLeave);
entityManager.persist(cdr);
totalCDRsCreated++;
}
}
em.flush();
long finished = System.currentTimeMillis();
info("generated total CDRs #0 after #1 [ms]", totalCDRsCreated, (finished - started));
}
|
diff --git a/WEB-INF/lps/server/src/org/openlaszlo/sc/JavascriptGenerator.java b/WEB-INF/lps/server/src/org/openlaszlo/sc/JavascriptGenerator.java
index f91e78f7..214a9eda 100644
--- a/WEB-INF/lps/server/src/org/openlaszlo/sc/JavascriptGenerator.java
+++ b/WEB-INF/lps/server/src/org/openlaszlo/sc/JavascriptGenerator.java
@@ -1,1775 +1,1775 @@
/* -*- mode: Java; c-basic-offset: 2; -*- */
/**
* Javascript Generation
*
* @author [email protected]
* @author [email protected]
* @description: JavaScript -> JavaScript translator
*
* Transform the parse tree from ECMA ~4 to ECMA 3. Includes
* analyzing constraint functions and generating their dependencies.
*/
// TODO: [2006-01-25 ptw] Share this with the SWF Code generator, from
// which this was derived.
package org.openlaszlo.sc;
import java.io.*;
import java.util.*;
import org.openlaszlo.sc.parser.*;
public class JavascriptGenerator extends CommonGenerator implements Translator {
protected void setRuntime(String runtime) {
assert org.openlaszlo.compiler.Compiler.SCRIPT_RUNTIMES.contains(runtime) : "unknown runtime " + runtime;
}
// Make Javascript globals 'known'
Set globals = new HashSet(Arrays.asList(new String[] {
"NaN", "Infinity", "undefined",
"eval", "parseInt", "parseFloat", "isNaN", "isFinite",
"decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent",
"Object", "Function", "Array", "String", "Boolean", "Number", "Date",
"RegExp", "Error", "EvalError", "RangeError", "ReferenceError",
"SyntaxError", "TypeError", "URIError",
"Math"}));
public SimpleNode translate(SimpleNode program) {
// TODO: [2003-04-15 ptw] bind context slot macro
try {
context = new TranslationContext(ASTProgram.class, context);
context.setProperty(TranslationContext.VARIABLES, globals);
return translateInternal(program, "b", true);
}
finally {
context = context.parent;
}
}
public String newLabel(SimpleNode node) {
throw new CompilerImplementationError("nyi: newLabel");
}
int tempNum = 0;
String newTemp() {
return newTemp("$lzsc$");
}
String newTemp(String prefix) {
return prefix + tempNum++;
}
static LessHalfAssedHashMap XfixInstrs = new LessHalfAssedHashMap();
static {
XfixInstrs.put(ParserConstants.INCR, "+");
XfixInstrs.put(ParserConstants.DECR, "-");
};
static LessHalfAssedHashMap AssignOpTable = new LessHalfAssedHashMap();
static {
AssignOpTable.put(ParserConstants.PLUSASSIGN, "+");
AssignOpTable.put(ParserConstants.MINUSASSIGN, "-");
AssignOpTable.put(ParserConstants.STARASSIGN, "*");
AssignOpTable.put(ParserConstants.SLASHASSIGN, "/");
AssignOpTable.put(ParserConstants.ANDASSIGN, "&");
AssignOpTable.put(ParserConstants.ORASSIGN, "|");
AssignOpTable.put(ParserConstants.XORASSIGN, "^");
AssignOpTable.put(ParserConstants.REMASSIGN, "%");
AssignOpTable.put(ParserConstants.LSHIFTASSIGN, "<<");
AssignOpTable.put(ParserConstants.RSIGNEDSHIFTASSIGN, ">>");
AssignOpTable.put(ParserConstants.RUNSIGNEDSHIFTASSIGN, ">>>");
};
// Code to meter a function call. If name is set, uses that,
// otherwise uses arguments.callee._dbg_name. This code must be appended
// to the function prefix or suffix, as appropriate.
//
// NOTE: [2006-06-24 ptw] This is an inline version of the LFC
// `LzProfile.event` method and must be kept in sync with that.
SimpleNode meterFunctionEvent(SimpleNode node, String event, String name) {
String getname;
if (name != null) {
getname = "'" + name + "'";
} else {
getname = "arguments.callee._dbg_name";
}
// Note _root.$lzprofiler can be undedefined to disable profiling
// at run time.
// N.B., According to the Javascript spec, getTime() returns
// the time in milliseconds, but we have observed that the
// Flash player on some platforms tries to be accurate to
// microseconds (by including fractional milliseconds). On
// other platforms, the time is not even accurate to
// milliseconds, hence the kludge to manually increment the
// clock to create a monotonic ordering.
// The choice of 0.01 to increment by is based on the
// observation that when floats are used as member names in an
// object they are coerced to strings with only 15 significant
// digits. This should suffice for the next (10^13)-1
// microseconds (about 300 years).
return parseFragment(
"var $lzsc$lzp = global['$lzprofiler'];" +
"if ($lzsc$lzp) {" +
" var $lzsc$tick = $lzsc$lzp.tick;" +
" var $lzsc$now = (new Date).getTime();" +
" if ($lzsc$tick >= $lzsc$now) {" +
" $lzsc$now = $lzsc$tick + 0.0078125;" +
" }" +
" $lzsc$lzp.tick = $lzsc$now;" +
" $lzsc$lzp." + event + "[$lzsc$now] = " + getname + ";" +
"}");
}
// Only used by warning generator, hence not metered.
// FIXME: [2006-01-17 ptw] Regression compatibility Object -> String
String report(String reportMethod, SimpleNode node, Object message) {
return reportMethod + "(" + message + "," + node.filename + "," + node.beginLine + ")";
}
// Only used by warning generator, hence not metered.
// FIXME: [2006-01-17 ptw] Regression compatibility Object -> String
String report(String reportMethod, SimpleNode node, Object message, String extraArg) {
return reportMethod + "(" + message + "," + node.filename + "," + node.beginLine + "," + extraArg + ")";
}
// Emits code to check that a function is defined. If reference is
// set, expects the function reference to be at the top of the stack
// when called, otherwise expects the function object.
// TODO: [2006-01-04 ptw] Rewrite as a source transform
SimpleNode checkUndefinedFunction(SimpleNode node, JavascriptReference reference) {
if (options.getBoolean(Compiler.DEBUG) && options.getBoolean(Compiler.WARN_UNDEFINED_REFERENCES) && node.filename != null) {
return parseFragment(
"typeof " + reference.get() + " != 'function' ? " +
report("$reportNotFunction", node, reference.get()) + " : " +
reference.get());
}
return null;
}
// Emits code to check that an object method is defined. Does a trial
// fetch of methodName to verify that it is a function.
SimpleNode checkUndefinedMethod(SimpleNode node, JavascriptReference reference, String methodName) {
if (options.getBoolean(Compiler.DEBUG) && options.getBoolean(Compiler.WARN_UNDEFINED_REFERENCES) && node.filename != null) {
String o = newTemp();
String om = newTemp();
return parseFragment(
"var " + o + " = " + reference.get() + ";" +
"if (typeof(" + o + ") == undefined) {" +
" " + report("$reportUndefinedObjectProperty", node, methodName) +
"}" +
"var " + om + " = " + o + "[" + methodName + "];" +
"if (typeof(" + om + ") != 'function') {" +
" " + report("$reportUndefinedMethod", node, methodName, om) +
"}");
}
return null;
}
SimpleNode translateInternal(SimpleNode program, String cpass, boolean top) {
assert program instanceof ASTProgram;
// TODO: [2003-04-15 ptw] bind context slot macro
try {
context = new TranslationContext(ASTProgram.class, context);
return visitProgram(program, program.getChildren(), cpass, top);
}
finally {
context = context.parent;
}
}
void showStats(SimpleNode node) {
// No implementation to collect stats for Javascript
}
public String preProcess(String source) {
return source;
}
public List makeTranslationUnits(SimpleNode translatedNode, boolean compress, boolean obfuscate)
{
boolean trackLines = options.getBoolean(Compiler.TRACK_LINES);
String dumpann = (String)options.get(Compiler.DUMP_LINE_ANNOTATIONS);
return (new ParseTreePrinter(compress, obfuscate, trackLines, dumpann)).makeTranslationUnits(translatedNode, sources);
}
public byte[] postProcess(List tunits) {
assert (tunits.size() == 1);
return ((TranslationUnit)tunits.get(0)).getContents().getBytes();
}
public SimpleNode visitProgram(SimpleNode node, SimpleNode[] directives, String cpass) {
return visitProgram(node, directives, cpass, false);
}
public SimpleNode visitProgram(SimpleNode node, SimpleNode[] directives, String cpass, boolean top) {
// cpass is "b"oth, 1, or 2
assert "b".equals(cpass) || "1".equals(cpass) || "2".equals(cpass) : "bad pass: " + cpass;
if ("b".equals(cpass)) {
node = visitProgram(node, directives, "1", top);
// Everything is done in one pass for now.
// directives = node.getChildren();
// node = visitProgram(node, directives, "2", top);
return node;
}
if ("1".equals(cpass) && top) {
// emit compile-time contants to runtime
Map constants = (Map)options.get(Compiler.COMPILE_TIME_CONSTANTS);
if (constants != null) {
String code = "";
for (Iterator i = constants.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
Object value = entry.getValue();
// Python cruft
if (value instanceof String) {
value = "\"" + value + "\"";
} else if ((new Integer(0)).equals(value)) {
value = "false";
} else if ((new Integer(1)).equals(value)) {
value = "true";
}
code += "var " + entry.getKey() + " = " + value + ";";
}
List c = new ArrayList();
c.add(parseFragment(code));
c.addAll(Arrays.asList(directives));
directives = (SimpleNode[])c.toArray(directives);
node.setChildren(directives);
}
}
// System.err.println("visitProgram: " + cpass);
for (int index = 0, len = directives.length; index < len; index++) {
SimpleNode directive = directives[index];
SimpleNode newDirective = directive;
SimpleNode[] children = directive.getChildren();
if (directive instanceof ASTDirectiveBlock) {
Compiler.OptionMap savedOptions = options;
try {
options = options.copy();
newDirective = visitProgram(directive, children, cpass);
}
finally {
options = savedOptions;
}
} else if (directive instanceof ASTIfDirective) {
if (! options.getBoolean(Compiler.CONDITIONAL_COMPILATION)) {
// TBD: different type; change to CONDITIONALS
throw new CompilerError("`if` at top level");
}
Boolean value = evaluateCompileTimeConditional(directive.get(0));
if (value == null) {
newDirective = visitIfStatement(directive, children);
} else if (value.booleanValue()) {
SimpleNode clause = directive.get(1);
newDirective = visitProgram(clause, clause.getChildren(), cpass);
} else if (directive.size() > 2) {
SimpleNode clause = directive.get(2);
newDirective = visitProgram(clause, clause.getChildren(), cpass);
} else {
newDirective = new ASTEmptyExpression(0);
}
} else if (directive instanceof ASTIncludeDirective) {
// Disabled by default, since it isn't supported in the
// product. (It doesn't go through the compilation
// manager for dependency tracking.)
if (! options.getBoolean(Compiler.INCLUDES)) {
throw new UnimplementedError("unimplemented: #include", directive);
}
String userfname = (String)((ASTLiteral)directive.get(0)).getValue();
newDirective = translateInclude(userfname, cpass);
} else if (directive instanceof ASTProgram) {
// This is what an include looks like in pass 2
newDirective = visitProgram(directive, children, cpass);
} else if (directive instanceof ASTPragmaDirective) {
newDirective = visitPragmaDirective(directive, directive.getChildren());
} else if (directive instanceof ASTPassthroughDirective) {
newDirective = visitPassthroughDirective(directive, directive.getChildren());
} else {
if ("1".equals(cpass)) {
// Function, class, and top-level expressions are processed in pass 1
if (directive instanceof ASTFunctionDeclaration) {
newDirective = visitStatement(directive);
} else if (directive instanceof ASTClassDefinition) {
newDirective = visitStatement(directive);
} else if (directive instanceof ASTModifiedDefinition) {
newDirective = visitModifiedDefinition(directive, directive.getChildren());
} else if (directive instanceof ASTStatement) {
// Statements are processed in pass 1 for now
newDirective = visitStatement(directive);
;
} else {
newDirective = visitExpression(directive, false);
}
}
if ("2".equals(cpass)) {
// There is no pass 2 any more
assert false : "bad pass " + cpass;
}
}
if (! newDirective.equals(directive)) {
// System.err.println("directive: " + directive + " -> " + newDirective);
directives[index] = newDirective;
}
}
showStats(node);
return node;
}
SimpleNode translateInclude(String userfname, String cpass) {
if (Compiler.CachedInstructions == null) {
Compiler.CachedInstructions = new ScriptCompilerCache();
}
File file = includeNameToFile(userfname);
String source = includeFileToSourceString(file, userfname);
try {
String optionsKey =
getCodeGenerationOptionsKey(Collections.singletonList(
// The constant pool isn't cached, so it doesn't affect code
// generation so far as the cache is concerned.
Compiler.DISABLE_CONSTANT_POOL));
// If these could be omitted from the key for files that didn't
// reference them, then the cache could be shared between krank
// and krank debug. (The other builds differ either on OBFUSCATE,
// RUNTIME, NAMEFUNCTIONS, or PROFILE, so there isn't any other
// possible sharing.)
String instrsKey = file.getAbsolutePath();
// Only cache on file and pass, to keep cache size resonable,
// but check against optionsKey
String instrsChecksum = "" + file.lastModified() + optionsKey; // source;
// Use previously modified parse tree if it exists
SimpleNode instrs = (SimpleNode)Compiler.CachedInstructions.get(instrsKey + cpass, instrsChecksum);
if (instrs == null) {
ParseResult result = parseFile(file, userfname, source);
if ("1".equals(cpass)) {
instrs = result.parse;
instrs = translateInternal(instrs, cpass, false);
} else if ("2".equals(cpass)) {
instrs = (SimpleNode)Compiler.CachedInstructions.get(instrsKey + "1", instrsChecksum);
assert instrs != null : "pass 2 before pass 1?";
instrs = translateInternal(instrs, cpass, false);
} else {
assert false : "bad pass " + cpass;
}
if (! result.hasIncludes) {
if (options.getBoolean(Compiler.CACHE_COMPILES)) {
Compiler.CachedInstructions.put(instrsKey + cpass, instrsChecksum, instrs);
}
}
}
return instrs;
}
catch (ParseException e) {
System.err.println("while compiling " + file.getAbsolutePath());
throw e;
}
}
public SimpleNode visitFunctionDeclaration(SimpleNode node, SimpleNode[] ast) {
// Inner functions are handled by translateFunction
if (context.findFunctionContext() != null) {
return null;
} else {
assert (! options.getBoolean(Compiler.CONSTRAINT_FUNCTION));
// Make sure all our top-level functions have root context
if (false && ASTProgram.class.equals(context.type)) {
Map map = new HashMap();
map.put("_1", new Compiler.Splice(ast));
SimpleNode newNode = (new Compiler.Parser()).substitute(node, "with (_root) { _1 }", map);
return visitStatement(newNode);
} else {
return translateFunction(node, true, ast);
}
}
}
//
// Statements
//
public SimpleNode visitVariableStatement(SimpleNode node, SimpleNode[] children) {
boolean scriptElement = options.getBoolean(Compiler.SCRIPT_ELEMENT);
if (scriptElement) {
assert children.length == 1;
// In script, variables are declared at the top of the function
// so we convert the variableStatement into a Statement here.
node = new ASTStatement(0);
node.set(0, children[0]);
}
return visitChildren(node);
}
public SimpleNode visitVariableDeclaration(SimpleNode node, SimpleNode[] children) {
ASTIdentifier id = (ASTIdentifier)children[0];
boolean scriptElement = options.getBoolean(Compiler.SCRIPT_ELEMENT);
if (scriptElement) {
if (children.length > 1) {
// In script, variables are declared at the top of the
// function so we convert the declaration into an assignment
// here.
SimpleNode newNode = new ASTAssignmentExpression(0);
newNode.set(0, children[0]);
ASTOperator assign = new ASTOperator(0);
assign.setOperator(ParserConstants.ASSIGN);
newNode.set(1, assign);
newNode.set(2, children[1]);
return visitExpression(newNode);
} else {
// Declarations already handled in a script
return new ASTEmptyExpression(0);
}
} else {
if (children.length > 1) {
SimpleNode initValue = children[1];
JavascriptReference ref = translateReference(id);
children[1] = visitExpression(initValue);
children[0] = ref.init();
return node;
} else {
JavascriptReference ref = translateReference(id);
children[0] = ref.declare();
return node;
}
}
}
public SimpleNode visitIfStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode test = children[0];
SimpleNode a = children[1];
SimpleNode b = (children.length > 2) ? children[2] : null;
// Compile-time conditional evaluations
// System.err.println("visitIfStatement: " + (new ParseTreePrinter()).text(node));
Boolean value = evaluateCompileTimeConditional(test);
if (value != null) {
// System.err.println("" + test + " == " + value);
if (value.booleanValue()) {
return visitStatement(a);
} else if (b != null) {
return visitStatement(b);
} else {
return new ASTEmptyExpression(0);
}
} else if (b != null) {
children[0] = visitExpression(test);
children[1] = visitStatement(a);
children[2] = visitStatement(b);
} else {
children[0] = visitExpression(test);
children[1] = visitStatement(a);
}
return node;
}
public SimpleNode visitWhileStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode test = children[0];
SimpleNode body = children[1];
// TODO: [2003-04-15 ptw] bind context slot macro
try {
context = new TranslationContext(ASTWhileStatement.class, context);
children[0] = visitExpression(test);
children[1] = visitStatement(body);
return node;
}
finally {
context = context.parent;
}
}
public SimpleNode visitDoWhileStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode body = children[0];
SimpleNode test = children[1];
// TODO: [2003-04-15 ptw] bind context slot macro
try {
context = new TranslationContext(ASTDoWhileStatement.class, context);
children[0] = visitStatement(body);
children[1] = visitExpression(test);
return node;
}
finally {
context = context.parent;
}
}
public SimpleNode visitForStatement(SimpleNode node, SimpleNode[] children) {
return translateForStatement(node, children);
}
public SimpleNode visitForVarStatement(SimpleNode node, SimpleNode[] children) {
return translateForStatement(node, children);
}
SimpleNode translateForStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode init = children[0];
SimpleNode test = children[1];
SimpleNode step = children[2];
SimpleNode body = children[3];
// TODO: [2003-04-15 ptw] bind context slot macro
Compiler.OptionMap savedOptions = options;
try {
options = options.copy();
context = new TranslationContext(ASTForStatement.class, context);
options.putBoolean(Compiler.WARN_GLOBAL_ASSIGNMENTS, true);
children[0] = visitStatement(init);
options.putBoolean(Compiler.WARN_GLOBAL_ASSIGNMENTS, false);
children[1] = visitExpression(test);
children[3] = visitStatement(body);
children[2] = visitStatement(step);
return node;
}
finally {
context = context.parent;
options = savedOptions;
}
}
public SimpleNode visitForInStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode var = children[0];
SimpleNode obj = children[1];
SimpleNode body = children[2];
// TODO: [2003-04-15 ptw] bind context slot macro
try {
context = new TranslationContext(ASTForInStatement.class, context);
children[1] = visitExpression(obj);
JavascriptReference ref = translateReference(var);
children[0] = ref.set(true);
children[2] = visitStatement(body);
return node;
}
finally {
context = context.parent;
}
}
// This works because keys are always strings, and enumerate pushes
// a null before all the keys
public void unwindEnumeration(SimpleNode node) {
}
SimpleNode translateForInStatement(SimpleNode node, SimpleNode var,
Instructions.Instruction varset, SimpleNode obj,
SimpleNode body) {
// TODO: [2003-04-15 ptw] bind context slot macro
try {
SimpleNode[] children = node.getChildren();
context = new TranslationContext(ASTForInStatement.class, context);
children[2] = visitExpression(obj);
JavascriptReference ref = translateReference(var);
if (varset == Instructions.VarEquals) {
children[0] = ref.init();
} else {
children[0] = ref.set(true);
}
children[3] = visitStatement(body);
return node;
}
finally {
context = context.parent;
}
}
SimpleNode translateAbruptCompletion(SimpleNode node, String type, ASTIdentifier label) {
return node;
}
public SimpleNode visitReturnStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode value = children[0];
children[0] = visitExpression(value);
return node;
}
public SimpleNode visitWithStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode expr = children[0];
SimpleNode stmt = children[1];
children[0] = visitExpression(expr);
children[1] = visitStatement(stmt);
return node;
}
public SimpleNode visitTryStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode block = children[0];
int len = children.length;
assert len == 2 || len == 3;
children[0] = visitStatement(block);
if (len == 2) {
// Could be catch or finally clause
SimpleNode catfin = children[1];
if (catfin instanceof ASTCatchClause) {
// Treat the catch identifier as a binding. This is not quite
// right, need to integrate with variable analyzer, but this is
// the one case in ECMAScript where a variable does have block
// extent.
catfin.set(0, translateReference(catfin.get(0)).declare());
catfin.set(1, visitStatement(catfin.get(1)));
} else {
assert catfin instanceof ASTFinallyClause;
catfin.set(0, visitStatement(catfin.get(0)));
}
} else if (len == 3) {
SimpleNode cat = children[1];
SimpleNode fin = children[2];
assert cat instanceof ASTCatchClause;
// Treat the catch identifier as a binding. This is not quite
// right, need to integrate with variable analyzer, but this is
// the one case in ECMAScript where a variable does have block
// extent.
cat.set(0, translateReference(cat.get(0)).declare());
cat.set(1, visitStatement(cat.get(1)));
assert fin instanceof ASTFinallyClause;
fin.set(0, visitStatement(fin.get(0)));
}
return node;
}
public SimpleNode visitThrowStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode expr = children[0];
children[0] = visitExpression(expr);
return node;
}
public SimpleNode visitSwitchStatement(SimpleNode node, SimpleNode[] children) {
SimpleNode expr = children[0];
// TODO: [2003-04-15 ptw] bind context slot macro
try {
context = new TranslationContext(ASTSwitchStatement.class, context);
children[0] = visitExpression(expr);
for (int i = 1, len = children.length; i < len; i++) {
SimpleNode clause = children[i];
if (clause instanceof ASTDefaultClause) {
if (clause.size() > 0) {
clause.set(0, visitStatement(clause.get(0)));
}
} else {
assert clause instanceof ASTCaseClause : "case clause expected";
clause.set(0, visitExpression(clause.get(0)));
if (clause.size() > 1) {
clause.set(1, visitStatement(clause.get(1)));
}
}
}
return node;
}
finally {
context = context.parent;
}
}
//
// Expressions
//
boolean isExpressionType(SimpleNode node) {
if (node instanceof Compiler.PassThroughNode) {
node = ((Compiler.PassThroughNode)node).realNode;
}
return super.isExpressionType(node);
}
public SimpleNode visitExpression(SimpleNode node) {
return visitExpression(node, true);
}
/* This function, unlike the other expression visitors, can be
applied to any expression node, so it dispatches based on the
node's class. */
public SimpleNode visitExpression(SimpleNode node, boolean isReferenced) {
assert isExpressionType(node) : "" + node + ": " + (new ParseTreePrinter()).text(node) + " is not an expression";
if (this.debugVisit) {
System.err.println("visitExpression: " + node.getClass());
}
SimpleNode newNode = dispatchExpression(node, isReferenced);
if ((! isReferenced) && (newNode == null)) {
newNode = new ASTEmptyExpression(0);
}
if (this.debugVisit) {
if (! newNode.equals(node)) {
System.err.println("expression: " + node + " -> " + newNode);
}
}
return newNode;
}
public SimpleNode visitIdentifier(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
// Side-effect free expressions can be suppressed if not referenced
// Following is disabled by default for regression testing.
// TODO: [2003-02-17 ows] enable this
if ((! isReferenced) && options.getBoolean(Compiler.ELIMINATE_DEAD_EXPRESSIONS)) {
return null;
}
if ("_root".equals(((ASTIdentifier)node).getName()) && (! options.getBoolean(Compiler.ALLOW_ROOT))) {
throw new SemanticError("Illegal variable name: " + node, node);
}
return translateReference(node).get();
}
public SimpleNode visitLiteral(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
// Side-effect free expressions can be suppressed if not referenced
// Following is disabled by default for regression testing.
// TODO: [2003-02-17 ows] enable this
if ((! isReferenced) && options.getBoolean(Compiler.ELIMINATE_DEAD_EXPRESSIONS)) {
return null;
}
return translateLiteralNode(node);
}
public SimpleNode visitExpressionList(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
// all but last expression will not be referenced, so
// visitExpression will pop it. If the list is not referenced,
// then the last will be popped too
int i = 0, len = children.length - 1;
for ( ; i < len; i++) {
children[i] = visitExpression(children[i], false);
}
children[len] = visitExpression(children[len], isReferenced);
return node;
}
public SimpleNode visitEmptyExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
// Side-effect free expressions can be suppressed if not referenced
if ((! isReferenced)) {
return null;
}
return node;
}
public SimpleNode visitThisReference(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
// Side-effect free expressions can be suppressed if not referenced
if ((! isReferenced)) {
return null;
}
return translateReference(node).get();
}
public SimpleNode visitArrayLiteral(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
boolean suppressed = (! isReferenced);
for (int i = 0, len = children.length; i <len; i++) {
children[i] = visitExpression(children[i], isReferenced);
}
return node;
}
public SimpleNode visitObjectLiteral(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
boolean isKey = true;
for (int i = 0, len = children.length; i < len; i++) {
SimpleNode item = children[i];
if (isKey && item instanceof ASTIdentifier) {
// Identifiers are a shorthand for a literal string, should
// not be evaluated (or remapped).
;
} else {
children[i] = visitExpression(item);
}
isKey = (! isKey);
}
return node;
}
public SimpleNode visitFunctionExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
Compiler.OptionMap savedOptions = options;
try {
options = options.copy();
options.putBoolean(Compiler.CONSTRAINT_FUNCTION, false);
// Make sure all our top-level functions have root context
// if (ASTProgram.class.equals(context.type)) {
// Map map = new HashMap();
// map.put("_1", new Compiler.Splice(children));
// SimpleNode newNode = (new Compiler.Parser()).substitute(node, "with (_root) { _1 }", map);
// visitStatement(newNode);
// } else {
return translateFunction(node, false, children);
// }
}
finally {
options = savedOptions;
}
}
public SimpleNode visitFunctionCallParameters(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
translateFunctionCallParameters(node, isReferenced, children);
return node;
}
public SimpleNode[] translateFunctionCallParameters(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
for (int i = 0, len = children.length; i < len; i++) {
children[i] = visitExpression(children[i]);
}
return children;
}
public SimpleNode visitPropertyIdentifierReference(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
return translateReference(node).get();
}
public SimpleNode visitPropertyValueReference(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
return translateReference(node).get();
}
public SimpleNode makeCheckedNode(SimpleNode node) {
if (options.getBoolean(Compiler.DEBUG) && options.getBoolean(Compiler.WARN_UNDEFINED_REFERENCES)
// Only check this where 'this' is available
&& (context.findFunctionContext() != null)) {
String file = "null";
String line = "null";
if (node.filename != null) {
file = ScriptCompiler.quote(node.filename);
line = "" + node.beginLine;
}
Map map = new HashMap();
map.put("_1", node);
return new Compiler.PassThroughNode((new Compiler.Parser()).substitute(
node,
"(Debug.evalCarefully(" + file + ", " + line + ", function () { return _1; }, this))", map));
}
return node;
}
SimpleNode noteCallSite(SimpleNode node) {
// Note current call-site in a function context and backtracing
if ((options.getBoolean(Compiler.DEBUG_BACKTRACE) && (node.beginLine != 0)) &&
(context.findFunctionContext() != null)) {
SimpleNode newNode = new ASTExpressionList(0);
newNode.set(0, (new Compiler.Parser()).parse("$lzsc$a.lineno = " + node.beginLine).get(0).get(0));
newNode.set(1, new Compiler.PassThroughNode(node));
return visitExpression(newNode);
}
return node;
}
// Could do inline expansions here, like setAttribute
public SimpleNode visitCallExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
SimpleNode fnexpr = children[0];
SimpleNode[] args = children[1].getChildren();
int arglen = args.length;
// TODO: [2002-12-03 ptw] There should be a more general
// mechanism for matching patterns against AST's and replacing
// them.
// FIXME: [2002-12-03 ptw] This substitution is not correct
// because it does not verify that the method being inlined is
// actually LzNode.setAttribute.
if (
// Here this means 'compiling the lfc'
options.getBoolean(Compiler.FLASH_COMPILER_COMPATABILITY) &&
(! options.getBoolean("passThrough")) &&
(fnexpr instanceof ASTPropertyIdentifierReference)) {
SimpleNode[] fnchildren = fnexpr.getChildren();
String name = ((ASTIdentifier)fnchildren[1]).getName();
// We can't expand this if an expression value is expected,
// since we don't have 'let'
if (name.equals("setAttribute") && (! isReferenced)) {
SimpleNode scope = fnchildren[0];
SimpleNode property = args[0];
SimpleNode value = args[1];
List newBody = new ArrayList();
String thisvar = "$lzsc$" + UUID().toString();
String propvar = "$lzsc$" + UUID().toString();
String valvar = "$lzsc$" + UUID().toString();
String changedvar = "$lzsc$" + UUID().toString();
String svar = "$lzsc$" + UUID().toString();
String evtvar = "$lzsc$" + UUID().toString();
String decls = "";
ParseTreePrinter ptp = new ParseTreePrinter();
if (scope instanceof ASTIdentifier || scope instanceof ASTThisReference) {
thisvar = ptp.text(scope);
} else {
decls += "var " + thisvar + " = " + ptp.text(scope) + ";";
}
if (property instanceof ASTLiteral || property instanceof ASTIdentifier) {
propvar = ptp.text(property);
if (property instanceof ASTLiteral) {
assert propvar.startsWith("\"") || propvar.startsWith("'");
svar = propvar.substring(0,1) + "$lzc$set_" + propvar.substring(1);
}
} else {
decls += "var " + propvar + " = " + ptp.text(property) + ";";
}
if (value instanceof ASTLiteral || value instanceof ASTIdentifier) {
valvar = ptp.text(value);
} else {
decls += "var " + valvar + " = " + ptp.text(value) + ";";
}
if (arglen > 2) {
SimpleNode ifchanged = args[2];
if (ifchanged instanceof ASTLiteral || ifchanged instanceof ASTIdentifier) {
changedvar = ptp.text(ifchanged);
} else {
decls += "var " + changedvar + " = " + ptp.text(ifchanged) + ";";
}
}
newBody.add(parseFragment(decls));
String fragment =
"if (! (" + thisvar + ".__LZdeleted " +
((arglen > 2) ? ("|| (" + changedvar + " && (" + thisvar + "[" + propvar + "] == " + valvar + "))") : "") +
")) {" +
((property instanceof ASTLiteral) ? "" : ("var " + svar + " = \"$lzc$set_\" + " + propvar + ";")) +
"if (" + thisvar + "[" + svar + "] is Function) {" +
" " + thisvar + "[" + svar + "](" + valvar + ");" +
"} else {" +
" " + thisvar + "[ " + propvar + " ] = " + valvar + ";" +
" var " + evtvar + " = " + thisvar + "[" +
((property instanceof ASTLiteral) ?
(propvar.substring(0,1) + "on" + propvar.substring(1)) :
("\"on\" + " + propvar)) +
"];" +
" if (" + evtvar + " is LzEvent) {" +
" if (" + evtvar + ".ready) {" + evtvar + ".sendEvent( " + valvar + " ); }" +
" }" +
"}" +
"}";
newBody.add(parseFragment(fragment));
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])newBody.toArray(new SimpleNode[0]));
return visitStatement(newStmts);
}
}
children[1].setChildren(translateFunctionCallParameters(node, isReferenced, args));
children[0] = translateReferenceForCall(fnexpr, true, node);
// if (options.getBoolean(Compiler.WARN_UNDEFINED_REFERENCES)) {
// return makeCheckedNode(node);
// }
return noteCallSite(node);
}
public SimpleNode visitSuperCallExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
SimpleNode n = translateSuperCallExpression(node, isReferenced, children);
children = n.getChildren();
for (int i = 0, len = children.length ; i < len; i++) {
children[i] = visitExpression(children[i], isReferenced);
}
return n;
}
public SimpleNode visitNewExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
for (int i = 0, len = children.length; i < len; i++) {
SimpleNode child = children[i];
children[i] = visitExpression(child, isReferenced);
}
return noteCallSite(node);
}
public SimpleNode visitPrefixExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
int op = ((ASTOperator)children[0]).getOperator();
SimpleNode ref = children[1];
if (translateReference(ref).isChecked()) {
// The undefined reference checker needs to have this expanded
// to work
Map map = new HashMap();
map.put("_1", ref);
String pattern = "(function () { var $lzsc$tmp = _1; return _1 = $lzsc$tmp " + XfixInstrs.get(op) + " 1; })()";
SimpleNode n = (new Compiler.Parser()).substitute(node, pattern, map);
return visitExpression(n);
}
children[1] = translateReference(ref, 2).get();
return node;
}
public SimpleNode visitPostfixExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
SimpleNode ref = children[0];
int op = ((ASTOperator)children[1]).getOperator();
if (translateReference(ref).isChecked()) {
// The undefined reference checker needs to have this expanded
// to work
Map map = new HashMap();
map.put("_1", ref);
String pattern = "(function () { var $lzsc$tmp = _1; _1 = $lzsc$tmp " + XfixInstrs.get(op) + " 1; return $lzsc$tmp; })()";
SimpleNode n = (new Compiler.Parser()).substitute(node, pattern, map);
return visitExpression(n);
}
children[0] = translateReference(ref, 2).get();
return node;
}
public SimpleNode visitUnaryExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
int op = ((ASTOperator)children[0]).getOperator();
// I guess the parser doesn't know the difference
if (ParserConstants.INCR == (op) || ParserConstants.DECR == (op)) {
return visitPrefixExpression(node, isReferenced, children);
}
SimpleNode arg = children[1];
// special-case typeof(variable) to not emit undefined-variable
// checks so there is a warning-free way to check for undefined
if (ParserConstants.TYPEOF == (op) &&
(arg instanceof ASTIdentifier ||
arg instanceof ASTPropertyValueReference ||
arg instanceof ASTPropertyIdentifierReference)) {
children[1] = translateReference(arg).get(false);
} else {
children[1] = visitExpression(arg);
}
return node;
}
public SimpleNode visitBinaryExpressionSequence(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
SimpleNode a = children[0];
SimpleNode op = children[1];
SimpleNode b = children[2];
if (ParserConstants.CAST == ((ASTOperator)op).getOperator()) {
// Approximate a cast b as a
// TODO: [2008-01-08 ptw] We could typecheck and throw an error
// in debug mode
return visitExpression(a);
}
if (ParserConstants.IS == ((ASTOperator)op).getOperator()) {
// Approximate a is b as b['$lzsc$isa'] ? b.$lzsc$isa(a) : (a
// instanceof b)
Map map = new HashMap();
map.put("_1", a);
map.put("_2", b);
String pattern;
if ((a instanceof ASTIdentifier ||
a instanceof ASTPropertyValueReference ||
a instanceof ASTPropertyIdentifierReference) &&
(b instanceof ASTIdentifier ||
b instanceof ASTPropertyValueReference ||
b instanceof ASTPropertyIdentifierReference)) {
pattern = "(_2['$lzsc$isa'] ? _2.$lzsc$isa(_1) : (_1 instanceof _2))";
} else {
pattern = "((function (a, b) {return b['$lzsc$isa'] ? b.$lzsc$isa(a) : (a instanceof b)})(_1, _2))";
}
SimpleNode n = (new Compiler.Parser()).substitute(node, pattern, map);
return visitExpression(n);
}
children[0] = visitExpression(a);
children[2] = visitExpression(b);
return node;
}
SimpleNode translateAndOrExpression(SimpleNode node, boolean isand, SimpleNode a, SimpleNode b) {
SimpleNode[] children = node.getChildren();
children[0] = visitExpression(a);
children[1] = visitExpression(b);
return node;
}
public SimpleNode visitConditionalExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
SimpleNode test = children[0];
SimpleNode a = children[1];
SimpleNode b = children[2];
children[0] = visitExpression(test);
children[1] = visitExpression(a);
children[2] = visitExpression(b);
return node;
}
public SimpleNode visitAssignmentExpression(SimpleNode node, boolean isReferenced, SimpleNode[] children) {
JavascriptReference lhs = translateReference(children[0]);
int op = ((ASTOperator)children[1]).getOperator();
SimpleNode rhs = visitExpression(children[2]);
if (op != ParserConstants.ASSIGN &&
lhs.isChecked()) {
// The undefined reference checker needs to have this expanded
// to work
Map map = new HashMap();
map.put("_1", lhs.get());
map.put("_2", rhs);
map.put("_3", lhs.set());
String pattern = "(function () { var $lzsc$tmp = _1; return _3 = $lzsc$tmp " + AssignOpTable.get(op) + " _2; })()";
SimpleNode n = (new Compiler.Parser()).substitute(node, pattern, map);
return visitExpression(n);
}
children[2] = rhs;
children[0] = lhs.set();
return node;
}
// useName => declaration not expression
SimpleNode translateFunction(SimpleNode node, boolean useName, SimpleNode[] children) {
// TODO: [2003-04-15 ptw] bind context slot macro
SimpleNode[] result;
// methodName and scriptElement
Compiler.OptionMap savedOptions = options;
try {
options = options.copy();
context = new TranslationContext(ASTFunctionExpression.class, context);
node = formalArgumentsTransformations(node);
children = node.getChildren();
result = translateFunctionInternal(node, useName, children);
}
finally {
options = savedOptions;
context = context.parent;
}
node = result[0];
// Dependency function is not compiled in the function context
if (result[1] != null) {
SimpleNode dependencies = result[1];
Map map = new HashMap();
map.put("_1", node);
map.put("_2", translateFunction(dependencies, false, dependencies.getChildren()));
SimpleNode newNode = (new Compiler.Parser()).substitute(node,
"(function () {var $lzsc$f = _1; $lzsc$f.dependencies = _2; return $lzsc$f })();", map);
return newNode;
}
return node;
}
static java.util.regex.Pattern identifierPattern = java.util.regex.Pattern.compile("[\\w$_]+");
// Internal helper function for above
// useName => declaration not expression
SimpleNode[] translateFunctionInternal(SimpleNode node, boolean useName, SimpleNode[] children) {
// ast can be any of:
// FunctionDefinition(name, args, body)
// FunctionDeclaration(name, args, body)
// FunctionDeclaration(args, body)
// Handle the two arities:
String functionName = null;
SimpleNode params;
SimpleNode stmts;
SimpleNode depExpr = null;
int stmtsIndex;
ASTIdentifier functionNameIdentifier = null;
if (children.length == 3) {
if (children[0] instanceof ASTIdentifier) {
functionNameIdentifier = (ASTIdentifier)children[0];
functionName = functionNameIdentifier.getName();
}
params = children[1];
stmts = children[stmtsIndex = 2];
} else {
params = children[0];
stmts = children[stmtsIndex = 1];
}
// inner functions do not get scriptElement treatment, shadow any
// outer declaration
options.putBoolean(Compiler.SCRIPT_ELEMENT, false);
// or the magic with(this) treatment
options.putBoolean(Compiler.WITH_THIS, false);
// function block
String userFunctionName = null;
String filename = node.filename != null? node.filename : "unknown file";
String lineno = "" + node.beginLine;
if (functionName != null) {
userFunctionName = functionName;
if (! useName) {
if ((! identifierPattern.matcher(functionName).matches())
// Some JS engines die if you name function expressions
|| options.getBoolean(Compiler.DEBUG_SIMPLE)) {
// This is a function-expression that has been annotated
// with a non-legal function name, so remove that and put it
// in _dbg_name (below)
functionName = null;
children[0] = new ASTEmptyExpression(0);
}
}
} else {
userFunctionName = "" + filename + "#" + lineno + "/" + node.beginColumn;
}
// Tell metering to look up the name at runtime if it is not a
// global name (this allows us to name closures more
// mnemonically at runtime
String meterFunctionName = useName ? functionName : null;
SimpleNode[] paramIds = params.getChildren();
// Pull all the pragmas from the list: process them, and remove
// them
assert stmts instanceof ASTStatementList;
List stmtList = new ArrayList(Arrays.asList(stmts.getChildren()));
for (int i = 0, len = stmtList.size(); i < len; i++) {
SimpleNode stmt = (SimpleNode)stmtList.get(i);
if (stmt instanceof ASTPragmaDirective) {
SimpleNode newNode = visitStatement(stmt);
if (! newNode.equals(stmt)) {
stmtList.set(i, newNode);
}
}
}
String methodName = (String)options.get(Compiler.METHOD_NAME);
// Backwards compatibility with tag compiler
if (methodName != null && functionNameIdentifier != null) {
functionNameIdentifier.setName(functionName = methodName);
}
if (options.getBoolean(Compiler.CONSTRAINT_FUNCTION)) {
// assert (functionName != null);
if (ReferenceCollector.DebugConstraints) {
System.err.println("stmts: " + stmts);
}
// Find dependencies.
//
// Compute this before any transformations on the function body.
//
// The job of a constraint function is to compute a value.
// The current implementation inlines the call to set the
// attribute that the constraint is attached to, within the
// constraint function it Walking the statements of
// the function will process the expression that computes
// the value; it will also process the call to
// setAttribute, but ReferenceCollector knows to ignore
//
ReferenceCollector dependencies = new ReferenceCollector(options.getBoolean(Compiler.COMPUTE_METAREFERENCES));
// Only visit original body
for (Iterator i = stmtList.iterator(); i.hasNext(); ) {
SimpleNode stmt = (SimpleNode)i.next();
dependencies.visit(stmt);
}
depExpr = dependencies.computeReferences(userFunctionName);
if (options.getBoolean(Compiler.PRINT_CONSTRAINTS)) {
(new ParseTreePrinter()).print(depExpr);
}
}
List prefix = new ArrayList();
List error = new ArrayList();
List suffix = new ArrayList();
if (options.getBoolean(Compiler.DEBUG_BACKTRACE)) {
prefix.add(parseFragment(
"var $lzsc$d = Debug, $lzsc$s = $lzsc$d.backtraceStack;" +
"if ($lzsc$s) {" +
" var $lzsc$a = Array.prototype.slice.call(arguments, 0);" +
" $lzsc$a.callee = arguments.callee;" +
" $lzsc$a['this'] = this;" +
" $lzsc$s.push($lzsc$a);" +
" if ($lzsc$s.length > $lzsc$s.maxDepth) {$lzsc$d.stackOverflow()};" +
"}"));
error.add(parseFragment(
"if ($lzsc$s && (! $lzsc$d.uncaughtBacktraceStack)) {" +
" $lzsc$d.uncaughtBacktraceStack = $lzsc$s.slice(0);" +
"}" +
"throw($lzsc$e);"));
suffix.add(parseFragment(
"if ($lzsc$s) {" +
" $lzsc$s.pop();" +
"}"));
}
if (options.getBoolean(Compiler.PROFILE)) {
prefix.add((meterFunctionEvent(node, "calls", meterFunctionName)));
suffix.add((meterFunctionEvent(node, "returns", meterFunctionName)));
}
// Analyze local variables (and functions)
VariableAnalyzer analyzer = new VariableAnalyzer(params, options.getBoolean(Compiler.FLASH_COMPILER_COMPATABILITY));
for (Iterator i = prefix.iterator(); i.hasNext(); ) {
analyzer.visit((SimpleNode)i.next());
}
for (Iterator i = stmtList.iterator(); i.hasNext(); ) {
analyzer.visit((SimpleNode)i.next());
}
for (Iterator i = suffix.iterator(); i.hasNext(); ) {
analyzer.visit((SimpleNode)i.next());
}
analyzer.computeReferences();
// Parameter _must_ be in order
LinkedHashSet parameters = analyzer.parameters;
// Linked for determinism for regression testing
Set variables = analyzer.variables;
LinkedHashMap fundefs = analyzer.fundefs;
Set closed = analyzer.closed;
Set free = analyzer.free;
// Note usage due to activation object and withThis
if (! free.isEmpty()) {
// TODO: [2005-06-29 ptw] with (_root) should not be
// necessary for the activation object case now that it is
// done at top level to get [[scope]] right.
if (options.getBoolean(Compiler.ACTIVATION_OBJECT)) {
analyzer.incrementUsed("_root");
}
if (options.getBoolean(Compiler.WITH_THIS)) {
analyzer.incrementUsed("this");
}
}
Map used = analyzer.used;
// If this is a closure, annotate the Username for metering
if ((! closed.isEmpty()) && (userFunctionName != null) && options.getBoolean(Compiler.PROFILE)) {
// Is there any other way to construct a closure in js
// other than a function returning a function?
if (context.findFunctionContext().parent.findFunctionContext() != null) {
userFunctionName = "" + closed + "." + userFunctionName;
}
}
if (false) {
System.err.println(userFunctionName +
":: parameters: " + parameters +
", variables: " + variables +
", fundefs: " + fundefs +
", used: " + used +
", closed: " + closed +
", free: " + free);
}
// Deal with warnings
if (options.getBoolean(Compiler.WARN_UNUSED_PARAMETERS)) {
Set unusedParams = new LinkedHashSet(parameters);
unusedParams.removeAll(used.keySet());
for (Iterator i = unusedParams.iterator(); i.hasNext(); ) {
System.err.println("Warning: parameter " + i.next() + " of " + userFunctionName +
" unused in " + filename + "(" + lineno + ")");
}
}
if (options.getBoolean(Compiler.WARN_UNUSED_LOCALS)) {
Set unusedVariables = new LinkedHashSet(variables);
unusedVariables.removeAll(used.keySet());
for (Iterator i = unusedVariables.iterator(); i.hasNext(); ) {
System.err.println("Warning: variable " + i.next() + " of " + userFunctionName +
" unused in " + filename + "(" + lineno + ")");
}
}
// auto-declared locals
Set auto = new LinkedHashSet();
auto.add("this");
auto.add("arguments");
auto.retainAll(used.keySet());
// parameters, locals, and auto-registers
Set known = new LinkedHashSet(parameters);
known.addAll(variables);
known.addAll(auto);
// for now, ensure that super has a value
known.remove("super");
// Look for #pragma
boolean scriptElement = options.getBoolean(Compiler.SCRIPT_ELEMENT);
Map registerMap = new HashMap();
if (remapLocals()) {
// All parameters and locals are remapped to 'registers' of the
// form `$n`. This prevents them from colliding with member
// slots due to implicit `with (this)` added below, and also makes
// the emitted code more compact.
int regno = 1;
boolean debug = options.getBoolean(Compiler.NAME_FUNCTIONS);
for (Iterator i = (new LinkedHashSet(known)).iterator(); i.hasNext(); ) {
String k = (String)i.next();
String r;
if (auto.contains(k) || closed.contains(k)) {
;
} else {
if (debug) {
- r = "$" + regno++ + "_" + k;
+ r = k + "_$" + regno++ ;
} else {
r = "$" + regno++;
}
registerMap.put(k, r);
// remove from known map
known.remove(k);
}
}
}
// Always set register map. Inner functions should not see
// parent registers (which they would if the setting of the
// registermap were conditional on function vs. function2)
context.setProperty(TranslationContext.REGISTERS, registerMap);
// Set the knownSet. This includes the parent's known set, so
// closed over variables are not treated as free.
Set knownSet = new LinkedHashSet(known);
// Add parent known
Set parentKnown = (Set)context.parent.get(TranslationContext.VARIABLES);
if (parentKnown != null) {
knownSet.addAll(parentKnown);
}
context.setProperty(TranslationContext.VARIABLES, knownSet);
// Replace params
for (int i = 0, len = paramIds.length; i < len; i++) {
if (paramIds[i] instanceof ASTIdentifier) {
ASTIdentifier oldParam = (ASTIdentifier)paramIds[i];
SimpleNode newParam = translateReference(oldParam).declare();
params.set(i, newParam);
}
}
translateFormalParameters(params);
List newBody = new ArrayList();
int activationObjectSize = 0;
if (scriptElement) {
// Create all variables (including inner functions) in global scope
if (! variables.isEmpty()) {
String code = "";
for (Iterator i = variables.iterator(); i.hasNext(); ) {
String name = (String)i.next();
// TODO: [2008-04-16 ptw] Retain type information through
// analyzer so it can be passed on here
addGlobalVar(name, null, "void 0");
code += name + "= void 0;";
}
newBody.add(parseFragment(code));
}
} else {
// Leave var declarations as is
// Emit function declarations here
if (! fundefs.isEmpty()) {
String code = "";
for (Iterator i = fundefs.keySet().iterator(); i.hasNext(); ) {
code += "var " + (String)i.next() + ";";
}
newBody.add(parseFragment(code));
}
}
// Cf. LPP-4850: Prefix has to come after declarations (above).
// FIXME: (LPP-2075) [2006-05-19 ptw] Wrap body in try and make
// suffix be a finally clause, so suffix will not be skipped by
// inner returns.
newBody.addAll(prefix);
// Now emit functions in the activation context
// Note: variable has already been declared so assignment does the
// right thing (either assigns to global or local
for (Iterator i = fundefs.keySet().iterator(); i.hasNext(); ) {
String name = (String)i.next();
if (scriptElement || used.containsKey(name)) {
SimpleNode fundecl = (SimpleNode)fundefs.get(name);
SimpleNode funexpr = new ASTFunctionExpression(0);
funexpr.setBeginLocation(fundecl.filename, fundecl.beginLine, fundecl.beginColumn);
funexpr.setChildren(fundecl.getChildren());
Map map = new HashMap();
map.put("_1", funexpr);
// Do I need a new one of these each time?
newBody.add((new Compiler.Parser()).substitute(fundecl, name + " = _1;", map));
}
}
// If the locals are not remapped, we assume we are in a runtime
// that already does implicit this in methods...
if ((! free.isEmpty()) && options.getBoolean(Compiler.WITH_THIS) && remapLocals()) {
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])stmtList.toArray(new SimpleNode[0]));
SimpleNode withNode = new ASTWithStatement(0);
SimpleNode id = new ASTThisReference(0);
withNode.set(0, id);
withNode.set(1, newStmts);
newBody.add(withNode);
} else {
newBody.addAll(stmtList);
}
// FIXME: (LPP-2075) [2006-05-19 ptw] Wrap body in try and make
// suffix be a finally clause, so suffix will not be skipped by
// inner returns.
if (! suffix.isEmpty() || ! error.isEmpty()) {
int i = 0;
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])newBody.toArray(new SimpleNode[0]));
SimpleNode tryNode = new ASTTryStatement(0);
tryNode.set(i++, newStmts);
if (! error.isEmpty()) {
SimpleNode catchNode = new ASTCatchClause(0);
SimpleNode catchStmts = new ASTStatementList(0);
catchStmts.setChildren((SimpleNode[])error.toArray(new SimpleNode[0]));
catchNode.set(0, new ASTIdentifier("$lzsc$e"));
catchNode.set(1, catchStmts);
tryNode.set(i++, catchNode);
}
if (! suffix.isEmpty()) {
SimpleNode finallyNode = new ASTFinallyClause(0);
SimpleNode suffixStmts = new ASTStatementList(0);
suffixStmts.setChildren((SimpleNode[])suffix.toArray(new SimpleNode[0]));
finallyNode.set(0, suffixStmts);
tryNode.set(i, finallyNode);
}
newBody = new ArrayList();
newBody.add(tryNode);
}
// Process amended body
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])newBody.toArray(new SimpleNode[0]));
newStmts = visitStatement(newStmts);
// Finally replace the function body with that whole enchilada
children[stmtsIndex] = newStmts;
if ( options.getBoolean(Compiler.NAME_FUNCTIONS) && (! options.getBoolean(Compiler.DEBUG_SWF9))) {
// TODO: [2007-09-04 ptw] Come up with a better way to
// distinguish LFC from user stack frames. See
// lfc/debugger/LzBactrace
String fn = (options.getBoolean(Compiler.FLASH_COMPILER_COMPATABILITY) ? "lfc/" : "") + filename;
if (functionName != null &&
// Either it is a declaration or we are not doing
// backtraces, so the name will be available from the
// runtime
(useName || (! (options.getBoolean(Compiler.DEBUG_BACKTRACE))))) {
if (options.getBoolean(Compiler.DEBUG_BACKTRACE)) {
SimpleNode newNode = new ASTStatementList(0);
newNode.set(0, new Compiler.PassThroughNode(node));
newNode.set(1, parseFragment(functionName + "._dbg_filename = " + ScriptCompiler.quote(fn)));
newNode.set(2, parseFragment(functionName + "._dbg_lineno = " + lineno));
node = visitStatement(newNode);
}
} else {
Map map = new HashMap();
map.put("_1", node);
SimpleNode newNode = new Compiler.PassThroughNode((new Compiler.Parser()).substitute(
node,
"(function () {" +
" var $lzsc$temp = _1;" +
" $lzsc$temp._dbg_name = " + ScriptCompiler.quote(userFunctionName) + ";" +
((options.getBoolean(Compiler.DEBUG_BACKTRACE)) ?
(" $lzsc$temp._dbg_filename = " + ScriptCompiler.quote(fn) + ";" +
" $lzsc$temp._dbg_lineno = " + lineno + ";") :
"") +
" return $lzsc$temp})()",
map));
node = newNode;
}
}
if (options.getBoolean(Compiler.CONSTRAINT_FUNCTION)) {
return new SimpleNode[] { node, depExpr };
}
return new SimpleNode[] { node, null };
}
SimpleNode translateLiteralNode(SimpleNode node) {
return node;
}
SimpleNode translateReferenceForCall(SimpleNode ast) {
return translateReferenceForCall(ast, false, null);
}
/* Contract is to leave a reference on the stack that will be
dereferenced by CallFunction, etc. Returns true if it
succeeds. Returns false if the ast is such that only the
value of the reference can be pushed. In this case, the
callee, must use "CallMethod UNDEF" to call the value
instead */
SimpleNode translateReferenceForCall(SimpleNode ast, boolean checkDefined, SimpleNode node) {
SimpleNode[] children = ast.getChildren();
if (checkDefined) {
assert node != null : "Must supply node for checkDefined";
}
if (ast instanceof ASTPropertyIdentifierReference) {
JavascriptReference ref = translateReference(children[0]);
String name = ((ASTIdentifier)children[1]).getName();
// if (checkDefined) {
// // TODO: needs to transform node
// checkUndefinedMethod(node, ref, name);
// }
children[0] = ref.get();
}
if (ast instanceof ASTPropertyValueReference) {
// TODO: [2002-10-26 ptw] (undefined reference coverage) Check
JavascriptReference ref = translateReference(children[0]);
children[1] = visitExpression(children[1]);
children[0] = ref.get();
}
// The only other reason you visit a reference is to make a funcall
boolean isref = true;
if (ast instanceof ASTIdentifier) {
JavascriptReference ref = translateReference(ast);
ast = ref.preset();
} else {
ast = visitExpression(ast);
}
// TODO: wrap into node
// if (checkDefined) {
// checkUndefinedFunction(
// node,
// isref && ast instanceof ASTIdentifier ? ((ASTIdentifier)ast).getName() : null);
// }
return ast;
}
JavascriptReference translateReference(SimpleNode node) {
return translateReference(node, 1);
}
static public class JavascriptReference {
protected Compiler.OptionMap options;
SimpleNode node;
SimpleNode checkedNode = null;
public JavascriptReference(Translator translator, SimpleNode node, int referenceCount) {
this.options = translator.getOptions();
this.node = node;
}
public boolean isChecked() {
return checkedNode != null;
}
public SimpleNode get(boolean checkUndefined) {
if (checkUndefined && checkedNode != null) {
return checkedNode;
}
return this.node;
}
public SimpleNode get() {
return get(true);
}
public SimpleNode preset() {
return this.node;
}
public SimpleNode set (Boolean warnGlobal) {
return this.node;
}
public SimpleNode set() {
return set(null);
}
public SimpleNode set(boolean warnGlobal) {
return set(Boolean.valueOf(warnGlobal));
}
public SimpleNode declare() {
return this.node;
}
public SimpleNode init() {
return this.node;
}
}
static public abstract class MemberReference extends JavascriptReference {
protected SimpleNode object;
public MemberReference(Translator translator, SimpleNode node, int referenceCount,
SimpleNode object) {
super(translator, node, referenceCount);
this.object = object;
}
}
static public class VariableReference extends JavascriptReference {
TranslationContext context;
public final String name;
public VariableReference(Translator translator, SimpleNode node, int referenceCount, String name) {
super(translator, node, referenceCount);
this.name = name;
this.context = (TranslationContext)translator.getContext();
Map registers = (Map)context.get(TranslationContext.REGISTERS);
// Replace identifiers with their 'register' (i.e. rename them)
if (registers != null && registers.containsKey(name)) {
String register = (String)registers.get(name);
ASTIdentifier newNode = new ASTIdentifier(0);
newNode.setLocation(node);
if (node instanceof ASTIdentifier) {
ASTIdentifier oldid = (ASTIdentifier)node;
newNode.setEllipsis(oldid.getEllipsis());
newNode.setType(oldid.getType());
}
newNode.setName(register);
this.node = new Compiler.PassThroughNode(newNode);
return;
}
if (options.getBoolean(Compiler.WARN_UNDEFINED_REFERENCES)) {
Set variables = (Set)context.get(TranslationContext.VARIABLES);
if (variables != null) {
boolean known = variables.contains(name);
// Ensure undefined is "defined"
known |= "undefined".equals(name);
if (! known) {
this.checkedNode = ((JavascriptGenerator)translator).makeCheckedNode(node);
}
}
}
}
public SimpleNode declare() {
Set variables = (Set)context.get(TranslationContext.VARIABLES);
if (variables != null) {
variables.add(this.name);
}
return this.node;
}
public SimpleNode init() {
Set variables = (Set)context.get(TranslationContext.VARIABLES);
if (variables != null) {
variables.add(this.name);
}
return this.node;
}
public SimpleNode get(boolean checkUndefined) {
if (checkUndefined && checkedNode != null) {
return checkedNode;
}
return node;
}
public SimpleNode set(Boolean warnGlobal) {
if (warnGlobal == null) {
if (context.type instanceof ASTProgram) {
warnGlobal = Boolean.FALSE;
} else {
warnGlobal = Boolean.valueOf(options.getBoolean(Compiler.WARN_GLOBAL_ASSIGNMENTS));
}
}
if ((checkedNode != null) && warnGlobal.booleanValue()) {
System.err.println("Warning: Assignment to free variable " + name +
" in " + node.filename +
" (" + node.beginLine + ")");
}
return node;
}
}
static public Set uncheckedProperties = new HashSet(Arrays.asList(new String[] {"call", "apply", "prototype"}));
static public class PropertyReference extends MemberReference {
String propertyName;
public PropertyReference(Translator translator, SimpleNode node, int referenceCount,
SimpleNode object, ASTIdentifier propertyName) {
super(translator, node, referenceCount, object);
this.propertyName = (String)propertyName.getName();
// TODO: [2006-04-24 ptw] Don't make checkedNode when you know
// that the member exists
// This is not right, but Opera does not support [[Call]] on
// call or apply, so we can't check for them
// if (! uncheckedProperties.contains(this.propertyName)) {
// this.checkedNode = ((JavascriptGenerator)translator).makeCheckedNode(node);
// }
}
}
static public class IndexReference extends MemberReference {
SimpleNode indexExpr;
public IndexReference(Translator translator, SimpleNode node, int referenceCount,
SimpleNode object, SimpleNode indexExpr) {
super(translator, node, referenceCount, object);
this.indexExpr = indexExpr;
// We don't check index references for compatibility with SWF compiler
}
}
JavascriptReference translateReference(SimpleNode node, int referenceCount) {
if (node instanceof ASTIdentifier) {
return new VariableReference(this, node, referenceCount, ((ASTIdentifier)node).getName());
}
SimpleNode[] args = node.getChildren();
if (node instanceof ASTPropertyIdentifierReference) {
args[0] = visitExpression(args[0]);
// If args[1] is an identifier, it is a literal, otherwise
// translate it.
if (! (args[1] instanceof ASTIdentifier)) {
args[1] = visitExpression(args[1]);
}
return new PropertyReference(this, node, referenceCount, args[0], (ASTIdentifier)args[1]);
} else if (node instanceof ASTPropertyValueReference) {
args[0] = visitExpression(args[0]);
args[1] = visitExpression(args[1]);
return new IndexReference(this, node, referenceCount, args[0], args[1]);
}
return new JavascriptReference(this, node, referenceCount);
}
/**
* Returns true if local variables and parameters
* should have remapped names (like $1, $2, ...) to prevent
* them from colliding with member names that may be exposed
* by implicit insertion of with(this).
*
* This method can be overridden when subclassed.
*/
public boolean remapLocals() {
boolean scriptElement = options.getBoolean(Compiler.SCRIPT_ELEMENT);
return !scriptElement;
}
}
/**
* @copyright Copyright 2006-2008 Laszlo Systems, Inc. All Rights
* Reserved. Use is subject to license terms.
*/
| true | true | SimpleNode[] translateFunctionInternal(SimpleNode node, boolean useName, SimpleNode[] children) {
// ast can be any of:
// FunctionDefinition(name, args, body)
// FunctionDeclaration(name, args, body)
// FunctionDeclaration(args, body)
// Handle the two arities:
String functionName = null;
SimpleNode params;
SimpleNode stmts;
SimpleNode depExpr = null;
int stmtsIndex;
ASTIdentifier functionNameIdentifier = null;
if (children.length == 3) {
if (children[0] instanceof ASTIdentifier) {
functionNameIdentifier = (ASTIdentifier)children[0];
functionName = functionNameIdentifier.getName();
}
params = children[1];
stmts = children[stmtsIndex = 2];
} else {
params = children[0];
stmts = children[stmtsIndex = 1];
}
// inner functions do not get scriptElement treatment, shadow any
// outer declaration
options.putBoolean(Compiler.SCRIPT_ELEMENT, false);
// or the magic with(this) treatment
options.putBoolean(Compiler.WITH_THIS, false);
// function block
String userFunctionName = null;
String filename = node.filename != null? node.filename : "unknown file";
String lineno = "" + node.beginLine;
if (functionName != null) {
userFunctionName = functionName;
if (! useName) {
if ((! identifierPattern.matcher(functionName).matches())
// Some JS engines die if you name function expressions
|| options.getBoolean(Compiler.DEBUG_SIMPLE)) {
// This is a function-expression that has been annotated
// with a non-legal function name, so remove that and put it
// in _dbg_name (below)
functionName = null;
children[0] = new ASTEmptyExpression(0);
}
}
} else {
userFunctionName = "" + filename + "#" + lineno + "/" + node.beginColumn;
}
// Tell metering to look up the name at runtime if it is not a
// global name (this allows us to name closures more
// mnemonically at runtime
String meterFunctionName = useName ? functionName : null;
SimpleNode[] paramIds = params.getChildren();
// Pull all the pragmas from the list: process them, and remove
// them
assert stmts instanceof ASTStatementList;
List stmtList = new ArrayList(Arrays.asList(stmts.getChildren()));
for (int i = 0, len = stmtList.size(); i < len; i++) {
SimpleNode stmt = (SimpleNode)stmtList.get(i);
if (stmt instanceof ASTPragmaDirective) {
SimpleNode newNode = visitStatement(stmt);
if (! newNode.equals(stmt)) {
stmtList.set(i, newNode);
}
}
}
String methodName = (String)options.get(Compiler.METHOD_NAME);
// Backwards compatibility with tag compiler
if (methodName != null && functionNameIdentifier != null) {
functionNameIdentifier.setName(functionName = methodName);
}
if (options.getBoolean(Compiler.CONSTRAINT_FUNCTION)) {
// assert (functionName != null);
if (ReferenceCollector.DebugConstraints) {
System.err.println("stmts: " + stmts);
}
// Find dependencies.
//
// Compute this before any transformations on the function body.
//
// The job of a constraint function is to compute a value.
// The current implementation inlines the call to set the
// attribute that the constraint is attached to, within the
// constraint function it Walking the statements of
// the function will process the expression that computes
// the value; it will also process the call to
// setAttribute, but ReferenceCollector knows to ignore
//
ReferenceCollector dependencies = new ReferenceCollector(options.getBoolean(Compiler.COMPUTE_METAREFERENCES));
// Only visit original body
for (Iterator i = stmtList.iterator(); i.hasNext(); ) {
SimpleNode stmt = (SimpleNode)i.next();
dependencies.visit(stmt);
}
depExpr = dependencies.computeReferences(userFunctionName);
if (options.getBoolean(Compiler.PRINT_CONSTRAINTS)) {
(new ParseTreePrinter()).print(depExpr);
}
}
List prefix = new ArrayList();
List error = new ArrayList();
List suffix = new ArrayList();
if (options.getBoolean(Compiler.DEBUG_BACKTRACE)) {
prefix.add(parseFragment(
"var $lzsc$d = Debug, $lzsc$s = $lzsc$d.backtraceStack;" +
"if ($lzsc$s) {" +
" var $lzsc$a = Array.prototype.slice.call(arguments, 0);" +
" $lzsc$a.callee = arguments.callee;" +
" $lzsc$a['this'] = this;" +
" $lzsc$s.push($lzsc$a);" +
" if ($lzsc$s.length > $lzsc$s.maxDepth) {$lzsc$d.stackOverflow()};" +
"}"));
error.add(parseFragment(
"if ($lzsc$s && (! $lzsc$d.uncaughtBacktraceStack)) {" +
" $lzsc$d.uncaughtBacktraceStack = $lzsc$s.slice(0);" +
"}" +
"throw($lzsc$e);"));
suffix.add(parseFragment(
"if ($lzsc$s) {" +
" $lzsc$s.pop();" +
"}"));
}
if (options.getBoolean(Compiler.PROFILE)) {
prefix.add((meterFunctionEvent(node, "calls", meterFunctionName)));
suffix.add((meterFunctionEvent(node, "returns", meterFunctionName)));
}
// Analyze local variables (and functions)
VariableAnalyzer analyzer = new VariableAnalyzer(params, options.getBoolean(Compiler.FLASH_COMPILER_COMPATABILITY));
for (Iterator i = prefix.iterator(); i.hasNext(); ) {
analyzer.visit((SimpleNode)i.next());
}
for (Iterator i = stmtList.iterator(); i.hasNext(); ) {
analyzer.visit((SimpleNode)i.next());
}
for (Iterator i = suffix.iterator(); i.hasNext(); ) {
analyzer.visit((SimpleNode)i.next());
}
analyzer.computeReferences();
// Parameter _must_ be in order
LinkedHashSet parameters = analyzer.parameters;
// Linked for determinism for regression testing
Set variables = analyzer.variables;
LinkedHashMap fundefs = analyzer.fundefs;
Set closed = analyzer.closed;
Set free = analyzer.free;
// Note usage due to activation object and withThis
if (! free.isEmpty()) {
// TODO: [2005-06-29 ptw] with (_root) should not be
// necessary for the activation object case now that it is
// done at top level to get [[scope]] right.
if (options.getBoolean(Compiler.ACTIVATION_OBJECT)) {
analyzer.incrementUsed("_root");
}
if (options.getBoolean(Compiler.WITH_THIS)) {
analyzer.incrementUsed("this");
}
}
Map used = analyzer.used;
// If this is a closure, annotate the Username for metering
if ((! closed.isEmpty()) && (userFunctionName != null) && options.getBoolean(Compiler.PROFILE)) {
// Is there any other way to construct a closure in js
// other than a function returning a function?
if (context.findFunctionContext().parent.findFunctionContext() != null) {
userFunctionName = "" + closed + "." + userFunctionName;
}
}
if (false) {
System.err.println(userFunctionName +
":: parameters: " + parameters +
", variables: " + variables +
", fundefs: " + fundefs +
", used: " + used +
", closed: " + closed +
", free: " + free);
}
// Deal with warnings
if (options.getBoolean(Compiler.WARN_UNUSED_PARAMETERS)) {
Set unusedParams = new LinkedHashSet(parameters);
unusedParams.removeAll(used.keySet());
for (Iterator i = unusedParams.iterator(); i.hasNext(); ) {
System.err.println("Warning: parameter " + i.next() + " of " + userFunctionName +
" unused in " + filename + "(" + lineno + ")");
}
}
if (options.getBoolean(Compiler.WARN_UNUSED_LOCALS)) {
Set unusedVariables = new LinkedHashSet(variables);
unusedVariables.removeAll(used.keySet());
for (Iterator i = unusedVariables.iterator(); i.hasNext(); ) {
System.err.println("Warning: variable " + i.next() + " of " + userFunctionName +
" unused in " + filename + "(" + lineno + ")");
}
}
// auto-declared locals
Set auto = new LinkedHashSet();
auto.add("this");
auto.add("arguments");
auto.retainAll(used.keySet());
// parameters, locals, and auto-registers
Set known = new LinkedHashSet(parameters);
known.addAll(variables);
known.addAll(auto);
// for now, ensure that super has a value
known.remove("super");
// Look for #pragma
boolean scriptElement = options.getBoolean(Compiler.SCRIPT_ELEMENT);
Map registerMap = new HashMap();
if (remapLocals()) {
// All parameters and locals are remapped to 'registers' of the
// form `$n`. This prevents them from colliding with member
// slots due to implicit `with (this)` added below, and also makes
// the emitted code more compact.
int regno = 1;
boolean debug = options.getBoolean(Compiler.NAME_FUNCTIONS);
for (Iterator i = (new LinkedHashSet(known)).iterator(); i.hasNext(); ) {
String k = (String)i.next();
String r;
if (auto.contains(k) || closed.contains(k)) {
;
} else {
if (debug) {
r = "$" + regno++ + "_" + k;
} else {
r = "$" + regno++;
}
registerMap.put(k, r);
// remove from known map
known.remove(k);
}
}
}
// Always set register map. Inner functions should not see
// parent registers (which they would if the setting of the
// registermap were conditional on function vs. function2)
context.setProperty(TranslationContext.REGISTERS, registerMap);
// Set the knownSet. This includes the parent's known set, so
// closed over variables are not treated as free.
Set knownSet = new LinkedHashSet(known);
// Add parent known
Set parentKnown = (Set)context.parent.get(TranslationContext.VARIABLES);
if (parentKnown != null) {
knownSet.addAll(parentKnown);
}
context.setProperty(TranslationContext.VARIABLES, knownSet);
// Replace params
for (int i = 0, len = paramIds.length; i < len; i++) {
if (paramIds[i] instanceof ASTIdentifier) {
ASTIdentifier oldParam = (ASTIdentifier)paramIds[i];
SimpleNode newParam = translateReference(oldParam).declare();
params.set(i, newParam);
}
}
translateFormalParameters(params);
List newBody = new ArrayList();
int activationObjectSize = 0;
if (scriptElement) {
// Create all variables (including inner functions) in global scope
if (! variables.isEmpty()) {
String code = "";
for (Iterator i = variables.iterator(); i.hasNext(); ) {
String name = (String)i.next();
// TODO: [2008-04-16 ptw] Retain type information through
// analyzer so it can be passed on here
addGlobalVar(name, null, "void 0");
code += name + "= void 0;";
}
newBody.add(parseFragment(code));
}
} else {
// Leave var declarations as is
// Emit function declarations here
if (! fundefs.isEmpty()) {
String code = "";
for (Iterator i = fundefs.keySet().iterator(); i.hasNext(); ) {
code += "var " + (String)i.next() + ";";
}
newBody.add(parseFragment(code));
}
}
// Cf. LPP-4850: Prefix has to come after declarations (above).
// FIXME: (LPP-2075) [2006-05-19 ptw] Wrap body in try and make
// suffix be a finally clause, so suffix will not be skipped by
// inner returns.
newBody.addAll(prefix);
// Now emit functions in the activation context
// Note: variable has already been declared so assignment does the
// right thing (either assigns to global or local
for (Iterator i = fundefs.keySet().iterator(); i.hasNext(); ) {
String name = (String)i.next();
if (scriptElement || used.containsKey(name)) {
SimpleNode fundecl = (SimpleNode)fundefs.get(name);
SimpleNode funexpr = new ASTFunctionExpression(0);
funexpr.setBeginLocation(fundecl.filename, fundecl.beginLine, fundecl.beginColumn);
funexpr.setChildren(fundecl.getChildren());
Map map = new HashMap();
map.put("_1", funexpr);
// Do I need a new one of these each time?
newBody.add((new Compiler.Parser()).substitute(fundecl, name + " = _1;", map));
}
}
// If the locals are not remapped, we assume we are in a runtime
// that already does implicit this in methods...
if ((! free.isEmpty()) && options.getBoolean(Compiler.WITH_THIS) && remapLocals()) {
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])stmtList.toArray(new SimpleNode[0]));
SimpleNode withNode = new ASTWithStatement(0);
SimpleNode id = new ASTThisReference(0);
withNode.set(0, id);
withNode.set(1, newStmts);
newBody.add(withNode);
} else {
newBody.addAll(stmtList);
}
// FIXME: (LPP-2075) [2006-05-19 ptw] Wrap body in try and make
// suffix be a finally clause, so suffix will not be skipped by
// inner returns.
if (! suffix.isEmpty() || ! error.isEmpty()) {
int i = 0;
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])newBody.toArray(new SimpleNode[0]));
SimpleNode tryNode = new ASTTryStatement(0);
tryNode.set(i++, newStmts);
if (! error.isEmpty()) {
SimpleNode catchNode = new ASTCatchClause(0);
SimpleNode catchStmts = new ASTStatementList(0);
catchStmts.setChildren((SimpleNode[])error.toArray(new SimpleNode[0]));
catchNode.set(0, new ASTIdentifier("$lzsc$e"));
catchNode.set(1, catchStmts);
tryNode.set(i++, catchNode);
}
if (! suffix.isEmpty()) {
SimpleNode finallyNode = new ASTFinallyClause(0);
SimpleNode suffixStmts = new ASTStatementList(0);
suffixStmts.setChildren((SimpleNode[])suffix.toArray(new SimpleNode[0]));
finallyNode.set(0, suffixStmts);
tryNode.set(i, finallyNode);
}
newBody = new ArrayList();
newBody.add(tryNode);
}
// Process amended body
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])newBody.toArray(new SimpleNode[0]));
newStmts = visitStatement(newStmts);
// Finally replace the function body with that whole enchilada
children[stmtsIndex] = newStmts;
if ( options.getBoolean(Compiler.NAME_FUNCTIONS) && (! options.getBoolean(Compiler.DEBUG_SWF9))) {
// TODO: [2007-09-04 ptw] Come up with a better way to
// distinguish LFC from user stack frames. See
// lfc/debugger/LzBactrace
String fn = (options.getBoolean(Compiler.FLASH_COMPILER_COMPATABILITY) ? "lfc/" : "") + filename;
if (functionName != null &&
// Either it is a declaration or we are not doing
// backtraces, so the name will be available from the
// runtime
(useName || (! (options.getBoolean(Compiler.DEBUG_BACKTRACE))))) {
if (options.getBoolean(Compiler.DEBUG_BACKTRACE)) {
SimpleNode newNode = new ASTStatementList(0);
newNode.set(0, new Compiler.PassThroughNode(node));
newNode.set(1, parseFragment(functionName + "._dbg_filename = " + ScriptCompiler.quote(fn)));
newNode.set(2, parseFragment(functionName + "._dbg_lineno = " + lineno));
node = visitStatement(newNode);
}
} else {
Map map = new HashMap();
map.put("_1", node);
SimpleNode newNode = new Compiler.PassThroughNode((new Compiler.Parser()).substitute(
node,
"(function () {" +
" var $lzsc$temp = _1;" +
" $lzsc$temp._dbg_name = " + ScriptCompiler.quote(userFunctionName) + ";" +
((options.getBoolean(Compiler.DEBUG_BACKTRACE)) ?
(" $lzsc$temp._dbg_filename = " + ScriptCompiler.quote(fn) + ";" +
" $lzsc$temp._dbg_lineno = " + lineno + ";") :
"") +
" return $lzsc$temp})()",
map));
node = newNode;
}
}
if (options.getBoolean(Compiler.CONSTRAINT_FUNCTION)) {
return new SimpleNode[] { node, depExpr };
}
return new SimpleNode[] { node, null };
}
| SimpleNode[] translateFunctionInternal(SimpleNode node, boolean useName, SimpleNode[] children) {
// ast can be any of:
// FunctionDefinition(name, args, body)
// FunctionDeclaration(name, args, body)
// FunctionDeclaration(args, body)
// Handle the two arities:
String functionName = null;
SimpleNode params;
SimpleNode stmts;
SimpleNode depExpr = null;
int stmtsIndex;
ASTIdentifier functionNameIdentifier = null;
if (children.length == 3) {
if (children[0] instanceof ASTIdentifier) {
functionNameIdentifier = (ASTIdentifier)children[0];
functionName = functionNameIdentifier.getName();
}
params = children[1];
stmts = children[stmtsIndex = 2];
} else {
params = children[0];
stmts = children[stmtsIndex = 1];
}
// inner functions do not get scriptElement treatment, shadow any
// outer declaration
options.putBoolean(Compiler.SCRIPT_ELEMENT, false);
// or the magic with(this) treatment
options.putBoolean(Compiler.WITH_THIS, false);
// function block
String userFunctionName = null;
String filename = node.filename != null? node.filename : "unknown file";
String lineno = "" + node.beginLine;
if (functionName != null) {
userFunctionName = functionName;
if (! useName) {
if ((! identifierPattern.matcher(functionName).matches())
// Some JS engines die if you name function expressions
|| options.getBoolean(Compiler.DEBUG_SIMPLE)) {
// This is a function-expression that has been annotated
// with a non-legal function name, so remove that and put it
// in _dbg_name (below)
functionName = null;
children[0] = new ASTEmptyExpression(0);
}
}
} else {
userFunctionName = "" + filename + "#" + lineno + "/" + node.beginColumn;
}
// Tell metering to look up the name at runtime if it is not a
// global name (this allows us to name closures more
// mnemonically at runtime
String meterFunctionName = useName ? functionName : null;
SimpleNode[] paramIds = params.getChildren();
// Pull all the pragmas from the list: process them, and remove
// them
assert stmts instanceof ASTStatementList;
List stmtList = new ArrayList(Arrays.asList(stmts.getChildren()));
for (int i = 0, len = stmtList.size(); i < len; i++) {
SimpleNode stmt = (SimpleNode)stmtList.get(i);
if (stmt instanceof ASTPragmaDirective) {
SimpleNode newNode = visitStatement(stmt);
if (! newNode.equals(stmt)) {
stmtList.set(i, newNode);
}
}
}
String methodName = (String)options.get(Compiler.METHOD_NAME);
// Backwards compatibility with tag compiler
if (methodName != null && functionNameIdentifier != null) {
functionNameIdentifier.setName(functionName = methodName);
}
if (options.getBoolean(Compiler.CONSTRAINT_FUNCTION)) {
// assert (functionName != null);
if (ReferenceCollector.DebugConstraints) {
System.err.println("stmts: " + stmts);
}
// Find dependencies.
//
// Compute this before any transformations on the function body.
//
// The job of a constraint function is to compute a value.
// The current implementation inlines the call to set the
// attribute that the constraint is attached to, within the
// constraint function it Walking the statements of
// the function will process the expression that computes
// the value; it will also process the call to
// setAttribute, but ReferenceCollector knows to ignore
//
ReferenceCollector dependencies = new ReferenceCollector(options.getBoolean(Compiler.COMPUTE_METAREFERENCES));
// Only visit original body
for (Iterator i = stmtList.iterator(); i.hasNext(); ) {
SimpleNode stmt = (SimpleNode)i.next();
dependencies.visit(stmt);
}
depExpr = dependencies.computeReferences(userFunctionName);
if (options.getBoolean(Compiler.PRINT_CONSTRAINTS)) {
(new ParseTreePrinter()).print(depExpr);
}
}
List prefix = new ArrayList();
List error = new ArrayList();
List suffix = new ArrayList();
if (options.getBoolean(Compiler.DEBUG_BACKTRACE)) {
prefix.add(parseFragment(
"var $lzsc$d = Debug, $lzsc$s = $lzsc$d.backtraceStack;" +
"if ($lzsc$s) {" +
" var $lzsc$a = Array.prototype.slice.call(arguments, 0);" +
" $lzsc$a.callee = arguments.callee;" +
" $lzsc$a['this'] = this;" +
" $lzsc$s.push($lzsc$a);" +
" if ($lzsc$s.length > $lzsc$s.maxDepth) {$lzsc$d.stackOverflow()};" +
"}"));
error.add(parseFragment(
"if ($lzsc$s && (! $lzsc$d.uncaughtBacktraceStack)) {" +
" $lzsc$d.uncaughtBacktraceStack = $lzsc$s.slice(0);" +
"}" +
"throw($lzsc$e);"));
suffix.add(parseFragment(
"if ($lzsc$s) {" +
" $lzsc$s.pop();" +
"}"));
}
if (options.getBoolean(Compiler.PROFILE)) {
prefix.add((meterFunctionEvent(node, "calls", meterFunctionName)));
suffix.add((meterFunctionEvent(node, "returns", meterFunctionName)));
}
// Analyze local variables (and functions)
VariableAnalyzer analyzer = new VariableAnalyzer(params, options.getBoolean(Compiler.FLASH_COMPILER_COMPATABILITY));
for (Iterator i = prefix.iterator(); i.hasNext(); ) {
analyzer.visit((SimpleNode)i.next());
}
for (Iterator i = stmtList.iterator(); i.hasNext(); ) {
analyzer.visit((SimpleNode)i.next());
}
for (Iterator i = suffix.iterator(); i.hasNext(); ) {
analyzer.visit((SimpleNode)i.next());
}
analyzer.computeReferences();
// Parameter _must_ be in order
LinkedHashSet parameters = analyzer.parameters;
// Linked for determinism for regression testing
Set variables = analyzer.variables;
LinkedHashMap fundefs = analyzer.fundefs;
Set closed = analyzer.closed;
Set free = analyzer.free;
// Note usage due to activation object and withThis
if (! free.isEmpty()) {
// TODO: [2005-06-29 ptw] with (_root) should not be
// necessary for the activation object case now that it is
// done at top level to get [[scope]] right.
if (options.getBoolean(Compiler.ACTIVATION_OBJECT)) {
analyzer.incrementUsed("_root");
}
if (options.getBoolean(Compiler.WITH_THIS)) {
analyzer.incrementUsed("this");
}
}
Map used = analyzer.used;
// If this is a closure, annotate the Username for metering
if ((! closed.isEmpty()) && (userFunctionName != null) && options.getBoolean(Compiler.PROFILE)) {
// Is there any other way to construct a closure in js
// other than a function returning a function?
if (context.findFunctionContext().parent.findFunctionContext() != null) {
userFunctionName = "" + closed + "." + userFunctionName;
}
}
if (false) {
System.err.println(userFunctionName +
":: parameters: " + parameters +
", variables: " + variables +
", fundefs: " + fundefs +
", used: " + used +
", closed: " + closed +
", free: " + free);
}
// Deal with warnings
if (options.getBoolean(Compiler.WARN_UNUSED_PARAMETERS)) {
Set unusedParams = new LinkedHashSet(parameters);
unusedParams.removeAll(used.keySet());
for (Iterator i = unusedParams.iterator(); i.hasNext(); ) {
System.err.println("Warning: parameter " + i.next() + " of " + userFunctionName +
" unused in " + filename + "(" + lineno + ")");
}
}
if (options.getBoolean(Compiler.WARN_UNUSED_LOCALS)) {
Set unusedVariables = new LinkedHashSet(variables);
unusedVariables.removeAll(used.keySet());
for (Iterator i = unusedVariables.iterator(); i.hasNext(); ) {
System.err.println("Warning: variable " + i.next() + " of " + userFunctionName +
" unused in " + filename + "(" + lineno + ")");
}
}
// auto-declared locals
Set auto = new LinkedHashSet();
auto.add("this");
auto.add("arguments");
auto.retainAll(used.keySet());
// parameters, locals, and auto-registers
Set known = new LinkedHashSet(parameters);
known.addAll(variables);
known.addAll(auto);
// for now, ensure that super has a value
known.remove("super");
// Look for #pragma
boolean scriptElement = options.getBoolean(Compiler.SCRIPT_ELEMENT);
Map registerMap = new HashMap();
if (remapLocals()) {
// All parameters and locals are remapped to 'registers' of the
// form `$n`. This prevents them from colliding with member
// slots due to implicit `with (this)` added below, and also makes
// the emitted code more compact.
int regno = 1;
boolean debug = options.getBoolean(Compiler.NAME_FUNCTIONS);
for (Iterator i = (new LinkedHashSet(known)).iterator(); i.hasNext(); ) {
String k = (String)i.next();
String r;
if (auto.contains(k) || closed.contains(k)) {
;
} else {
if (debug) {
r = k + "_$" + regno++ ;
} else {
r = "$" + regno++;
}
registerMap.put(k, r);
// remove from known map
known.remove(k);
}
}
}
// Always set register map. Inner functions should not see
// parent registers (which they would if the setting of the
// registermap were conditional on function vs. function2)
context.setProperty(TranslationContext.REGISTERS, registerMap);
// Set the knownSet. This includes the parent's known set, so
// closed over variables are not treated as free.
Set knownSet = new LinkedHashSet(known);
// Add parent known
Set parentKnown = (Set)context.parent.get(TranslationContext.VARIABLES);
if (parentKnown != null) {
knownSet.addAll(parentKnown);
}
context.setProperty(TranslationContext.VARIABLES, knownSet);
// Replace params
for (int i = 0, len = paramIds.length; i < len; i++) {
if (paramIds[i] instanceof ASTIdentifier) {
ASTIdentifier oldParam = (ASTIdentifier)paramIds[i];
SimpleNode newParam = translateReference(oldParam).declare();
params.set(i, newParam);
}
}
translateFormalParameters(params);
List newBody = new ArrayList();
int activationObjectSize = 0;
if (scriptElement) {
// Create all variables (including inner functions) in global scope
if (! variables.isEmpty()) {
String code = "";
for (Iterator i = variables.iterator(); i.hasNext(); ) {
String name = (String)i.next();
// TODO: [2008-04-16 ptw] Retain type information through
// analyzer so it can be passed on here
addGlobalVar(name, null, "void 0");
code += name + "= void 0;";
}
newBody.add(parseFragment(code));
}
} else {
// Leave var declarations as is
// Emit function declarations here
if (! fundefs.isEmpty()) {
String code = "";
for (Iterator i = fundefs.keySet().iterator(); i.hasNext(); ) {
code += "var " + (String)i.next() + ";";
}
newBody.add(parseFragment(code));
}
}
// Cf. LPP-4850: Prefix has to come after declarations (above).
// FIXME: (LPP-2075) [2006-05-19 ptw] Wrap body in try and make
// suffix be a finally clause, so suffix will not be skipped by
// inner returns.
newBody.addAll(prefix);
// Now emit functions in the activation context
// Note: variable has already been declared so assignment does the
// right thing (either assigns to global or local
for (Iterator i = fundefs.keySet().iterator(); i.hasNext(); ) {
String name = (String)i.next();
if (scriptElement || used.containsKey(name)) {
SimpleNode fundecl = (SimpleNode)fundefs.get(name);
SimpleNode funexpr = new ASTFunctionExpression(0);
funexpr.setBeginLocation(fundecl.filename, fundecl.beginLine, fundecl.beginColumn);
funexpr.setChildren(fundecl.getChildren());
Map map = new HashMap();
map.put("_1", funexpr);
// Do I need a new one of these each time?
newBody.add((new Compiler.Parser()).substitute(fundecl, name + " = _1;", map));
}
}
// If the locals are not remapped, we assume we are in a runtime
// that already does implicit this in methods...
if ((! free.isEmpty()) && options.getBoolean(Compiler.WITH_THIS) && remapLocals()) {
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])stmtList.toArray(new SimpleNode[0]));
SimpleNode withNode = new ASTWithStatement(0);
SimpleNode id = new ASTThisReference(0);
withNode.set(0, id);
withNode.set(1, newStmts);
newBody.add(withNode);
} else {
newBody.addAll(stmtList);
}
// FIXME: (LPP-2075) [2006-05-19 ptw] Wrap body in try and make
// suffix be a finally clause, so suffix will not be skipped by
// inner returns.
if (! suffix.isEmpty() || ! error.isEmpty()) {
int i = 0;
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])newBody.toArray(new SimpleNode[0]));
SimpleNode tryNode = new ASTTryStatement(0);
tryNode.set(i++, newStmts);
if (! error.isEmpty()) {
SimpleNode catchNode = new ASTCatchClause(0);
SimpleNode catchStmts = new ASTStatementList(0);
catchStmts.setChildren((SimpleNode[])error.toArray(new SimpleNode[0]));
catchNode.set(0, new ASTIdentifier("$lzsc$e"));
catchNode.set(1, catchStmts);
tryNode.set(i++, catchNode);
}
if (! suffix.isEmpty()) {
SimpleNode finallyNode = new ASTFinallyClause(0);
SimpleNode suffixStmts = new ASTStatementList(0);
suffixStmts.setChildren((SimpleNode[])suffix.toArray(new SimpleNode[0]));
finallyNode.set(0, suffixStmts);
tryNode.set(i, finallyNode);
}
newBody = new ArrayList();
newBody.add(tryNode);
}
// Process amended body
SimpleNode newStmts = new ASTStatementList(0);
newStmts.setChildren((SimpleNode[])newBody.toArray(new SimpleNode[0]));
newStmts = visitStatement(newStmts);
// Finally replace the function body with that whole enchilada
children[stmtsIndex] = newStmts;
if ( options.getBoolean(Compiler.NAME_FUNCTIONS) && (! options.getBoolean(Compiler.DEBUG_SWF9))) {
// TODO: [2007-09-04 ptw] Come up with a better way to
// distinguish LFC from user stack frames. See
// lfc/debugger/LzBactrace
String fn = (options.getBoolean(Compiler.FLASH_COMPILER_COMPATABILITY) ? "lfc/" : "") + filename;
if (functionName != null &&
// Either it is a declaration or we are not doing
// backtraces, so the name will be available from the
// runtime
(useName || (! (options.getBoolean(Compiler.DEBUG_BACKTRACE))))) {
if (options.getBoolean(Compiler.DEBUG_BACKTRACE)) {
SimpleNode newNode = new ASTStatementList(0);
newNode.set(0, new Compiler.PassThroughNode(node));
newNode.set(1, parseFragment(functionName + "._dbg_filename = " + ScriptCompiler.quote(fn)));
newNode.set(2, parseFragment(functionName + "._dbg_lineno = " + lineno));
node = visitStatement(newNode);
}
} else {
Map map = new HashMap();
map.put("_1", node);
SimpleNode newNode = new Compiler.PassThroughNode((new Compiler.Parser()).substitute(
node,
"(function () {" +
" var $lzsc$temp = _1;" +
" $lzsc$temp._dbg_name = " + ScriptCompiler.quote(userFunctionName) + ";" +
((options.getBoolean(Compiler.DEBUG_BACKTRACE)) ?
(" $lzsc$temp._dbg_filename = " + ScriptCompiler.quote(fn) + ";" +
" $lzsc$temp._dbg_lineno = " + lineno + ";") :
"") +
" return $lzsc$temp})()",
map));
node = newNode;
}
}
if (options.getBoolean(Compiler.CONSTRAINT_FUNCTION)) {
return new SimpleNode[] { node, depExpr };
}
return new SimpleNode[] { node, null };
}
|
diff --git a/src/main/java/me/znickq/playerplus/TextureChooser.java b/src/main/java/me/znickq/playerplus/TextureChooser.java
index bce11cf..e65a31c 100644
--- a/src/main/java/me/znickq/playerplus/TextureChooser.java
+++ b/src/main/java/me/znickq/playerplus/TextureChooser.java
@@ -1,165 +1,165 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package me.znickq.playerplus;
import java.util.ArrayList;
import java.util.List;
import me.znickq.playerplus.widgets.*;
import org.bukkit.Material;
import org.getspout.spoutapi.gui.GenericButton;
import org.getspout.spoutapi.gui.GenericPopup;
import org.getspout.spoutapi.gui.GenericTexture;
import org.getspout.spoutapi.gui.ListWidget;
import org.getspout.spoutapi.gui.ListWidgetItem;
import org.getspout.spoutapi.gui.WidgetAnchor;
import org.getspout.spoutapi.player.SpoutPlayer;
import org.getspout.spoutapi.player.accessories.AccessoryType;
/**
*
* @author ZNickq
*/
public class TextureChooser extends GenericPopup {
private PlayerPlus instance;
private SpoutPlayer player;
private ListWidget lw;
private MyComboBox cb;
private GenericTexture gt;
private AccessoryType current;
private List<WebAccessory> list;
public TextureChooser(PlayerPlus instance, SpoutPlayer player) {
this.instance = instance;
this.player = player;
current = AccessoryType.BRACELET;
cb = new MyComboBox(this);
cb.setText("Accessories");
cb.setAnchor(WidgetAnchor.CENTER_CENTER);
- cb.setX(-160).setY(-110);
+ cb.shiftXPos(-160).shiftYPos(-90);
cb.setHeight(20).setWidth(100);
cb.setSelection(0);
cb.setItems(getAvailableAccessories(player));
lw = new MyListWidget(this);
lw.setAnchor(WidgetAnchor.CENTER_CENTER);
lw.setHeight(150).setWidth(100);
- lw.setX(-160).setY(-70);
+ lw.shiftXPos(-160).shiftYPos(-60);
updateList();
gt = new GenericTexture();
gt.setAnchor(WidgetAnchor.CENTER_CENTER);
gt.setHeight(200).setWidth(200);
- gt.setX(-10).setY(-110);
+ gt.shiftXPos(-40).shiftYPos(-110);
updateTexture();
GenericButton pre = new ActionButton("<", this, -1);
pre.setAnchor(WidgetAnchor.CENTER_CENTER);
pre.setHeight(20).setWidth(20);
- pre.setX(-10).setY(80);
+ pre.shiftXPos(-40).shiftYPos(70);
GenericButton select = new ActionButton("Select", this, 0);
select.setAnchor(WidgetAnchor.CENTER_CENTER);
select.setHeight(20).setWidth(50);
- select.setX(59).setY(80);
+ select.shiftXPos(19).shiftYPos(70);
GenericButton next = new ActionButton(">", this, 1);
next.setAnchor(WidgetAnchor.CENTER_CENTER);
next.setHeight(20).setWidth(20);
- next.setX(148).setY(80);
+ next.shiftXPos(108).shiftYPos(70);
updateSelection();
attachWidgets(instance, lw, cb, gt, pre, select, next);
player.getMainScreen().attachPopupScreen(this);
}
public void updateTexture() {
int sel = lw.getSelectedRow();
if (sel < 1) {
gt.setUrl("");
} else {
gt.setUrl(list.get(sel - 1).getUrl());
}
gt.setDirty(true);
}
public void updateList() {
lw.clear();
list = instance.getAvailable(current);
lw.addItem(new ListWidgetItem("None", ""));
for (WebAccessory toAdd : list) {
lw.addItem(new ListWidgetItem(toAdd.getName(), "", toAdd.getUrl()));
}
lw.setDirty(true);
}
private List<String> getAvailableAccessories(SpoutPlayer player) {
//TODO Dockter, good place to put permision check in ^^
List<String> available = new ArrayList<String>();
for (AccessoryType type : AccessoryType.values()) {
available.add(type.name().toLowerCase());
}
return available;
}
public void onSelected(int item) {
if (lw != null && item != -1) {
current = AccessoryType.values()[item];
updateList();
updateSelection();
updateTexture();
}
}
public void onListSelected(int item) {
updateTexture();
}
public void onActionClick(int id) {
if (id == 0) {
if (lw.getSelectedRow() > 0) {
player.addAccessory(current, list.get(lw.getSelectedRow() - 1).getUrl());
} else {
System.out.println("Removing!");
player.removeAccessory(current);
}
player.sendNotification("Set Accessory", current.name().toLowerCase(), Material.GOLD_CHESTPLATE);
instance.save(player, current);
return;
}
int cuRow = lw.getSelectedRow();
cuRow += id;
if (cuRow == -1) {
cuRow = lw.getItems().length - 1;
}
if (cuRow == lw.getItems().length) {
cuRow = 0;
}
lw.setSelection(cuRow);
lw.setDirty(true);
updateTexture();
}
private void updateSelection() {
int which = 0;
String url = player.getAccessoryURL(current);
if(url == null) {
lw.setSelection(which);
return;
}
for(int i=0;i<list.size();i++) {
WebAccessory wa = list.get(i);
if(url.equals(wa.getUrl())) {
which = i + 1;
break;
}
}
lw.setSelection(which);
}
}
| false | true | public TextureChooser(PlayerPlus instance, SpoutPlayer player) {
this.instance = instance;
this.player = player;
current = AccessoryType.BRACELET;
cb = new MyComboBox(this);
cb.setText("Accessories");
cb.setAnchor(WidgetAnchor.CENTER_CENTER);
cb.setX(-160).setY(-110);
cb.setHeight(20).setWidth(100);
cb.setSelection(0);
cb.setItems(getAvailableAccessories(player));
lw = new MyListWidget(this);
lw.setAnchor(WidgetAnchor.CENTER_CENTER);
lw.setHeight(150).setWidth(100);
lw.setX(-160).setY(-70);
updateList();
gt = new GenericTexture();
gt.setAnchor(WidgetAnchor.CENTER_CENTER);
gt.setHeight(200).setWidth(200);
gt.setX(-10).setY(-110);
updateTexture();
GenericButton pre = new ActionButton("<", this, -1);
pre.setAnchor(WidgetAnchor.CENTER_CENTER);
pre.setHeight(20).setWidth(20);
pre.setX(-10).setY(80);
GenericButton select = new ActionButton("Select", this, 0);
select.setAnchor(WidgetAnchor.CENTER_CENTER);
select.setHeight(20).setWidth(50);
select.setX(59).setY(80);
GenericButton next = new ActionButton(">", this, 1);
next.setAnchor(WidgetAnchor.CENTER_CENTER);
next.setHeight(20).setWidth(20);
next.setX(148).setY(80);
updateSelection();
attachWidgets(instance, lw, cb, gt, pre, select, next);
player.getMainScreen().attachPopupScreen(this);
}
| public TextureChooser(PlayerPlus instance, SpoutPlayer player) {
this.instance = instance;
this.player = player;
current = AccessoryType.BRACELET;
cb = new MyComboBox(this);
cb.setText("Accessories");
cb.setAnchor(WidgetAnchor.CENTER_CENTER);
cb.shiftXPos(-160).shiftYPos(-90);
cb.setHeight(20).setWidth(100);
cb.setSelection(0);
cb.setItems(getAvailableAccessories(player));
lw = new MyListWidget(this);
lw.setAnchor(WidgetAnchor.CENTER_CENTER);
lw.setHeight(150).setWidth(100);
lw.shiftXPos(-160).shiftYPos(-60);
updateList();
gt = new GenericTexture();
gt.setAnchor(WidgetAnchor.CENTER_CENTER);
gt.setHeight(200).setWidth(200);
gt.shiftXPos(-40).shiftYPos(-110);
updateTexture();
GenericButton pre = new ActionButton("<", this, -1);
pre.setAnchor(WidgetAnchor.CENTER_CENTER);
pre.setHeight(20).setWidth(20);
pre.shiftXPos(-40).shiftYPos(70);
GenericButton select = new ActionButton("Select", this, 0);
select.setAnchor(WidgetAnchor.CENTER_CENTER);
select.setHeight(20).setWidth(50);
select.shiftXPos(19).shiftYPos(70);
GenericButton next = new ActionButton(">", this, 1);
next.setAnchor(WidgetAnchor.CENTER_CENTER);
next.setHeight(20).setWidth(20);
next.shiftXPos(108).shiftYPos(70);
updateSelection();
attachWidgets(instance, lw, cb, gt, pre, select, next);
player.getMainScreen().attachPopupScreen(this);
}
|
diff --git a/src/main/java/de/cismet/cids/custom/butler/PredefinedBoxes.java b/src/main/java/de/cismet/cids/custom/butler/PredefinedBoxes.java
index 5b560ba3..ef0c3db2 100644
--- a/src/main/java/de/cismet/cids/custom/butler/PredefinedBoxes.java
+++ b/src/main/java/de/cismet/cids/custom/butler/PredefinedBoxes.java
@@ -1,163 +1,163 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.cids.custom.butler;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Properties;
/**
* DOCUMENT ME!
*
* @author daniel
* @version $Revision$, $Date$
*/
public class PredefinedBoxes {
//~ Static fields/initializers ---------------------------------------------
protected static final ArrayList<PredefinedBoxes> butler1Boxes = new ArrayList<PredefinedBoxes>();
protected static final ArrayList<PredefinedBoxes> butler2Boxes = new ArrayList<PredefinedBoxes>();
private static final Logger LOG = Logger.getLogger(PredefinedBoxes.class);
static {
Properties prop = new Properties();
try {
prop.load(PredefinedBoxes.class.getResourceAsStream("butler1Boxes.properties"));
loadPropertiesIntoList(butler1Boxes, prop);
prop = new Properties();
prop.load(PredefinedBoxes.class.getResourceAsStream("butler2Boxes.properties"));
loadPropertiesIntoList(butler2Boxes, prop);
} catch (IOException ex) {
LOG.error("Could not read property file with defined boxes for butler 1", ex);
}
}
//~ Instance fields --------------------------------------------------------
private final String displayName;
private double eSize;
private final double nSize;
private String key;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new PredefinedBoxes object.
*
* @param displayName DOCUMENT ME!
* @param eSize DOCUMENT ME!
* @param nSize DOCUMENT ME!
*/
private PredefinedBoxes(final String displayName, final double eSize, final double nSize) {
this.displayName = displayName;
this.eSize = eSize;
this.nSize = nSize;
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getDisplayName() {
return displayName;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public double getEastSize() {
return eSize;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public double getNorthSize() {
return nSize;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getKey() {
return key;
}
/**
* DOCUMENT ME!
*
* @param key DOCUMENT ME!
*/
public void setKey(final String key) {
this.key = key;
}
@Override
public String toString() {
return displayName;
}
/**
* DOCUMENT ME!
*
* @param list DOCUMENT ME!
* @param prop DOCUMENT ME!
*/
private static void loadPropertiesIntoList(final ArrayList list, final Properties prop) {
final Enumeration keys = prop.propertyNames();
final ArrayList<String> keyList = new ArrayList<String>();
while (keys.hasMoreElements()) {
final String key = (String)keys.nextElement();
keyList.add(key);
}
final Comparator<String> keyComp = new Comparator<String>() {
@Override
public int compare(final String o1, final String o2) {
final int number1 = Integer.parseInt(o1.replaceAll("box", ""));
final int number2 = Integer.parseInt(o2.replaceAll("box", ""));
- return Integer.compare(number1, number2);
+ return Integer.valueOf(number1).compareTo(number2);
}
};
Collections.sort(keyList, keyComp);
for (final String key : keyList) {
final String[] splittedVal = ((String)prop.getProperty(key)).split(";");
final double width = Double.parseDouble(splittedVal[1]);
final double height = Double.parseDouble(splittedVal[2]);
final PredefinedBoxes box = new PredefinedBoxes(
splittedVal[0],
width,
height);
if (splittedVal.length == 4) {
box.setKey(splittedVal[3]);
}
list.add(box);
}
}
}
| true | true | private static void loadPropertiesIntoList(final ArrayList list, final Properties prop) {
final Enumeration keys = prop.propertyNames();
final ArrayList<String> keyList = new ArrayList<String>();
while (keys.hasMoreElements()) {
final String key = (String)keys.nextElement();
keyList.add(key);
}
final Comparator<String> keyComp = new Comparator<String>() {
@Override
public int compare(final String o1, final String o2) {
final int number1 = Integer.parseInt(o1.replaceAll("box", ""));
final int number2 = Integer.parseInt(o2.replaceAll("box", ""));
return Integer.compare(number1, number2);
}
};
Collections.sort(keyList, keyComp);
for (final String key : keyList) {
final String[] splittedVal = ((String)prop.getProperty(key)).split(";");
final double width = Double.parseDouble(splittedVal[1]);
final double height = Double.parseDouble(splittedVal[2]);
final PredefinedBoxes box = new PredefinedBoxes(
splittedVal[0],
width,
height);
if (splittedVal.length == 4) {
box.setKey(splittedVal[3]);
}
list.add(box);
}
}
| private static void loadPropertiesIntoList(final ArrayList list, final Properties prop) {
final Enumeration keys = prop.propertyNames();
final ArrayList<String> keyList = new ArrayList<String>();
while (keys.hasMoreElements()) {
final String key = (String)keys.nextElement();
keyList.add(key);
}
final Comparator<String> keyComp = new Comparator<String>() {
@Override
public int compare(final String o1, final String o2) {
final int number1 = Integer.parseInt(o1.replaceAll("box", ""));
final int number2 = Integer.parseInt(o2.replaceAll("box", ""));
return Integer.valueOf(number1).compareTo(number2);
}
};
Collections.sort(keyList, keyComp);
for (final String key : keyList) {
final String[] splittedVal = ((String)prop.getProperty(key)).split(";");
final double width = Double.parseDouble(splittedVal[1]);
final double height = Double.parseDouble(splittedVal[2]);
final PredefinedBoxes box = new PredefinedBoxes(
splittedVal[0],
width,
height);
if (splittedVal.length == 4) {
box.setKey(splittedVal[3]);
}
list.add(box);
}
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/CallTemplateParameterImpl.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/CallTemplateParameterImpl.java
index 73e7b1e0b..bc1889c45 100644
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/CallTemplateParameterImpl.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/CallTemplateParameterImpl.java
@@ -1,447 +1,447 @@
/**
* Copyright 2009-2010 WSO2, Inc. (http://wso2.com)
*
* 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.wso2.developerstudio.eclipse.esb.mediators.impl;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.w3c.dom.Element;
import org.wso2.developerstudio.eclipse.esb.NamespacedProperty;
import org.wso2.developerstudio.eclipse.esb.impl.ModelObjectImpl;
import org.wso2.developerstudio.eclipse.esb.mediators.CallTemplateParameter;
import org.wso2.developerstudio.eclipse.esb.mediators.MediatorsPackage;
import org.wso2.developerstudio.eclipse.esb.mediators.RuleOptionType;
import org.wso2.developerstudio.eclipse.esb.util.ObjectValidator;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Call Template Parameter</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.CallTemplateParameterImpl#getParameterName <em>Parameter Name</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.CallTemplateParameterImpl#getTemplateParameterType <em>Template Parameter Type</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.CallTemplateParameterImpl#getParameterValue <em>Parameter Value</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.CallTemplateParameterImpl#getParameterExpression <em>Parameter Expression</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class CallTemplateParameterImpl extends ModelObjectImpl implements CallTemplateParameter {
/**
* The default value of the '{@link #getParameterName() <em>Parameter Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterName()
* @generated NOT
* @ordered
*/
protected static final String PARAMETER_NAME_EDEFAULT = "Parameter";
/**
* The cached value of the '{@link #getParameterName() <em>Parameter Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterName()
* @generated
* @ordered
*/
protected String parameterName = PARAMETER_NAME_EDEFAULT;
/**
* The default value of the '{@link #getTemplateParameterType() <em>Template Parameter Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTemplateParameterType()
* @generated
* @ordered
*/
protected static final RuleOptionType TEMPLATE_PARAMETER_TYPE_EDEFAULT = RuleOptionType.VALUE;
/**
* The cached value of the '{@link #getTemplateParameterType() <em>Template Parameter Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTemplateParameterType()
* @generated
* @ordered
*/
protected RuleOptionType templateParameterType = TEMPLATE_PARAMETER_TYPE_EDEFAULT;
/**
* The default value of the '{@link #getParameterValue() <em>Parameter Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterValue()
* @generated NOT
* @ordered
*/
protected static final String PARAMETER_VALUE_EDEFAULT = "Value";
/**
* The cached value of the '{@link #getParameterValue() <em>Parameter Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterValue()
* @generated
* @ordered
*/
protected String parameterValue = PARAMETER_VALUE_EDEFAULT;
/**
* The cached value of the '{@link #getParameterExpression() <em>Parameter Expression</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterExpression()
* @generated
* @ordered
*/
protected NamespacedProperty parameterExpression;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
protected CallTemplateParameterImpl() {
super();
/* Initialize parameter expression. */
parameterExpression = getEsbFactory()
.createNamespacedProperty();
parameterExpression.setPrettyName("expression");
parameterExpression.setPropertyName("Expression");
parameterExpression.setPropertyValue("/default/expression");
setParameterExpression(parameterExpression);
}
/**
* {@inheritDoc}
*/
protected void doLoad(Element self) throws Exception {
if (self.hasAttribute("value")) {
String attributeValue = self.getAttribute("value");
if (attributeValue == null) {
attributeValue = "";
}
attributeValue = attributeValue.trim();
if (attributeValue.startsWith("{") && attributeValue.endsWith("}")) {
setTemplateParameterType(RuleOptionType.EXPRESSION);
- attributeValue = attributeValue.replaceAll("^{","").replaceAll("}$", "");
+ attributeValue = attributeValue.replaceAll("^\\{","").replaceAll("\\}$", "");
getParameterExpression().setPropertyValue(attributeValue);
} else {
setTemplateParameterType(RuleOptionType.VALUE);
setParameterValue(attributeValue);
}
}
if (self.hasAttribute("name")) {
String attributeValue = self.getAttribute("name");
if (attributeValue == null) {
attributeValue = "";
}
setParameterName(attributeValue);
} else {
setParameterName("");
}
super.doLoad(self);
}
/**
* {@inheritDoc}
*/
protected Element doSave(Element parent) throws Exception {
Element self = createChildElement(parent, "with-param");
self.setAttribute("name", getParameterName());
switch (getTemplateParameterType()) {
case VALUE:
if (null != getParameterValue()) {
self.setAttribute("value", getParameterValue());
}
break;
case EXPRESSION:
if (null != getParameterExpression().getPropertyValue()) {
self.setAttribute("value", "{"
+ getParameterExpression().getPropertyValue()
+ "}");
}
break;
}
addComments(self);
return self;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return MediatorsPackage.Literals.CALL_TEMPLATE_PARAMETER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getParameterName() {
return parameterName;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParameterName(String newParameterName) {
String oldParameterName = parameterName;
parameterName = newParameterName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME, oldParameterName, parameterName));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RuleOptionType getTemplateParameterType() {
return templateParameterType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTemplateParameterType(RuleOptionType newTemplateParameterType) {
RuleOptionType oldTemplateParameterType = templateParameterType;
templateParameterType = newTemplateParameterType == null ? TEMPLATE_PARAMETER_TYPE_EDEFAULT : newTemplateParameterType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE, oldTemplateParameterType, templateParameterType));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getParameterValue() {
return parameterValue;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParameterValue(String newParameterValue) {
String oldParameterValue = parameterValue;
parameterValue = newParameterValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE, oldParameterValue, parameterValue));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamespacedProperty getParameterExpression() {
if (parameterExpression != null && parameterExpression.eIsProxy()) {
InternalEObject oldParameterExpression = (InternalEObject)parameterExpression;
parameterExpression = (NamespacedProperty)eResolveProxy(oldParameterExpression);
if (parameterExpression != oldParameterExpression) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION, oldParameterExpression, parameterExpression));
}
}
return parameterExpression;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamespacedProperty basicGetParameterExpression() {
return parameterExpression;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParameterExpression(NamespacedProperty newParameterExpression) {
NamespacedProperty oldParameterExpression = parameterExpression;
parameterExpression = newParameterExpression;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION, oldParameterExpression, parameterExpression));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME:
return getParameterName();
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE:
return getTemplateParameterType();
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE:
return getParameterValue();
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION:
if (resolve) return getParameterExpression();
return basicGetParameterExpression();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME:
setParameterName((String)newValue);
return;
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE:
setTemplateParameterType((RuleOptionType)newValue);
return;
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE:
setParameterValue((String)newValue);
return;
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION:
setParameterExpression((NamespacedProperty)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME:
setParameterName(PARAMETER_NAME_EDEFAULT);
return;
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE:
setTemplateParameterType(TEMPLATE_PARAMETER_TYPE_EDEFAULT);
return;
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE:
setParameterValue(PARAMETER_VALUE_EDEFAULT);
return;
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION:
setParameterExpression((NamespacedProperty)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME:
return PARAMETER_NAME_EDEFAULT == null ? parameterName != null : !PARAMETER_NAME_EDEFAULT.equals(parameterName);
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE:
return templateParameterType != TEMPLATE_PARAMETER_TYPE_EDEFAULT;
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE:
return PARAMETER_VALUE_EDEFAULT == null ? parameterValue != null : !PARAMETER_VALUE_EDEFAULT.equals(parameterValue);
case MediatorsPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION:
return parameterExpression != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (parameterName: ");
result.append(parameterName);
result.append(", templateParameterType: ");
result.append(templateParameterType);
result.append(", parameterValue: ");
result.append(parameterValue);
result.append(')');
return result.toString();
}
public Map<String, ObjectValidator> validate() {
ObjectValidator objectValidator = new ObjectValidator();
Map<String, String> validateMap = new HashMap<String, String>();
Map<String, ObjectValidator> mediatorValidateMap = new HashMap<String, ObjectValidator>();
if(null==getParameterName() || getParameterName().trim().isEmpty()){
validateMap.put("Parameter Name", "Parameter Name is empty");
}
switch (getTemplateParameterType()) {
case VALUE:
if (null == getParameterValue() || getParameterValue().trim().isEmpty()) {
validateMap.put("Parameter Value", "Parameter Value is empty");
}
break;
case EXPRESSION:
if (null == getParameterExpression().getPropertyValue() ||
getParameterExpression().getPropertyValue().trim().isEmpty()) {
validateMap.put("Parameter Expression", "Parameter Expression is empty");
}
break;
}
objectValidator.setMediatorErrorMap(validateMap);
mediatorValidateMap.put("CallTemplate Parameter", objectValidator);
return mediatorValidateMap;
}
} //CallTemplateParameterImpl
| true | true | protected void doLoad(Element self) throws Exception {
if (self.hasAttribute("value")) {
String attributeValue = self.getAttribute("value");
if (attributeValue == null) {
attributeValue = "";
}
attributeValue = attributeValue.trim();
if (attributeValue.startsWith("{") && attributeValue.endsWith("}")) {
setTemplateParameterType(RuleOptionType.EXPRESSION);
attributeValue = attributeValue.replaceAll("^{","").replaceAll("}$", "");
getParameterExpression().setPropertyValue(attributeValue);
} else {
setTemplateParameterType(RuleOptionType.VALUE);
setParameterValue(attributeValue);
}
}
if (self.hasAttribute("name")) {
String attributeValue = self.getAttribute("name");
if (attributeValue == null) {
attributeValue = "";
}
setParameterName(attributeValue);
} else {
setParameterName("");
}
super.doLoad(self);
}
| protected void doLoad(Element self) throws Exception {
if (self.hasAttribute("value")) {
String attributeValue = self.getAttribute("value");
if (attributeValue == null) {
attributeValue = "";
}
attributeValue = attributeValue.trim();
if (attributeValue.startsWith("{") && attributeValue.endsWith("}")) {
setTemplateParameterType(RuleOptionType.EXPRESSION);
attributeValue = attributeValue.replaceAll("^\\{","").replaceAll("\\}$", "");
getParameterExpression().setPropertyValue(attributeValue);
} else {
setTemplateParameterType(RuleOptionType.VALUE);
setParameterValue(attributeValue);
}
}
if (self.hasAttribute("name")) {
String attributeValue = self.getAttribute("name");
if (attributeValue == null) {
attributeValue = "";
}
setParameterName(attributeValue);
} else {
setParameterName("");
}
super.doLoad(self);
}
|
diff --git a/src/ca/ariselab/myhhw/Utils.java b/src/ca/ariselab/myhhw/Utils.java
index 7d66846..c5b10d8 100644
--- a/src/ca/ariselab/myhhw/Utils.java
+++ b/src/ca/ariselab/myhhw/Utils.java
@@ -1,87 +1,87 @@
/*
* Project: MyRobots.com integration for ARISE Human Hamster Wheel
* Authors: Jeffrey Arcand <[email protected]>
* File: ca/ariselab/myhhw/Utils.java
* Date: Sat 2013-04-13
* Copyright: Copyright (c) 2013 by Jeffrey Arcand. All rights reserved.
* License: GNU GPL v3
*
* 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 ca.ariselab.myhhw;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;
public final class Utils {
/** Cannot instantiate this class. */
private Utils() {
}
/**
* Determine if the HHW is usually open at this time.
* @return Whether or not the HHW is expected to be open.
*/
public static boolean getHHWOpen() {
Calendar now = Calendar.getInstance();
// Opens at 09:00 and closes 17:00
int hour = now.get(Calendar.HOUR);
if (hour < 9 || hour >= 17) {
return false;
}
// Closed on Mondays from Sept to April (inclusive)
- int dow = now.get(DAY_OF_WEEK);
+ int dow = now.get(Calendar.DAY_OF_WEEK);
int month = now.get(Calendar.MONTH);
if (dow == Calendar.MONDAY
&& (month <= Calendar.APRIL || month >= Calendar.SEPTEMBER)) {
return false;
}
// Otherwise open
return true;
}
/**
* Get the system uptime.
* @return The uptime in minutes.
*/
public static int getSystemUptime() {
int uptime = -1;
try {
FileReader fr = new FileReader("/proc/uptime");
BufferedReader br = new BufferedReader(fr);
String[] parts = br.readLine().split(" ");
br.close();
fr.close();
uptime = (int) Float.parseFloat(parts[0]) / 60;
} catch (IOException e) {
e.printStackTrace();
}
return uptime;
}
}
| true | true | public static boolean getHHWOpen() {
Calendar now = Calendar.getInstance();
// Opens at 09:00 and closes 17:00
int hour = now.get(Calendar.HOUR);
if (hour < 9 || hour >= 17) {
return false;
}
// Closed on Mondays from Sept to April (inclusive)
int dow = now.get(DAY_OF_WEEK);
int month = now.get(Calendar.MONTH);
if (dow == Calendar.MONDAY
&& (month <= Calendar.APRIL || month >= Calendar.SEPTEMBER)) {
return false;
}
// Otherwise open
return true;
}
| public static boolean getHHWOpen() {
Calendar now = Calendar.getInstance();
// Opens at 09:00 and closes 17:00
int hour = now.get(Calendar.HOUR);
if (hour < 9 || hour >= 17) {
return false;
}
// Closed on Mondays from Sept to April (inclusive)
int dow = now.get(Calendar.DAY_OF_WEEK);
int month = now.get(Calendar.MONTH);
if (dow == Calendar.MONDAY
&& (month <= Calendar.APRIL || month >= Calendar.SEPTEMBER)) {
return false;
}
// Otherwise open
return true;
}
|
diff --git a/src/de/highbyte_le/weberknecht/request/error/DefaultErrorHandler.java b/src/de/highbyte_le/weberknecht/request/error/DefaultErrorHandler.java
index 764be4d..f49b500 100644
--- a/src/de/highbyte_le/weberknecht/request/error/DefaultErrorHandler.java
+++ b/src/de/highbyte_le/weberknecht/request/error/DefaultErrorHandler.java
@@ -1,100 +1,100 @@
/*
* DefaultErrorHandler.java (weberknecht)
*
* Copyright 2012-2013 Patrick Mairif.
* The program is distributed under the terms of the Apache License (ALv2).
*
* tabstop=4, charset=UTF-8
*/
package de.highbyte_le.weberknecht.request.error;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import de.highbyte_le.weberknecht.Controller;
import de.highbyte_le.weberknecht.db.DBConnectionException;
import de.highbyte_le.weberknecht.request.ContentProcessingException;
import de.highbyte_le.weberknecht.request.actions.ActionExecutionException;
import de.highbyte_le.weberknecht.request.actions.ActionInstantiationException;
import de.highbyte_le.weberknecht.request.actions.ActionNotFoundException;
import de.highbyte_le.weberknecht.request.processing.ProcessingException;
import de.highbyte_le.weberknecht.request.routing.RoutingTarget;
/**
* error handler used by default
*
* @author pmairif
*/
public class DefaultErrorHandler implements ErrorHandler {
private int statusCode;
/**
* Logger for this class
*/
private final Log log = LogFactory.getLog(Controller.class);
/* (non-Javadoc)
* @see de.highbyte_le.weberknecht.request.ErrorHandler#handleException(java.lang.Exception, javax.servlet.http.HttpServletRequest)
*/
@Override
public boolean handleException(Exception exception, HttpServletRequest request, RoutingTarget routingTarget) {
if (exception instanceof ActionNotFoundException) {
log.warn("action not found: "+exception.getMessage()+"; request URI was "+request.getRequestURI());
this.statusCode = HttpServletResponse.SC_NOT_FOUND; //throw 404, if action doesn't exist
}
else if (exception instanceof ContentProcessingException) {
- log.error("doGet() - ContentProcessingException: "+exception.getMessage()); //$NON-NLS-1$
+ log.error("doGet() - "+exception.getClass().getSimpleName()+": "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = ((ContentProcessingException) exception).getHttpStatusCode();
//TODO error page with error message or set request attribute to be able to write it on standard error pages
}
else if (exception instanceof ActionInstantiationException) {
log.warn("action could not be instantiated: "+exception.getMessage(), exception);
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500, if action could not instantiated
}
else if (exception instanceof ProcessingException) {
log.error("doGet() - PreProcessingException: "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
else if (exception instanceof DBConnectionException) {
log.error("doGet() - DBConnectionException: "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
else if (exception instanceof ActionExecutionException) {
log.error("doGet() - ActionExecutionException: "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
else {
log.error("doGet() - "+exception.getClass().getSimpleName()+": "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
return true;
}
/* (non-Javadoc)
* @see de.highbyte_le.weberknecht.request.ErrorHandler#getStatus()
*/
@Override
public int getStatus() {
return statusCode;
}
/**
* @param statusCode the statusCode to set
*/
protected void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/* (non-Javadoc)
* @see de.highbyte_le.weberknecht.request.view.AutoView#getViewProcessorName()
*/
@Override
public String getViewProcessorName() {
return null; //no view, let the controller use sendError()
}
}
| true | true | public boolean handleException(Exception exception, HttpServletRequest request, RoutingTarget routingTarget) {
if (exception instanceof ActionNotFoundException) {
log.warn("action not found: "+exception.getMessage()+"; request URI was "+request.getRequestURI());
this.statusCode = HttpServletResponse.SC_NOT_FOUND; //throw 404, if action doesn't exist
}
else if (exception instanceof ContentProcessingException) {
log.error("doGet() - ContentProcessingException: "+exception.getMessage()); //$NON-NLS-1$
this.statusCode = ((ContentProcessingException) exception).getHttpStatusCode();
//TODO error page with error message or set request attribute to be able to write it on standard error pages
}
else if (exception instanceof ActionInstantiationException) {
log.warn("action could not be instantiated: "+exception.getMessage(), exception);
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500, if action could not instantiated
}
else if (exception instanceof ProcessingException) {
log.error("doGet() - PreProcessingException: "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
else if (exception instanceof DBConnectionException) {
log.error("doGet() - DBConnectionException: "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
else if (exception instanceof ActionExecutionException) {
log.error("doGet() - ActionExecutionException: "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
else {
log.error("doGet() - "+exception.getClass().getSimpleName()+": "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
return true;
}
| public boolean handleException(Exception exception, HttpServletRequest request, RoutingTarget routingTarget) {
if (exception instanceof ActionNotFoundException) {
log.warn("action not found: "+exception.getMessage()+"; request URI was "+request.getRequestURI());
this.statusCode = HttpServletResponse.SC_NOT_FOUND; //throw 404, if action doesn't exist
}
else if (exception instanceof ContentProcessingException) {
log.error("doGet() - "+exception.getClass().getSimpleName()+": "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = ((ContentProcessingException) exception).getHttpStatusCode();
//TODO error page with error message or set request attribute to be able to write it on standard error pages
}
else if (exception instanceof ActionInstantiationException) {
log.warn("action could not be instantiated: "+exception.getMessage(), exception);
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500, if action could not instantiated
}
else if (exception instanceof ProcessingException) {
log.error("doGet() - PreProcessingException: "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
else if (exception instanceof DBConnectionException) {
log.error("doGet() - DBConnectionException: "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
else if (exception instanceof ActionExecutionException) {
log.error("doGet() - ActionExecutionException: "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
else {
log.error("doGet() - "+exception.getClass().getSimpleName()+": "+exception.getMessage(), exception); //$NON-NLS-1$
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; //throw 500
}
return true;
}
|
diff --git a/modules/updatetrackerwebservice/updatetrackerwebserviceImpl/src/dk/statsbiblioteket/doms/updatetracker/webservice/UpdateTrackerWebserviceImpl.java b/modules/updatetrackerwebservice/updatetrackerwebserviceImpl/src/dk/statsbiblioteket/doms/updatetracker/webservice/UpdateTrackerWebserviceImpl.java
index 1dfa797..415d434 100644
--- a/modules/updatetrackerwebservice/updatetrackerwebserviceImpl/src/dk/statsbiblioteket/doms/updatetracker/webservice/UpdateTrackerWebserviceImpl.java
+++ b/modules/updatetrackerwebservice/updatetrackerwebserviceImpl/src/dk/statsbiblioteket/doms/updatetracker/webservice/UpdateTrackerWebserviceImpl.java
@@ -1,178 +1,178 @@
package dk.statsbiblioteket.doms.updatetracker.webservice;
import dk.statsbiblioteket.doms.webservices.Credentials;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.WebServiceContext;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.String;
import java.util.List;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.net.MalformedURLException;
/**
* Update tracker webservice. Provides upper layers of DOMS with info on changes
* to objects in Fedora. Used by DOMS Server aka. Central to provide Summa with
* said info.
*/
@WebService(endpointInterface
= "dk.statsbiblioteket.doms.updatetracker.webservice"
+ ".UpdateTrackerWebservice")
public class UpdateTrackerWebserviceImpl implements UpdateTrackerWebservice{
@Resource
WebServiceContext context;
private XMLGregorianCalendar lastChangedTime;
public UpdateTrackerWebserviceImpl() throws MethodFailedException {
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone(
"Europe/Copenhagen"));
calendar.set(GregorianCalendar.YEAR, 1999);
calendar.set(GregorianCalendar.MONTH, 12);
calendar.set(GregorianCalendar.DAY_OF_MONTH, 31);
calendar.set(GregorianCalendar.HOUR_OF_DAY, 23);
calendar.set(GregorianCalendar.MINUTE, 59);
calendar.set(GregorianCalendar.SECOND, 59);
calendar.set(GregorianCalendar.MILLISECOND, 999);
try {
lastChangedTime
= DatatypeFactory.newInstance().newXMLGregorianCalendar(
calendar);
} catch (DatatypeConfigurationException e) {
throw new MethodFailedException(
"Could not make new XMLGregorianCalendar", "");
}
}
/**
* Lists the entry objects of views (records) in Fedora, in the given
* collection, that have changed since the given time.
*
* @param collectionPid The PID of the collection in which we are looking
* for changes.
* @param entryCMPid The PID of the content model which all listed records
* should adhere to.
* @param viewAngle ...TODO doc
* @param beginTime The time since which we are looking for changes.
* @return returns java.util.List<dk.statsbiblioteket.doms.updatetracker
* .webservice.PidDatePidPid>
*
* @throws MethodFailedException
* @throws InvalidCredentialsException
*
*/
public List<PidDatePidPid> listObjectsChangedSince(
@WebParam(name = "collectionPid", targetNamespace = "")
String collectionPid,
@WebParam(name = "entryCMPid", targetNamespace = "")
String entryCMPid,
@WebParam(name = "viewAngle", targetNamespace = "")
String viewAngle,
@WebParam(name = "beginTime", targetNamespace = "")
XMLGregorianCalendar beginTime)
throws InvalidCredentialsException, MethodFailedException {
// TODO Un-mockup this class please :-)
List<PidDatePidPid> result = new ArrayList<PidDatePidPid>();
// Mockup: If wanted beginTime is AFTER our hardcoded lastChangedTime,
// we just return no objects/views/records at all.
if (beginTime.toGregorianCalendar().after(
lastChangedTime.toGregorianCalendar())) {
return result;
}
// Mockup: If wanted beginTime is BEFORE (or =) our hardcoded
// lastChangedTime, connect to ECM and get a list of all entry objects
// in (hardcoded:) our RadioTVCollection. Return all these.
String pidOfCollection = "doms:RadioTV_Collection";
List<String> allEntryObjectsInRadioTVCollection;
ECM ecmConnector;
try {
ecmConnector = new ECM(getCredentials(), "http://alhena:7980/ecm");
} catch (MalformedURLException e) {
throw new MethodFailedException("Malformed URL", "", e);
}
// TODO Mockup by calling the getAllEntryObjectsInCollection method in
// ECM with collectionPID to get <PID, collectionPID, entryPID>.
try {
allEntryObjectsInRadioTVCollection
= ecmConnector.getAllEntryObjectsInCollection(
- pidOfCollection, "", "");
+ pidOfCollection, viewAngle, entryCMPid);
} catch (BackendInvalidCredsException e) {
throw new InvalidCredentialsException("Invalid credentials", "", e);
} catch (BackendMethodFailedException e) {
throw new MethodFailedException("Method failed", "", e);
}
for (String pid : allEntryObjectsInRadioTVCollection) {
PidDatePidPid objectThatChanged = new PidDatePidPid();
objectThatChanged.setPid(pid);
objectThatChanged.setLastChangedTime(lastChangedTime);
objectThatChanged.setCollectionPid(collectionPid);
objectThatChanged.setEntryCMPid(entryCMPid);
result.add(objectThatChanged);
}
return result;
}
/**
* Return the last time a view/record conforming to the content model of the
* given content model entry, and in the given collection, has been changed.
*
* @param collectionPid The PID of the collection in which we are looking
* for the last change.
* @param entryCMPid The PID of the entry object of the content model which
* our changed record should adhere to.
* @param viewAngle ...TODO doc
* @return The date/time of the last change.
* @throws InvalidCredentialsException
* @throws MethodFailedException
*/
public XMLGregorianCalendar getLatestModificationTime(
@WebParam(name = "collectionPid", targetNamespace = "")
String collectionPid,
@WebParam(name = "entryCMPid", targetNamespace = "")
String entryCMPid,
@WebParam(name = "viewAngle", targetNamespace = "")
String viewAngle)
throws InvalidCredentialsException, MethodFailedException {
return lastChangedTime;
}
/**
* TODO doc
*
* @return TODO doc
*/
private Credentials getCredentials() {
HttpServletRequest request = (HttpServletRequest) context
.getMessageContext()
.get(MessageContext.SERVLET_REQUEST);
Credentials creds = (Credentials) request.getAttribute("Credentials");
if (creds == null) {
// log.warn("Attempted call at Central without credentials");
creds = new Credentials("", "");
}
return creds;
}
}
| true | true | public List<PidDatePidPid> listObjectsChangedSince(
@WebParam(name = "collectionPid", targetNamespace = "")
String collectionPid,
@WebParam(name = "entryCMPid", targetNamespace = "")
String entryCMPid,
@WebParam(name = "viewAngle", targetNamespace = "")
String viewAngle,
@WebParam(name = "beginTime", targetNamespace = "")
XMLGregorianCalendar beginTime)
throws InvalidCredentialsException, MethodFailedException {
// TODO Un-mockup this class please :-)
List<PidDatePidPid> result = new ArrayList<PidDatePidPid>();
// Mockup: If wanted beginTime is AFTER our hardcoded lastChangedTime,
// we just return no objects/views/records at all.
if (beginTime.toGregorianCalendar().after(
lastChangedTime.toGregorianCalendar())) {
return result;
}
// Mockup: If wanted beginTime is BEFORE (or =) our hardcoded
// lastChangedTime, connect to ECM and get a list of all entry objects
// in (hardcoded:) our RadioTVCollection. Return all these.
String pidOfCollection = "doms:RadioTV_Collection";
List<String> allEntryObjectsInRadioTVCollection;
ECM ecmConnector;
try {
ecmConnector = new ECM(getCredentials(), "http://alhena:7980/ecm");
} catch (MalformedURLException e) {
throw new MethodFailedException("Malformed URL", "", e);
}
// TODO Mockup by calling the getAllEntryObjectsInCollection method in
// ECM with collectionPID to get <PID, collectionPID, entryPID>.
try {
allEntryObjectsInRadioTVCollection
= ecmConnector.getAllEntryObjectsInCollection(
pidOfCollection, "", "");
} catch (BackendInvalidCredsException e) {
throw new InvalidCredentialsException("Invalid credentials", "", e);
} catch (BackendMethodFailedException e) {
throw new MethodFailedException("Method failed", "", e);
}
for (String pid : allEntryObjectsInRadioTVCollection) {
PidDatePidPid objectThatChanged = new PidDatePidPid();
objectThatChanged.setPid(pid);
objectThatChanged.setLastChangedTime(lastChangedTime);
objectThatChanged.setCollectionPid(collectionPid);
objectThatChanged.setEntryCMPid(entryCMPid);
result.add(objectThatChanged);
}
return result;
}
| public List<PidDatePidPid> listObjectsChangedSince(
@WebParam(name = "collectionPid", targetNamespace = "")
String collectionPid,
@WebParam(name = "entryCMPid", targetNamespace = "")
String entryCMPid,
@WebParam(name = "viewAngle", targetNamespace = "")
String viewAngle,
@WebParam(name = "beginTime", targetNamespace = "")
XMLGregorianCalendar beginTime)
throws InvalidCredentialsException, MethodFailedException {
// TODO Un-mockup this class please :-)
List<PidDatePidPid> result = new ArrayList<PidDatePidPid>();
// Mockup: If wanted beginTime is AFTER our hardcoded lastChangedTime,
// we just return no objects/views/records at all.
if (beginTime.toGregorianCalendar().after(
lastChangedTime.toGregorianCalendar())) {
return result;
}
// Mockup: If wanted beginTime is BEFORE (or =) our hardcoded
// lastChangedTime, connect to ECM and get a list of all entry objects
// in (hardcoded:) our RadioTVCollection. Return all these.
String pidOfCollection = "doms:RadioTV_Collection";
List<String> allEntryObjectsInRadioTVCollection;
ECM ecmConnector;
try {
ecmConnector = new ECM(getCredentials(), "http://alhena:7980/ecm");
} catch (MalformedURLException e) {
throw new MethodFailedException("Malformed URL", "", e);
}
// TODO Mockup by calling the getAllEntryObjectsInCollection method in
// ECM with collectionPID to get <PID, collectionPID, entryPID>.
try {
allEntryObjectsInRadioTVCollection
= ecmConnector.getAllEntryObjectsInCollection(
pidOfCollection, viewAngle, entryCMPid);
} catch (BackendInvalidCredsException e) {
throw new InvalidCredentialsException("Invalid credentials", "", e);
} catch (BackendMethodFailedException e) {
throw new MethodFailedException("Method failed", "", e);
}
for (String pid : allEntryObjectsInRadioTVCollection) {
PidDatePidPid objectThatChanged = new PidDatePidPid();
objectThatChanged.setPid(pid);
objectThatChanged.setLastChangedTime(lastChangedTime);
objectThatChanged.setCollectionPid(collectionPid);
objectThatChanged.setEntryCMPid(entryCMPid);
result.add(objectThatChanged);
}
return result;
}
|
diff --git a/eclihand/webapp/src/main/java/com/pedrero/eclihand/ui/panel/TeamsScreen.java b/eclihand/webapp/src/main/java/com/pedrero/eclihand/ui/panel/TeamsScreen.java
index fa20bae..62c097e 100644
--- a/eclihand/webapp/src/main/java/com/pedrero/eclihand/ui/panel/TeamsScreen.java
+++ b/eclihand/webapp/src/main/java/com/pedrero/eclihand/ui/panel/TeamsScreen.java
@@ -1,112 +1,112 @@
package com.pedrero.eclihand.ui.panel;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import com.pedrero.eclihand.controller.panel.TeamsPanelController;
import com.pedrero.eclihand.model.dto.TeamDto;
import com.pedrero.eclihand.navigation.EclihandPlace;
import com.pedrero.eclihand.navigation.EclihandViewImpl;
import com.pedrero.eclihand.navigation.places.TeamsPlace;
import com.pedrero.eclihand.ui.table.GenericTable;
import com.pedrero.eclihand.utils.text.MessageResolver;
import com.pedrero.eclihand.utils.ui.EclihandLayoutFactory;
import com.pedrero.eclihand.utils.ui.EclihandUiFactory;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
@Component
@Scope(value = BeanDefinition.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TeamsScreen extends EclihandViewImpl {
private static final Logger LOGGER = LoggerFactory
.getLogger(TeamsScreen.class);
@Resource
private MessageResolver messageResolver;
@Resource
private TeamsPanelController teamsPanelController;
@Resource(name = "teamTableForTeamsPanel")
private GenericTable<TeamDto> teamTable;
@Resource
private EclihandLayoutFactory eclihandLayoutFactory;
@Resource
private EclihandUiFactory eclihandUiFactory;
@Resource
private TeamsPlace teamsPlace;
private Button createNewTeamButton;
@Value(value = "${main.panel.width}")
private String panelWidth;
/**
*
*/
private static final long serialVersionUID = 5954828103989095039L;
@PostConstruct
protected void postConstruct() {
LOGGER.info("initializing TeamsPanel");
this.setCaption(messageResolver.getMessage("teams.panel.title"));
Layout layout = eclihandLayoutFactory.createCommonVerticalLayout();
layout.setWidth(panelWidth);
this.setContent(layout);
// this.createNewTeamButton = eclihandUiFactory.createButton();
// this.createNewTeamButton.setCaption(messageResolver
// .getMessage("players.create.new"));
//
// this.createNewTeamButton.addClickListener(new ClickListener() {
//
// /**
// *
// */
// private static final long serialVersionUID = -7117656998497854385L;
//
// @Override
// public void buttonClick(ClickEvent event) {
// teamsPanelController.openNewTeamForm();
//
// }
// });
//
- // // FIXME : Ajout de la table des �quipes
+ // // FIXME : Ajout de la table des équipes
// // layout.addComponent(teamTable);
// layout.addComponent(createNewTeamButton);
//
// teamTable.feed(teamsPanelController.searchTeamsToDisplay());
layout.addComponent(new Label("Toto"));
this.setCaption(messageResolver.getMessage("home.caption"));
}
public GenericTable<TeamDto> getTeamsTable() {
return teamTable;
}
public void refreshTeams(List<TeamDto> teams) {
teamTable.removeAllDataObjects();
}
@Override
public EclihandPlace retrieveAssociatedPlace() {
return teamsPlace;
}
}
| true | true | protected void postConstruct() {
LOGGER.info("initializing TeamsPanel");
this.setCaption(messageResolver.getMessage("teams.panel.title"));
Layout layout = eclihandLayoutFactory.createCommonVerticalLayout();
layout.setWidth(panelWidth);
this.setContent(layout);
// this.createNewTeamButton = eclihandUiFactory.createButton();
// this.createNewTeamButton.setCaption(messageResolver
// .getMessage("players.create.new"));
//
// this.createNewTeamButton.addClickListener(new ClickListener() {
//
// /**
// *
// */
// private static final long serialVersionUID = -7117656998497854385L;
//
// @Override
// public void buttonClick(ClickEvent event) {
// teamsPanelController.openNewTeamForm();
//
// }
// });
//
// // FIXME : Ajout de la table des �quipes
// // layout.addComponent(teamTable);
// layout.addComponent(createNewTeamButton);
//
// teamTable.feed(teamsPanelController.searchTeamsToDisplay());
layout.addComponent(new Label("Toto"));
this.setCaption(messageResolver.getMessage("home.caption"));
}
| protected void postConstruct() {
LOGGER.info("initializing TeamsPanel");
this.setCaption(messageResolver.getMessage("teams.panel.title"));
Layout layout = eclihandLayoutFactory.createCommonVerticalLayout();
layout.setWidth(panelWidth);
this.setContent(layout);
// this.createNewTeamButton = eclihandUiFactory.createButton();
// this.createNewTeamButton.setCaption(messageResolver
// .getMessage("players.create.new"));
//
// this.createNewTeamButton.addClickListener(new ClickListener() {
//
// /**
// *
// */
// private static final long serialVersionUID = -7117656998497854385L;
//
// @Override
// public void buttonClick(ClickEvent event) {
// teamsPanelController.openNewTeamForm();
//
// }
// });
//
// // FIXME : Ajout de la table des équipes
// // layout.addComponent(teamTable);
// layout.addComponent(createNewTeamButton);
//
// teamTable.feed(teamsPanelController.searchTeamsToDisplay());
layout.addComponent(new Label("Toto"));
this.setCaption(messageResolver.getMessage("home.caption"));
}
|
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/perf/ui/PerfDoubleClickAction.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/perf/ui/PerfDoubleClickAction.java
index 26178b1c1..a338869b1 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/perf/ui/PerfDoubleClickAction.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/perf/ui/PerfDoubleClickAction.java
@@ -1,90 +1,91 @@
/*******************************************************************************
* (C) Copyright 2010 IBM Corp. 2010
* 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:
* Thavidu Ranatunga (IBM) - Initial implementation.
*******************************************************************************/
package org.eclipse.linuxtools.perf.ui;
import java.util.HashMap;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.linuxtools.perf.PerfPlugin;
import org.eclipse.linuxtools.perf.model.PMDso;
import org.eclipse.linuxtools.perf.model.PMFile;
import org.eclipse.linuxtools.perf.model.PMLineRef;
import org.eclipse.linuxtools.perf.model.PMSymbol;
import org.eclipse.linuxtools.profiling.ui.ProfileUIUtils;
import org.eclipse.ui.PartInitException;
public class PerfDoubleClickAction extends Action {
private TreeViewer viewer;
public PerfDoubleClickAction(TreeViewer v) {
super();
viewer = v;
}
public void run() {
ISelection selection = viewer.getSelection();
Object obj = ((IStructuredSelection)selection).getFirstElement();
if (obj instanceof PMLineRef) {
//Open in editor
- PMFile file = (PMFile) ((PMLineRef) obj).getParent();
+ PMLineRef line = (PMLineRef) obj;
+ PMFile file = (PMFile) ((PMSymbol) line.getParent()).getParent();
try {
- ProfileUIUtils.openEditorAndSelect(file.getPath(), Integer.parseInt(file.getName()));
+ ProfileUIUtils.openEditorAndSelect(file.getPath(), Integer.parseInt(line.getName()));
} catch (PartInitException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
} else if (obj instanceof PMFile) {
PMFile file = (PMFile)obj;
try {
ProfileUIUtils.openEditorAndSelect(file.getName(), 1);
} catch (PartInitException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
} else if (obj instanceof PMSymbol) {
PMSymbol sym = (PMSymbol)obj;
PMFile file = (PMFile) sym.getParent();
PMDso dso = (PMDso) file.getParent();
if (file.getName().equals(PerfPlugin.STRINGS_UnfiledSymbols))
return; //Don't try to do anything if we don't know where or what the symbol is.
String binaryPath = dso.getPath();
ICProject project;
try {
project = ProfileUIUtils.findCProjectWithAbsolutePath(binaryPath);
HashMap<String, int[]> map = ProfileUIUtils.findFunctionsInProject(project, sym.getFunctionName(), -1, file.getPath(), true);
boolean bFound = false;
for (String loc : map.keySet()) {
ProfileUIUtils.openEditorAndSelect(loc, map.get(loc)[0], map.get(loc)[1]);
bFound = true;
}
if (!bFound) {
ProfileUIUtils.openEditorAndSelect(file.getPath(), 1);
}
} catch (CoreException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
| false | true | public void run() {
ISelection selection = viewer.getSelection();
Object obj = ((IStructuredSelection)selection).getFirstElement();
if (obj instanceof PMLineRef) {
//Open in editor
PMFile file = (PMFile) ((PMLineRef) obj).getParent();
try {
ProfileUIUtils.openEditorAndSelect(file.getPath(), Integer.parseInt(file.getName()));
} catch (PartInitException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
} else if (obj instanceof PMFile) {
PMFile file = (PMFile)obj;
try {
ProfileUIUtils.openEditorAndSelect(file.getName(), 1);
} catch (PartInitException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
} else if (obj instanceof PMSymbol) {
PMSymbol sym = (PMSymbol)obj;
PMFile file = (PMFile) sym.getParent();
PMDso dso = (PMDso) file.getParent();
if (file.getName().equals(PerfPlugin.STRINGS_UnfiledSymbols))
return; //Don't try to do anything if we don't know where or what the symbol is.
String binaryPath = dso.getPath();
ICProject project;
try {
project = ProfileUIUtils.findCProjectWithAbsolutePath(binaryPath);
HashMap<String, int[]> map = ProfileUIUtils.findFunctionsInProject(project, sym.getFunctionName(), -1, file.getPath(), true);
boolean bFound = false;
for (String loc : map.keySet()) {
ProfileUIUtils.openEditorAndSelect(loc, map.get(loc)[0], map.get(loc)[1]);
bFound = true;
}
if (!bFound) {
ProfileUIUtils.openEditorAndSelect(file.getPath(), 1);
}
} catch (CoreException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
| public void run() {
ISelection selection = viewer.getSelection();
Object obj = ((IStructuredSelection)selection).getFirstElement();
if (obj instanceof PMLineRef) {
//Open in editor
PMLineRef line = (PMLineRef) obj;
PMFile file = (PMFile) ((PMSymbol) line.getParent()).getParent();
try {
ProfileUIUtils.openEditorAndSelect(file.getPath(), Integer.parseInt(line.getName()));
} catch (PartInitException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
} else if (obj instanceof PMFile) {
PMFile file = (PMFile)obj;
try {
ProfileUIUtils.openEditorAndSelect(file.getName(), 1);
} catch (PartInitException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
} else if (obj instanceof PMSymbol) {
PMSymbol sym = (PMSymbol)obj;
PMFile file = (PMFile) sym.getParent();
PMDso dso = (PMDso) file.getParent();
if (file.getName().equals(PerfPlugin.STRINGS_UnfiledSymbols))
return; //Don't try to do anything if we don't know where or what the symbol is.
String binaryPath = dso.getPath();
ICProject project;
try {
project = ProfileUIUtils.findCProjectWithAbsolutePath(binaryPath);
HashMap<String, int[]> map = ProfileUIUtils.findFunctionsInProject(project, sym.getFunctionName(), -1, file.getPath(), true);
boolean bFound = false;
for (String loc : map.keySet()) {
ProfileUIUtils.openEditorAndSelect(loc, map.get(loc)[0], map.get(loc)[1]);
bFound = true;
}
if (!bFound) {
ProfileUIUtils.openEditorAndSelect(file.getPath(), 1);
}
} catch (CoreException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
|
diff --git a/src/ru/narod/vn91/pointsop/server/ServerZagram2.java b/src/ru/narod/vn91/pointsop/server/ServerZagram2.java
index 1504e57..6c1c8e7 100644
--- a/src/ru/narod/vn91/pointsop/server/ServerZagram2.java
+++ b/src/ru/narod/vn91/pointsop/server/ServerZagram2.java
@@ -1,1180 +1,1181 @@
package ru.narod.vn91.pointsop.server;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.ImageIcon;
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import ru.narod.vn91.pointsop.data.GameOuterInfo.GameState;
import ru.narod.vn91.pointsop.data.TimeLeft;
import ru.narod.vn91.pointsop.data.TimeSettings;
import ru.narod.vn91.pointsop.model.GuiForServerInterface;
import ru.narod.vn91.pointsop.server.zagram.MessageQueue;
import ru.narod.vn91.pointsop.utils.Function;
import ru.narod.vn91.pointsop.utils.Settings;
import ru.narod.vn91.pointsop.utils.Wait;
@SuppressWarnings("serial")
public class ServerZagram2 implements ServerInterface {
final String myNameOnServer;
final boolean isPassworded;
final boolean isInvisible;
final GuiForServerInterface gui;
final String secretId;
volatile boolean isDisposed = false;
final MessageQueue queue = new MessageQueue(10);
final List<String> transiendQueue = new ArrayList<String>();
volatile boolean isBusy = false;
Set<String> personalInvitesIncoming = new LinkedHashSet<String>();
Set<String> personalInvitesOutgoing = new LinkedHashSet<String>();
String currentInvitationPlayer = "";
Set<String> subscribedRooms = new LinkedHashSet<String>();
Map<String,Set<String>> playerRooms = new HashMap<String, Set<String>>();
ThreadMain threadMain;
final Map<String,String> avatarUrls = new HashMap<String, String>();
final Map<String,ImageIcon> avatarImages = new HashMap<String, ImageIcon>();
public ServerZagram2(GuiForServerInterface gui, String myNameOnServer, String password, boolean isInvisible) {
if (myNameOnServer.matches(".*[a-zA-Z].*")) {
myNameOnServer = myNameOnServer.replaceAll("[^a-zA-Z0-9 ]", "");
} else if (myNameOnServer.matches(".*[ёа-яЁА-Я].*")) {
myNameOnServer = myNameOnServer.replaceAll("[^ёа-яЁА-Я0-9 ]", "");
} else if (myNameOnServer.matches(".*[a-żA-Ż].*")) {
myNameOnServer = myNameOnServer.replaceAll("[^a-żA-Ż0-9 ]", "");
} else {
myNameOnServer = myNameOnServer.replaceAll("[^0-9 ]", "");
}
isPassworded = !myNameOnServer.equals("") && !password.equals("");
this.isInvisible = isInvisible;
if (isPassworded) {
this.myNameOnServer = myNameOnServer;
this.gui = gui;
this.secretId =
getBase64ZagramVersion(
getSha1(myNameOnServer + "9WB2qGYzzWry1vbVjoSK" + password)).
substring(0, 10);
} else {
if (myNameOnServer.equals("")) {
myNameOnServer = String.format("Guest%04d", (int) (Math.random() * 9999));
}
myNameOnServer = "*" + myNameOnServer;
this.myNameOnServer = myNameOnServer;
this.gui = gui;
Integer secretIdAsInt = (int) (Math.random() * 999999);
secretId = secretIdAsInt.toString();
}
}
class ZagramGameTyme{
final int fieldX, FieldY;
final boolean isStopEnabled, isEmptyScored;
final int timeStarting, timeAdditional;
final String startingPosition;
final boolean isRated;
final int instantWin;
public ZagramGameTyme(int fieldX, int fieldY, boolean isStopEnabled, boolean isEmptyScored, int timeStarting, int timeAdditional,
String startingPosition, boolean isRated, int instantWin) {
this.fieldX = fieldX;
this.FieldY = fieldY;
this.isStopEnabled = isStopEnabled;
this.isEmptyScored = isEmptyScored;
this.timeStarting = timeStarting;
this.timeAdditional = timeAdditional;
this.startingPosition = startingPosition;
this.isRated = isRated;
this.instantWin = instantWin;
}
}
private static String getGameTypeString(
int fieldX, int fieldY, int startingTime, int periodAdditionalTime, boolean isRanked) {
return String.format("%s%sstan%s0.%s.%s",
fieldX, fieldY, isRanked ? "R" : "F", startingTime, periodAdditionalTime);
// return "" + fieldX + fieldY + "stanF0." + startingTime + "." + periodAdditionalTime;
}
ZagramGameTyme getZagramGameTyme(String str) {
// 2525noT4R0.180.15
String[] dotSplitted = str.split("\\.");
try {
int startingTime = Integer.parseInt(dotSplitted[1]);
int addTime = Integer.parseInt(dotSplitted[2]);
String hellishString = dotSplitted[0];
int sizeX = Integer.parseInt(hellishString.substring(0, 2));
int sizeY = Integer.parseInt(hellishString.substring(2, 4));
String rulesAsString = hellishString.substring(4, 8);
boolean isStopEnabled = rulesAsString.matches("noT4|noT1|terr");
boolean isEmptyScored = rulesAsString.matches("terr");
// boolean manualEnclosings = rulesAsString.matches("terr");
// boolean stopEnabled = rulesAsString.matches("noT4|noT1");
String startingPosition = rulesAsString.replaceAll("no|terr|stan", "");
boolean isRated = !(hellishString.substring(8, 9).equals("F"));
Integer instantWin = Integer.parseInt(hellishString.substring(9));
return new ZagramGameTyme(
sizeX, sizeY, isStopEnabled, isEmptyScored,
startingTime, addTime,
startingPosition,
isRated, instantWin);
} catch (NumberFormatException e) {
return null;
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
private static String getBase64ZagramVersion(String input) {
if (input.length() % 3 == 2) {
input = input + "0";
} else if (input.length() % 3 == 1) {
input = input + "00";
} else {
}
final char[] base64ZagramStyle = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.".toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i + 2 < input.length(); i = i + 3) {
// 111122223333
// aaaaaabbbbbb
int hex0 = Integer.parseInt(input.substring(i,i+1), 16);
int hex1 = Integer.parseInt(input.substring(i+1,i+2), 16);
int hex2 = Integer.parseInt(input.substring(i+2,i+3), 16);
int base64_1 = hex0 * 4 + hex1 / 4;
int base64_2 = (hex1 & 3) * 16 + hex2;
stringBuilder.append(base64ZagramStyle[base64_1]);
stringBuilder.append(base64ZagramStyle[base64_2]);
}
return stringBuilder.toString();
}
private static String getSha1(String input) {
try {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
byte[] digest = sha1.digest(input.getBytes());
return HexBin.encode(digest);
} catch (NoSuchAlgorithmException ex) {
return input;
}
}
@Override
public void connect() {
Thread threadStartup = new Thread() {
@Override
public void run() {
if (isInvisible) {
// do not authorize
threadMain = new ThreadMain();
threadMain.start();
} else {
gui.rawConnectionState(ServerZagram2.this, "Подключение...");
String authorizationURL;
if (isPassworded) {
authorizationURL = "http://zagram.org/auth.py?co=loguj&opisGracza=" +
getServerEncoded(myNameOnServer) +
"&idGracza=" +
secretId +
"&lang=ru";
} else {
authorizationURL = "http://zagram.org/a.kropki?co=guestLogin&idGracza=" +
secretId + "&opis=" +
getServerEncoded(myNameOnServer) + "&lang=ru";
}
String authorizationResult = getLinkContent(authorizationURL);
boolean isAuthorized;
if (authorizationResult.equals("")) {
gui.rawConnectionState(ServerZagram2.this, "Соединился. Подключаюсь к основной комнате...");
isAuthorized = true;
} else if (authorizationResult.startsWith("ok.zalogowanyNaSerwer.")) {
// avatarUrls.put(myNameOnServer, authorizationResult.split("\\.")[2]);
gui.rawConnectionState(ServerZagram2.this,
"Авторизовался (" + myNameOnServer + "). Подключаюсь к основной комнате...");
isAuthorized = true;
} else {
gui.rawConnectionState(ServerZagram2.this, "Ошибка авторизации! Возможно, вы ввели неправильный пароль.");
isAuthorized = false;
}
if (isAuthorized) {
getLinkContent("http://zagram.org/a.kropki?idGracza=" + secretId + "&co=changeLang&na=ru");
final Thread disconnectThread = new Thread() {
@Override
public void run() {
disconnectServer();
}
};
Thread killUltimatively = new Thread() {
@Override
public void run() {
// give the "disconnectThread" a little time, and after that kill it
Wait.waitExactly(1000L);
disconnectThread.interrupt();
};
};
killUltimatively.setDaemon(true);
Runtime.getRuntime().addShutdownHook(killUltimatively);
Runtime.getRuntime().addShutdownHook(disconnectThread);
threadMain = new ThreadMain();
threadMain.start();
}
}
};
};
threadStartup.setDaemon(true);
threadStartup.setPriority(Thread.MIN_PRIORITY);
threadStartup.setName("zagramThread");
threadStartup.start();
}
@Override
public void disconnectServer() {
this.isDisposed = true;
final Thread urlInformer = new Thread() {
@Override
public void run() {
getLinkContent("http://zagram.org/a.kropki?playerId=" +
secretId + "&co=usunGracza");
}
};
urlInformer.start();
Thread killer = new Thread() {
@Override
public void run() {
Wait.waitExactly(1000L);
urlInformer.interrupt();
}
};
killer.start();
}
@Override
public String getMainRoom() {
return "0";
}
@Override
public String getMyName() {
return myNameOnServer;
}
@Override
public String getServerName() {
return "zagram.org";
}
@Override
public int getMaximumMessageLength() {
return 100;
}
@Override
public void makeMove(String roomName, int x, int y) {
String message = "s" + queue.sizePlusOne() +
"." + roomName + "." + coordinatesToString(x, y);
sendCommandToServer(message);
}
@Override
public void askGameVacancyPlay(String gameRoomName) {
throw new UnsupportedOperationException();
}
@Override
public void acceptGameVacancyOpponent(String roomName, String newOpponent) {
gui.raw(this, "MultiPoints пока-что не умеет оставлять заявки на игру на этом сервере..");
}
@Override
public void rejectGameVacancyOpponent(String roomName, String notWantedOpponent) {
gui.raw(this, "MultiPoints пока-что не умеет оставлять заявки на игру на этом сервере..");
}
@Override
public void acceptPersonalGameInvite(String playerId) {
// if (personalInvites.contains(playerId)) {
String message = "v" + queue.sizePlusOne() +
"." + getMainRoom() + "." + "a";
sendCommandToServer(message);
// }
}
@Override
public void cancelPersonalGameInvite(String playerId) {
String message = "v" + queue.sizePlusOne() +
"." + getMainRoom() + "." + "c";
sendCommandToServer(message);
gui.youCancelledPersonalInvite(this, playerId, playerId + "@outgoing");
}
@Override
public void rejectPersonalGameInvite(String playerId) {
if (personalInvitesIncoming.contains(playerId)) {
String message = "v" + queue.sizePlusOne() +
"." + getMainRoom() + "." + "r";
sendCommandToServer(message);
}
}
@Override
public void addPersonalGameInvite(String playerId, TimeSettings time, int fieldX, int fieldY, boolean isRanked) {
String msgToSend =
"v" + queue.sizePlusOne() + "." + "0"/* room# */+ "." +
"s." + getServerEncoded(playerId) + "." +
getGameTypeString(fieldX, fieldY, time.starting, time.periodAdditional, isRanked);
sendCommandToServer(msgToSend);
gui.updateGameInfo(this, playerId + "@outgoing", getMainRoom(), getMyName(), null,
fieldX, fieldY, false, false, 0, 0, false,
false, false, null, 0, time.periodAdditional, time.starting, 1, playerId);
// gui.yourPersonalInviteSent(this, playerId, playerId + "@outgoing");
}
@Override
public void createGameVacancy() {
gui.rawError(this, "невозможно оставлять заявки на игру на этом сервере");
}
@Override
public void sendChat(String room, String message) {
String msgToSend = "c" + queue.sizePlusOne() + "." + room + "."
+ getServerEncoded(message);
sendCommandToServer(msgToSend);
}
@Override
public void sendPrivateMsg(String target, String message) {
gui.rawError(this, "невозможно писать приватные сообщения на этом сервере");
}
@Override
public void stopGameVacancy() {
gui.rawError(this, "невозможно оставлять заявки на игру на этом сервере");
}
@Override
public void subscribeRoom(String room) {
String msgToSend = "b" + queue.sizePlusOne() + "." + room + ".";
sendCommandToServer(msgToSend);
}
@Override
public void unsubscribeRoom(String room) {
String msgToSend = "q" + queue.sizePlusOne() + "." + room + ".";
sendCommandToServer(msgToSend);
// gui.unsubscribedRoom(this, room);
}
@Override
public void setStatus(boolean isBusy) {
this.isBusy = isBusy;
sendCommandToServerTransient("i0nJ" + (isBusy ? "b" : "a"));
gui.statusSet(this, isBusy);
}
@Override
public void surrender(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "resign";
sendCommandToServer(msgToSend);
}
@Override
public void stop(String roomId) {
getLinkContent("http://zagram.org/a.kropki?idGracza=" + secretId +
"&co=stopMove&stol=" + roomId);
}
@Override
public void askNewGame(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "new";
sendCommandToServer(msgToSend);
}
@Override
public void cancelAskingNewGame(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "cancel1new";
sendCommandToServer(msgToSend);
}
@Override
public void acceptNewGame(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "new"; // same as ask
sendCommandToServer(msgToSend);
}
@Override
public void rejectNewGame(String roomId) {
// cannot reject, just ignore
}
@Override
public void askEndGameAndScore(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "score";
sendCommandToServer(msgToSend);
}
@Override
public void cancelAskingEndGameAndScore(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "cancel1score";
sendCommandToServer(msgToSend);
}
@Override
public void acceptEndGameAndScore(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "accept2score";
sendCommandToServer(msgToSend);
}
@Override
public void rejectEndGameAndScore(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "reject2score";
sendCommandToServer(msgToSend);
}
@Override
public void askUndo(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "undo";
sendCommandToServer(msgToSend);
}
@Override
public void cancelAskingUndo(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "cancel1undo";
sendCommandToServer(msgToSend);
}
@Override
public void acceptUndo(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "accept2undo";
sendCommandToServer(msgToSend);
}
@Override
public void rejectUndo(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "reject2undo";
sendCommandToServer(msgToSend);
}
@Override
public void askDraw(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "draw";
sendCommandToServer(msgToSend);
}
@Override
public void cancelAskingDraw(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "cancel1draw";
sendCommandToServer(msgToSend);
}
@Override
public void acceptDraw(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "accept2draw";
sendCommandToServer(msgToSend);
}
@Override
public void rejectDraw(String roomId) {
String msgToSend = "u" + queue.sizePlusOne() + "." + roomId + "." + "reject2draw";
sendCommandToServer(msgToSend);
}
@Override
public void pauseOpponentTime(String roomId) {
String msgToSend = "t" + queue.sizePlusOne() + "." + roomId + "." + "p";
sendCommandToServer(msgToSend);
}
@Override
public void unpauseOpponentTime(String roomId) {
String msgToSend = "t" + queue.sizePlusOne() + "." + roomId + "." + "u";
sendCommandToServer(msgToSend);
}
@Override
public void addOpponentTime(String roomId, int seconds) {
getLinkContent("http://zagram.org/a.kropki" +
"?idGracza=" + secretId +
"&co=dodajeCzas&ile=" + seconds +
"&stol=" + roomId);
}
private static synchronized String getLinkContent(String link) {
StringBuilder result = new StringBuilder();
try {
URL url;
URLConnection urlConn;
InputStreamReader inStream;
url = new URL(link);
urlConn = url.openConnection();
inStream = new InputStreamReader(
urlConn.getInputStream(), "UTF-8");
BufferedReader buff = new BufferedReader(inStream);
while (true) {
String nextLine;
nextLine = buff.readLine();
if (nextLine != null) {
result.append(nextLine);
} else {
break;
}
}
} catch (MalformedURLException e) {
} catch (IOException e) {
}
// if (Settings.isDebug()) {
System.out.println("visiting: " + link);
System.out.println("received: " + result.toString());
// }
return result.toString();
}
private void sendCommandToServer(String message) {
queue.add(message);
}
private void sendCommandToServerTransient(String message) {
transiendQueue.add(message);
}
private static String get1SgfCoord(int i) {
if (i <= 26) {
return Character.toString((char) ('a' + i - 1));
} else {
return Character.toString((char) ('A' + i - 26 - 1));
}
}
private static String coordinatesToString(int x, int y) {
return get1SgfCoord(x) + get1SgfCoord(y);
}
private static Integer charToCoordinate(char c) {
if (c >= 'a' && c <= 'z') {
return Integer.class.cast(c - 'a' + 1);
} else if (c >= 'A' && c <= 'Z') {
return Integer.class.cast(c - 'A' + 27);
} else {
return null;
}
}
private static Point stringToCoordinates(String twoLetterString) {
if (twoLetterString.length() >= 2) {
try {
char xAsChar = twoLetterString.charAt(0);
char yAsChar = twoLetterString.charAt(1);
return new Point(
charToCoordinate(xAsChar),
charToCoordinate(yAsChar));
} catch (NullPointerException e) {
return null;
}
} else {
return null;
}
}
private static String getServerEncoded(String s) {
// the order of replacing matters
s = s.replaceAll("@", "@A");
s = s.replaceAll("/", "@S");
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
return "";
}
}
private static String getServerDecoded(String s) {
// the order of replacing matters
return s
.replaceAll("@S", "/")
.replaceAll("@A", "@")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("'", "'")
.replaceAll(""", "\"")
.replaceAll("-", "-");
}
private class ThreadMain extends Thread {
int lastSentCommandNumber = 0;
int lastServerMessageNumber = 0;
@Override
public void run() {
sendCommandToServerTransient("i0nJ" + (isBusy ? "b" : "a"));
while (isDisposed == false) {
String commands = "";
for (String message : transiendQueue) {
commands = commands + message + "/";
}
transiendQueue.clear();
for (int i = lastSentCommandNumber + 1; i < queue.size() + 1; i++) {
// (non-standard interval. Here is: A < x <= B)
commands = commands + queue.get(i) + "/";
}
lastSentCommandNumber = queue.size();
if (commands.equals("")) {
commands = "x";
} else {
commands = commands.substring(0, commands.length() - 1);
}
String text = getLinkContent(
"http://zagram.org/a.kropki?playerId=" +
secretId + "&co=getBMsg&msgNo=" +
lastServerMessageNumber + "&msgFromClient=" + commands);
handleText(text);
Wait.waitExactly(1000L);
}
}
private synchronized void handleText(String text) {
// if (text.startsWith("ok/") && text.endsWith("/end")) {
ServerInterface server = ServerZagram2.this;
if (text.matches("ok.*(end|oend)") ||
(text.matches("sd.*(end|oend)") && isInvisible)) {
String[] splitted =
text
// .substring(
// text.indexOf("ok/") + "ok/".length(),
// text.length() - "/end".length())
.split("/");
Set<String> personalInvitesIncomingNew = new LinkedHashSet<String>();
Set<String> personalInvitesOutgoingNew = new LinkedHashSet<String>();
Set<String> modifiedSubscribedRooms = new HashSet<String>();
String currentRoom = "";
for (String message : splitted) {
if (message.startsWith("b")) { // room subscriptions
// b*Вася.0.234.1234.1451.21
String player = message.replaceAll("\\..*", "").substring(1);
String[] dotSplitted = message.replaceFirst(".*?\\.", "").split("\\.");
final Set<String> newRooms = new LinkedHashSet<String>();
for (String room : dotSplitted) {
newRooms.add(room);
}
final Set<String> oldRooms = playerRooms.get(player);
if (oldRooms==null) {
// for (String room : newRooms) {
// gui.userJoinedRoom(server, room, player, true);
// }
}
else {
for (String room : oldRooms) {
if (newRooms.contains(room)==false) {
// gui.userLeftRoom(server, room, player, "");
}
}
for (String room : newRooms) {
if (oldRooms.contains(room)==false) {
// gui.userJoinedRoom(server, room, player, false);
}
}
}
}
else if (message.startsWith("ca") || message.startsWith("cr")) { // chat
String[] dotSplitted = message.substring("ca".length())
.split("\\.", 4);
try {
long time = Long.parseLong(dotSplitted[0]) * 1000L;
String nick = dotSplitted[1];
// String nickType = dotSplitted[2];
String chatMessage =
getServerDecoded(dotSplitted[3]);
gui.chatReceived(server,
currentRoom, nick, chatMessage, time);
} catch (NumberFormatException e) {
gui.raw(server, "unkown chat: " + message.substring(2));
} catch (ArrayIndexOutOfBoundsException e) {
gui.raw(server, "unknown chat: " + message.substring(2));
}
}
else if (message.startsWith("d")) { // game description
// first section and last two sections
String suffecientPart = message.
replaceFirst("[^.]*.", "").
replaceFirst("\\.[^.]*$", "").
replaceFirst("\\.[^.]*$", "");
ZagramGameTyme gameType = getZagramGameTyme(suffecientPart);
String[] dotSplitted = message.split("\\.");
String roomId = dotSplitted[0].replaceFirst("d", "");
String player1 = dotSplitted[dotSplitted.length - 2];
String player2 = dotSplitted[dotSplitted.length - 1];
gui.updateGameInfo(
server, roomId,
currentRoom, player1, player2,
gameType.fieldX, gameType.FieldY,
false, gameType.isRated, 0, gameType.instantWin,
false, gameType.isStopEnabled, false, null, 0,
gameType.timeAdditional, gameType.timeStarting, 1,
null);
} else if (message.startsWith("f")) { // flags
try {
String timeLimitsAsString = message.split("_")[1];
if (timeLimitsAsString.equals("")) {
} else {
Integer time1 = Integer.parseInt(
timeLimitsAsString.split("\\.")[0]);
Integer time2 = Integer.parseInt(
timeLimitsAsString.split("\\.")[1]);
gui.timeUpdate(server, currentRoom,
new TimeLeft(time1, time2, null, null));
}
} catch (Exception e) {
}
} else if (message.startsWith("ga") || message.startsWith("gr")) { // +game
String[] dotSplitted = message.substring("ga".length())
.split("\\.");
for (String gameId : dotSplitted) {
if (gameId.length() != 0) {
gui.gameRowCreated(server, currentRoom, gameId);
}
}
} else if (message.startsWith("gd")) { // - game
String[] dotSplitted = message.substring("gd".length())
.split("\\.");
for (String gameId : dotSplitted) {
if (gameId.length() != 0) {
gui.gameRowDestroyed(server, gameId);
}
}
} else if (message.startsWith("h")) { // additional flags
} else if (message.startsWith("i")) { // player info
String[] dotSplitted = message.substring("i".length()).split("\\.");
String player = null, status = null, language = null, myStatus = null;
Integer rating = null, winCount = null, lossCount = null, drawCount = null;
if (dotSplitted.length == 4 || dotSplitted.length == 8) {
player = dotSplitted[0];
avatarUrls.put(player, dotSplitted[1]);
status = (dotSplitted[2].matches(".*(N|b).*") ? "" : "free");
// + (dotSplitted[2].contains("J") ? " java" : "web");
language = dotSplitted[3];
myStatus = language + " (" + status + ")";
}
if (dotSplitted.length == 8) {
try {
rating = Integer.parseInt(dotSplitted[4]);
winCount = Integer.parseInt(dotSplitted[5]);
lossCount = Integer.parseInt(dotSplitted[7]);
drawCount = Integer.parseInt(dotSplitted[6]);
} catch (NumberFormatException e) {
}
}
gui.updateUserInfo(server, player, player, null, rating,
winCount, lossCount, drawCount, myStatus, null);
} else if (message.startsWith("m")) { // message numbers info
// try {
String tail = message.substring(1);
String[] dotSplitted = tail.split("\\.");
String a1 = dotSplitted.length >= 1 ? dotSplitted[0] : "";
String a2 = dotSplitted.length >= 2 ? dotSplitted[1] : "";
String a3 = dotSplitted.length >= 3 ? dotSplitted[2] : "";
int i1 = Integer.parseInt(a1);
int i2 = Integer.parseInt(a2);
int i3 = Integer.parseInt(a3);
if (i1 > lastServerMessageNumber + 1) {
// break; no, don't break on this step -- we
// want to stay alive in case of a server restart.
}
lastServerMessageNumber = i2;
lastSentCommandNumber = i3;
// } catch (IndexOutOfBoundsException ignore) {
// } catch (NumberFormatException e) {
// }
// don't catch anything.
// If an exception would be thrown then we are completely
// unfamiliar with this server protocol.
// } else if (message.startsWith("b")) { // player in tables
// String playerId = message.replaceAll("\\..*", "");
// String[] roomList = message.replaceFirst(".*\\.",
// "").split("\\.");
// for (String roomId : roomList) {
// gui.userJoinedRoom(server, roomId, playerId, false);
// }
} else if (message.startsWith("pa") || message.startsWith("pr")) { // player joined
String[] dotSplitted = message.substring("pa".length()).split("\\.");
for (String player : dotSplitted) {
if (player.length() != 0) {
gui.userJoinedRoom(
server, currentRoom, player, message.startsWith("pr"));
}
}
} else if (message.startsWith("pd")) { // - player
String[] dotSplitted = message.substring("pd".length())
.split("\\.");
for (String player : dotSplitted) {
if (player.length() != 0) {
gui.userLeftRoom(server, currentRoom, player, "");
}
}
} else if (message.startsWith("q")) { // current room
String room = message.substring(1);
currentRoom = room;
modifiedSubscribedRooms.add(room);
if (subscribedRooms.contains(room)) { // old set
} else {
if (currentRoom.equals("0")) {
gui.subscribedLangRoom(
currentRoom,
server,
"общий чат: zagram",
true);
} else {
gui.subscribedGame(server, currentRoom);
}
}
} else if (message.matches("sa.*|sr.*")) { // game actions
message = message.replaceAll("\\(|\\)", "");
class FatalGameRoomError extends Exception {
public FatalGameRoomError(String s) {
super(s);
}
}
try {
String usefulPart = message.replaceFirst("sa;|sr;", "");
String[] semiSplitted = usefulPart.split(";");
for (String sgfNode : semiSplitted) {
// ([A-Z]{1,2}\[([^\]|\\\\)*?\])*
// ([A-Z]{1,2}\[.*?\])*
if (sgfNode.matches("([A-Z]{1,2}\\[.*\\])*") == false) {
gui.raw(server, "unknown message structure: " + message);
} else {
String lastMovePropertyName = "";
String[] sgfPropertyList = sgfNode.split("\\]");
for (String sgfProperty : sgfPropertyList) {
String propertyName = sgfProperty.replaceAll("\\[.*", "");
String propertyValue = sgfProperty.replaceFirst(".*\\[", "");
if (propertyName.matches("U(B|W)")) {
throw new FatalGameRoomError("UNDO is unsupported");
} else if (propertyName.matches("B|W|AB|AW|")) {
boolean isWhite = propertyName.matches("W|AW")
|| (propertyName.equals("") && lastMovePropertyName.matches("A|AW"));
- lastMovePropertyName = propertyName;
+ if (!propertyName.equals(""))
+ lastMovePropertyName = propertyName;
gui.makedMove(
server, currentRoom,
message.startsWith("sr"),
stringToCoordinates(propertyValue).x,
stringToCoordinates(propertyValue).y,
isWhite, !isWhite
);
} else {
}
}
}
}
gui.makedMove(server, currentRoom, false, -1, -1, true, false);
} catch (FatalGameRoomError e) {
// server.unsubscribeRoom(currentRoom);
gui.raw(server, "ERROR in game room '" +
e.getMessage() +
"'. The game position is not guaranteed to be correct in this game for now on.");
}
} else if (message.matches("u.undo")) {
boolean isRed = message.charAt(1) == '1';
String playerAsString = isRed ? "red" : "blue";
gui.chatReceived(
server,
currentRoom,
"",
"player "
+ playerAsString
+
" Запрос на 'undo'. Клиент MultiPoints пока-что не умеет обрабатывать этот вызов.:(",
null
);
} else if (message.startsWith("vg")) { // game invite
String usefulPart = message.substring(2);
String sender = usefulPart.replaceAll("\\..*", ""); // first part
if (personalInvitesIncoming.contains(sender) == false) {
String gameDescription = usefulPart.replaceFirst("[^.]*\\.", ""); // other
ZagramGameTyme gameType = getZagramGameTyme(gameDescription);
if (isBusy == true) {
personalInvitesIncoming.add(sender);
server.rejectPersonalGameInvite(sender);
personalInvitesIncoming.remove(sender); // kind of a hack
}
else if (gameType.isEmptyScored == true) {
personalInvitesIncoming.add(sender);
server.rejectPersonalGameInvite(sender);
personalInvitesIncoming.remove(sender); // kind of a hack
gui.raw(server, String.format(
"Игрок '%s' вызвал(а) тебя на игру: " +
"К сожалению, принять заявку невозможно, " +
"т.к. польские правила с ручными обводами территории " +
"пока-что не поддерживаютяс программой. " +
"Отослан отказ от игры. ",
sender));
} else {
gui.updateGameInfo(
server, sender + "@incoming", currentRoom,
sender, null,
gameType.fieldX, gameType.FieldY, false,
gameType.isRated, 0,
gameType.instantWin, false, gameType.isStopEnabled, false,
GameState.SearchingOpponent,
0, gameType.timeAdditional, gameType.timeStarting, 1,
sender + "to YOU");
gui.personalInviteReceived(server, sender, sender + "@incoming");
personalInvitesIncomingNew.add(sender);
}
} else {
personalInvitesIncomingNew.add(sender);
}
} else if (message.startsWith("vr")) {
String user = message.substring(2);
gui.yourPersonalInviteRejected(server, user, user + "@outgoing");
// "OK to the fact that someone rejected your invitation" :-/
sendCommandToServer("v" + queue.sizePlusOne() + "." + "0" + "." + "o");
} else if (message.startsWith("vs")) {
String user = message.substring(2).split("\\.")[0];
if (personalInvitesOutgoing.contains(user) == false) {
gui.yourPersonalInviteSent(server, user, user + "@outgoing");
}
personalInvitesOutgoingNew.add(user);
}
}
{
// warning: UGLY CODE
// now I have to compare two sets of player invitations
// if I don't have a player in the new set -
// then the invitation is closed and I should delete it.
for (Iterator<String> iterator = personalInvitesIncoming.iterator(); iterator.hasNext();) {
String player = iterator.next();
if (personalInvitesIncomingNew.contains(player) == false) {
// invitation cancelled
gui.personalInviteCancelled(server, player, player + "@incoming");
sendCommandToServerTransient("i0nJa");
}
}
personalInvitesIncoming = personalInvitesIncomingNew;
personalInvitesIncomingNew = new LinkedHashSet<String>();
}
{
for (Iterator<String> iterator = personalInvitesOutgoing.iterator(); iterator.hasNext();) {
String player = iterator.next();
if (personalInvitesOutgoingNew.contains(player) == false) {
// invitation cancelled
gui.yourPersonalInviteRejected(server, player, player + "@outgoing");
}
}
personalInvitesOutgoing = personalInvitesOutgoingNew;
personalInvitesOutgoingNew = new LinkedHashSet<String>();
}
{
for (Iterator<String> iterator = subscribedRooms.iterator(); iterator.hasNext();) {
String room = iterator.next();
if (modifiedSubscribedRooms.contains(room) == false) {
// unsubscribed room
gui.unsubscribedRoom(server, room);
}
}
subscribedRooms = modifiedSubscribedRooms;
modifiedSubscribedRooms = new LinkedHashSet<String>();
}
} else if (text.equals("")) {
// we got an empty result. Well, lets treat that as normal.
} else {
gui.serverClosed(server);
isDisposed = true;
}
}
}
@Override
public String coordinatesToString(Integer xOrNull, Integer yOrNull) {
Function<Integer, String> getGuiX = new Function<Integer, String>() {
@Override
public String call(Integer i) {
if (i <= 8) {
// "a" .. "h"
return Character.toString((char) ('a' + i - 1));
} else if (i > 8 && i <= 25) {
// "j" .. "z"
// letter "i" is skipped in zagram coordinates
return Character.toString((char) ('a' + i));
} else if (i > 25 && i <= 25 + 8) {
// "A" .. "H"
return Character.toString((char) ('A' + i - 26));
} else if (i > 25 + 8) {
// "J" .. "Z"
return Character.toString((char) ('A' + i - 26 + 1));
} else {
return "";
}
}
};
if (xOrNull != null && yOrNull != null) {
return String.format("%s%s", getGuiX.call(xOrNull), yOrNull);
} else if (xOrNull != null) {
return String.format("%s", getGuiX.call(xOrNull));
} else if (yOrNull != null) {
return String.format("%s", yOrNull);
} else {
return "";
}
}
public void getUserInfoText(String user) {
}
public void getUserpic(String user) {
try {
if (avatarImages.get(user) != null) {
} else if (
avatarUrls.get(user) != null
// && !avatarUrls.get(user).equals("")
// && !avatarUrls.get(user).equals("0")
) {
URL url;
if (avatarUrls.get(user).equals("") ||
avatarUrls.get(user).equals("0")) {
url = new URL("http://zagram.org/awatar2.png");
} else {
url = new URL("http://zagram.org/awatary/" + avatarUrls.get(user) + ".gif");
}
// URL url = new URL("http://www.citilink.com/~grizzly/anigifs/bear.gif"); // animation
ImageIcon imageIcon = new ImageIcon(url);
// imageIcon.getImage().
gui.updateUserInfo(this, user, null, imageIcon, null, null, null, null, null, null);
}
} catch (Exception ex) {
}
}
@Override
public boolean isIncomingYInverted() {
return true;
}
@Override
public boolean isGuiYInverted() {
return false;
}
@Override
public boolean isPrivateChatEnabled() {
return false;
}
@Override
public boolean isPingEnabled() {
return false;
}
@Override
public boolean isStopEnabled() {
return true;
}
@Override
public boolean isSoundNotifyEnabled() {
return false;
}
@Override
public boolean isField20x20Allowed() {
return true;
}
@Override
public boolean isField25x25Allowed() {
return true;
}
@Override
public boolean isField30x30Allowed() {
return true;
}
@Override
public boolean isField39x32Allowed() {
return true;
}
@Override
public boolean isStartingEmptyFieldAllowed() {
return true;
}
@Override
public boolean isStartingCrossAllowed() {
return false;
}
@Override
public boolean isStarting4CrossAllowed() {
return false;
}
@Override
public TimeSettings getTimeSettingsMaximum() {
return new TimeSettings(120 * 60 /* 120 minutes */, 60, 0, 1, 0);
}
@Override
public TimeSettings getTimeSettingsMinimum() {
return new TimeSettings(60, 2, 0, 1, 0);
}
@Override
public TimeSettings getTimeSettingsDefault() {
return new TimeSettings(3 * 60, 15, 0, 1, 0);
}
@Override
public boolean isPrivateGameInviteAllowed() {
return true;
}
@Override
public boolean isGlobalGameVacancyAllowed() {
return false;
}
}
| true | true | private synchronized void handleText(String text) {
// if (text.startsWith("ok/") && text.endsWith("/end")) {
ServerInterface server = ServerZagram2.this;
if (text.matches("ok.*(end|oend)") ||
(text.matches("sd.*(end|oend)") && isInvisible)) {
String[] splitted =
text
// .substring(
// text.indexOf("ok/") + "ok/".length(),
// text.length() - "/end".length())
.split("/");
Set<String> personalInvitesIncomingNew = new LinkedHashSet<String>();
Set<String> personalInvitesOutgoingNew = new LinkedHashSet<String>();
Set<String> modifiedSubscribedRooms = new HashSet<String>();
String currentRoom = "";
for (String message : splitted) {
if (message.startsWith("b")) { // room subscriptions
// b*Вася.0.234.1234.1451.21
String player = message.replaceAll("\\..*", "").substring(1);
String[] dotSplitted = message.replaceFirst(".*?\\.", "").split("\\.");
final Set<String> newRooms = new LinkedHashSet<String>();
for (String room : dotSplitted) {
newRooms.add(room);
}
final Set<String> oldRooms = playerRooms.get(player);
if (oldRooms==null) {
// for (String room : newRooms) {
// gui.userJoinedRoom(server, room, player, true);
// }
}
else {
for (String room : oldRooms) {
if (newRooms.contains(room)==false) {
// gui.userLeftRoom(server, room, player, "");
}
}
for (String room : newRooms) {
if (oldRooms.contains(room)==false) {
// gui.userJoinedRoom(server, room, player, false);
}
}
}
}
else if (message.startsWith("ca") || message.startsWith("cr")) { // chat
String[] dotSplitted = message.substring("ca".length())
.split("\\.", 4);
try {
long time = Long.parseLong(dotSplitted[0]) * 1000L;
String nick = dotSplitted[1];
// String nickType = dotSplitted[2];
String chatMessage =
getServerDecoded(dotSplitted[3]);
gui.chatReceived(server,
currentRoom, nick, chatMessage, time);
} catch (NumberFormatException e) {
gui.raw(server, "unkown chat: " + message.substring(2));
} catch (ArrayIndexOutOfBoundsException e) {
gui.raw(server, "unknown chat: " + message.substring(2));
}
}
else if (message.startsWith("d")) { // game description
// first section and last two sections
String suffecientPart = message.
replaceFirst("[^.]*.", "").
replaceFirst("\\.[^.]*$", "").
replaceFirst("\\.[^.]*$", "");
ZagramGameTyme gameType = getZagramGameTyme(suffecientPart);
String[] dotSplitted = message.split("\\.");
String roomId = dotSplitted[0].replaceFirst("d", "");
String player1 = dotSplitted[dotSplitted.length - 2];
String player2 = dotSplitted[dotSplitted.length - 1];
gui.updateGameInfo(
server, roomId,
currentRoom, player1, player2,
gameType.fieldX, gameType.FieldY,
false, gameType.isRated, 0, gameType.instantWin,
false, gameType.isStopEnabled, false, null, 0,
gameType.timeAdditional, gameType.timeStarting, 1,
null);
} else if (message.startsWith("f")) { // flags
try {
String timeLimitsAsString = message.split("_")[1];
if (timeLimitsAsString.equals("")) {
} else {
Integer time1 = Integer.parseInt(
timeLimitsAsString.split("\\.")[0]);
Integer time2 = Integer.parseInt(
timeLimitsAsString.split("\\.")[1]);
gui.timeUpdate(server, currentRoom,
new TimeLeft(time1, time2, null, null));
}
} catch (Exception e) {
}
} else if (message.startsWith("ga") || message.startsWith("gr")) { // +game
String[] dotSplitted = message.substring("ga".length())
.split("\\.");
for (String gameId : dotSplitted) {
if (gameId.length() != 0) {
gui.gameRowCreated(server, currentRoom, gameId);
}
}
} else if (message.startsWith("gd")) { // - game
String[] dotSplitted = message.substring("gd".length())
.split("\\.");
for (String gameId : dotSplitted) {
if (gameId.length() != 0) {
gui.gameRowDestroyed(server, gameId);
}
}
} else if (message.startsWith("h")) { // additional flags
} else if (message.startsWith("i")) { // player info
String[] dotSplitted = message.substring("i".length()).split("\\.");
String player = null, status = null, language = null, myStatus = null;
Integer rating = null, winCount = null, lossCount = null, drawCount = null;
if (dotSplitted.length == 4 || dotSplitted.length == 8) {
player = dotSplitted[0];
avatarUrls.put(player, dotSplitted[1]);
status = (dotSplitted[2].matches(".*(N|b).*") ? "" : "free");
// + (dotSplitted[2].contains("J") ? " java" : "web");
language = dotSplitted[3];
myStatus = language + " (" + status + ")";
}
if (dotSplitted.length == 8) {
try {
rating = Integer.parseInt(dotSplitted[4]);
winCount = Integer.parseInt(dotSplitted[5]);
lossCount = Integer.parseInt(dotSplitted[7]);
drawCount = Integer.parseInt(dotSplitted[6]);
} catch (NumberFormatException e) {
}
}
gui.updateUserInfo(server, player, player, null, rating,
winCount, lossCount, drawCount, myStatus, null);
} else if (message.startsWith("m")) { // message numbers info
// try {
String tail = message.substring(1);
String[] dotSplitted = tail.split("\\.");
String a1 = dotSplitted.length >= 1 ? dotSplitted[0] : "";
String a2 = dotSplitted.length >= 2 ? dotSplitted[1] : "";
String a3 = dotSplitted.length >= 3 ? dotSplitted[2] : "";
int i1 = Integer.parseInt(a1);
int i2 = Integer.parseInt(a2);
int i3 = Integer.parseInt(a3);
if (i1 > lastServerMessageNumber + 1) {
// break; no, don't break on this step -- we
// want to stay alive in case of a server restart.
}
lastServerMessageNumber = i2;
lastSentCommandNumber = i3;
// } catch (IndexOutOfBoundsException ignore) {
// } catch (NumberFormatException e) {
// }
// don't catch anything.
// If an exception would be thrown then we are completely
// unfamiliar with this server protocol.
// } else if (message.startsWith("b")) { // player in tables
// String playerId = message.replaceAll("\\..*", "");
// String[] roomList = message.replaceFirst(".*\\.",
// "").split("\\.");
// for (String roomId : roomList) {
// gui.userJoinedRoom(server, roomId, playerId, false);
// }
} else if (message.startsWith("pa") || message.startsWith("pr")) { // player joined
String[] dotSplitted = message.substring("pa".length()).split("\\.");
for (String player : dotSplitted) {
if (player.length() != 0) {
gui.userJoinedRoom(
server, currentRoom, player, message.startsWith("pr"));
}
}
} else if (message.startsWith("pd")) { // - player
String[] dotSplitted = message.substring("pd".length())
.split("\\.");
for (String player : dotSplitted) {
if (player.length() != 0) {
gui.userLeftRoom(server, currentRoom, player, "");
}
}
} else if (message.startsWith("q")) { // current room
String room = message.substring(1);
currentRoom = room;
modifiedSubscribedRooms.add(room);
if (subscribedRooms.contains(room)) { // old set
} else {
if (currentRoom.equals("0")) {
gui.subscribedLangRoom(
currentRoom,
server,
"общий чат: zagram",
true);
} else {
gui.subscribedGame(server, currentRoom);
}
}
} else if (message.matches("sa.*|sr.*")) { // game actions
message = message.replaceAll("\\(|\\)", "");
class FatalGameRoomError extends Exception {
public FatalGameRoomError(String s) {
super(s);
}
}
try {
String usefulPart = message.replaceFirst("sa;|sr;", "");
String[] semiSplitted = usefulPart.split(";");
for (String sgfNode : semiSplitted) {
// ([A-Z]{1,2}\[([^\]|\\\\)*?\])*
// ([A-Z]{1,2}\[.*?\])*
if (sgfNode.matches("([A-Z]{1,2}\\[.*\\])*") == false) {
gui.raw(server, "unknown message structure: " + message);
} else {
String lastMovePropertyName = "";
String[] sgfPropertyList = sgfNode.split("\\]");
for (String sgfProperty : sgfPropertyList) {
String propertyName = sgfProperty.replaceAll("\\[.*", "");
String propertyValue = sgfProperty.replaceFirst(".*\\[", "");
if (propertyName.matches("U(B|W)")) {
throw new FatalGameRoomError("UNDO is unsupported");
} else if (propertyName.matches("B|W|AB|AW|")) {
boolean isWhite = propertyName.matches("W|AW")
|| (propertyName.equals("") && lastMovePropertyName.matches("A|AW"));
lastMovePropertyName = propertyName;
gui.makedMove(
server, currentRoom,
message.startsWith("sr"),
stringToCoordinates(propertyValue).x,
stringToCoordinates(propertyValue).y,
isWhite, !isWhite
);
} else {
}
}
}
}
gui.makedMove(server, currentRoom, false, -1, -1, true, false);
} catch (FatalGameRoomError e) {
// server.unsubscribeRoom(currentRoom);
gui.raw(server, "ERROR in game room '" +
e.getMessage() +
"'. The game position is not guaranteed to be correct in this game for now on.");
}
} else if (message.matches("u.undo")) {
boolean isRed = message.charAt(1) == '1';
String playerAsString = isRed ? "red" : "blue";
gui.chatReceived(
server,
currentRoom,
"",
"player "
+ playerAsString
+
" Запрос на 'undo'. Клиент MultiPoints пока-что не умеет обрабатывать этот вызов.:(",
null
);
} else if (message.startsWith("vg")) { // game invite
String usefulPart = message.substring(2);
String sender = usefulPart.replaceAll("\\..*", ""); // first part
if (personalInvitesIncoming.contains(sender) == false) {
String gameDescription = usefulPart.replaceFirst("[^.]*\\.", ""); // other
ZagramGameTyme gameType = getZagramGameTyme(gameDescription);
if (isBusy == true) {
personalInvitesIncoming.add(sender);
server.rejectPersonalGameInvite(sender);
personalInvitesIncoming.remove(sender); // kind of a hack
}
else if (gameType.isEmptyScored == true) {
personalInvitesIncoming.add(sender);
server.rejectPersonalGameInvite(sender);
personalInvitesIncoming.remove(sender); // kind of a hack
gui.raw(server, String.format(
"Игрок '%s' вызвал(а) тебя на игру: " +
"К сожалению, принять заявку невозможно, " +
"т.к. польские правила с ручными обводами территории " +
"пока-что не поддерживаютяс программой. " +
"Отослан отказ от игры. ",
sender));
} else {
gui.updateGameInfo(
server, sender + "@incoming", currentRoom,
sender, null,
gameType.fieldX, gameType.FieldY, false,
gameType.isRated, 0,
gameType.instantWin, false, gameType.isStopEnabled, false,
GameState.SearchingOpponent,
0, gameType.timeAdditional, gameType.timeStarting, 1,
sender + "to YOU");
gui.personalInviteReceived(server, sender, sender + "@incoming");
personalInvitesIncomingNew.add(sender);
}
} else {
personalInvitesIncomingNew.add(sender);
}
} else if (message.startsWith("vr")) {
String user = message.substring(2);
gui.yourPersonalInviteRejected(server, user, user + "@outgoing");
// "OK to the fact that someone rejected your invitation" :-/
sendCommandToServer("v" + queue.sizePlusOne() + "." + "0" + "." + "o");
} else if (message.startsWith("vs")) {
String user = message.substring(2).split("\\.")[0];
if (personalInvitesOutgoing.contains(user) == false) {
gui.yourPersonalInviteSent(server, user, user + "@outgoing");
}
personalInvitesOutgoingNew.add(user);
}
}
{
// warning: UGLY CODE
// now I have to compare two sets of player invitations
// if I don't have a player in the new set -
// then the invitation is closed and I should delete it.
for (Iterator<String> iterator = personalInvitesIncoming.iterator(); iterator.hasNext();) {
String player = iterator.next();
if (personalInvitesIncomingNew.contains(player) == false) {
// invitation cancelled
gui.personalInviteCancelled(server, player, player + "@incoming");
sendCommandToServerTransient("i0nJa");
}
}
personalInvitesIncoming = personalInvitesIncomingNew;
personalInvitesIncomingNew = new LinkedHashSet<String>();
}
{
for (Iterator<String> iterator = personalInvitesOutgoing.iterator(); iterator.hasNext();) {
String player = iterator.next();
if (personalInvitesOutgoingNew.contains(player) == false) {
// invitation cancelled
gui.yourPersonalInviteRejected(server, player, player + "@outgoing");
}
}
personalInvitesOutgoing = personalInvitesOutgoingNew;
personalInvitesOutgoingNew = new LinkedHashSet<String>();
}
{
for (Iterator<String> iterator = subscribedRooms.iterator(); iterator.hasNext();) {
String room = iterator.next();
if (modifiedSubscribedRooms.contains(room) == false) {
// unsubscribed room
gui.unsubscribedRoom(server, room);
}
}
subscribedRooms = modifiedSubscribedRooms;
modifiedSubscribedRooms = new LinkedHashSet<String>();
}
} else if (text.equals("")) {
// we got an empty result. Well, lets treat that as normal.
} else {
gui.serverClosed(server);
isDisposed = true;
}
}
| private synchronized void handleText(String text) {
// if (text.startsWith("ok/") && text.endsWith("/end")) {
ServerInterface server = ServerZagram2.this;
if (text.matches("ok.*(end|oend)") ||
(text.matches("sd.*(end|oend)") && isInvisible)) {
String[] splitted =
text
// .substring(
// text.indexOf("ok/") + "ok/".length(),
// text.length() - "/end".length())
.split("/");
Set<String> personalInvitesIncomingNew = new LinkedHashSet<String>();
Set<String> personalInvitesOutgoingNew = new LinkedHashSet<String>();
Set<String> modifiedSubscribedRooms = new HashSet<String>();
String currentRoom = "";
for (String message : splitted) {
if (message.startsWith("b")) { // room subscriptions
// b*Вася.0.234.1234.1451.21
String player = message.replaceAll("\\..*", "").substring(1);
String[] dotSplitted = message.replaceFirst(".*?\\.", "").split("\\.");
final Set<String> newRooms = new LinkedHashSet<String>();
for (String room : dotSplitted) {
newRooms.add(room);
}
final Set<String> oldRooms = playerRooms.get(player);
if (oldRooms==null) {
// for (String room : newRooms) {
// gui.userJoinedRoom(server, room, player, true);
// }
}
else {
for (String room : oldRooms) {
if (newRooms.contains(room)==false) {
// gui.userLeftRoom(server, room, player, "");
}
}
for (String room : newRooms) {
if (oldRooms.contains(room)==false) {
// gui.userJoinedRoom(server, room, player, false);
}
}
}
}
else if (message.startsWith("ca") || message.startsWith("cr")) { // chat
String[] dotSplitted = message.substring("ca".length())
.split("\\.", 4);
try {
long time = Long.parseLong(dotSplitted[0]) * 1000L;
String nick = dotSplitted[1];
// String nickType = dotSplitted[2];
String chatMessage =
getServerDecoded(dotSplitted[3]);
gui.chatReceived(server,
currentRoom, nick, chatMessage, time);
} catch (NumberFormatException e) {
gui.raw(server, "unkown chat: " + message.substring(2));
} catch (ArrayIndexOutOfBoundsException e) {
gui.raw(server, "unknown chat: " + message.substring(2));
}
}
else if (message.startsWith("d")) { // game description
// first section and last two sections
String suffecientPart = message.
replaceFirst("[^.]*.", "").
replaceFirst("\\.[^.]*$", "").
replaceFirst("\\.[^.]*$", "");
ZagramGameTyme gameType = getZagramGameTyme(suffecientPart);
String[] dotSplitted = message.split("\\.");
String roomId = dotSplitted[0].replaceFirst("d", "");
String player1 = dotSplitted[dotSplitted.length - 2];
String player2 = dotSplitted[dotSplitted.length - 1];
gui.updateGameInfo(
server, roomId,
currentRoom, player1, player2,
gameType.fieldX, gameType.FieldY,
false, gameType.isRated, 0, gameType.instantWin,
false, gameType.isStopEnabled, false, null, 0,
gameType.timeAdditional, gameType.timeStarting, 1,
null);
} else if (message.startsWith("f")) { // flags
try {
String timeLimitsAsString = message.split("_")[1];
if (timeLimitsAsString.equals("")) {
} else {
Integer time1 = Integer.parseInt(
timeLimitsAsString.split("\\.")[0]);
Integer time2 = Integer.parseInt(
timeLimitsAsString.split("\\.")[1]);
gui.timeUpdate(server, currentRoom,
new TimeLeft(time1, time2, null, null));
}
} catch (Exception e) {
}
} else if (message.startsWith("ga") || message.startsWith("gr")) { // +game
String[] dotSplitted = message.substring("ga".length())
.split("\\.");
for (String gameId : dotSplitted) {
if (gameId.length() != 0) {
gui.gameRowCreated(server, currentRoom, gameId);
}
}
} else if (message.startsWith("gd")) { // - game
String[] dotSplitted = message.substring("gd".length())
.split("\\.");
for (String gameId : dotSplitted) {
if (gameId.length() != 0) {
gui.gameRowDestroyed(server, gameId);
}
}
} else if (message.startsWith("h")) { // additional flags
} else if (message.startsWith("i")) { // player info
String[] dotSplitted = message.substring("i".length()).split("\\.");
String player = null, status = null, language = null, myStatus = null;
Integer rating = null, winCount = null, lossCount = null, drawCount = null;
if (dotSplitted.length == 4 || dotSplitted.length == 8) {
player = dotSplitted[0];
avatarUrls.put(player, dotSplitted[1]);
status = (dotSplitted[2].matches(".*(N|b).*") ? "" : "free");
// + (dotSplitted[2].contains("J") ? " java" : "web");
language = dotSplitted[3];
myStatus = language + " (" + status + ")";
}
if (dotSplitted.length == 8) {
try {
rating = Integer.parseInt(dotSplitted[4]);
winCount = Integer.parseInt(dotSplitted[5]);
lossCount = Integer.parseInt(dotSplitted[7]);
drawCount = Integer.parseInt(dotSplitted[6]);
} catch (NumberFormatException e) {
}
}
gui.updateUserInfo(server, player, player, null, rating,
winCount, lossCount, drawCount, myStatus, null);
} else if (message.startsWith("m")) { // message numbers info
// try {
String tail = message.substring(1);
String[] dotSplitted = tail.split("\\.");
String a1 = dotSplitted.length >= 1 ? dotSplitted[0] : "";
String a2 = dotSplitted.length >= 2 ? dotSplitted[1] : "";
String a3 = dotSplitted.length >= 3 ? dotSplitted[2] : "";
int i1 = Integer.parseInt(a1);
int i2 = Integer.parseInt(a2);
int i3 = Integer.parseInt(a3);
if (i1 > lastServerMessageNumber + 1) {
// break; no, don't break on this step -- we
// want to stay alive in case of a server restart.
}
lastServerMessageNumber = i2;
lastSentCommandNumber = i3;
// } catch (IndexOutOfBoundsException ignore) {
// } catch (NumberFormatException e) {
// }
// don't catch anything.
// If an exception would be thrown then we are completely
// unfamiliar with this server protocol.
// } else if (message.startsWith("b")) { // player in tables
// String playerId = message.replaceAll("\\..*", "");
// String[] roomList = message.replaceFirst(".*\\.",
// "").split("\\.");
// for (String roomId : roomList) {
// gui.userJoinedRoom(server, roomId, playerId, false);
// }
} else if (message.startsWith("pa") || message.startsWith("pr")) { // player joined
String[] dotSplitted = message.substring("pa".length()).split("\\.");
for (String player : dotSplitted) {
if (player.length() != 0) {
gui.userJoinedRoom(
server, currentRoom, player, message.startsWith("pr"));
}
}
} else if (message.startsWith("pd")) { // - player
String[] dotSplitted = message.substring("pd".length())
.split("\\.");
for (String player : dotSplitted) {
if (player.length() != 0) {
gui.userLeftRoom(server, currentRoom, player, "");
}
}
} else if (message.startsWith("q")) { // current room
String room = message.substring(1);
currentRoom = room;
modifiedSubscribedRooms.add(room);
if (subscribedRooms.contains(room)) { // old set
} else {
if (currentRoom.equals("0")) {
gui.subscribedLangRoom(
currentRoom,
server,
"общий чат: zagram",
true);
} else {
gui.subscribedGame(server, currentRoom);
}
}
} else if (message.matches("sa.*|sr.*")) { // game actions
message = message.replaceAll("\\(|\\)", "");
class FatalGameRoomError extends Exception {
public FatalGameRoomError(String s) {
super(s);
}
}
try {
String usefulPart = message.replaceFirst("sa;|sr;", "");
String[] semiSplitted = usefulPart.split(";");
for (String sgfNode : semiSplitted) {
// ([A-Z]{1,2}\[([^\]|\\\\)*?\])*
// ([A-Z]{1,2}\[.*?\])*
if (sgfNode.matches("([A-Z]{1,2}\\[.*\\])*") == false) {
gui.raw(server, "unknown message structure: " + message);
} else {
String lastMovePropertyName = "";
String[] sgfPropertyList = sgfNode.split("\\]");
for (String sgfProperty : sgfPropertyList) {
String propertyName = sgfProperty.replaceAll("\\[.*", "");
String propertyValue = sgfProperty.replaceFirst(".*\\[", "");
if (propertyName.matches("U(B|W)")) {
throw new FatalGameRoomError("UNDO is unsupported");
} else if (propertyName.matches("B|W|AB|AW|")) {
boolean isWhite = propertyName.matches("W|AW")
|| (propertyName.equals("") && lastMovePropertyName.matches("A|AW"));
if (!propertyName.equals(""))
lastMovePropertyName = propertyName;
gui.makedMove(
server, currentRoom,
message.startsWith("sr"),
stringToCoordinates(propertyValue).x,
stringToCoordinates(propertyValue).y,
isWhite, !isWhite
);
} else {
}
}
}
}
gui.makedMove(server, currentRoom, false, -1, -1, true, false);
} catch (FatalGameRoomError e) {
// server.unsubscribeRoom(currentRoom);
gui.raw(server, "ERROR in game room '" +
e.getMessage() +
"'. The game position is not guaranteed to be correct in this game for now on.");
}
} else if (message.matches("u.undo")) {
boolean isRed = message.charAt(1) == '1';
String playerAsString = isRed ? "red" : "blue";
gui.chatReceived(
server,
currentRoom,
"",
"player "
+ playerAsString
+
" Запрос на 'undo'. Клиент MultiPoints пока-что не умеет обрабатывать этот вызов.:(",
null
);
} else if (message.startsWith("vg")) { // game invite
String usefulPart = message.substring(2);
String sender = usefulPart.replaceAll("\\..*", ""); // first part
if (personalInvitesIncoming.contains(sender) == false) {
String gameDescription = usefulPart.replaceFirst("[^.]*\\.", ""); // other
ZagramGameTyme gameType = getZagramGameTyme(gameDescription);
if (isBusy == true) {
personalInvitesIncoming.add(sender);
server.rejectPersonalGameInvite(sender);
personalInvitesIncoming.remove(sender); // kind of a hack
}
else if (gameType.isEmptyScored == true) {
personalInvitesIncoming.add(sender);
server.rejectPersonalGameInvite(sender);
personalInvitesIncoming.remove(sender); // kind of a hack
gui.raw(server, String.format(
"Игрок '%s' вызвал(а) тебя на игру: " +
"К сожалению, принять заявку невозможно, " +
"т.к. польские правила с ручными обводами территории " +
"пока-что не поддерживаютяс программой. " +
"Отослан отказ от игры. ",
sender));
} else {
gui.updateGameInfo(
server, sender + "@incoming", currentRoom,
sender, null,
gameType.fieldX, gameType.FieldY, false,
gameType.isRated, 0,
gameType.instantWin, false, gameType.isStopEnabled, false,
GameState.SearchingOpponent,
0, gameType.timeAdditional, gameType.timeStarting, 1,
sender + "to YOU");
gui.personalInviteReceived(server, sender, sender + "@incoming");
personalInvitesIncomingNew.add(sender);
}
} else {
personalInvitesIncomingNew.add(sender);
}
} else if (message.startsWith("vr")) {
String user = message.substring(2);
gui.yourPersonalInviteRejected(server, user, user + "@outgoing");
// "OK to the fact that someone rejected your invitation" :-/
sendCommandToServer("v" + queue.sizePlusOne() + "." + "0" + "." + "o");
} else if (message.startsWith("vs")) {
String user = message.substring(2).split("\\.")[0];
if (personalInvitesOutgoing.contains(user) == false) {
gui.yourPersonalInviteSent(server, user, user + "@outgoing");
}
personalInvitesOutgoingNew.add(user);
}
}
{
// warning: UGLY CODE
// now I have to compare two sets of player invitations
// if I don't have a player in the new set -
// then the invitation is closed and I should delete it.
for (Iterator<String> iterator = personalInvitesIncoming.iterator(); iterator.hasNext();) {
String player = iterator.next();
if (personalInvitesIncomingNew.contains(player) == false) {
// invitation cancelled
gui.personalInviteCancelled(server, player, player + "@incoming");
sendCommandToServerTransient("i0nJa");
}
}
personalInvitesIncoming = personalInvitesIncomingNew;
personalInvitesIncomingNew = new LinkedHashSet<String>();
}
{
for (Iterator<String> iterator = personalInvitesOutgoing.iterator(); iterator.hasNext();) {
String player = iterator.next();
if (personalInvitesOutgoingNew.contains(player) == false) {
// invitation cancelled
gui.yourPersonalInviteRejected(server, player, player + "@outgoing");
}
}
personalInvitesOutgoing = personalInvitesOutgoingNew;
personalInvitesOutgoingNew = new LinkedHashSet<String>();
}
{
for (Iterator<String> iterator = subscribedRooms.iterator(); iterator.hasNext();) {
String room = iterator.next();
if (modifiedSubscribedRooms.contains(room) == false) {
// unsubscribed room
gui.unsubscribedRoom(server, room);
}
}
subscribedRooms = modifiedSubscribedRooms;
modifiedSubscribedRooms = new LinkedHashSet<String>();
}
} else if (text.equals("")) {
// we got an empty result. Well, lets treat that as normal.
} else {
gui.serverClosed(server);
isDisposed = true;
}
}
|
diff --git a/src/soot/jimple/toolkits/annotation/LineNumberAdder.java b/src/soot/jimple/toolkits/annotation/LineNumberAdder.java
index a238955d..a5e8902f 100644
--- a/src/soot/jimple/toolkits/annotation/LineNumberAdder.java
+++ b/src/soot/jimple/toolkits/annotation/LineNumberAdder.java
@@ -1,57 +1,59 @@
package soot.jimple.toolkits.annotation;
import soot.*;
import java.util.*;
import soot.jimple.*;
import soot.tagkit.*;
public class LineNumberAdder extends SceneTransformer {
public LineNumberAdder( Singletons.Global g) {}
public static LineNumberAdder v() { return G.v().soot_jimple_toolkits_annotation_LineNumberAdder();}
public void internalTransform(String phaseName, Map opts){
Iterator it = Scene.v().getApplicationClasses().iterator();
while (it.hasNext()){
SootClass sc = (SootClass)it.next();
// make map of first line to each method
HashMap lineToMeth = new HashMap();
Iterator methIt = sc.getMethods().iterator();
while (methIt.hasNext()){
SootMethod meth = (SootMethod)methIt.next();
+ if (!meth.isConcrete()) continue;
Body body = meth.retrieveActiveBody();
Stmt s = (Stmt)body.getUnits().getFirst();
while (s instanceof IdentityStmt){
s = (Stmt)body.getUnits().getSuccOf(s);
}
if (s.hasTag("LineNumberTag")){
LineNumberTag tag = (LineNumberTag)s.getTag("LineNumberTag");
lineToMeth.put(new Integer(tag.getLineNumber()), meth);
}
}
Iterator methIt2 = sc.getMethods().iterator();
while (methIt2.hasNext()){
SootMethod meth = (SootMethod)methIt2.next();
+ if (!meth.isConcrete()) continue;
Body body = meth.retrieveActiveBody();
Stmt s = (Stmt)body.getUnits().getFirst();
while (s instanceof IdentityStmt){
s = (Stmt)body.getUnits().getSuccOf(s);
}
if (s.hasTag("LineNumberTag")){
LineNumberTag tag = (LineNumberTag)s.getTag("LineNumberTag");
int line_num = tag.getLineNumber() - 1;
// already taken
if (lineToMeth.containsKey(new Integer(line_num))){
meth.addTag(new LineNumberTag(line_num + 1));
}
// still available - so use it for this meth
else {
meth.addTag(new LineNumberTag(line_num));
}
}
}
}
}
}
| false | true | public void internalTransform(String phaseName, Map opts){
Iterator it = Scene.v().getApplicationClasses().iterator();
while (it.hasNext()){
SootClass sc = (SootClass)it.next();
// make map of first line to each method
HashMap lineToMeth = new HashMap();
Iterator methIt = sc.getMethods().iterator();
while (methIt.hasNext()){
SootMethod meth = (SootMethod)methIt.next();
Body body = meth.retrieveActiveBody();
Stmt s = (Stmt)body.getUnits().getFirst();
while (s instanceof IdentityStmt){
s = (Stmt)body.getUnits().getSuccOf(s);
}
if (s.hasTag("LineNumberTag")){
LineNumberTag tag = (LineNumberTag)s.getTag("LineNumberTag");
lineToMeth.put(new Integer(tag.getLineNumber()), meth);
}
}
Iterator methIt2 = sc.getMethods().iterator();
while (methIt2.hasNext()){
SootMethod meth = (SootMethod)methIt2.next();
Body body = meth.retrieveActiveBody();
Stmt s = (Stmt)body.getUnits().getFirst();
while (s instanceof IdentityStmt){
s = (Stmt)body.getUnits().getSuccOf(s);
}
if (s.hasTag("LineNumberTag")){
LineNumberTag tag = (LineNumberTag)s.getTag("LineNumberTag");
int line_num = tag.getLineNumber() - 1;
// already taken
if (lineToMeth.containsKey(new Integer(line_num))){
meth.addTag(new LineNumberTag(line_num + 1));
}
// still available - so use it for this meth
else {
meth.addTag(new LineNumberTag(line_num));
}
}
}
}
}
| public void internalTransform(String phaseName, Map opts){
Iterator it = Scene.v().getApplicationClasses().iterator();
while (it.hasNext()){
SootClass sc = (SootClass)it.next();
// make map of first line to each method
HashMap lineToMeth = new HashMap();
Iterator methIt = sc.getMethods().iterator();
while (methIt.hasNext()){
SootMethod meth = (SootMethod)methIt.next();
if (!meth.isConcrete()) continue;
Body body = meth.retrieveActiveBody();
Stmt s = (Stmt)body.getUnits().getFirst();
while (s instanceof IdentityStmt){
s = (Stmt)body.getUnits().getSuccOf(s);
}
if (s.hasTag("LineNumberTag")){
LineNumberTag tag = (LineNumberTag)s.getTag("LineNumberTag");
lineToMeth.put(new Integer(tag.getLineNumber()), meth);
}
}
Iterator methIt2 = sc.getMethods().iterator();
while (methIt2.hasNext()){
SootMethod meth = (SootMethod)methIt2.next();
if (!meth.isConcrete()) continue;
Body body = meth.retrieveActiveBody();
Stmt s = (Stmt)body.getUnits().getFirst();
while (s instanceof IdentityStmt){
s = (Stmt)body.getUnits().getSuccOf(s);
}
if (s.hasTag("LineNumberTag")){
LineNumberTag tag = (LineNumberTag)s.getTag("LineNumberTag");
int line_num = tag.getLineNumber() - 1;
// already taken
if (lineToMeth.containsKey(new Integer(line_num))){
meth.addTag(new LineNumberTag(line_num + 1));
}
// still available - so use it for this meth
else {
meth.addTag(new LineNumberTag(line_num));
}
}
}
}
}
|
diff --git a/geogebra/geogebra/kernel/Kernel.java b/geogebra/geogebra/kernel/Kernel.java
index fdda9f158..e9e3d4834 100644
--- a/geogebra/geogebra/kernel/Kernel.java
+++ b/geogebra/geogebra/kernel/Kernel.java
@@ -1,7535 +1,7537 @@
/*
GeoGebra - Dynamic Mathematics for Everyone
http://www.geogebra.org
This file is part of GeoGebra.
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.
*/
/*
* Kernel.java
*
* Created on 30. August 2001, 20:12
*/
package geogebra.kernel;
import geogebra.cas.GeoGebraCAS;
import geogebra.euclidian.EuclidianConstants;
import geogebra.io.MyXMLHandler;
import geogebra.kernel.arithmetic.Equation;
import geogebra.kernel.arithmetic.ExpressionNode;
import geogebra.kernel.arithmetic.ExpressionNodeEvaluator;
import geogebra.kernel.arithmetic.Function;
import geogebra.kernel.arithmetic.FunctionNVar;
import geogebra.kernel.arithmetic.FunctionalNVar;
import geogebra.kernel.arithmetic.MyDouble;
import geogebra.kernel.arithmetic.NumberValue;
import geogebra.kernel.arithmetic.Polynomial;
import geogebra.kernel.commands.AlgebraProcessor;
import geogebra.kernel.discrete.AlgoConvexHull;
import geogebra.kernel.discrete.AlgoDelauneyTriangulation;
import geogebra.kernel.discrete.AlgoHull;
import geogebra.kernel.discrete.AlgoMinimumSpanningTree;
import geogebra.kernel.discrete.AlgoTravelingSalesman;
import geogebra.kernel.discrete.AlgoVoronoi;
import geogebra.kernel.optimization.ExtremumFinder;
import geogebra.kernel.parser.Parser;
import geogebra.kernel.statistics.AlgoCauchy;
import geogebra.kernel.statistics.AlgoChiSquared;
import geogebra.kernel.statistics.AlgoDoubleListCovariance;
import geogebra.kernel.statistics.AlgoDoubleListPMCC;
import geogebra.kernel.statistics.AlgoDoubleListSXX;
import geogebra.kernel.statistics.AlgoDoubleListSXY;
import geogebra.kernel.statistics.AlgoDoubleListSigmaXX;
import geogebra.kernel.statistics.AlgoDoubleListSigmaXY;
import geogebra.kernel.statistics.AlgoDoubleListSigmaYY;
import geogebra.kernel.statistics.AlgoExponential;
import geogebra.kernel.statistics.AlgoFDistribution;
import geogebra.kernel.statistics.AlgoFit;
import geogebra.kernel.statistics.AlgoFitExp;
import geogebra.kernel.statistics.AlgoFitGrowth;
import geogebra.kernel.statistics.AlgoFitLineX;
import geogebra.kernel.statistics.AlgoFitLineY;
import geogebra.kernel.statistics.AlgoFitLog;
import geogebra.kernel.statistics.AlgoFitLogistic;
import geogebra.kernel.statistics.AlgoFitPoly;
import geogebra.kernel.statistics.AlgoFitPow;
import geogebra.kernel.statistics.AlgoFitSin;
import geogebra.kernel.statistics.AlgoGamma;
import geogebra.kernel.statistics.AlgoHyperGeometric;
import geogebra.kernel.statistics.AlgoInverseCauchy;
import geogebra.kernel.statistics.AlgoInverseChiSquared;
import geogebra.kernel.statistics.AlgoInverseExponential;
import geogebra.kernel.statistics.AlgoInverseFDistribution;
import geogebra.kernel.statistics.AlgoInverseGamma;
import geogebra.kernel.statistics.AlgoInverseHyperGeometric;
import geogebra.kernel.statistics.AlgoInverseNormal;
import geogebra.kernel.statistics.AlgoInversePascal;
import geogebra.kernel.statistics.AlgoInverseTDistribution;
import geogebra.kernel.statistics.AlgoInverseWeibull;
import geogebra.kernel.statistics.AlgoInverseZipf;
import geogebra.kernel.statistics.AlgoListCovariance;
import geogebra.kernel.statistics.AlgoListMeanX;
import geogebra.kernel.statistics.AlgoListMeanY;
import geogebra.kernel.statistics.AlgoListPMCC;
import geogebra.kernel.statistics.AlgoListSXX;
import geogebra.kernel.statistics.AlgoListSXY;
import geogebra.kernel.statistics.AlgoListSYY;
import geogebra.kernel.statistics.AlgoListSigmaXX;
import geogebra.kernel.statistics.AlgoListSigmaXY;
import geogebra.kernel.statistics.AlgoListSigmaYY;
import geogebra.kernel.statistics.AlgoMean;
import geogebra.kernel.statistics.AlgoMedian;
import geogebra.kernel.statistics.AlgoMode;
import geogebra.kernel.statistics.AlgoNormal;
import geogebra.kernel.statistics.AlgoPascal;
import geogebra.kernel.statistics.AlgoProduct;
import geogebra.kernel.statistics.AlgoQ1;
import geogebra.kernel.statistics.AlgoQ3;
import geogebra.kernel.statistics.AlgoRSquare;
import geogebra.kernel.statistics.AlgoRandom;
import geogebra.kernel.statistics.AlgoRandomBinomial;
import geogebra.kernel.statistics.AlgoRandomNormal;
import geogebra.kernel.statistics.AlgoRandomPoisson;
import geogebra.kernel.statistics.AlgoRandomUniform;
import geogebra.kernel.statistics.AlgoRank;
import geogebra.kernel.statistics.AlgoSXX;
import geogebra.kernel.statistics.AlgoSample;
import geogebra.kernel.statistics.AlgoSampleStandardDeviation;
import geogebra.kernel.statistics.AlgoSampleVariance;
import geogebra.kernel.statistics.AlgoShuffle;
import geogebra.kernel.statistics.AlgoSigmaXX;
import geogebra.kernel.statistics.AlgoStandardDeviation;
import geogebra.kernel.statistics.AlgoSum;
import geogebra.kernel.statistics.AlgoSumSquaredErrors;
import geogebra.kernel.statistics.AlgoTDistribution;
import geogebra.kernel.statistics.AlgoVariance;
import geogebra.kernel.statistics.AlgoWeibull;
import geogebra.kernel.statistics.AlgoZipf;
import geogebra.kernel.statistics.RegressionMath;
import geogebra.main.Application;
import geogebra.main.MyError;
import geogebra.util.ScientificFormat;
import geogebra.util.Unicode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Stack;
import java.util.TreeSet;
import org.apache.commons.math.complex.Complex;
public class Kernel {
/** standard precision */
public final static double STANDARD_PRECISION = 1E-8;
/** minimum precision */
public final static double MIN_PRECISION = 1E-5;
private final static double INV_MIN_PRECISION = 1E5;
/** maximum reasonable precision */
public final static double MAX_PRECISION = 1E-12;
/** current working precision */
public static double EPSILON = STANDARD_PRECISION;
/** maximum precision of double numbers */
public final static double MAX_DOUBLE_PRECISION = 1E-15;
/** reciprocal of maximum precision of double numbers */
public final static double INV_MAX_DOUBLE_PRECISION = 1E15;
// style of point/vector coordinates
/** A = (3, 2) and B = (3; 90�)*/
public static final int COORD_STYLE_DEFAULT = 0;
/** A(3|2) and B(3; 90�)*/
public static final int COORD_STYLE_AUSTRIAN = 1;
/** A: (3, 2) and B: (3; 90�) */
public static final int COORD_STYLE_FRENCH = 2;
private int coordStyle = 0;
// STATIC
final public static int ANGLE_RADIANT = 1;
final public static int ANGLE_DEGREE = 2;
final public static int COORD_CARTESIAN = 3;
final public static int COORD_POLAR = 4;
final public static int COORD_COMPLEX = 5;
/** Unicode symbol for e */
final public static String EULER_STRING = "\u212f"; // "\u0435";
/** Unicode symbol for pi */
final public static String PI_STRING = "\u03c0";
final public static double PI_2 = 2.0 * Math.PI;
final public static double PI_HALF = Math.PI / 2.0;
final public static double SQRT_2_HALF = Math.sqrt(2.0) / 2.0;
final public static double PI_180 = Math.PI / 180;
final public static double CONST_180_PI = 180 / Math.PI;
//private static boolean KEEP_LEADING_SIGN = true;
//G.Sturr 2009-10-18
// algebra style
final public static int ALGEBRA_STYLE_VALUE = 0;
final public static int ALGEBRA_STYLE_DEFINITION = 1;
final public static int ALGEBRA_STYLE_COMMAND = 2;
private int algebraStyle = Kernel.ALGEBRA_STYLE_VALUE;
//end G.Sturr
// print precision
public static final int STANDARD_PRINT_DECIMALS = 2;
private double PRINT_PRECISION = 1E-2;
private NumberFormat nf;
private ScientificFormat sf;
public boolean useSignificantFigures = false;
// angle unit: degree, radians
private int angleUnit = Kernel.ANGLE_DEGREE;
// rounding hack, see format()
private static final double ROUND_HALF_UP_FACTOR_DEFAULT = 1.0 + 1E-15;
private double ROUND_HALF_UP_FACTOR = ROUND_HALF_UP_FACTOR_DEFAULT;
// used to store info when rounding is temporarily changed
private Stack<Boolean> useSignificantFiguresList;
private Stack<Integer> noOfSignificantFiguresList;
private Stack<Integer> noOfDecimalPlacesList;
/* Significant figures
*
* How to do:
*
* private ScientificFormat sf;
* sf = new ScientificFormat(5, 20, false);
* String s = sf.format(double)
*
* need to address:
*
* PRINT_PRECISION
* setPrintDecimals()
* getPrintDecimals()
* getMaximumFractionDigits()
* setMaximumFractionDigits()
*
* how to determine whether to use nf or sf
*/
private int casPrintForm;
private String casPrintFormPI; // for pi
// before May 23, 2005 the function acos(), asin() and atan()
// had an angle as result. Now the result is a number.
// this flag is used to distinguish the different behaviour
// depending on the the age of saved construction files
/** if true, cyclometric functions return GeoAngle, if false, they return GeoNumeric**/
public boolean arcusFunctionCreatesAngle = false;
private boolean translateCommandName = true;
private boolean undoActive = false;
private boolean notifyViewsActive = true;
private boolean viewReiniting = false;
private boolean allowVisibilitySideEffects = true;
// silentMode is used to create helper objects without any side effects
// i.e. in silentMode no labels are created and no objects are added to views
private boolean silentMode = false;
// setResolveUnkownVarsAsDummyGeos
private boolean resolveUnkownVarsAsDummyGeos = false;
private double xmin, xmax, ymin, ymax, xscale, yscale;
// Views may register to be informed about
// changes to the Kernel
// (add, remove, update)
private View[] views = new View[20];
private int viewCnt = 0;
protected Construction cons;
protected Application app;
protected AlgebraProcessor algProcessor;
private EquationSolver eqnSolver;
private RegressionMath regMath;
private ExtremumFinder extrFinder;
protected Parser parser;
private Object ggbCAS;
// Continuity on or off, default: false since V3.0
private boolean continuous = false;
private MacroManager macroManager;
/** Evaluator for ExpressionNode */
protected ExpressionNodeEvaluator expressionNodeEvaluator;
public Kernel(Application app) {
this();
this.app = app;
newConstruction();
newExpressionNodeEvaluator();
}
/**
* creates the construction cons
*/
protected void newConstruction(){
cons = new Construction(this);
}
/**
* creates a new MyXMLHandler (used for 3D)
* @param cons construction used in MyXMLHandler constructor
* @return a new MyXMLHandler
*/
public MyXMLHandler newMyXMLHandler(Construction cons){
return new MyXMLHandler(this, cons);
}
/**
* creates the Evaluator for ExpressionNode
*/
protected void newExpressionNodeEvaluator(){
expressionNodeEvaluator = new ExpressionNodeEvaluator();
}
/** return the Evaluator for ExpressionNode
* @return the Evaluator for ExpressionNode
*/
public ExpressionNodeEvaluator getExpressionNodeEvaluator(){
if (expressionNodeEvaluator == null)
newExpressionNodeEvaluator();
return expressionNodeEvaluator;
}
public Kernel() {
nf = NumberFormat.getInstance(Locale.ENGLISH);
nf.setGroupingUsed(false);
sf = new ScientificFormat(5, 16, false);
setCASPrintForm(ExpressionNode.STRING_TYPE_GEOGEBRA);
}
/**
* Returns this kernel's algebra processor that handles
* all input and commands.
* @return Algebra processor
*/
public AlgebraProcessor getAlgebraProcessor() {
if (algProcessor == null)
algProcessor = new AlgebraProcessor(this);
return algProcessor;
}
/**
* Returns a GeoElement for the given label.
* @return may return null
*/
final public GeoElement lookupLabel(String label) {
return lookupLabel(label, false);
}
/**
* Finds element with given the label and possibly creates it
* @param label Label of element we are looking for
* @param autoCreate true iff new geo should be created if missing
* @return GeoElement with given label
*/
final public GeoElement lookupLabel(String label, boolean autoCreate) {
GeoElement geo = cons.lookupLabel(label, autoCreate);
if (geo == null && resolveUnkownVarsAsDummyGeos) {
// resolve unknown variable as dummy geo to keep its name and
// avoid an "unknown variable" error message
geo = new GeoDummyVariable(cons, label);
}
return geo;
}
/**
* returns GeoElement at (row,col) in spreadsheet
* may return nully
* @param col Spreadsheet column
* @param row Spreadsheet row
* @return Spreadsheet cell content (may be null)
*/
public GeoElement getGeoAt(int col, int row) {
return lookupLabel(GeoElement.getSpreadsheetCellName(col, row));
}
final public GeoAxis getXAxis() {
return cons.getXAxis();
}
final public GeoAxis getYAxis() {
return cons.getYAxis();
}
final public boolean isAxis(GeoElement geo) {
return (geo == cons.getXAxis() || geo == cons.getYAxis());
}
public void updateLocalAxesNames() {
cons.updateLocalAxesNames();
}
final public Application getApplication() {
return app;
}
public void setShowOnlyBreakpoints(boolean flag) {
cons.setShowOnlyBreakpoints(flag);
}
final public boolean showOnlyBreakpoints() {
return cons.showOnlyBreakpoints();
}
final public EquationSolver getEquationSolver() {
if (eqnSolver == null)
eqnSolver = new EquationSolver(this);
return eqnSolver;
}
final public ExtremumFinder getExtremumFinder() {
if (extrFinder == null)
extrFinder = new ExtremumFinder();
return extrFinder;
}
final public RegressionMath getRegressionMath() {
if (regMath == null)
regMath = new RegressionMath();
return regMath;
}
final public Parser getParser() {
if (parser == null)
parser = new Parser(this, cons);
return parser;
}
/**
* Evaluates an expression in GeoGebraCAS syntax.
* @return result string (null possible)
* @throws Throwable
*/
final public String evaluateGeoGebraCAS(String exp) throws Throwable {
if (ggbCAS == null) {
getGeoGebraCAS();
}
return ((geogebra.cas.GeoGebraCAS) ggbCAS).evaluateGeoGebraCAS(exp);
}
/**
* Evaluates an expression in MathPiper syntax with.
* @return result string (null possible)
* @throws Throwable
*/
final public String evaluateMathPiper(String exp) {
if (ggbCAS == null) {
getGeoGebraCAS();
}
return ((geogebra.cas.GeoGebraCAS) ggbCAS).evaluateMathPiper(exp);
}
/**
* Evaluates an expression in Maxima syntax with.
* @return result string (null possible)
* @throws Throwable
*/
final public String evaluateMaxima(String exp) {
if (ggbCAS == null) {
getGeoGebraCAS();
}
return ((geogebra.cas.GeoGebraCAS) ggbCAS).evaluateMaxima(exp);
}
/**
* Returns whether var is a defined variable in GeoGebraCAS.
*/
final public boolean isCASVariableBound(String var) {
if (ggbCAS == null) {
return false;
} else {
return ((geogebra.cas.GeoGebraCAS) ggbCAS).isVariableBound(var);
}
}
final public boolean isGeoGebraCASready() {
return ggbCAS != null;
}
public static int DEFAULT_CAS = Application.CAS_MATHPIPER; // default
/*
* needed eg change MathPiper -> Maxima
*/
final public void setDefaultCAS(int cas) {
DEFAULT_CAS = cas;
if (ggbCAS != null) ((geogebra.cas.GeoGebraCAS) ggbCAS).setCurrentCAS(DEFAULT_CAS);
}
/**
* Returns this kernel's GeoGebraCAS object.
*/
public synchronized Object getGeoGebraCAS() {
if (ggbCAS == null) {
ggbCAS = new geogebra.cas.GeoGebraCAS(this);
}
return ggbCAS;
}
/**
* Finds the polynomial coefficients of
* the given expression and returns it in ascending order.
* If exp is not a polynomial null is returned.
*
* example: getPolynomialCoeffs("3*a*x^2 + b"); returns
* ["0", "b", "3*a"]
*/
final public String [] getPolynomialCoeffs(String exp, String variable) {
if (ggbCAS == null) {
getGeoGebraCAS();
}
return ((geogebra.cas.GeoGebraCAS) ggbCAS).getPolynomialCoeffs(exp, variable);
}
final public void setEpsilon(double epsilon) {
EPSILON = epsilon;
if (EPSILON > MIN_PRECISION)
EPSILON = MIN_PRECISION;
else if (EPSILON < MAX_PRECISION)
EPSILON = MAX_PRECISION;
getEquationSolver().setEpsilon(EPSILON);
}
/**
* Sets the working epsilon precision according to the given
* print precision. After this method epsilon will always be
* less or equal STANDARD_PRECISION.
* @param printPrecision
*/
private void setEpsilonForPrintPrecision(double printPrecision) {
if (printPrecision < STANDARD_PRECISION) {
setEpsilon(printPrecision);
} else {
setEpsilon(STANDARD_PRECISION);
}
}
final public double getEpsilon() {
return EPSILON;
}
final public void setMinPrecision() {
setEpsilon(MIN_PRECISION);
}
final public void resetPrecision() {
setEpsilon(STANDARD_PRECISION);
}
/**
* Tells this kernel about the bounds and the scales for x-Axis and y-Axis used
* in EudlidianView. The scale is the number of pixels per unit.
* (useful for some algorithms like findminimum). All
*/
final public void setEuclidianViewBounds(double xmin, double xmax,
double ymin, double ymax, double xscale, double yscale) {
this.xmin = xmin;
this.xmax = xmax;
this.ymin = ymin;
this.ymax = ymax;
this.xscale = xscale;
this.yscale = yscale;
notifyEuclidianViewAlgos();
}
private void notifyEuclidianViewAlgos() {
if (macroManager != null)
macroManager.notifyEuclidianViewAlgos();
cons.notifyEuclidianViewAlgos();
}
double getXmax() {
return xmax;
}
double getXmin() {
return xmin;
}
double getXscale() {
return xscale;
}
double getYmax() {
return ymax;
}
double getYmin() {
return ymin;
}
double getYscale() {
return yscale;
}
/**
* Registers an algorithm that needs to be updated when notifyRename(),
* notifyAdd(), or notifyRemove() is called.
*/
void registerRenameListenerAlgo(AlgoElement algo) {
if (renameListenerAlgos == null) {
renameListenerAlgos = new ArrayList();
}
if (!renameListenerAlgos.contains(algo))
renameListenerAlgos.add(algo);
}
void unregisterRenameListenerAlgo(AlgoElement algo) {
if (renameListenerAlgos != null)
renameListenerAlgos.remove(algo);
}
private ArrayList renameListenerAlgos;
private void notifyRenameListenerAlgos() {
AlgoElement.updateCascadeAlgos(renameListenerAlgos);
}
//G.Sturr 2009-10-18
final public void setAlgebraStyle(int style) {
algebraStyle = style;
}
final public int getAlgebraStyle() {
return algebraStyle;
}
//end G.Sturr
final public void setAngleUnit(int unit) {
angleUnit = unit;
}
final public int getAngleUnit() {
return angleUnit;
}
final public int getMaximumFractionDigits() {
return nf.getMaximumFractionDigits();
}
final public void setMaximumFractionDigits(int digits) {
//Application.debug(""+digits);
useSignificantFigures = false;
nf.setMaximumFractionDigits(digits);
}
final public String getPiString() {
return casPrintFormPI;
}
final public void setCASPrintForm(int type) {
casPrintForm = type;
switch (casPrintForm) {
case ExpressionNode.STRING_TYPE_MATH_PIPER:
casPrintFormPI = "Pi";
break;
case ExpressionNode.STRING_TYPE_MAXIMA:
casPrintFormPI = "%pi";
break;
case ExpressionNode.STRING_TYPE_JASYMCA:
case ExpressionNode.STRING_TYPE_GEOGEBRA_XML:
casPrintFormPI = "pi";
break;
default:
casPrintFormPI = PI_STRING;
}
}
final public int getCASPrintForm() {
return casPrintForm;
}
final public int getCurrentCAS() {
return ((GeoGebraCAS)getGeoGebraCAS()).currentCAS;
}
final public void setPrintDecimals(int decimals) {
if (decimals >= 0) {
useSignificantFigures = false;
nf.setMaximumFractionDigits(decimals);
ROUND_HALF_UP_FACTOR = decimals < 15 ? ROUND_HALF_UP_FACTOR_DEFAULT : 1;
PRINT_PRECISION = Math.pow(10, -decimals);
setEpsilonForPrintPrecision(PRINT_PRECISION);
}
}
final public int getPrintDecimals() {
return nf.getMaximumFractionDigits();
}
final public void setPrintFigures(int figures) {
if (figures >= 0) {
useSignificantFigures = true;
sf.setSigDigits(figures);
sf.setMaxWidth(16); // for scientific notation
ROUND_HALF_UP_FACTOR = figures < 15 ? ROUND_HALF_UP_FACTOR_DEFAULT : 1;
PRINT_PRECISION = MAX_PRECISION;
setEpsilonForPrintPrecision(PRINT_PRECISION);
}
}
/**
* Sets the print accuracy to at least the given decimals
* or significant figures. If the current accuracy is already higher, nothing is changed.
*
* @param decimalsOrFigures
* @return whether the print accuracy was changed
*/
public boolean ensureTemporaryPrintAccuracy(int decimalsOrFigures) {
if (useSignificantFigures) {
if (sf.getSigDigits() < decimalsOrFigures) {
setTemporaryPrintFigures(decimalsOrFigures);
return true;
}
} else {
// decimals
if (nf.getMaximumFractionDigits() < decimalsOrFigures) {
setTemporaryPrintDecimals(decimalsOrFigures);
return true;
}
}
return false;
}
final public void setTemporaryPrintFigures(int figures) {
storeTemporaryRoundingInfoInList();
setPrintFigures(figures);
}
final public void setTemporaryPrintDecimals(int decimals) {
storeTemporaryRoundingInfoInList();
setPrintDecimals(decimals);
}
/*
* stores information about the current no of decimal places/sig figures used
* for when it is (temporarily changed)
* needs to be in a list as it can be nested
*/
private void storeTemporaryRoundingInfoInList()
{
if (useSignificantFiguresList == null) {
useSignificantFiguresList = new Stack<Boolean>();
noOfSignificantFiguresList = new Stack<Integer>();
noOfDecimalPlacesList = new Stack<Integer>();
}
useSignificantFiguresList.push(new Boolean(useSignificantFigures));
noOfSignificantFiguresList.push(new Integer(sf.getSigDigits()));
noOfDecimalPlacesList.push(new Integer(nf.getMaximumFractionDigits()));
}
/**
* gets previous values of print acuracy from stacks
*/
final public void restorePrintAccuracy()
{
useSignificantFigures = useSignificantFiguresList.pop().booleanValue();
int sigFigures = noOfSignificantFiguresList.pop().intValue();
int decDigits = noOfDecimalPlacesList.pop().intValue();
if (useSignificantFigures)
setPrintFigures(sigFigures);
else
setPrintDecimals(decDigits);
//Application.debug("list size"+noOfSignificantFiguresList.size());
}
/*
* returns number of significant digits, or -1 if using decimal places
*/
final public int getPrintFigures() {
if (!useSignificantFigures) return -1;
return sf.getSigDigits();
}
/**
* returns 10^(-PrintDecimals)
*
final public double getPrintPrecision() {
return PRINT_PRECISION;
} */
final public int getCoordStyle() {
return coordStyle;
}
public void setCoordStyle(int coordStlye) {
coordStyle = coordStlye;
}
/*
* GeoElement specific
*/
/**
* Creates a new GeoElement object for the given type string.
* @param type: String as produced by GeoElement.getXMLtypeString()
*/
public GeoElement createGeoElement(Construction cons, String type) throws MyError {
// the type strings are the classnames in lowercase without the beginning "geo"
// due to a bug in GeoGebra 2.6c the type strings for conics
// in XML may be "ellipse", "hyperbola", ...
switch (type.charAt(0)) {
case 'a': //angle
return new GeoAngle(cons);
case 'b': //angle
if (type.equals("boolean"))
return new GeoBoolean(cons);
else
return new GeoButton(cons); // "button"
case 'c': // conic
if (type.equals("conic"))
return new GeoConic(cons);
else if (type.equals("conicpart"))
return new GeoConicPart(cons, 0);
else if (type.equals("circle")) { // bug in GeoGebra 2.6c
return new GeoConic(cons);
}
case 'd': // doubleLine // bug in GeoGebra 2.6c
return new GeoConic(cons);
case 'e': // ellipse, emptyset // bug in GeoGebra 2.6c
return new GeoConic(cons);
case 'f': // function
return new GeoFunction(cons);
case 'h': // hyperbola // bug in GeoGebra 2.6c
return new GeoConic(cons);
case 'i': // image,implicitpoly
if (type.equals("image"))
return new GeoImage(cons);
else if (type.equals("intersectinglines")) // bug in GeoGebra 2.6c
return new GeoConic(cons);
else if (type.equals("implicitpoly"))
return new GeoImplicitPoly(cons);
case 'l': // line, list, locus
if (type.equals("line"))
return new GeoLine(cons);
else if (type.equals("list"))
return new GeoList(cons);
else if (type.equals("linearinequality"))
return new GeoLinearInequality(cons, null);
else
return new GeoLocus(cons);
case 'n': // numeric
return new GeoNumeric(cons);
case 'p': // point, polygon
if (type.equals("point"))
return new GeoPoint(cons);
else if (type.equals("polygon"))
return new GeoPolygon(cons, null);
else if (type.equals("polyline"))
return new GeoPolyLine(cons, null);
else // parabola, parallelLines, point // bug in GeoGebra 2.6c
return new GeoConic(cons);
case 'r': // ray
return new GeoRay(cons, null);
case 's': // segment
return new GeoSegment(cons, null, null);
case 't':
if (type.equals("text"))
return new GeoText(cons); // text
else
return new GeoTextField(cons); // textfield
case 'v': // vector
return new GeoVector(cons);
default:
throw new MyError(cons.getApplication(), "Kernel: GeoElement of type "
+ type + " could not be created.");
}
}
/* *******************************************
* Methods for EuclidianView/EuclidianView3D
* ********************************************/
public String getModeText(int mode) {
switch (mode) {
case EuclidianConstants.MODE_SELECTION_LISTENER:
return "Select";
case EuclidianConstants.MODE_MOVE:
return "Move";
case EuclidianConstants.MODE_POINT:
return "Point";
case EuclidianConstants.MODE_POINT_IN_REGION:
return "PointInRegion";
case EuclidianConstants.MODE_JOIN:
return "Join";
case EuclidianConstants.MODE_SEGMENT:
return "Segment";
case EuclidianConstants.MODE_SEGMENT_FIXED:
return "SegmentFixed";
case EuclidianConstants.MODE_RAY:
return "Ray";
case EuclidianConstants.MODE_POLYGON:
return "Polygon";
case EuclidianConstants.MODE_POLYLINE:
return "PolyLine";
case EuclidianConstants.MODE_RIGID_POLYGON:
return "RigidPolygon";
case EuclidianConstants.MODE_PARALLEL:
return "Parallel";
case EuclidianConstants.MODE_ORTHOGONAL:
return "Orthogonal";
case EuclidianConstants.MODE_INTERSECT:
return "Intersect";
case EuclidianConstants.MODE_LINE_BISECTOR:
return "LineBisector";
case EuclidianConstants.MODE_ANGULAR_BISECTOR:
return "AngularBisector";
case EuclidianConstants.MODE_TANGENTS:
return "Tangent";
case EuclidianConstants.MODE_POLAR_DIAMETER:
return "PolarDiameter";
case EuclidianConstants.MODE_CIRCLE_TWO_POINTS:
return "Circle2";
case EuclidianConstants.MODE_CIRCLE_THREE_POINTS:
return "Circle3";
case EuclidianConstants.MODE_ELLIPSE_THREE_POINTS:
return "Ellipse3";
case EuclidianConstants.MODE_PARABOLA:
return "Parabola";
case EuclidianConstants.MODE_HYPERBOLA_THREE_POINTS:
return "Hyperbola3";
// Michael Borcherds 2008-03-13
case EuclidianConstants.MODE_COMPASSES:
return "Compasses";
case EuclidianConstants.MODE_CONIC_FIVE_POINTS:
return "Conic5";
case EuclidianConstants.MODE_RELATION:
return "Relation";
case EuclidianConstants.MODE_TRANSLATEVIEW:
return "TranslateView";
case EuclidianConstants.MODE_SHOW_HIDE_OBJECT:
return "ShowHideObject";
case EuclidianConstants.MODE_SHOW_HIDE_LABEL:
return "ShowHideLabel";
case EuclidianConstants.MODE_COPY_VISUAL_STYLE:
return "CopyVisualStyle";
case EuclidianConstants.MODE_DELETE:
return "Delete";
case EuclidianConstants.MODE_VECTOR:
return "Vector";
case EuclidianConstants.MODE_TEXT:
return "Text";
case EuclidianConstants.MODE_IMAGE:
return "Image";
case EuclidianConstants.MODE_MIDPOINT:
return "Midpoint";
case EuclidianConstants.MODE_SEMICIRCLE:
return "Semicircle";
case EuclidianConstants.MODE_CIRCLE_ARC_THREE_POINTS:
return "CircleArc3";
case EuclidianConstants.MODE_CIRCLE_SECTOR_THREE_POINTS:
return "CircleSector3";
case EuclidianConstants.MODE_CIRCUMCIRCLE_ARC_THREE_POINTS:
return "CircumcircleArc3";
case EuclidianConstants.MODE_CIRCUMCIRCLE_SECTOR_THREE_POINTS:
return "CircumcircleSector3";
case EuclidianConstants.MODE_SLIDER:
return "Slider";
case EuclidianConstants.MODE_MIRROR_AT_POINT:
return "MirrorAtPoint";
case EuclidianConstants.MODE_MIRROR_AT_LINE:
return "MirrorAtLine";
case EuclidianConstants.MODE_MIRROR_AT_CIRCLE:
return "MirrorAtCircle";
case EuclidianConstants.MODE_TRANSLATE_BY_VECTOR:
return "TranslateByVector";
case EuclidianConstants.MODE_ROTATE_BY_ANGLE:
return "RotateByAngle";
case EuclidianConstants.MODE_DILATE_FROM_POINT:
return "DilateFromPoint";
case EuclidianConstants.MODE_CIRCLE_POINT_RADIUS:
return "CirclePointRadius";
case EuclidianConstants.MODE_ANGLE:
return "Angle";
case EuclidianConstants.MODE_ANGLE_FIXED:
return "AngleFixed";
case EuclidianConstants.MODE_VECTOR_FROM_POINT:
return "VectorFromPoint";
case EuclidianConstants.MODE_DISTANCE:
return "Distance";
case EuclidianConstants.MODE_MOVE_ROTATE:
return "MoveRotate";
case EuclidianConstants.MODE_ZOOM_IN:
return "ZoomIn";
case EuclidianConstants.MODE_ZOOM_OUT:
return "ZoomOut";
case EuclidianConstants.MODE_LOCUS:
return "Locus";
case EuclidianConstants.MODE_AREA:
return "Area";
case EuclidianConstants.MODE_SLOPE:
return "Slope";
case EuclidianConstants.MODE_REGULAR_POLYGON:
return "RegularPolygon";
case EuclidianConstants.MODE_SHOW_HIDE_CHECKBOX:
return "ShowCheckBox";
case EuclidianConstants.MODE_BUTTON_ACTION:
return "ButtonAction";
case EuclidianConstants.MODE_TEXTFIELD_ACTION:
return "TextFieldAction";
case EuclidianConstants.MODE_PEN:
return "Pen";
case EuclidianConstants.MODE_VISUAL_STYLE:
return "VisualStyle";
case EuclidianConstants.MODE_FITLINE:
return "FitLine";
case EuclidianConstants.MODE_RECORD_TO_SPREADSHEET:
return "RecordToSpreadsheet";
case EuclidianConstants.MODE_PROBABILITY_CALCULATOR:
return "ProbabilityCalculator";
// CAS
case EuclidianConstants.MODE_CAS_EVALUATE:
return "Evaluate";
case EuclidianConstants.MODE_CAS_NUMERIC:
return "Numeric";
case EuclidianConstants.MODE_CAS_KEEP_INPUT:
return "KeepInput";
case EuclidianConstants.MODE_CAS_EXPAND:
return "Expand";
case EuclidianConstants.MODE_CAS_FACTOR:
return "Factor";
case EuclidianConstants.MODE_CAS_SUBSTITUTE:
return "Substitute";
case EuclidianConstants.MODE_CAS_SOLVE:
return "Solve";
case EuclidianConstants.MODE_CAS_DERIVATIVE:
return "Derivative";
case EuclidianConstants.MODE_CAS_INTEGRAL:
return "Integral";
default:
return "";
}
}
/* *******************************************
* Methods for MyXMLHandler
* ********************************************/
public boolean handleCoords(GeoElement geo, LinkedHashMap<String, String> attrs) {
if (!(geo instanceof GeoVec3D)) {
Application.debug("wrong element type for <coords>: "
+ geo.getClass());
return false;
}
GeoVec3D v = (GeoVec3D) geo;
try {
double x = Double.parseDouble((String) attrs.get("x"));
double y = Double.parseDouble((String) attrs.get("y"));
double z = Double.parseDouble((String) attrs.get("z"));
v.setCoords(x, y, z);
return true;
} catch (Exception e) {
return false;
}
}
/* *******************************************
* Construction specific methods
* ********************************************/
/**
* Returns the ConstructionElement for the given GeoElement.
* If geo is independent geo itself is returned. If geo is dependent
* it's parent algorithm is returned.
*/
public static ConstructionElement getConstructionElement(GeoElement geo) {
AlgoElement algo = geo.getParentAlgorithm();
if (algo == null)
return geo;
else
return algo;
}
/**
* Returns the Construction object of this kernel.
*/
public Construction getConstruction() {
return cons;
}
/**
* Returns the ConstructionElement for the given construction index.
*/
public ConstructionElement getConstructionElement(int index) {
return cons.getConstructionElement(index);
}
public void setConstructionStep(int step) {
if (cons.getStep() != step) {
cons.setStep(step);
app.setUnsaved();
}
}
public int getConstructionStep() {
return cons.getStep();
}
public int getLastConstructionStep() {
return cons.steps() - 1;
}
/**
* Sets construction step to
* first step of construction protocol.
* Note: showOnlyBreakpoints() is important here
*/
public void firstStep() {
int step = 0;
if (showOnlyBreakpoints()) {
setConstructionStep(getNextBreakpoint(step));
} else {
setConstructionStep(step);
}
}
/**
* Sets construction step to
* last step of construction protocol.
* Note: showOnlyBreakpoints() is important here
*/
public void lastStep() {
int step = getLastConstructionStep();
if (showOnlyBreakpoints()) {
setConstructionStep(getPreviousBreakpoint(step));
} else {
setConstructionStep(step);
}
}
/**
* Sets construction step to
* next step of construction protocol.
* Note: showOnlyBreakpoints() is important here
*/
public void nextStep() {
int step = cons.getStep() + 1;
if (showOnlyBreakpoints()) {
setConstructionStep(getNextBreakpoint(step));
} else {
setConstructionStep(step);
}
}
private int getNextBreakpoint(int step) {
int lastStep = getLastConstructionStep();
// go to next breakpoint
while (step <= lastStep) {
if (cons.getConstructionElement(step).isConsProtocolBreakpoint()) {
return step;
}
step++;
}
return lastStep;
}
/**
* Sets construction step to
* previous step of construction protocol
* Note: showOnlyBreakpoints() is important here
*/
public void previousStep() {
int step = cons.getStep() - 1;
if (showOnlyBreakpoints()) {
cons.setStep(getPreviousBreakpoint(step));
}
else {
cons.setStep(step);
}
}
private int getPreviousBreakpoint(int step) {
// go to previous breakpoint
while (step >= 0) {
if (cons.getConstructionElement(step).isConsProtocolBreakpoint())
return step;
step--;
}
return -1;
}
/**
* Move object at position from to position to in current construction.
*/
public boolean moveInConstructionList(int from, int to) {
return cons.moveInConstructionList(from, to);
}
public void clearConstruction() {
if (macroManager != null)
macroManager.setAllMacrosUnused();
// clear animations
if (animationManager != null) {
animationManager.stopAnimation();
animationManager.clearAnimatedGeos();
}
cons.clearConstruction();
notifyClearView();
notifyRepaint();
System.gc();
}
public void updateConstruction() {
cons.updateConstruction();
notifyRepaint();
}
/**
* Tests if the current construction has no elements.
* @return true if the current construction has no GeoElements; false otherwise.
*/
public boolean isEmpty() {
return cons.isEmpty();
}
/* ******************************
* redo / undo for current construction
* ******************************/
public void setUndoActive(boolean flag) {
undoActive = flag;
}
public boolean isUndoActive() {
return undoActive;
}
public void storeUndoInfo() {
if (undoActive) {
cons.storeUndoInfo();
}
}
public void restoreCurrentUndoInfo() {
if (undoActive) cons.restoreCurrentUndoInfo();
}
public void initUndoInfo() {
if (undoActive) cons.initUndoInfo();
}
public void redo() {
if (undoActive){
notifyReset();
cons.redo();
notifyReset();
}
}
public void undo() {
if (undoActive) {
notifyReset();
cons.undo();
notifyReset();
}
}
public boolean undoPossible() {
return undoActive && cons.undoPossible();
}
public boolean redoPossible() {
return undoActive && cons.redoPossible();
}
/* *******************************************************
* methods for view-Pattern (Model-View-Controller)
* *******************************************************/
public void attach(View view) {
// Application.debug("ATTACH " + view + ", notifyActive: " + notifyViewsActive);
if (!notifyViewsActive) {
viewCnt = oldViewCnt;
}
// view already attached?
boolean viewFound = false;
for (int i = 0; i < viewCnt; i++) {
if (views[i] == view) {
viewFound = true;
break;
}
}
if (!viewFound) {
// new view
views[viewCnt++] = view;
}
//TODO: remove
System.out.print(" current views:\n");
for (int i = 0; i < viewCnt; i++) {
System.out.print(views[i] + "\n");
}
System.out.print("\n");
//Application.debug();
if (!notifyViewsActive) {
oldViewCnt = viewCnt;
viewCnt = 0;
}
}
public void detach(View view) {
// Application.debug("detach " + view);
if (!notifyViewsActive) {
viewCnt = oldViewCnt;
}
int pos = -1;
for (int i = 0; i < viewCnt; ++i) {
if (views[i] == view) {
pos = i;
views[pos] = null; // delete view
break;
}
}
// view found
if (pos > -1) {
// copy following views
viewCnt--;
for (; pos < viewCnt; ++pos) {
views[pos] = views[pos + 1];
}
}
/*
System.out.print(" current views: ");
for (int i = 0; i < viewCnt; i++) {
System.out.print(views[i] + ", ");
}
Application.debug();
*/
if (!notifyViewsActive) {
oldViewCnt = viewCnt;
viewCnt = 0;
}
}
/**
* Notify the views that the mode changed.
*
* @param mode
*/
final public void notifyModeChanged(int mode) {
for(int i = 0; i < viewCnt; ++i) {
views[i].setMode(mode);
}
}
final public void notifyAddAll(View view) {
int consStep = cons.getStep();
notifyAddAll(view, consStep);
}
final public void notifyAddAll(View view, int consStep) {
if (!notifyViewsActive) return;
Iterator it = cons.getGeoSetConstructionOrder().iterator();
while (it.hasNext()) {
GeoElement geo = (GeoElement) it.next();
// stop when not visible for current construction step
if (!geo.isAvailableAtConstructionStep(consStep))
break;
view.add(geo);
}
}
// final public void notifyRemoveAll(View view) {
// Iterator it = cons.getGeoSetConstructionOrder().iterator();
// while (it.hasNext()) {
// GeoElement geo = (GeoElement) it.next();
// view.remove(geo);
// }
// }
/**
* Tells views to update all labeled elements of current construction.
*
final public static void notifyUpdateAll() {
notifyUpdate(kernelConstruction.getAllGeoElements());
}*/
final void notifyAdd(GeoElement geo) {
if (notifyViewsActive) {
for (int i = 0; i < viewCnt; ++i) {
views[i].add(geo);
}
}
notifyRenameListenerAlgos();
}
final void notifyRemove(GeoElement geo) {
if (notifyViewsActive) {
for (int i = 0; i < viewCnt; ++i) {
views[i].remove(geo);
}
}
notifyRenameListenerAlgos();
}
protected final void notifyUpdate(GeoElement geo) {
if (notifyViewsActive) {
for (int i = 0; i < viewCnt; ++i) {
views[i].update(geo);
}
}
}
final void notifyUpdateAuxiliaryObject(GeoElement geo) {
if (notifyViewsActive) {
for (int i = 0; i < viewCnt; ++i) {
views[i].updateAuxiliaryObject(geo);
}
}
}
final void notifyRename(GeoElement geo) {
if (notifyViewsActive) {
for (int i = 0; i < viewCnt; ++i) {
views[i].rename(geo);
}
}
notifyRenameListenerAlgos();
}
public void setNotifyViewsActive(boolean flag) {
//Application.debug("setNotifyViews: " + flag);
if (flag != notifyViewsActive) {
notifyViewsActive = flag;
if (flag) {
//Application.debug("Activate VIEWS");
viewReiniting = true;
// "attach" views again
viewCnt = oldViewCnt;
// add all geos to all views
Iterator it = cons.getGeoSetConstructionOrder().iterator();
while (it.hasNext()) {
GeoElement geo = (GeoElement) it.next();
notifyAdd(geo);
}
/*
Object [] geos =
getConstruction().getGeoSetConstructionOrder().toArray();
for (int i = 0 ; i < geos.length ; i++) {
GeoElement geo = (GeoElement) geos[i];
notifyAdd(geo);
}*/
//app.setMoveMode();
notifyEuclidianViewAlgos();
notifyReset();
viewReiniting = false;
}
else {
//Application.debug("Deactivate VIEWS");
// "detach" views
notifyClearView();
oldViewCnt = viewCnt;
viewCnt = 0;
}
}
}
private int oldViewCnt;
public boolean isNotifyViewsActive() {
return notifyViewsActive && !viewReiniting;
}
public boolean isViewReiniting() {
return viewReiniting;
}
private boolean notifyRepaint = true;
public void setNotifyRepaintActive(boolean flag) {
if (flag != notifyRepaint) {
notifyRepaint = flag;
if (notifyRepaint)
notifyRepaint();
}
}
final public boolean isNotifyRepaintActive() {
return notifyRepaint;
}
public final void notifyRepaint() {
if (notifyRepaint) {
for (int i = 0; i < viewCnt; ++i) {
views[i].repaintView();
}
}
}
final void notifyReset() {
for (int i = 0; i < viewCnt; ++i) {
views[i].reset();
}
}
final void notifyClearView() {
for (int i = 0; i < viewCnt; ++i) {
views[i].clearView();
}
}
/* **********************************
* MACRO handling
* **********************************/
/**
* Creates a new macro within the kernel. A macro is a user defined
* command in GeoGebra.
*/
public void addMacro(Macro macro) {
if (macroManager == null) {
macroManager = new MacroManager();
}
macroManager.addMacro(macro);
}
/**
* Removes a macro from the kernel.
*/
public void removeMacro(Macro macro) {
if (macroManager != null)
macroManager.removeMacro(macro);
}
/**
* Removes all macros from the kernel.
*/
public void removeAllMacros() {
if (macroManager != null) {
app.removeMacroCommands();
macroManager.removeAllMacros();
}
}
/**
* Sets the command name of a macro. Note: if the given name is
* already used nothing is done.
* @return if the command name was really set
*/
public boolean setMacroCommandName(Macro macro, String cmdName) {
boolean nameUsed = macroManager.getMacro(cmdName) != null;
if (nameUsed || cmdName == null || cmdName.length() == 0)
return false;
macroManager.setMacroCommandName(macro, cmdName);
return true;
}
/**
* Returns the macro object for a given macro name.
* Note: null may be returned.
*/
public Macro getMacro(String name) {
return (macroManager == null) ? null : macroManager.getMacro(name);
}
/**
* Returns the number of currently registered macros
*/
public int getMacroNumber() {
if (macroManager == null)
return 0;
else
return macroManager.getMacroNumber();
}
/**
* Returns a list with all currently registered macros.
*/
public ArrayList getAllMacros() {
if (macroManager == null)
return null;
else
return macroManager.getAllMacros();
}
/**
* Returns i-th registered macro
*/
public Macro getMacro(int i) {
try {
return macroManager.getMacro(i);
} catch (Exception e) {
return null;
}
}
/**
* Returns the ID of the given macro.
*/
public int getMacroID(Macro macro) {
return (macroManager == null) ? -1 : macroManager.getMacroID(macro);
}
/**
* Creates a new algorithm that uses the given macro.
* @return output of macro algorithm
*/
final public GeoElement [] useMacro(String [] labels, Macro macro, GeoElement [] input) {
try {
AlgoMacro algo = new AlgoMacro(cons, labels, macro, input);
return algo.getOutput();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns an XML represenation of the given macros in this kernel.
*
* @return
*/
public String getMacroXML(ArrayList macros) {
if (hasMacros())
return MacroManager.getMacroXML(macros);
else
return "";
}
/**
* Returns whether any macros have been added to this kernel.
*/
public boolean hasMacros() {
return (macroManager != null && macroManager.getMacroNumber() > 0);
}
/***********************************
* FACTORY METHODS FOR GeoElements
***********************************/
/** Point label with cartesian coordinates (x,y) */
final public GeoPoint Point(String label, double x, double y) {
GeoPoint p = new GeoPoint(cons);
p.setCoords(x, y, 1.0);
p.setMode(COORD_CARTESIAN);
p.setLabel(label); // invokes add()
return p;
}
/** Point label with cartesian coordinates (x,y) */
final public GeoPoint Point(String label, double x, double y, boolean complex) {
GeoPoint p = new GeoPoint(cons);
p.setCoords(x, y, 1.0);
if (complex) {
p.setMode(COORD_COMPLEX);
// we have to reset the visual style as the constructor
// did not know that this was a complex number
p.setConstructionDefaults();
}
else
p.setMode(COORD_CARTESIAN);
p.setLabel(label); // invokes add()
return p;
}
/** Vector label with cartesian coordinates (x,y) */
final public GeoVector Vector(String label, double x, double y) {
GeoVector v = new GeoVector(cons);
v.setCoords(x, y, 0.0);
v.setMode(COORD_CARTESIAN);
v.setLabel(label); // invokes add()
return v;
}
/** Line a x + b y + c = 0 named label */
final public GeoLine Line(
String label,
double a,
double b,
double c) {
GeoLine line = new GeoLine(cons, label, a, b, c);
return line;
}
/** Line a x + b y + c = 0 named label */
final public GeoLinearInequality Inequality(
String label,
double a,
double b,
double c,
char op) {
GeoLinearInequality line = new GeoLinearInequality(cons, label, a, b, c, op);
return line;
}
/** Conic label with equation ax� + bxy + cy� + dx + ey + f = 0 */
final public GeoConic Conic(
String label,
double a,
double b,
double c,
double d,
double e,
double f) {
double[] coeffs = { a, b, c, d, e, f };
GeoConic conic = new GeoConic(cons, label, coeffs);
return conic;
}
/** Implicit Polynomial */
final public GeoImplicitPoly ImplicitPoly(String label,Polynomial poly) {
GeoImplicitPoly implicitPoly = new GeoImplicitPoly(cons, label, poly);
return implicitPoly;
}
/** Converts number to angle */
final public GeoAngle Angle(String label, GeoNumeric num) {
AlgoAngleNumeric algo = new AlgoAngleNumeric(cons, label, num);
GeoAngle angle = algo.getAngle();
return angle;
}
/** Function in x, e.g. f(x) = 4 x� + 3 x�
*/
final public GeoFunction Function(String label, Function fun) {
GeoFunction f = new GeoFunction(cons, label, fun);
return f;
}
/** Function in multiple variables, e.g. f(x,y) = 4 x^2 + 3 y^2
*/
final public GeoFunctionNVar FunctionNVar(String label, FunctionNVar fun) {
GeoFunctionNVar f = new GeoFunctionNVar(cons, label, fun);
return f;
}
/** Interval in x, e.g. x > 3 && x < 6
*/
final public GeoInterval Interval(String label, Function fun) {
GeoInterval f = new GeoInterval(cons, label, fun);
return f;
}
final public GeoText Text(String label, String text) {
GeoText t = new GeoText(cons);
t.setTextString(text);
t.setLabel(label);
return t;
}
final public GeoBoolean Boolean(String label, boolean value) {
GeoBoolean b = new GeoBoolean(cons);
b.setValue(value);
b.setLabel(label);
return b;
}
/**
* Creates a free list object with the given
* @param label
* @param geoElementList: list of GeoElement objects
* @return
*/
final public GeoList List(String label, ArrayList geoElementList, boolean isIndependent) {
if (isIndependent) {
GeoList list = new GeoList(cons);
int size = geoElementList.size();
for (int i=0; i < size; i++) {
list.add((GeoElement) geoElementList.get(i));
}
list.setLabel(label);
return list;
}
else {
AlgoDependentList algoList = new AlgoDependentList(cons, label, geoElementList);
return algoList.getGeoList();
}
}
/**
* Creates a dependent list object with the given label,
* e.g. {3, 2, 1} + {a, b, 2}
*/
final public GeoList ListExpression(String label, ExpressionNode root) {
AlgoDependentListExpression algo =
new AlgoDependentListExpression(cons, label, root);
return algo.getList();
}
/**
* Creates a list object for a range of cells in the spreadsheet.
* e.g. A1:B2
*/
final public GeoList CellRange(String label, GeoElement startCell, GeoElement endCell) {
AlgoCellRange algo =
new AlgoCellRange(cons, label, startCell, endCell);
return algo.getList();
}
/********************
* ALGORITHMIC PART *
********************/
/**
* If-then-else construct.
*/
final public GeoElement If(String label,
GeoBoolean condition,
GeoElement geoIf, GeoElement geoElse) {
// check if geoIf and geoElse are of same type
/* if (geoElse == null ||
geoIf.isNumberValue() && geoElse.isNumberValue() ||
geoIf.getTypeString().equals(geoElse.getTypeString()))
{*/
AlgoIf algo = new AlgoIf(cons, label, condition, geoIf, geoElse);
return algo.getGeoElement();
/* }
else {
// incompatible types
Application.debug("if incompatible: " + geoIf + ", " + geoElse);
return null;
} */
}
/**
* If-then-else construct for functions.
* example: If[ x < 2, x^2, x + 2 ]
*/
final public GeoFunction If(String label,
GeoFunction boolFun,
GeoFunction ifFun, GeoFunction elseFun) {
AlgoIfFunction algo = new AlgoIfFunction(cons, label, boolFun, ifFun, elseFun);
return algo.getGeoFunction();
}
/**
* If-then-else construct for functions.
* example: If[ x < 2, x^2, x + 2 ]
*/
final public GeoNumeric CountIf(String label,
GeoFunction boolFun,
GeoList list) {
AlgoCountIf algo = new AlgoCountIf(cons, label, boolFun, list);
return algo.getResult();
}
/**
* Sequence command:
* Sequence[ <expression>, <number-var>, <from>, <to>, <step> ]
* @return array with GeoList object and its list items
*/
final public GeoElement [] Sequence(String label,
GeoElement expression, GeoNumeric localVar,
NumberValue from, NumberValue to, NumberValue step) {
AlgoSequence algo = new AlgoSequence(cons, label, expression, localVar, from, to, step);
return algo.getOutput();
}
/**
* Cartesian curve command:
* Curve[ <expression x-coord>, <expression x-coord>, <number-var>, <from>, <to> ]
*/
final public GeoCurveCartesian CurveCartesian(String label,
NumberValue xcoord, NumberValue ycoord,
GeoNumeric localVar, NumberValue from, NumberValue to)
{
AlgoCurveCartesian algo = new AlgoCurveCartesian(cons, label, new NumberValue[] {xcoord, ycoord} , localVar, from, to);
return (GeoCurveCartesian) algo.getCurve();
}
/**
* Converts a NumberValue object to an ExpressionNode object.
*/
public ExpressionNode convertNumberValueToExpressionNode(NumberValue nv) {
GeoElement geo = nv.toGeoElement();
AlgoElement algo = geo.getParentAlgorithm();
if (algo != null && algo instanceof AlgoDependentNumber) {
AlgoDependentNumber algoDep = (AlgoDependentNumber) algo;
return algoDep.getExpression().getCopy(this);
}
else {
return new ExpressionNode(this, geo);
}
}
/** Number dependent on arithmetic expression with variables,
* represented by a tree. e.g. t = 6z - 2
*/
final public GeoNumeric DependentNumber(
String label,
ExpressionNode root,
boolean isAngle) {
AlgoDependentNumber algo =
new AlgoDependentNumber(cons, label, root, isAngle);
GeoNumeric number = algo.getNumber();
return number;
}
/** Point dependent on arithmetic expression with variables,
* represented by a tree. e.g. P = (4t, 2s)
*/
final public GeoPoint DependentPoint(
String label,
ExpressionNode root, boolean complex) {
AlgoDependentPoint algo = new AlgoDependentPoint(cons, label, root, complex);
GeoPoint P = algo.getPoint();
return P;
}
/** Vector dependent on arithmetic expression with variables,
* represented by a tree. e.g. v = u + 3 w
*/
final public GeoVector DependentVector(
String label,
ExpressionNode root) {
AlgoDependentVector algo = new AlgoDependentVector(cons, label, root);
GeoVector v = algo.getVector();
return v;
}
/** Line dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. y = k x + d
*/
final public GeoLine DependentLine(String label, Equation equ) {
AlgoDependentLine algo = new AlgoDependentLine(cons, label, equ, false);
GeoLine line = algo.getLine();
return line;
}
/** Inequality dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. y < k x + d
*/
final public GeoLinearInequality DependentInequality(String label, Equation equ) {
AlgoDependentLine algo = new AlgoDependentLine(cons, label, equ, true);
GeoLine line = algo.getLine();
return (GeoLinearInequality)line;
}
/** Conic dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. y� = 2 p x
*/
final public GeoConic DependentConic(String label, Equation equ) {
AlgoDependentConic algo = new AlgoDependentConic(cons, label, equ);
GeoConic conic = algo.getConic();
return conic;
}
final public GeoImplicitPoly DependentImplicitPoly(String label, Equation equ) {
AlgoDependentImplicitPoly algo = new AlgoDependentImplicitPoly(cons, label, equ);
GeoImplicitPoly implicitPoly = algo.getImplicitPoly();
return implicitPoly;
}
/** Function dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. f(x) = a x� + b x�
*/
final public GeoFunction DependentFunction(
String label,
Function fun) {
AlgoDependentFunction algo = new AlgoDependentFunction(cons, label, fun);
GeoFunction f = algo.getFunction();
return f;
}
/** Multivariate Function depending on coefficients of arithmetic expressions with variables,
* e.g. f(x,y) = a x^2 + b y^2
*/
final public GeoFunctionNVar DependentFunctionNVar(
String label,
FunctionNVar fun) {
AlgoDependentFunctionNVar algo = new AlgoDependentFunctionNVar(cons, label, fun);
GeoFunctionNVar f = algo.getFunction();
return f;
}
/** Interval dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. x > a && x < b
*/
final public GeoFunction DependentInterval(
String label,
Function fun) {
AlgoDependentInterval algo = new AlgoDependentInterval(cons, label, fun);
GeoFunction f = algo.getFunction();
return f;
}
/** Text dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. text = "Radius: " + r
*/
final public GeoText DependentText(
String label,
ExpressionNode root) {
AlgoDependentText algo = new AlgoDependentText(cons, label, root);
GeoText t = algo.getGeoText();
return t;
}
/**
* Creates a dependent copy of origGeo with label
*/
final public GeoElement DependentGeoCopy(String label, ExpressionNode origGeoNode) {
AlgoDependentGeoCopy algo = new AlgoDependentGeoCopy(cons, label, origGeoNode);
return algo.getGeo();
}
/**
* Name of geo.
*/
final public GeoText Name(
String label,
GeoElement geo) {
AlgoName algo = new AlgoName(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* Object from name
*/
final public GeoElement Object(
String label,
GeoText text) {
AlgoObject algo = new AlgoObject(cons, label, text);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Spreadsheet Object from coords
*/
final public GeoElement Cell(
String label,
NumberValue a, NumberValue b) {
AlgoCell algo = new AlgoCell(cons, label, a, b);
GeoElement ret = algo.getResult();
return ret;
}
/**
* ColumnName[]
*/
final public GeoText ColumnName(
String label,
GeoElement geo) {
AlgoColumnName algo = new AlgoColumnName(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* LaTeX of geo.
*/
final public GeoText LaTeX(
String label,
GeoElement geo, GeoBoolean substituteVars) {
AlgoLaTeX algo = new AlgoLaTeX(cons, label, geo, substituteVars);
GeoText t = algo.getGeoText();
return t;
}
/**
* LaTeX of geo.
*/
final public GeoText LaTeX(
String label,
GeoElement geo) {
AlgoLaTeX algo = new AlgoLaTeX(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo) {
AlgoText algo = new AlgoText(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoBoolean substituteVars) {
AlgoText algo = new AlgoText(cons, label, geo, substituteVars);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoPoint p, GeoBoolean substituteVars) {
AlgoText algo = new AlgoText(cons, label, geo, p, substituteVars);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoPoint p, GeoBoolean substituteVars, GeoBoolean latex) {
AlgoText algo = new AlgoText(cons, label, geo, p, substituteVars, latex);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoPoint p) {
AlgoText algo = new AlgoText(cons, label, geo, p);
GeoText t = algo.getGeoText();
return t;
}
/**
* Row of geo.
*/
final public GeoNumeric Row(
String label,
GeoElement geo) {
AlgoRow algo = new AlgoRow(cons, label, geo);
GeoNumeric ret = algo.getResult();
return ret;
}
/**
* Column of geo.
*/
final public GeoNumeric Column(
String label,
GeoElement geo) {
AlgoColumn algo = new AlgoColumn(cons, label, geo);
GeoNumeric ret = algo.getResult();
return ret;
}
/**
* ToNumber
*/
final public GeoNumeric LetterToUnicode(
String label,
GeoText geo) {
AlgoLetterToUnicode algo = new AlgoLetterToUnicode(cons, label, geo);
GeoNumeric ret = algo.getResult();
return ret;
}
/**
* ToNumbers
*/
final public GeoList TextToUnicode(
String label,
GeoText geo) {
AlgoTextToUnicode algo = new AlgoTextToUnicode(cons, label, geo);
GeoList ret = algo.getResult();
return ret;
}
/**
* ToText(number)
*/
final public GeoText UnicodeToLetter(String label, NumberValue a) {
AlgoUnicodeToLetter algo = new AlgoUnicodeToLetter(cons, label, a);
GeoText text = algo.getResult();
return text;
}
/**
* ToText(list)
*/
final public GeoText UnicodeToText(
String label,
GeoList geo) {
AlgoUnicodeToText algo = new AlgoUnicodeToText(cons, label, geo);
GeoText ret = algo.getResult();
return ret;
}
/**
* returns the current x-axis step
* Michael Borcherds
*/
final public GeoNumeric AxisStepX(
String label) {
AlgoAxisStepX algo = new AlgoAxisStepX(cons, label);
GeoNumeric t = algo.getResult();
return t;
}
/**
* returns the current y-axis step
* Michael Borcherds
*/
final public GeoNumeric AxisStepY(
String label) {
AlgoAxisStepY algo = new AlgoAxisStepY(cons, label);
GeoNumeric t = algo.getResult();
return t;
}
/**
* returns the current construction protocol step
* Michael Borcherds 2008-05-15
*/
final public GeoNumeric ConstructionStep(
String label) {
AlgoConstructionStep algo = new AlgoConstructionStep(cons, label);
GeoNumeric t = algo.getResult();
return t;
}
/**
* returns current construction protocol step for an object
* Michael Borcherds 2008-05-15
*/
final public GeoNumeric ConstructionStep(
String label, GeoElement geo) {
AlgoStepObject algo = new AlgoStepObject(cons, label, geo);
GeoNumeric t = algo.getResult();
return t;
}
/**
* Text dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. c = a & b
*/
final public GeoBoolean DependentBoolean(
String label,
ExpressionNode root) {
AlgoDependentBoolean algo = new AlgoDependentBoolean(cons, label, root);
return algo.getGeoBoolean();
}
/** Point on path with cartesian coordinates (x,y) */
final public GeoPoint Point(String label, Path path, double x, double y, boolean addToConstruction) {
boolean oldMacroMode = false;
if (!addToConstruction) {
oldMacroMode = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
}
AlgoPointOnPath algo = new AlgoPointOnPath(cons, label, path, x, y);
GeoPoint p = algo.getP();
if (!addToConstruction) {
cons.setSuppressLabelCreation(oldMacroMode);
}
return p;
}
/** Point anywhere on path with */
final public GeoPoint Point(String label, Path path) {
// try (0,0)
AlgoPointOnPath algo = new AlgoPointOnPath(cons, label, path, 0, 0);
GeoPoint p = algo.getP();
// try (1,0)
if (!p.isDefined()) {
p.setCoords(1,0,1);
algo.update();
}
// try (random(),0)
if (!p.isDefined()) {
p.setCoords(Math.random(),0,1);
algo.update();
}
return p;
}
/** Point in region with cartesian coordinates (x,y) */
final public GeoPoint PointIn(String label, Region region, double x, double y) {
AlgoPointInRegion algo = new AlgoPointInRegion(cons, label, region, x, y);
Application.debug("PointIn - \n x="+x+"\n y="+y);
GeoPoint p = algo.getP();
return p;
}
/** Point in region */
final public GeoPoint PointIn(String label, Region region) {
return PointIn(label,region,0,0); //TODO do as for paths
}
/** Point P + v */
final public GeoPoint Point(String label, GeoPoint P, GeoVector v) {
AlgoPointVector algo = new AlgoPointVector(cons, label, P, v);
GeoPoint p = algo.getQ();
return p;
}
/**
* Returns the projected point of P on line g.
*/
final public GeoPoint ProjectedPoint(GeoPoint P, GeoLine g) {
boolean oldMacroMode = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
GeoLine perp = OrthogonalLine(null, P, g);
GeoPoint S = IntersectLines(null, perp, g);
cons.setSuppressLabelCreation(oldMacroMode);
return S;
}
/**
* Midpoint M = (P + Q)/2
*/
final public GeoPoint Midpoint(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoMidpoint algo = new AlgoMidpoint(cons, label, P, Q);
GeoPoint M = algo.getPoint();
return M;
}
/**
* Creates Midpoint M = (P + Q)/2 without label (for use as e.g. start point)
*/
final public GeoPoint Midpoint(
GeoPoint P,
GeoPoint Q) {
boolean oldValue = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
GeoPoint midPoint = Midpoint(null, P, Q);
cons.setSuppressLabelCreation(oldValue);
return midPoint;
}
/**
* Midpoint of segment
*/
final public GeoPoint Midpoint(
String label,
GeoSegment s) {
AlgoMidpointSegment algo = new AlgoMidpointSegment(cons, label, s);
GeoPoint M = algo.getPoint();
return M;
}
/**
* LineSegment named label from Point P to Point Q
*/
final public GeoSegment Segment(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoJoinPointsSegment algo = new AlgoJoinPointsSegment(cons, label, P, Q);
GeoSegment s = algo.getSegment();
return s;
}
/**
* Line named label through Points P and Q
*/
final public GeoLine Line(String label, GeoPoint P, GeoPoint Q) {
AlgoJoinPoints algo = new AlgoJoinPoints(cons, label, P, Q);
GeoLine g = algo.getLine();
return g;
}
/**
* Line named label through Point P with direction of vector v
*/
final public GeoLine Line(String label, GeoPoint P, GeoVector v) {
AlgoLinePointVector algo = new AlgoLinePointVector(cons, label, P, v);
GeoLine g = algo.getLine();
return g;
}
/**
* Ray named label through Points P and Q
*/
final public GeoRay Ray(String label, GeoPoint P, GeoPoint Q) {
AlgoJoinPointsRay algo = new AlgoJoinPointsRay(cons, label, P, Q);
return algo.getRay();
}
/**
* Ray named label through Point P with direction of vector v
*/
final public GeoRay Ray(String label, GeoPoint P, GeoVector v) {
AlgoRayPointVector algo = new AlgoRayPointVector(cons, label, P, v);
return algo.getRay();
}
/**
* Line named label through Point P parallel to Line l
*/
final public GeoLine Line(String label, GeoPoint P, GeoLine l) {
AlgoLinePointLine algo = new AlgoLinePointLine(cons, label, P, l);
GeoLine g = algo.getLine();
return g;
}
/**
* Line named label through Point P orthogonal to vector v
*/
final public GeoLine OrthogonalLine(
String label,
GeoPoint P,
GeoVector v) {
AlgoOrthoLinePointVector algo =
new AlgoOrthoLinePointVector(cons, label, P, v);
GeoLine g = algo.getLine();
return g;
}
/**
* Line named label through Point P orthogonal to line l
*/
final public GeoLine OrthogonalLine(
String label,
GeoPoint P,
GeoLine l) {
AlgoOrthoLinePointLine algo = new AlgoOrthoLinePointLine(cons, label, P, l);
GeoLine g = algo.getLine();
return g;
}
/**
* Line bisector of points A, B
*/
final public GeoLine LineBisector(
String label,
GeoPoint A,
GeoPoint B) {
AlgoLineBisector algo = new AlgoLineBisector(cons, label, A, B);
GeoLine g = algo.getLine();
return g;
}
/**
* Line bisector of segment s
*/
final public GeoLine LineBisector(String label, GeoSegment s) {
AlgoLineBisectorSegment algo = new AlgoLineBisectorSegment(cons, label, s);
GeoLine g = algo.getLine();
return g;
}
/**
* Angular bisector of points A, B, C
*/
final public GeoLine AngularBisector(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoAngularBisectorPoints algo =
new AlgoAngularBisectorPoints(cons, label, A, B, C);
GeoLine g = algo.getLine();
return g;
}
/**
* Angular bisectors of lines g, h
*/
final public GeoLine[] AngularBisector(
String[] labels,
GeoLine g,
GeoLine h) {
AlgoAngularBisectorLines algo =
new AlgoAngularBisectorLines(cons, labels, g, h);
GeoLine[] lines = algo.getLines();
return lines;
}
/**
* Vector named label from Point P to Q
*/
final public GeoVector Vector(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoVector algo = new AlgoVector(cons, label, P, Q);
GeoVector v = (GeoVector) algo.getVector();
v.setEuclidianVisible(true);
v.update();
notifyUpdate(v);
return v;
}
/**
* Vector (0,0) to P
*/
final public GeoVector Vector(String label, GeoPoint P) {
AlgoVectorPoint algo = new AlgoVectorPoint(cons, label, P);
GeoVector v = algo.getVector();
v.setEuclidianVisible(true);
v.update();
notifyUpdate(v);
return v;
}
/**
* Direction vector of line g
*/
final public GeoVector Direction(String label, GeoLine g) {
AlgoDirection algo = new AlgoDirection(cons, label, g);
GeoVector v = algo.getVector();
return v;
}
/**
* Slope of line g
*/
final public GeoNumeric Slope(String label, GeoLine g) {
AlgoSlope algo = new AlgoSlope(cons, label, g);
GeoNumeric slope = algo.getSlope();
return slope;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
NumberValue a, NumberValue b, GeoList list) {
AlgoBarChart algo = new AlgoBarChart(cons, label, a, b, list);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
GeoList list1, GeoList list2) {
AlgoBarChart algo = new AlgoBarChart(cons, label, list1, list2);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
GeoList list1, GeoList list2, NumberValue width) {
AlgoBarChart algo = new AlgoBarChart(cons, label, list1, list2, width);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
GeoList list, GeoNumeric a) {
AlgoBarChart algo = new AlgoBarChart(cons, label, list, a);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
NumberValue a, NumberValue b, GeoElement expression, GeoNumeric localVar,
NumberValue from, NumberValue to, NumberValue step) {
AlgoSequence seq = new AlgoSequence(cons, expression, localVar, from, to, step);
cons.removeFromConstructionList(seq);
AlgoBarChart algo = new AlgoBarChart(cons, label, a, b, (GeoList)seq.getOutput()[0]);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BoxPlot
*/
final public GeoNumeric BoxPlot(String label,
NumberValue a, NumberValue b, GeoList rawData) {
/*
AlgoListMin min = new AlgoListMin(cons,rawData);
cons.removeFromConstructionList(min);
AlgoQ1 Q1 = new AlgoQ1(cons,rawData);
cons.removeFromConstructionList(Q1);
AlgoMedian median = new AlgoMedian(cons,rawData);
cons.removeFromConstructionList(median);
AlgoQ3 Q3 = new AlgoQ3(cons,rawData);
cons.removeFromConstructionList(Q3);
AlgoListMax max = new AlgoListMax(cons,rawData);
cons.removeFromConstructionList(max);
AlgoBoxPlot algo = new AlgoBoxPlot(cons, label, a, b, (NumberValue)(min.getMin()),
(NumberValue)(Q1.getQ1()), (NumberValue)(median.getMedian()), (NumberValue)(Q3.getQ3()), (NumberValue)(max.getMax()));
*/
AlgoBoxPlot algo = new AlgoBoxPlot(cons, label, a, b, rawData);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BoxPlot
*/
final public GeoNumeric BoxPlot(String label,
NumberValue a, NumberValue b, NumberValue min, NumberValue Q1,
NumberValue median, NumberValue Q3, NumberValue max) {
AlgoBoxPlot algo = new AlgoBoxPlot(cons, label, a, b, min, Q1, median, Q3, max);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* Histogram
*/
final public GeoNumeric Histogram(String label,
GeoList list1, GeoList list2) {
AlgoHistogram algo = new AlgoHistogram(cons, label, list1, list2);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* DotPlot
* G.Sturr 2010-8-10
*/
final public GeoList DotPlot(String label, GeoList list) {
AlgoDotPlot algo = new AlgoDotPlot(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* UpperSum of function f
*/
final public GeoNumeric UpperSum(String label, GeoFunction f,
NumberValue a, NumberValue b, NumberValue n) {
AlgoSumUpper algo = new AlgoSumUpper(cons, label, f, a, b, n);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* TrapezoidalSum of function f
*/
final public GeoNumeric TrapezoidalSum(String label, GeoFunction f,
NumberValue a, NumberValue b, NumberValue n) {
AlgoSumTrapezoidal algo = new AlgoSumTrapezoidal(cons, label, f, a, b, n);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* LowerSum of function f
*/
final public GeoNumeric LowerSum(String label, GeoFunction f,
NumberValue a, NumberValue b, NumberValue n) {
AlgoSumLower algo = new AlgoSumLower(cons, label, f, a, b, n);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* SumSquaredErrors[<List of Points>,<Function>]
* Hans-Petter Ulven
* 2010-02-22
*/
final public GeoNumeric SumSquaredErrors(String label, GeoList list, GeoFunctionable function) {
AlgoSumSquaredErrors algo = new AlgoSumSquaredErrors(cons, label, list, function);
GeoNumeric sse=algo.getsse();
return sse;
}
/**
* RSquare[<List of Points>,<Function>]
*/
final public GeoNumeric RSquare(String label, GeoList list, GeoFunctionable function) {
AlgoRSquare algo = new AlgoRSquare(cons, label, list, function);
GeoNumeric r2=algo.getRSquare();
return r2;
}
/**
* unit vector of line g
*/
final public GeoVector UnitVector(String label, GeoLine g) {
AlgoUnitVectorLine algo = new AlgoUnitVectorLine(cons, label, g);
GeoVector v = algo.getVector();
return v;
}
/**
* unit vector of vector v
*/
final public GeoVector UnitVector(String label, GeoVector v) {
AlgoUnitVectorVector algo = new AlgoUnitVectorVector(cons, label, v);
GeoVector u = algo.getVector();
return u;
}
/**
* orthogonal vector of line g
*/
final public GeoVector OrthogonalVector(String label, GeoLine g) {
AlgoOrthoVectorLine algo = new AlgoOrthoVectorLine(cons, label, g);
GeoVector n = algo.getVector();
return n;
}
/**
* orthogonal vector of vector v
*/
final public GeoVector OrthogonalVector(String label, GeoVector v) {
AlgoOrthoVectorVector algo = new AlgoOrthoVectorVector(cons, label, v);
GeoVector n = algo.getVector();
return n;
}
/**
* unit orthogonal vector of line g
*/
final public GeoVector UnitOrthogonalVector(
String label,
GeoLine g) {
AlgoUnitOrthoVectorLine algo = new AlgoUnitOrthoVectorLine(cons, label, g);
GeoVector n = algo.getVector();
return n;
}
/**
* unit orthogonal vector of vector v
*/
final public GeoVector UnitOrthogonalVector(
String label,
GeoVector v) {
AlgoUnitOrthoVectorVector algo =
new AlgoUnitOrthoVectorVector(cons, label, v);
GeoVector n = algo.getVector();
return n;
}
/**
* Length named label of vector v
*/
final public GeoNumeric Length(String label, GeoVec3D v) {
AlgoLengthVector algo = new AlgoLengthVector(cons, label, v);
GeoNumeric num = algo.getLength();
return num;
}
/**
* Distance named label between points P and Q
*/
final public GeoNumeric Distance(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoDistancePoints algo = new AlgoDistancePoints(cons, label, P, Q);
GeoNumeric num = algo.getDistance();
return num;
}
/**
* Distance named label between point P and line g
*/
final public GeoNumeric Distance(
String label,
GeoPoint P,
GeoLine g) {
AlgoDistancePointLine algo = new AlgoDistancePointLine(cons, label, P, g);
GeoNumeric num = algo.getDistance();
return num;
}
/**
* Distance named label between line g and line h
*/
final public GeoNumeric Distance(
String label,
GeoLine g,
GeoLine h) {
AlgoDistanceLineLine algo = new AlgoDistanceLineLine(cons, label, g, h);
GeoNumeric num = algo.getDistance();
return num;
}
/**
* Area named label of P[0], ..., P[n]
*/
final public GeoNumeric Area(String label, GeoPoint [] P) {
AlgoAreaPoints algo = new AlgoAreaPoints(cons, label, P);
GeoNumeric num = algo.getArea();
return num;
}
/**
* Area named label of conic
*/
final public GeoNumeric Area(String label, GeoConic c) {
AlgoAreaConic algo = new AlgoAreaConic(cons, label, c);
GeoNumeric num = algo.getArea();
return num;
}
/**
* Mod[a, b]
*/
final public GeoNumeric Mod(String label, NumberValue a, NumberValue b) {
AlgoMod algo = new AlgoMod(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Div[a, b]
*/
final public GeoNumeric Div(String label, NumberValue a, NumberValue b) {
AlgoDiv algo = new AlgoDiv(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Mod[a, b] Polynomial remainder
*/
final public GeoFunction Mod(String label, GeoFunction a, GeoFunction b) {
AlgoPolynomialMod algo = new AlgoPolynomialMod(cons, label, a, b);
GeoFunction f = algo.getResult();
return f;
}
/**
* Div[a, b] Polynomial Division
*/
final public GeoFunction Div(String label, GeoFunction a, GeoFunction b) {
AlgoPolynomialDiv algo = new AlgoPolynomialDiv(cons, label, a, b);
GeoFunction f = algo.getResult();
return f;
}
/**
* Min[a, b]
*/
final public GeoNumeric Min(String label, NumberValue a, NumberValue b) {
AlgoMin algo = new AlgoMin(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Min[list]
*/
final public GeoNumeric Min(String label, GeoList list) {
AlgoListMin algo = new AlgoListMin(cons, label, list);
GeoNumeric num = algo.getMin();
return num;
}
/**
* Max[a, b]
*/
final public GeoNumeric Max(String label, NumberValue a, NumberValue b) {
AlgoMax algo = new AlgoMax(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Max[list]
*/
final public GeoNumeric Max(String label, GeoList list) {
AlgoListMax algo = new AlgoListMax(cons, label, list);
GeoNumeric num = algo.getMax();
return num;
}
/**
* LCM[a, b]
* Michael Borcherds
*/
final public GeoNumeric LCM(String label, NumberValue a, NumberValue b) {
AlgoLCM algo = new AlgoLCM(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* LCM[list]
* Michael Borcherds
*/
final public GeoNumeric LCM(String label, GeoList list) {
AlgoListLCM algo = new AlgoListLCM(cons, label, list);
GeoNumeric num = algo.getLCM();
return num;
}
/**
* GCD[a, b]
* Michael Borcherds
*/
final public GeoNumeric GCD(String label, NumberValue a, NumberValue b) {
AlgoGCD algo = new AlgoGCD(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* GCD[list]
* Michael Borcherds
*/
final public GeoNumeric GCD(String label, GeoList list) {
AlgoListGCD algo = new AlgoListGCD(cons, label, list);
GeoNumeric num = algo.getGCD();
return num;
}
/**
* SigmaXY[list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXY(String label, GeoList list) {
AlgoListSigmaXY algo = new AlgoListSigmaXY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaYY[list]
* Michael Borcherds
*/
final public GeoNumeric SigmaYY(String label, GeoList list) {
AlgoListSigmaYY algo = new AlgoListSigmaYY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Covariance[list]
* Michael Borcherds
*/
final public GeoNumeric Covariance(String label, GeoList list) {
AlgoListCovariance algo = new AlgoListCovariance(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SXX[list]
* Michael Borcherds
*/
final public GeoNumeric SXX(String label, GeoList list) {
GeoNumeric num;
GeoElement geo = list.get(0);
if (geo.isNumberValue())
{ // list of numbers
AlgoSXX algo = new AlgoSXX(cons, label, list);
num = algo.getResult();
}
else
{ // (probably) list of points
AlgoListSXX algo = new AlgoListSXX(cons, label, list);
num = algo.getResult();
}
return num;
}
/**
* SXY[list]
* Michael Borcherds
*/
final public GeoNumeric SXY(String label, GeoList list) {
AlgoListSXY algo = new AlgoListSXY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SYY[list]
* Michael Borcherds
*/
final public GeoNumeric SYY(String label, GeoList list) {
AlgoListSYY algo = new AlgoListSYY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* MeanX[list]
* Michael Borcherds
*/
final public GeoNumeric MeanX(String label, GeoList list) {
AlgoListMeanX algo = new AlgoListMeanX(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* MeanY[list]
* Michael Borcherds
*/
final public GeoNumeric MeanY(String label, GeoList list) {
AlgoListMeanY algo = new AlgoListMeanY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* PMCC[list]
* Michael Borcherds
*/
final public GeoNumeric PMCC(String label, GeoList list) {
AlgoListPMCC algo = new AlgoListPMCC(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaXY[list,list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXY(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSigmaXY algo = new AlgoDoubleListSigmaXY(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaXX[list,list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXX(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSigmaXX algo = new AlgoDoubleListSigmaXX(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaYY[list,list]
* Michael Borcherds
*/
final public GeoNumeric SigmaYY(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSigmaYY algo = new AlgoDoubleListSigmaYY(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Covariance[list,list]
* Michael Borcherds
*/
final public GeoNumeric Covariance(String label, GeoList listX, GeoList listY) {
AlgoDoubleListCovariance algo = new AlgoDoubleListCovariance(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SXX[list,list]
* Michael Borcherds
*/
final public GeoNumeric SXX(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSXX algo = new AlgoDoubleListSXX(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SXY[list,list]
* Michael Borcherds
*/
final public GeoNumeric SXY(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSXY algo = new AlgoDoubleListSXY(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* PMCC[list,list]
* Michael Borcherds
*/
final public GeoNumeric PMCC(String label, GeoList listX, GeoList listY) {
AlgoDoubleListPMCC algo = new AlgoDoubleListPMCC(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* FitLineY[list of coords]
* Michael Borcherds
*/
final public GeoLine FitLineY(String label, GeoList list) {
AlgoFitLineY algo = new AlgoFitLineY(cons, label, list);
GeoLine line = algo.getFitLineY();
return line;
}
/**
* FitLineX[list of coords]
* Michael Borcherds
*/
final public GeoLine FitLineX(String label, GeoList list) {
AlgoFitLineX algo = new AlgoFitLineX(cons, label, list);
GeoLine line = algo.getFitLineX();
return line;
}
final public GeoLocus Voronoi(String label, GeoList list) {
AlgoVoronoi algo = new AlgoVoronoi(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus Hull(String label, GeoList list, GeoNumeric percent) {
AlgoHull algo = new AlgoHull(cons, label, list, percent);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus TravelingSalesman(String label, GeoList list) {
AlgoTravelingSalesman algo = new AlgoTravelingSalesman(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus ConvexHull(String label, GeoList list) {
AlgoConvexHull algo = new AlgoConvexHull(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus MinimumSpanningTree(String label, GeoList list) {
AlgoMinimumSpanningTree algo = new AlgoMinimumSpanningTree(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus DelauneyTriangulation(String label, GeoList list) {
AlgoDelauneyTriangulation algo = new AlgoDelauneyTriangulation(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
/**
* FitPoly[list of coords,degree]
* Hans-Petter Ulven
*/
final public GeoFunction FitPoly(String label, GeoList list, NumberValue degree) {
AlgoFitPoly algo = new AlgoFitPoly(cons, label, list, degree);
GeoFunction function = algo.getFitPoly();
return function;
}
/**
* FitExp[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitExp(String label, GeoList list) {
AlgoFitExp algo = new AlgoFitExp(cons, label, list);
GeoFunction function = algo.getFitExp();
return function;
}
/**
* FitLog[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitLog(String label, GeoList list) {
AlgoFitLog algo = new AlgoFitLog(cons, label, list);
GeoFunction function = algo.getFitLog();
return function;
}
/**
* FitPow[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitPow(String label, GeoList list) {
AlgoFitPow algo = new AlgoFitPow(cons, label, list);
GeoFunction function = algo.getFitPow();
return function;
}
/**
* FitSin[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitSin(String label, GeoList list) {
AlgoFitSin algo = new AlgoFitSin(cons, label, list);
GeoFunction function = algo.getFitSin();
return function;
}
/**
* FitLogistic[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitLogistic(String label, GeoList list) {
AlgoFitLogistic algo = new AlgoFitLogistic(cons, label, list);
GeoFunction function = algo.getFitLogistic();
return function;
}
/**
* Fit[list of points,list of functions]
* Hans-Petter Ulven
*/
final public GeoFunction Fit(String label, GeoList ptslist,GeoList funclist) {
AlgoFit algo = new AlgoFit(cons, label, ptslist,funclist);
GeoFunction function = algo.getFit();
return function;
}
/**
* 'FitGrowth[<List of Points>]
* Hans-Petter Ulven
*/
final public GeoFunction FitGrowth(String label, GeoList list) {
AlgoFitGrowth algo = new AlgoFitGrowth(cons, label, list);
GeoFunction function=algo.getFitGrowth();
return function;
}
/**
* Binomial[n,r]
* Michael Borcherds
*/
final public GeoNumeric Binomial(String label, NumberValue a, NumberValue b) {
AlgoBinomial algo = new AlgoBinomial(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomNormal[mean,variance]
* Michael Borcherds
*/
final public GeoNumeric RandomNormal(String label, NumberValue a, NumberValue b) {
AlgoRandomNormal algo = new AlgoRandomNormal(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Random[max,min]
* Michael Borcherds
*/
final public GeoNumeric Random(String label, NumberValue a, NumberValue b) {
AlgoRandom algo = new AlgoRandom(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomUniform[max,min]
* Michael Borcherds
*/
final public GeoNumeric RandomUniform(String label, NumberValue a, NumberValue b) {
AlgoRandomUniform algo = new AlgoRandomUniform(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomBinomial[n,p]
* Michael Borcherds
*/
final public GeoNumeric RandomBinomial(String label, NumberValue a, NumberValue b) {
AlgoRandomBinomial algo = new AlgoRandomBinomial(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomPoisson[lambda]
* Michael Borcherds
*/
final public GeoNumeric RandomPoisson(String label, NumberValue a) {
AlgoRandomPoisson algo = new AlgoRandomPoisson(cons, label, a);
GeoNumeric num = algo.getResult();
return num;
}
/**
* InverseNormal[mean,variance,x]
* Michael Borcherds
*/
final public GeoNumeric InverseNormal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseNormal algo = new AlgoInverseNormal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Normal[mean,variance,x]
* Michael Borcherds
*/
final public GeoNumeric Normal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoNormal algo = new AlgoNormal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
/**
* TDistribution[degrees of freedom,x]
* Michael Borcherds
*/
final public GeoNumeric TDistribution(String label, NumberValue a, NumberValue b) {
AlgoTDistribution algo = new AlgoTDistribution(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseTDistribution(String label, NumberValue a, NumberValue b) {
AlgoInverseTDistribution algo = new AlgoInverseTDistribution(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric ChiSquared(String label, NumberValue a, NumberValue b) {
AlgoChiSquared algo = new AlgoChiSquared(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseChiSquared(String label, NumberValue a, NumberValue b) {
AlgoInverseChiSquared algo = new AlgoInverseChiSquared(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Exponential(String label, NumberValue a, NumberValue b) {
AlgoExponential algo = new AlgoExponential(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseExponential(String label, NumberValue a, NumberValue b) {
AlgoInverseExponential algo = new AlgoInverseExponential(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric FDistribution(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoFDistribution algo = new AlgoFDistribution(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseFDistribution(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseFDistribution algo = new AlgoInverseFDistribution(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Gamma(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoGamma algo = new AlgoGamma(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseGamma(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseGamma algo = new AlgoInverseGamma(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Cauchy(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoCauchy algo = new AlgoCauchy(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseCauchy(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseCauchy algo = new AlgoInverseCauchy(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Weibull(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoWeibull algo = new AlgoWeibull(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseWeibull(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseWeibull algo = new AlgoInverseWeibull(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Zipf(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoZipf algo = new AlgoZipf(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseZipf(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseZipf algo = new AlgoInverseZipf(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Pascal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoPascal algo = new AlgoPascal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InversePascal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInversePascal algo = new AlgoInversePascal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric HyperGeometric(String label, NumberValue a, NumberValue b, NumberValue c, NumberValue d) {
AlgoHyperGeometric algo = new AlgoHyperGeometric(cons, label, a, b, c, d);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseHyperGeometric(String label, NumberValue a, NumberValue b, NumberValue c, NumberValue d) {
AlgoInverseHyperGeometric algo = new AlgoInverseHyperGeometric(cons, label, a, b, c, d);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Sort[list]
* Michael Borcherds
*/
final public GeoList Sort(String label, GeoList list) {
AlgoSort algo = new AlgoSort(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Rank[list]
* Michael Borcherds
*/
final public GeoList Rank(String label, GeoList list) {
AlgoRank algo = new AlgoRank(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Shuffle[list]
* Michael Borcherds
*/
final public GeoList Shuffle(String label, GeoList list) {
AlgoShuffle algo = new AlgoShuffle(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* PointList[list]
* Michael Borcherds
*/
final public GeoList PointList(String label, GeoList list) {
AlgoPointList algo = new AlgoPointList(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* RootList[list]
* Michael Borcherds
*/
final public GeoList RootList(String label, GeoList list) {
AlgoRootList algo = new AlgoRootList(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* First[list,n]
* Michael Borcherds
*/
final public GeoList First(String label, GeoList list, GeoNumeric n) {
AlgoFirst algo = new AlgoFirst(cons, label, list, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* First[string,n]
* Michael Borcherds
*/
final public GeoText First(String label, GeoText list, GeoNumeric n) {
AlgoFirstString algo = new AlgoFirstString(cons, label, list, n);
GeoText list2 = algo.getResult();
return list2;
}
/**
* Last[string,n]
* Michael Borcherds
*/
final public GeoText Last(String label, GeoText list, GeoNumeric n) {
AlgoLastString algo = new AlgoLastString(cons, label, list, n);
GeoText list2 = algo.getResult();
return list2;
}
/**
* First[string,n]
* Michael Borcherds
*/
final public GeoText Take(String label, GeoText list, GeoNumeric m, GeoNumeric n) {
AlgoTakeString algo = new AlgoTakeString(cons, label, list, m, n);
GeoText list2 = algo.getResult();
return list2;
}
/**
* Last[list,n]
* Michael Borcherds
*/
final public GeoList Last(String label, GeoList list, GeoNumeric n) {
AlgoLast algo = new AlgoLast(cons, label, list, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Take[list,m,n]
* Michael Borcherds
*/
final public GeoList Take(String label, GeoList list, GeoNumeric m, GeoNumeric n) {
AlgoTake algo = new AlgoTake(cons, label, list, m, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Append[list,object]
* Michael Borcherds
*/
final public GeoList Append(String label, GeoList list, GeoElement geo) {
AlgoAppend algo = new AlgoAppend(cons, label, list, geo);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Append[object,list]
* Michael Borcherds
*/
final public GeoList Append(String label, GeoElement geo, GeoList list) {
AlgoAppend algo = new AlgoAppend(cons, label, geo, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Join[list,list]
* Michael Borcherds
*/
final public GeoList Join(String label, GeoList list) {
AlgoJoin algo = new AlgoJoin(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Union[list,list]
* Michael Borcherds
*/
final public GeoList Union(String label, GeoList list, GeoList list1) {
AlgoUnion algo = new AlgoUnion(cons, label, list, list1);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Intersection[list,list]
* Michael Borcherds
*/
final public GeoList Intersection(String label, GeoList list, GeoList list1) {
AlgoIntersection algo = new AlgoIntersection(cons, label, list, list1);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Insert[list,list,n]
* Michael Borcherds
*/
final public GeoList Insert(String label, GeoElement geo, GeoList list, GeoNumeric n) {
AlgoInsert algo = new AlgoInsert(cons, label, geo, list, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* RemoveUndefined[list]
* Michael Borcherds
*/
final public GeoList RemoveUndefined(String label, GeoList list) {
AlgoRemoveUndefined algo = new AlgoRemoveUndefined(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Keep[boolean condition, list]
* Michael Borcherds
*/
final public GeoList KeepIf(String label, GeoFunction boolFun, GeoList list) {
AlgoKeepIf algo = new AlgoKeepIf(cons, label, boolFun, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Defined[object]
* Michael Borcherds
*/
final public GeoBoolean Defined(String label, GeoElement geo) {
AlgoDefined algo = new AlgoDefined(cons, label, geo);
GeoBoolean result = algo.getResult();
return result;
}
/**
* IsInteger[number]
* Michael Borcherds
*/
final public GeoBoolean IsInteger(String label, GeoNumeric geo) {
AlgoIsInteger algo = new AlgoIsInteger(cons, label, geo);
GeoBoolean result = algo.getResult();
return result;
}
/**
* Mode[list]
* Michael Borcherds
*/
final public GeoList Mode(String label, GeoList list) {
AlgoMode algo = new AlgoMode(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Invert[matrix]
* Michael Borcherds
*/
final public GeoList Invert(String label, GeoList list) {
AlgoInvert algo = new AlgoInvert(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Transpose[matrix]
* Michael Borcherds
*/
final public GeoList Transpose(String label, GeoList list) {
AlgoTranspose algo = new AlgoTranspose(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Transpose[matrix]
* Michael Borcherds
*/
final public GeoList ReducedRowEchelonForm(String label, GeoList list) {
AlgoReducedRowEchelonForm algo = new AlgoReducedRowEchelonForm(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Transpose[matrix]
* Michael Borcherds
*/
final public GeoNumeric Determinant(String label, GeoList list) {
AlgoDeterminant algo = new AlgoDeterminant(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Reverse[list]
* Michael Borcherds
*/
final public GeoList Reverse(String label, GeoList list) {
AlgoReverse algo = new AlgoReverse(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Product[list]
* Michael Borcherds
*/
final public GeoNumeric Product(String label, GeoList list) {
AlgoProduct algo = new AlgoProduct(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Sum[list]
* Michael Borcherds
*/
final public GeoElement Sum(String label, GeoList list) {
AlgoSum algo = new AlgoSum(cons, label, list);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list,n]
* Michael Borcherds
*/
final public GeoElement Sum(String label, GeoList list, GeoNumeric n) {
AlgoSum algo = new AlgoSum(cons, label, list, n);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of functions]
* Michael Borcherds
*/
final public GeoElement SumFunctions(String label, GeoList list) {
AlgoSumFunctions algo = new AlgoSumFunctions(cons, label, list);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of functions,n]
* Michael Borcherds
*/
final public GeoElement SumFunctions(String label, GeoList list, GeoNumeric num) {
AlgoSumFunctions algo = new AlgoSumFunctions(cons, label, list, num);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of points]
* Michael Borcherds
*/
final public GeoElement SumPoints(String label, GeoList list) {
AlgoSumPoints algo = new AlgoSumPoints(cons, label, list);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of points,n]
* Michael Borcherds
*/
final public GeoElement SumPoints(String label, GeoList list, GeoNumeric num) {
AlgoSumPoints algo = new AlgoSumPoints(cons, label, list, num);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of points]
* Michael Borcherds
*/
final public GeoElement SumText(String label, GeoList list) {
AlgoSumText algo = new AlgoSumText(cons, label, list);
GeoText ret = algo.getResult();
return ret;
}
/**
* Sum[list of text,n]
* Michael Borcherds
*/
final public GeoElement SumText(String label, GeoList list, GeoNumeric num) {
AlgoSumText algo = new AlgoSumText(cons, label, list, num);
GeoText ret = algo.getResult();
return ret;
}
/**
* Sample[list,n]
* Michael Borcherds
*/
final public GeoElement Sample(String label, GeoList list, NumberValue n) {
AlgoSample algo = new AlgoSample(cons, label, list, n, null);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sample[list,n, withReplacement]
* Michael Borcherds
*/
final public GeoElement Sample(String label, GeoList list, NumberValue n, GeoBoolean withReplacement) {
AlgoSample algo = new AlgoSample(cons, label, list, n, withReplacement);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Table[list]
* Michael Borcherds
*/
final public GeoText TableText(String label, GeoList list, GeoText args) {
AlgoTableText algo = new AlgoTableText(cons, label, list, args);
GeoText text = algo.getResult();
return text;
}
/**
* StemPlot[list]
* Michael Borcherds
*/
final public GeoText StemPlot(String label, GeoList list) {
AlgoStemPlot algo = new AlgoStemPlot(cons, label, list, null);
GeoText text = algo.getResult();
return text;
}
/**
* StemPlot[list, number]
* Michael Borcherds
*/
final public GeoText StemPlot(String label, GeoList list, GeoNumeric num) {
AlgoStemPlot algo = new AlgoStemPlot(cons, label, list, num);
GeoText text = algo.getResult();
return text;
}
/**
* ToFraction[number]
* Michael Borcherds
*/
final public GeoText FractionText(String label, GeoNumeric num) {
AlgoFractionText algo = new AlgoFractionText(cons, label, num);
GeoText text = algo.getResult();
return text;
}
/**
* Mean[list]
* Michael Borcherds
*/
final public GeoNumeric Mean(String label, GeoList list) {
AlgoMean algo = new AlgoMean(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoText VerticalText(String label, GeoText args) {
AlgoVerticalText algo = new AlgoVerticalText(cons, label, args);
GeoText text = algo.getResult();
return text;
}
final public GeoText RotateText(String label, GeoText args, GeoNumeric angle) {
AlgoRotateText algo = new AlgoRotateText(cons, label, args, angle);
GeoText text = algo.getResult();
return text;
}
/**
* Variance[list]
* Michael Borcherds
*/
final public GeoNumeric Variance(String label, GeoList list) {
AlgoVariance algo = new AlgoVariance(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SampleVariance[list]
* Michael Borcherds
*/
final public GeoNumeric SampleVariance(String label, GeoList list) {
AlgoSampleVariance algo = new AlgoSampleVariance(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SD[list]
* Michael Borcherds
*/
final public GeoNumeric StandardDeviation(String label, GeoList list) {
AlgoStandardDeviation algo = new AlgoStandardDeviation(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SampleSD[list]
* Michael Borcherds
*/
final public GeoNumeric SampleStandardDeviation(String label, GeoList list) {
AlgoSampleStandardDeviation algo = new AlgoSampleStandardDeviation(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaXX[list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXX(String label, GeoList list) {
GeoNumeric num;
GeoElement geo = list.get(0);
if (geo.isNumberValue())
{ // list of numbers
AlgoSigmaXX algo = new AlgoSigmaXX(cons, label, list);
num = algo.getResult();
}
else
{ // (probably) list of points
AlgoListSigmaXX algo = new AlgoListSigmaXX(cons, label, list);
num = algo.getResult();
}
return num;
}
/**
* Median[list]
* Michael Borcherds
*/
final public GeoNumeric Median(String label, GeoList list) {
AlgoMedian algo = new AlgoMedian(cons, label, list);
GeoNumeric num = algo.getMedian();
return num;
}
/**
* Q1[list] lower quartile
* Michael Borcherds
*/
final public GeoNumeric Q1(String label, GeoList list) {
AlgoQ1 algo = new AlgoQ1(cons, label, list);
GeoNumeric num = algo.getQ1();
return num;
}
/**
* Q3[list] upper quartile
* Michael Borcherds
*/
final public GeoNumeric Q3(String label, GeoList list) {
AlgoQ3 algo = new AlgoQ3(cons, label, list);
GeoNumeric num = algo.getQ3();
return num;
}
/**
* Iteration[ f(x), x0, n ]
*/
final public GeoNumeric Iteration(String label, GeoFunction f, NumberValue start,
NumberValue n) {
AlgoIteration algo = new AlgoIteration(cons, label, f, start, n);
GeoNumeric num = algo.getResult();
return num;
}
/**
* IterationList[ f(x), x0, n ]
*/
final public GeoList IterationList(String label, GeoFunction f, NumberValue start,
NumberValue n) {
AlgoIterationList algo = new AlgoIterationList(cons, label, f, start, n);
return algo.getResult();
}
/**
* RandomElement[list]
*/
final public GeoElement RandomElement(String label, GeoList list) {
AlgoRandomElement algo = new AlgoRandomElement(cons, label, list);
GeoElement geo = algo.getElement();
return geo;
}
/**
* Element[list, number]
*/
final public GeoElement Element(String label, GeoList list, NumberValue n) {
AlgoListElement algo = new AlgoListElement(cons, label, list, n);
GeoElement geo = algo.getElement();
return geo;
}
/**
* SelectedElement[list]
*/
final public GeoElement SelectedElement(String label, GeoList list) {
AlgoSelectedElement algo = new AlgoSelectedElement(cons, label, list);
GeoElement geo = algo.getElement();
return geo;
}
/**
* SelectedElement[list]
*/
final public GeoElement SelectedIndex(String label, GeoList list) {
AlgoSelectedIndex algo = new AlgoSelectedIndex(cons, label, list);
GeoElement geo = algo.getElement();
return geo;
}
/**
* Element[list, number, number]
*/
final public GeoElement Element(String label, GeoList list, NumberValue n, NumberValue m) {
AlgoListElement algo = new AlgoListElement(cons, label, list, n, m);
GeoElement geo = algo.getElement();
return geo;
}
/**
* Length[list]
*/
final public GeoNumeric Length(String label, GeoList list) {
AlgoListLength algo = new AlgoListLength(cons, label, list);
return algo.getLength();
}
/**
* Element[text, number]
*/
final public GeoElement Element(String label, GeoText text, NumberValue n) {
AlgoTextElement algo = new AlgoTextElement(cons, label, text, n);
GeoElement geo = algo.getText();
return geo;
}
/**
* Length[text]
*/
final public GeoNumeric Length(String label, GeoText text) {
AlgoTextLength algo = new AlgoTextLength(cons, label, text);
return algo.getLength();
}
// PhilippWeissenbacher 2007-04-10
/**
* Perimeter named label of GeoPolygon
*/
final public GeoNumeric Perimeter(String label, GeoPolygon polygon) {
AlgoPerimeterPoly algo = new AlgoPerimeterPoly(cons, label, polygon);
return algo.getCircumference();
}
/**
* Circumference named label of GeoConic
*/
final public GeoNumeric Circumference(String label, GeoConic conic) {
AlgoCircumferenceConic algo = new AlgoCircumferenceConic(cons, label, conic);
return algo.getCircumference();
}
// PhilippWeissenbacher 2007-04-10
/**
* polygon P[0], ..., P[n-1]
* The labels name the polygon itself and its segments
*/
final public GeoElement [] Polygon(String [] labels, GeoPoint [] P) {
AlgoPolygon algo = new AlgoPolygon(cons, labels, P);
return algo.getOutput();
}
//G.Sturr 2010-3-14
/**
* Polygon with vertices from geolist
* Only the polygon is labeled, segments are not labeled
*/
final public GeoElement [] Polygon(String [] labels, GeoList pointList) {
AlgoPolygon algo = new AlgoPolygon(cons, labels, pointList);
return algo.getOutput();
}
//END G.Sturr
/**
* polygon P[0], ..., P[n-1]
* The labels name the polygon itself and its segments
*/
final public GeoElement [] PolyLine(String [] labels, GeoPoint [] P) {
AlgoPolyLine algo = new AlgoPolyLine(cons, labels, P);
return algo.getOutput();
}
/**
* Polygon with vertices from geolist
* Only the polygon is labeled, segments are not labeled
*/
final public GeoElement [] PolyLine(String [] labels, GeoList pointList) {
AlgoPolyLine algo = new AlgoPolyLine(cons, labels, pointList);
return algo.getOutput();
}
final public GeoElement [] RigidPolygon(String [] labels, GeoPoint [] points) {
boolean oldMacroMode = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
GeoConic circle = Circle(null, points[0], new MyDouble(this, points[0].distance(points[1])));
cons.setSuppressLabelCreation(oldMacroMode);
GeoPoint p = Point(null, (Path)circle, points[1].inhomX, points[1].inhomY, true);
try {
cons.replace(points[1], p);
points[1] = p;
} catch (Exception e) {
e.printStackTrace();
return null;
}
StringBuilder sb = new StringBuilder();
double xA = points[0].inhomX;
double yA = points[0].inhomY;
double xB = points[1].inhomX;
double yB = points[1].inhomY;
GeoVec2D a = new GeoVec2D(this, xB - xA, yB - yA ); // vector AB
GeoVec2D b = new GeoVec2D(this, yA - yB, xB - xA ); // perpendicular to AB
a.makeUnitVector();
b.makeUnitVector();
for (int i = 2; i < points.length ; i++) {
double xC = points[i].inhomX;
double yC = points[i].inhomY;
GeoVec2D d = new GeoVec2D(this, xC - xA, yC - yA ); // vector AC
setTemporaryPrintFigures(15);
// make string like this
// A+3.76UnitVector[Segment[A,B]]+-1.74UnitPerpendicularVector[Segment[A,B]]
sb.setLength(0);
sb.append(points[0].getLabel());
sb.append('+');
sb.append(format(a.inner(d)));
// use internal command name
sb.append("UnitVector[Segment[");
sb.append(points[0].getLabel());
sb.append(',');
sb.append(points[1].getLabel());
sb.append("]]+");
sb.append(format(b.inner(d)));
// use internal command name
sb.append("UnitOrthogonalVector[Segment[");
sb.append(points[0].getLabel());
sb.append(',');
sb.append(points[1].getLabel());
sb.append("]]");
restorePrintAccuracy();
//Application.debug(sb.toString());
GeoPoint pp = (GeoPoint)getAlgebraProcessor().evaluateToPoint(sb.toString());
try {
cons.replace(points[i], pp);
points[i] = pp;
points[i].setEuclidianVisible(false);
points[i].update();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Application.debug(kernel.format(a.inner(d))+" UnitVector[Segment[A,B]] + "+kernel.format(b.inner(d))+" UnitPerpendicularVector[Segment[A,B]]");
points[0].setEuclidianVisible(false);
points[0].update();
return Polygon(labels, points);
}
/**
* Regular polygon with vertices A and B and n total vertices.
* The labels name the polygon itself, its segments and points
*/
final public GeoElement [] RegularPolygon(String [] labels, GeoPoint A, GeoPoint B, NumberValue n) {
AlgoPolygonRegular algo = new AlgoPolygonRegular(cons, labels, A, B, n);
return algo.getOutput();
}
//G.Sturr 2010-3-14
/**
* Polygon formed by operation on two input polygons.
* Possible operations: addition, subtraction or intersection
* The labels name the polygon itself, its segments and points
*/
final public GeoElement [] PolygonOperation(String [] labels, GeoPolygon A, GeoPolygon B, NumberValue n) {
AlgoPolygonOperation algo = new AlgoPolygonOperation(cons, labels, A, B,n);
return algo.getOutput();
}
//END G.Sturr
/**
* Creates new point B with distance n from A and new segment AB
* The labels[0] is for the segment, labels[1] for the new point
*/
final public GeoElement [] Segment (String [] labels, GeoPoint A, NumberValue n) {
// this is actually a macro
String pointLabel = null, segmentLabel = null;
if (labels != null) {
switch (labels.length) {
case 2:
pointLabel = labels[1];
case 1:
segmentLabel = labels[0];
default:
}
}
// create a circle around A with radius n
AlgoCirclePointRadius algoCircle = new AlgoCirclePointRadius(cons, A, n);
cons.removeFromConstructionList(algoCircle);
// place the new point on the circle
AlgoPointOnPath algoPoint = new AlgoPointOnPath(cons, pointLabel, algoCircle.getCircle(), A.inhomX+ n.getDouble(), A.inhomY );
// return segment and new point
GeoElement [] ret = { Segment(segmentLabel, A, algoPoint.getP()),
algoPoint.getP() };
return ret;
}
/**
* Creates a new point C by rotating B around A using angle alpha and
* a new angle BAC.
* The labels[0] is for the angle, labels[1] for the new point
*/
final public GeoElement [] Angle (String [] labels, GeoPoint B, GeoPoint A, NumberValue alpha) {
return Angle(labels, B, A, alpha, true);
}
/**
* Creates a new point C by rotating B around A using angle alpha and
* a new angle BAC (for positive orientation) resp. angle CAB (for negative orientation).
* The labels[0] is for the angle, labels[1] for the new point
*/
final public GeoElement [] Angle (String [] labels, GeoPoint B, GeoPoint A, NumberValue alpha, boolean posOrientation) {
// this is actually a macro
String pointLabel = null, angleLabel = null;
if (labels != null) {
switch (labels.length) {
case 2:
pointLabel = labels[1];
case 1:
angleLabel = labels[0];
default:
}
}
// rotate B around A using angle alpha
GeoPoint C = (GeoPoint) Rotate(pointLabel, B, alpha, A)[0];
// create angle according to orientation
GeoAngle angle;
if (posOrientation) {
angle = Angle(angleLabel, B, A, C);
} else {
angle = Angle(angleLabel, C, A, B);
}
//return angle and new point
GeoElement [] ret = { angle, C };
return ret;
}
/**
* Angle named label between line g and line h
*/
final public GeoAngle Angle(String label, GeoLine g, GeoLine h) {
AlgoAngleLines algo = new AlgoAngleLines(cons, label, g, h);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* Angle named label between vector v and vector w
*/
final public GeoAngle Angle(
String label,
GeoVector v,
GeoVector w) {
AlgoAngleVectors algo = new AlgoAngleVectors(cons, label, v, w);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* Angle named label for a point or a vector
*/
final public GeoAngle Angle(
String label,
GeoVec3D v) {
AlgoAngleVector algo = new AlgoAngleVector(cons, label, v);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* Angle named label between three points
*/
final public GeoAngle Angle(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoAnglePoints algo = new AlgoAnglePoints(cons, label, A, B, C);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* all angles of given polygon
*/
final public GeoAngle [] Angles(String [] labels, GeoPolygon poly) {
AlgoAnglePolygon algo = new AlgoAnglePolygon(cons, labels, poly);
GeoAngle [] angles = algo.getAngles();
//for (int i=0; i < angles.length; i++) {
// angles[i].setAlphaValue(0.0f);
//}
return angles;
}
/**
* IntersectLines yields intersection point named label of lines g, h
*/
final public GeoPoint IntersectLines(
String label,
GeoLine g,
GeoLine h) {
AlgoIntersectLines algo = new AlgoIntersectLines(cons, label, g, h);
GeoPoint S = algo.getPoint();
return S;
}
/**
* yields intersection point named label of line g and polygon p
*/
final public GeoElement[] IntersectLinePolygon(
String[] labels,
GeoLine g,
GeoPolygon p) {
AlgoIntersectLinePolygon algo = new AlgoIntersectLinePolygon(cons, labels, g, p);
return algo.getOutput();
}
/**
* Intersects f and g using starting point A (with Newton's root finding)
*/
final public GeoPoint IntersectFunctions(
String label,
GeoFunction f,
GeoFunction g, GeoPoint A) {
AlgoIntersectFunctionsNewton algo = new AlgoIntersectFunctionsNewton(cons, label, f, g, A);
GeoPoint S = algo.getIntersectionPoint();
return S;
}
/**
* Intersects f and l using starting point A (with Newton's root finding)
*/
final public GeoPoint IntersectFunctionLine(
String label,
GeoFunction f,
GeoLine l, GeoPoint A) {
AlgoIntersectFunctionLineNewton algo = new AlgoIntersectFunctionLineNewton(cons, label, f, l, A);
GeoPoint S = algo.getIntersectionPoint();
return S;
}
/*********************************************
* CONIC PART
*********************************************/
/**
* circle with midpoint M and radius r
*/
final public GeoConic Circle(
String label,
GeoPoint M,
NumberValue r) {
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, M, r);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint M and radius BC
* Michael Borcherds 2008-03-14
*/
final public GeoConic Circle(
// this is actually a macro
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C, boolean dummy) {
AlgoJoinPointsSegment algoSegment = new AlgoJoinPointsSegment(cons, B, C, null);
cons.removeFromConstructionList(algoSegment);
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, A, algoSegment.getSegment(),true);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint A and radius the same as circle
* Michael Borcherds 2008-03-14
*/
final public GeoConic Circle(
// this is actually a macro
String label,
GeoPoint A,
GeoConic c) {
AlgoRadius radius = new AlgoRadius(cons, c);
cons.removeFromConstructionList(radius);
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, A, radius.getRadius());
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint M and radius segment
* Michael Borcherds 2008-03-15
*/
final public GeoConic Circle(
String label,
GeoPoint A,
GeoSegment segment) {
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, A, segment, true);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint M through point P
*/
final public GeoConic Circle(String label, GeoPoint M, GeoPoint P) {
AlgoCircleTwoPoints algo = new AlgoCircleTwoPoints(cons, label, M, P);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* semicircle with midpoint M through point P
*/
final public GeoConicPart Semicircle(String label, GeoPoint M, GeoPoint P) {
AlgoSemicircle algo = new AlgoSemicircle(cons, label, M, P);
return algo.getSemicircle();
}
/**
* locus line for Q dependent on P. Note: P must be a point
* on a path.
*/
final public GeoLocus Locus(String label, GeoPoint Q, GeoPoint P) {
if (P.getPath() == null ||
Q.getPath() != null ||
!P.isParentOf(Q)) return null;
AlgoLocus algo = new AlgoLocus(cons, label, Q, P);
return algo.getLocus();
}
/**
* circle with through points A, B, C
*/
final public GeoConic Circle(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoCircleThreePoints algo = new AlgoCircleThreePoints(cons, label, A, B, C);
GeoConic circle = (GeoConic) algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* conic arc from conic and parameters
*/
final public GeoConicPart ConicArc(String label, GeoConic conic, NumberValue a, NumberValue b) {
AlgoConicPartConicParameters algo = new AlgoConicPartConicParameters(cons, label, conic, a, b,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* conic sector from conic and points
*/
final public GeoConicPart ConicArc(String label, GeoConic conic, GeoPoint P, GeoPoint Q) {
AlgoConicPartConicPoints algo = new AlgoConicPartConicPoints(cons, label, conic, P, Q,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* conic sector from conic and parameters
*/
final public GeoConicPart ConicSector(String label, GeoConic conic, NumberValue a, NumberValue b) {
AlgoConicPartConicParameters algo = new AlgoConicPartConicParameters(cons, label, conic, a, b,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* conic sector from conic and points
*/
final public GeoConicPart ConicSector(String label, GeoConic conic, GeoPoint P, GeoPoint Q) {
AlgoConicPartConicPoints algo = new AlgoConicPartConicPoints(cons, label, conic, P, Q,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* circle arc from three points
*/
final public GeoConicPart CircumcircleArc(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircumcircle algo = new AlgoConicPartCircumcircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* circle sector from three points
*/
final public GeoConicPart CircumcircleSector(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircumcircle algo = new AlgoConicPartCircumcircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* circle arc from center and twho points on arc
*/
final public GeoConicPart CircleArc(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircle algo = new AlgoConicPartCircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* circle sector from center and twho points on arc
*/
final public GeoConicPart CircleSector(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircle algo = new AlgoConicPartCircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* Focuses of conic. returns 2 GeoPoints
*/
final public GeoPoint[] Focus(String[] labels, GeoConic c) {
AlgoFocus algo = new AlgoFocus(cons, labels, c);
GeoPoint[] focus = algo.getFocus();
return focus;
}
/**
* Vertices of conic. returns 4 GeoPoints
*/
final public GeoPoint[] Vertex(String[] labels, GeoConic c) {
AlgoVertex algo = new AlgoVertex(cons, labels, c);
GeoPoint[] vertex = algo.getVertex();
return vertex;
}
/**
* Vertices of polygon. returns 3+ GeoPoints
*/
final public GeoElement[] Vertex(String[] labels, GeoPolygon p) {
AlgoVertexPolygon algo = new AlgoVertexPolygon(cons, labels, p);
GeoElement[] vertex = algo.getVertex();
return vertex;
}
/**
* Center of conic
*/
final public GeoPoint Center(String label, GeoConic c) {
AlgoCenterConic algo = new AlgoCenterConic(cons, label, c);
GeoPoint midpoint = algo.getPoint();
return midpoint;
}
/**
* Centroid of a
*/
final public GeoPoint Centroid(String label, GeoPolygon p) {
AlgoCentroidPolygon algo = new AlgoCentroidPolygon(cons, label, p);
GeoPoint centroid = algo.getPoint();
return centroid;
}
/**
* Corner of image
*/
final public GeoPoint Corner(String label, GeoImage img, NumberValue number) {
AlgoImageCorner algo = new AlgoImageCorner(cons, label, img, number);
return algo.getCorner();
}
/**
* Corner of text Michael Borcherds 2007-11-26
*/
final public GeoPoint Corner(String label, GeoText txt, NumberValue number) {
AlgoTextCorner algo = new AlgoTextCorner(cons, label, txt, number);
return algo.getCorner();
}
/**
* Corner of Drawing Pad Michael Borcherds 2008-05-10
*/
final public GeoPoint CornerOfDrawingPad(String label, NumberValue number) {
AlgoDrawingPadCorner algo = new AlgoDrawingPadCorner(cons, label, number);
return algo.getCorner();
}
/**
* parabola with focus F and line l
*/
final public GeoConic Parabola(
String label,
GeoPoint F,
GeoLine l) {
AlgoParabolaPointLine algo = new AlgoParabolaPointLine(cons, label, F, l);
GeoConic parabola = algo.getParabola();
return parabola;
}
/**
* ellipse with foci A, B and length of first half axis a
*/
final public GeoConic Ellipse(
String label,
GeoPoint A,
GeoPoint B,
NumberValue a) {
AlgoEllipseFociLength algo = new AlgoEllipseFociLength(cons, label, A, B, a);
GeoConic ellipse = algo.getConic();
return ellipse;
}
/**
* ellipse with foci A, B passing thorugh C
* Michael Borcherds 2008-04-06
*/
final public GeoConic Ellipse(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoEllipseFociPoint algo = new AlgoEllipseFociPoint(cons, label, A, B, C);
GeoConic ellipse = algo.getEllipse();
return ellipse;
}
/**
* hyperbola with foci A, B and length of first half axis a
*/
final public GeoConic Hyperbola(
String label,
GeoPoint A,
GeoPoint B,
NumberValue a) {
AlgoHyperbolaFociLength algo =
new AlgoHyperbolaFociLength(cons, label, A, B, a);
GeoConic hyperbola = algo.getConic();
return hyperbola;
}
/**
* hyperbola with foci A, B passing thorugh C
* Michael Borcherds 2008-04-06
*/
final public GeoConic Hyperbola(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoHyperbolaFociPoint algo =
new AlgoHyperbolaFociPoint(cons, label, A, B, C);
GeoConic hyperbola = algo.getHyperbola();
return hyperbola;
}
/**
* conic through five points
*/
final public GeoConic Conic(String label, GeoPoint[] points) {
AlgoConicFivePoints algo = new AlgoConicFivePoints(cons, label, points);
GeoConic conic = algo.getConic();
return conic;
}
/**
* IntersectLineConic yields intersection points named label1, label2
* of line g and conic c
*/
final public GeoPoint[] IntersectLineConic(
String[] labels,
GeoLine g,
GeoConic c) {
AlgoIntersectLineConic algo = getIntersectionAlgorithm(g, c);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
GeoElement.setLabels(labels, points);
return points;
}
/**
* IntersectConics yields intersection points named label1, label2, label3, label4
* of conics c1, c2
*/
final public GeoPoint[] IntersectConics(
String[] labels,
GeoConic a,
GeoConic b) {
AlgoIntersectConics algo = getIntersectionAlgorithm(a, b);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
GeoElement.setLabels(labels, points);
return points;
}
/**
* IntersectPolynomials yields all intersection points
* of polynomials a, b
*/
final public GeoPoint[] IntersectPolynomials(String[] labels, GeoFunction a, GeoFunction b) {
if (!a.isPolynomialFunction(false) || !b.isPolynomialFunction(false)) {
// dummy point
GeoPoint A = new GeoPoint(cons);
A.setZero();
AlgoIntersectFunctionsNewton algo = new AlgoIntersectFunctionsNewton(cons, labels[0], a, b, A);
GeoPoint[] ret = {algo.getIntersectionPoint()};
return ret;
}
AlgoIntersectPolynomials algo = getIntersectionAlgorithm(a, b);
algo.setPrintedInXML(true);
algo.setLabels(labels);
GeoPoint[] points = algo.getIntersectionPoints();
return points;
}
/**
* get only one intersection point of two polynomials a, b
* that is near to the given location (xRW, yRW)
*/
final public GeoPoint IntersectPolynomialsSingle(
String label, GeoFunction a, GeoFunction b,
double xRW, double yRW)
{
if (!a.isPolynomialFunction(false) || !b.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomials algo = getIntersectionAlgorithm(a, b);
int index = algo.getClosestPointIndex(xRW, yRW);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two polynomials a, b
* with given index
*/
final public GeoPoint IntersectPolynomialsSingle(
String label,
GeoFunction a,
GeoFunction b, NumberValue index) {
if (!a.isPolynomialFunction(false) || !b.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomials algo = getIntersectionAlgorithm(a, b); // index - 1 to start at 0
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* IntersectPolyomialLine yields all intersection points
* of polynomial f and line l
*/
final public GeoPoint[] IntersectPolynomialLine(
String[] labels,
GeoFunction f,
GeoLine l) {
if (!f.isPolynomialFunction(false)) {
// dummy point
GeoPoint A = new GeoPoint(cons);
A.setZero();
AlgoIntersectFunctionLineNewton algo = new AlgoIntersectFunctionLineNewton(cons, labels[0], f, l, A);
GeoPoint[] ret = {algo.getIntersectionPoint()};
return ret;
}
AlgoIntersectPolynomialLine algo = getIntersectionAlgorithm(f, l);
algo.setPrintedInXML(true);
algo.setLabels(labels);
GeoPoint[] points = algo.getIntersectionPoints();
return points;
}
/**
* one intersection point of polynomial f and line l near to (xRW, yRW)
*/
final public GeoPoint IntersectPolynomialLineSingle(
String label,
GeoFunction f,
GeoLine l, double xRW, double yRW) {
if (!f.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomialLine algo = getIntersectionAlgorithm(f, l);
int index = algo.getClosestPointIndex(xRW, yRW);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of a line and a function
*/
final public GeoPoint IntersectPolynomialLineSingle(
String label,
GeoFunction f,
GeoLine l, NumberValue index) {
if (!f.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomialLine algo = getIntersectionAlgorithm(f, l);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two conics that is near to the given
* location (xRW, yRW)
*/
final public GeoPoint IntersectLineConicSingle(
String label,
GeoLine g,
GeoConic c, double xRW, double yRW) {
AlgoIntersectLineConic algo = getIntersectionAlgorithm(g, c);
int index = algo.getClosestPointIndex(xRW, yRW);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of a line and a conic
*/
final public GeoPoint IntersectLineConicSingle(
String label,
GeoLine g,
GeoConic c, NumberValue index) {
AlgoIntersectLineConic algo = getIntersectionAlgorithm(g, c); // index - 1 to start at 0
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two conics that is near to the given
* location (xRW, yRW)
*/
final public GeoPoint IntersectConicsSingle(
String label,
GeoConic a,
GeoConic b, double xRW, double yRW) {
AlgoIntersectConics algo = getIntersectionAlgorithm(a, b);
int index = algo.getClosestPointIndex(xRW, yRW) ;
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two conics
*/
final public GeoPoint IntersectConicsSingle(
String label, GeoConic a, GeoConic b, NumberValue index) {
AlgoIntersectConics algo = getIntersectionAlgorithm(a, b); // index - 1 to start at 0
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of a polynomial and a conic
*/
final public GeoPoint[] IntersectPolynomialConic(
String[] labels,
GeoFunction f,
GeoConic c) {
AlgoIntersectPolynomialConic algo = getIntersectionAlgorithm(f, c);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
// GeoElement.setLabels(labels, points);
algo.setLabels(labels);
return points;
}
final public GeoPoint IntersectPolynomialConicSingle(String label,
GeoFunction f, GeoConic c,NumberValue idx){
AlgoIntersect algo = getIntersectionAlgorithm(f, c);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
final public GeoPoint IntersectPolynomialConicSingle(String label,
GeoFunction f, GeoConic c,double x,double y){
AlgoIntersect algo = getIntersectionAlgorithm(f, c);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of a implicitPoly and a line
*/
final public GeoPoint[] IntersectImplicitpolyLine(
String[] labels,
GeoImplicitPoly p,
GeoLine l) {
AlgoIntersectImplicitpolyParametric algo = getIntersectionAlgorithm(p, l);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of a implicitPoly and a line
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolyLineSingle(
String label,
GeoImplicitPoly p,
GeoLine l,NumberValue idx) {
AlgoIntersect algo = getIntersectionAlgorithm(p, l);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of a implicitPoly and a line
*/
final public GeoPoint IntersectImplicitpolyLineSingle(
String label,
GeoImplicitPoly p,
GeoLine l,double x,double y) {
AlgoIntersect algo = getIntersectionAlgorithm(p, l);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of a implicitPoly and a polynomial
*/
final public GeoPoint[] IntersectImplicitpolyPolynomial(
String[] labels,
GeoImplicitPoly p,
GeoFunction f) {
if (!f.isPolynomialFunction(false))
return null;
AlgoIntersectImplicitpolyParametric algo = getIntersectionAlgorithm(p, f);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of a implicitPoly and a line
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolyPolynomialSingle(
String label,
GeoImplicitPoly p,
GeoFunction f,NumberValue idx) {
if (!f.isPolynomialFunction(false))
return null;
AlgoIntersect algo = getIntersectionAlgorithm(p, f);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of a implicitPoly and a line
*/
final public GeoPoint IntersectImplicitpolyPolynomialSingle(
String label,
GeoImplicitPoly p,
GeoFunction f,double x,double y) {
if (!f.isPolynomialFunction(false))
return null;
AlgoIntersect algo = getIntersectionAlgorithm(p, f);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of two implicitPolys
*/
final public GeoPoint[] IntersectImplicitpolys(
String[] labels,
GeoImplicitPoly p1,
GeoImplicitPoly p2) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, p2);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of two implicitPolys
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolysSingle(
String label,
GeoImplicitPoly p1,
GeoImplicitPoly p2,NumberValue idx) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, p2);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of two implicitPolys near given Point (x,y)
* @param x
* @param y
*/
final public GeoPoint IntersectImplicitpolysSingle(
String label,
GeoImplicitPoly p1,
GeoImplicitPoly p2,double x,double y) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, p2);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of implicitPoly and conic
*/
final public GeoPoint[] IntersectImplicitpolyConic(
String[] labels,
GeoImplicitPoly p1,
GeoConic c1) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, c1);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of implicitPoly and conic
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolyConicSingle(
String label,
GeoImplicitPoly p1,
GeoConic c1,NumberValue idx) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, c1);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of implicitPolys and conic near given Point (x,y)
* @param x
* @param y
*/
final public GeoPoint IntersectImplicitpolyConicSingle(
String label,
GeoImplicitPoly p1,
GeoConic c1,double x,double y) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, c1);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/*
* to avoid multiple calculations of the intersection points of the same
* two objects, we remember all the intersection algorithms created
*/
private ArrayList intersectionAlgos = new ArrayList();
// intersect polynomial and conic
AlgoIntersectPolynomialConic getIntersectionAlgorithm(GeoFunction f, GeoConic c) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(f, c);
if (existingAlgo != null) return (AlgoIntersectPolynomialConic) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectPolynomialConic algo = new AlgoIntersectPolynomialConic(cons, f, c);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersect line and conic
AlgoIntersectLineConic getIntersectionAlgorithm(GeoLine g, GeoConic c) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(g, c);
if (existingAlgo != null) return (AlgoIntersectLineConic) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectLineConic algo = new AlgoIntersectLineConic(cons, g, c);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersect conics
AlgoIntersectConics getIntersectionAlgorithm(GeoConic a, GeoConic b) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(a, b);
if (existingAlgo != null) return (AlgoIntersectConics) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectConics algo = new AlgoIntersectConics(cons, a, b);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of polynomials
AlgoIntersectPolynomials getIntersectionAlgorithm(GeoFunction a, GeoFunction b) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(a, b);
if (existingAlgo != null) return (AlgoIntersectPolynomials) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectPolynomials algo = new AlgoIntersectPolynomials(cons, a, b);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of polynomials
AlgoIntersectPolynomialLine getIntersectionAlgorithm(GeoFunction a, GeoLine l) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(a, l);
if (existingAlgo != null) return (AlgoIntersectPolynomialLine) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectPolynomialLine algo = new AlgoIntersectPolynomialLine(cons, a, l);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of GeoImplicitPoly, GeoLine
AlgoIntersectImplicitpolyParametric getIntersectionAlgorithm(GeoImplicitPoly p, GeoLine l) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p, l);
if (existingAlgo != null) return (AlgoIntersectImplicitpolyParametric) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolyParametric algo = new AlgoIntersectImplicitpolyParametric(cons, p, l);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of GeoImplicitPoly, polynomial
AlgoIntersectImplicitpolyParametric getIntersectionAlgorithm(GeoImplicitPoly p, GeoFunction f) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p, f);
if (existingAlgo != null) return (AlgoIntersectImplicitpolyParametric) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolyParametric algo = new AlgoIntersectImplicitpolyParametric(cons, p, f);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of two GeoImplicitPoly
AlgoIntersectImplicitpolys getIntersectionAlgorithm(GeoImplicitPoly p1, GeoImplicitPoly p2) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p1, p2);
if (existingAlgo != null) return (AlgoIntersectImplicitpolys) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolys algo = new AlgoIntersectImplicitpolys(cons, p1, p2);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
AlgoIntersectImplicitpolys getIntersectionAlgorithm(GeoImplicitPoly p1, GeoConic c1) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p1, c1);
if (existingAlgo != null) return (AlgoIntersectImplicitpolys) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolys algo = new AlgoIntersectImplicitpolys(cons, p1, c1);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
private AlgoElement findExistingIntersectionAlgorithm(GeoElement a, GeoElement b) {
int size = intersectionAlgos.size();
AlgoElement algo;
for (int i=0; i < size; i++) {
algo = (AlgoElement) intersectionAlgos.get(i);
GeoElement [] input = algo.getInput();
if (a == input[0] && b == input[1] ||
a == input[1] && b == input[0])
// we found an existing intersection algorithm
return algo;
}
return null;
}
void removeIntersectionAlgorithm(AlgoIntersect algo) {
intersectionAlgos.remove(algo);
}
/**
* polar line to P relativ to c
*/
final public GeoLine PolarLine(
String label,
GeoPoint P,
GeoConic c) {
AlgoPolarLine algo = new AlgoPolarLine(cons, label, c, P);
GeoLine polar = algo.getLine();
return polar;
}
/**
* diameter line conjugate to direction of g relative to c
*/
final public GeoLine DiameterLine(
String label,
GeoLine g,
GeoConic c) {
AlgoDiameterLine algo = new AlgoDiameterLine(cons, label, c, g);
GeoLine diameter = algo.getDiameter();
return diameter;
}
/**
* diameter line conjugate to v relative to c
*/
final public GeoLine DiameterLine(
String label,
GeoVector v,
GeoConic c) {
AlgoDiameterVector algo = new AlgoDiameterVector(cons, label, c, v);
GeoLine diameter = algo.getDiameter();
return diameter;
}
/**
* tangents to c through P
*/
final public GeoLine[] Tangent(
String[] labels,
GeoPoint P,
GeoConic c) {
AlgoTangentPoint algo = new AlgoTangentPoint(cons, labels, P, c);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* tangents to c parallel to g
*/
final public GeoLine[] Tangent(
String[] labels,
GeoLine g,
GeoConic c) {
AlgoTangentLine algo = new AlgoTangentLine(cons, labels, g, c);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* tangent to f in x = a
*/
final public GeoLine Tangent(
String label,
NumberValue a,
GeoFunction f) {
AlgoTangentFunctionNumber algo =
new AlgoTangentFunctionNumber(cons, label, a, f);
GeoLine t = algo.getTangent();
t.setToExplicit();
t.update();
notifyUpdate(t);
return t;
}
/**
* tangent to f in x = x(P)
*/
final public GeoLine Tangent(
String label,
GeoPoint P,
GeoFunction f) {
AlgoTangentFunctionPoint algo =
new AlgoTangentFunctionPoint(cons, label, P, f);
GeoLine t = algo.getTangent();
t.setToExplicit();
t.update();
notifyUpdate(t);
return t;
}
/**
* tangents to p through P
*/
final public GeoLine[] Tangent(
String[] labels,
GeoPoint R,
GeoImplicitPoly p) {
AlgoTangentImplicitpoly algo = new AlgoTangentImplicitpoly(cons, labels, p, R);
algo.setLabels(labels);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* tangents to p parallel to g
*/
final public GeoLine[] Tangent(
String[] labels,
GeoLine g,
GeoImplicitPoly p) {
AlgoTangentImplicitpoly algo = new AlgoTangentImplicitpoly(cons, labels, p, g);
algo.setLabels(labels);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* asymptotes to c
*/
final public GeoLine[] Asymptote(String[] labels, GeoConic c) {
AlgoAsymptote algo = new AlgoAsymptote(cons, labels, c);
GeoLine[] asymptotes = algo.getAsymptotes();
return asymptotes;
}
/**
* axes of c
*/
final public GeoLine[] Axes(String[] labels, GeoConic c) {
AlgoAxes algo = new AlgoAxes(cons, labels, c);
GeoLine[] axes = algo.getAxes();
return axes;
}
/**
* first axis of c
*/
final public GeoLine FirstAxis(String label, GeoConic c) {
AlgoAxisFirst algo = new AlgoAxisFirst(cons, label, c);
GeoLine axis = algo.getAxis();
return axis;
}
/**
* second axis of c
*/
final public GeoLine SecondAxis(String label, GeoConic c) {
AlgoAxisSecond algo = new AlgoAxisSecond(cons, label, c);
GeoLine axis = algo.getAxis();
return axis;
}
/**
* directrix of c
*/
final public GeoLine Directrix(String label, GeoConic c) {
AlgoDirectrix algo = new AlgoDirectrix(cons, label, c);
GeoLine directrix = algo.getDirectrix();
return directrix;
}
/**
* linear eccentricity of c
*/
final public GeoNumeric Excentricity(String label, GeoConic c) {
AlgoExcentricity algo = new AlgoExcentricity(cons, label, c);
GeoNumeric linearEccentricity = algo.getLinearEccentricity();
return linearEccentricity;
}
/**
* eccentricity of c
*/
final public GeoNumeric Eccentricity(String label, GeoConic c) {
AlgoEccentricity algo = new AlgoEccentricity(cons, label, c);
GeoNumeric eccentricity = algo.getEccentricity();
return eccentricity;
}
/**
* first axis' length of c
*/
final public GeoNumeric FirstAxisLength(String label, GeoConic c) {
AlgoAxisFirstLength algo = new AlgoAxisFirstLength(cons, label, c);
GeoNumeric length = algo.getLength();
return length;
}
/**
* second axis' length of c
*/
final public GeoNumeric SecondAxisLength(String label, GeoConic c) {
AlgoAxisSecondLength algo = new AlgoAxisSecondLength(cons, label, c);
GeoNumeric length = algo.getLength();
return length;
}
/**
* (parabola) parameter of c
*/
final public GeoNumeric Parameter(String label, GeoConic c) {
AlgoParabolaParameter algo = new AlgoParabolaParameter(cons, label, c);
GeoNumeric length = algo.getParameter();
return length;
}
/**
* (circle) radius of c
*/
final public GeoNumeric Radius(String label, GeoConic c) {
AlgoRadius algo = new AlgoRadius(cons, label, c);
GeoNumeric length = algo.getRadius();
return length;
}
/**
* angle of c (angle between first eigenvector and (1,0))
*/
final public GeoAngle Angle(String label, GeoConic c) {
AlgoAngleConic algo = new AlgoAngleConic(cons, label, c);
GeoAngle angle = algo.getAngle();
return angle;
}
/********************************************************************
* TRANSFORMATIONS
********************************************************************/
/**
* translate geoTrans by vector v
*/
final public GeoElement [] Translate(String label, GeoElement geoTrans, GeoVec3D v) {
Transform t = new TransformTranslate(v);
return t.transform(geoTrans, label);
}
/**
* translates vector v to point A. The resulting vector is equal
* to v and has A as startPoint
*/
final public GeoVector Translate(String label, GeoVec3D v, GeoPoint A) {
AlgoTranslateVector algo = new AlgoTranslateVector(cons, label, v, A);
GeoVector vec = algo.getTranslatedVector();
return vec;
}
/**
* rotate geoRot by angle phi around (0,0)
*/
final public GeoElement [] Rotate(String label, GeoElement geoRot, NumberValue phi) {
Transform t = new TransformRotate(phi);
return t.transform(geoRot, label);
}
/**
* rotate geoRot by angle phi around Q
*/
final public GeoElement [] Rotate(String label, GeoElement geoRot, NumberValue phi, GeoPoint Q) {
Transform t = new TransformRotate(phi,Q);
return t.transform(geoRot, label);
}
/**
* dilate geoRot by r from S
*/
final public GeoElement [] Dilate(String label, GeoElement geoDil, NumberValue r, GeoPoint S) {
Transform t = new TransformDilate(r,S);
return t.transform(geoDil, label);
}
/**
* dilate geoRot by r from origin
*/
final public GeoElement [] Dilate(String label, GeoElement geoDil, NumberValue r) {
Transform t = new TransformDilate(r);
return t.transform(geoDil, label);
}
/**
* mirror geoMir at point Q
*/
final public GeoElement [] Mirror(String label, GeoElement geoMir, GeoPoint Q) {
Transform t = new TransformMirror(Q);
return t.transform(geoMir, label);
}
/**
* mirror (invert) element Q in circle
* Michael Borcherds 2008-02-10
*/
final public GeoElement [] Mirror(String label, GeoElement Q, GeoConic conic) {
Transform t = new TransformMirror(conic);
return t.transform(Q, label);
}
/**
* apply matrix
* Michael Borcherds 2010-05-27
*/
final public GeoElement [] ApplyMatrix(String label, GeoElement Q, GeoList matrix) {
Transform t = new TransformApplyMatrix(matrix);
return t.transform(Q, label);
}
/**
* shear
*/
final public GeoElement [] Shear(String label, GeoElement Q, GeoVec3D l, GeoNumeric num) {
Transform t = new TransformShearOrStretch(l,num,true);
return t.transform(Q, label);
}
/**
* apply matrix
* Michael Borcherds 2010-05-27
*/
final public GeoElement [] Stretch(String label, GeoElement Q, GeoVec3D l, GeoNumeric num) {
Transform t = new TransformShearOrStretch(l,num,false);
return t.transform(Q, label);
}
/**
* mirror geoMir at line g
*/
final public GeoElement [] Mirror(String label, GeoElement geoMir, GeoLine g) {
Transform t = new TransformMirror(g);
return t.transform(geoMir, label);
}
static final int TRANSFORM_TRANSLATE = 0;
static final int TRANSFORM_MIRROR_AT_POINT = 1;
static final int TRANSFORM_MIRROR_AT_LINE = 2;
static final int TRANSFORM_ROTATE = 3;
static final int TRANSFORM_ROTATE_AROUND_POINT = 4;
static final int TRANSFORM_DILATE = 5;
public static boolean keepOrientationForTransformation(int transformationType) {
switch (transformationType) {
case TRANSFORM_MIRROR_AT_LINE:
return false;
default:
return true;
}
}
/***********************************
* CALCULUS
***********************************/
/** function limited to interval [a, b]
*/
final public GeoFunction Function(String label, GeoFunction f,
NumberValue a, NumberValue b) {
AlgoFunctionInterval algo = new AlgoFunctionInterval(cons, label, f, a, b);
GeoFunction g = algo.getFunction();
return g;
}
/**
* n-th derivative of multivariate function f
*/
final public GeoElement Derivative(
String label,
CasEvaluableFunction f, GeoNumeric var,
NumberValue n) {
AlgoCasDerivative algo = new AlgoCasDerivative(cons, label, f, var, n);
return algo.getResult();
}
/**
* Tries to expand a function f to a polynomial.
*/
final public GeoFunction PolynomialFunction(String label, GeoFunction f) {
AlgoPolynomialFromFunction algo = new AlgoPolynomialFromFunction(cons, label, f);
return algo.getPolynomial();
}
/**
* Fits a polynomial exactly to a list of coordinates
* Michael Borcherds 2008-01-22
*/
final public GeoFunction PolynomialFunction(String label, GeoList list) {
AlgoPolynomialFromCoordinates algo = new AlgoPolynomialFromCoordinates(cons, label, list);
return algo.getPolynomial();
}
final public GeoElement Expand(String label, CasEvaluableFunction func) {
AlgoCasExpand algo = new AlgoCasExpand(cons, label, func);
return algo.getResult();
}
final public GeoElement Simplify(String label, CasEvaluableFunction func) {
AlgoCasSimplify algo = new AlgoCasSimplify(cons, label, func);
return algo.getResult();
}
final public GeoElement SolveODE(String label, CasEvaluableFunction func) {
AlgoCasSolveODE algo = new AlgoCasSolveODE(cons, label, func);
return algo.getResult();
}
/**
* Simplify text, eg "+-x" to "-x"
* @author Michael Borcherds
*/
final public GeoElement Simplify(String label, GeoText text) {
AlgoSimplifyText algo = new AlgoSimplifyText(cons, label, text);
return algo.getGeoText();
}
final public GeoElement DynamicCoordinates(String label, GeoPoint geoPoint,
NumberValue num1, NumberValue num2) {
AlgoDynamicCoordinates algo = new AlgoDynamicCoordinates(cons, label, geoPoint, num1, num2);
return algo.getPoint();
}
final public GeoElement Factor(String label, CasEvaluableFunction func) {
AlgoCasFactor algo = new AlgoCasFactor(cons, label, func);
return algo.getResult();
}
/**
* Factors
* Michael Borcherds
*/
final public GeoList Factors(String label, GeoFunction func) {
AlgoFactors algo = new AlgoFactors(cons, label, func);
return algo.getResult();
}
final public GeoLocus SolveODE(String label, FunctionalNVar f, FunctionalNVar g, GeoNumeric x, GeoNumeric y, GeoNumeric end, GeoNumeric step) {
AlgoSolveODE algo = new AlgoSolveODE(cons, label, f, g, x, y, end, step);
return algo.getResult();
}
/*
* second order ODEs
*/
final public GeoLocus SolveODE2(String label, GeoFunctionable f, GeoFunctionable g, GeoFunctionable h, GeoNumeric x, GeoNumeric y, GeoNumeric yDot, GeoNumeric end, GeoNumeric step) {
AlgoSolveODE2 algo = new AlgoSolveODE2(cons, label, f, g, h, x, y, yDot, end, step);
return algo.getResult();
}
/**
* Asymptotes
* Michael Borcherds
*/
final public GeoList AsymptoteFunction(String label, GeoFunction func) {
AlgoAsymptoteFunction algo = new AlgoAsymptoteFunction(cons, label, func);
return algo.getResult();
}
/**
* Numerator
* Michael Borcherds
*/
final public GeoFunction Numerator(String label, GeoFunction func) {
AlgoNumerator algo = new AlgoNumerator(cons, label, func);
return algo.getResult();
}
/**
* Denominator
* Michael Borcherds
*/
final public GeoFunction Denominator(String label, GeoFunction func) {
AlgoDenominator algo = new AlgoDenominator(cons, label, func);
return algo.getResult();
}
/**
* Degree
* Michael Borcherds
*/
final public GeoNumeric Degree(String label, GeoFunction func) {
AlgoDegree algo = new AlgoDegree(cons, label, func);
return algo.getResult();
}
/**
* Limit
* Michael Borcherds
*/
final public GeoNumeric Limit(String label, GeoFunction func, NumberValue num) {
AlgoLimit algo = new AlgoLimit(cons, label, func, num);
return algo.getResult();
}
/**
* LimitBelow
* Michael Borcherds
*/
final public GeoNumeric LimitBelow(String label, GeoFunction func, NumberValue num) {
AlgoLimitBelow algo = new AlgoLimitBelow(cons, label, func, num);
return algo.getResult();
}
/**
* LimitAbove
* Michael Borcherds
*/
final public GeoNumeric LimitAbove(String label, GeoFunction func, NumberValue num) {
AlgoLimitAbove algo = new AlgoLimitAbove(cons, label, func, num);
return algo.getResult();
}
/**
* Partial Fractions
* Michael Borcherds
*/
final public GeoElement PartialFractions(String label, CasEvaluableFunction func) {
AlgoCasPartialFractions algo = new AlgoCasPartialFractions(cons, label, func);
return algo.getResult();
}
/**
* Coefficients
* Michael Borcherds 2008-04-04
*/
final public GeoList Coefficients(String label, GeoFunction func) {
AlgoCoefficients algo = new AlgoCoefficients(cons, label, func);
return algo.getResult();
}
/**
* Coefficients
* Michael Borcherds 2008-04-04
*/
final public GeoList Coefficients(String label, GeoConic func) {
AlgoConicCoefficients algo = new AlgoConicCoefficients(cons, label, func);
return algo.getResult();
}
/**
* Taylor series of function f about point x=a of order n
*/
final public GeoFunction TaylorSeries(
String label,
GeoFunction f,
NumberValue a,
NumberValue n) {
AlgoTaylorSeries algo = new AlgoTaylorSeries(cons, label, f, a, n);
return algo.getPolynomial();
}
/**
* Integral of function f
*/
final public GeoElement Integral(String label, CasEvaluableFunction f, GeoNumeric var) {
AlgoCasIntegral algo = new AlgoCasIntegral(cons, label, f, var);
return algo.getResult();
}
/**
* definite Integral of function f from x=a to x=b
*/
final public GeoNumeric Integral(String label, GeoFunction f, NumberValue a, NumberValue b) {
AlgoIntegralDefinite algo = new AlgoIntegralDefinite(cons, label, f, a, b);
GeoNumeric n = algo.getIntegral();
return n;
}
/**
* definite integral of function (f - g) in interval [a, b]
*/
final public GeoNumeric Integral(String label, GeoFunction f, GeoFunction g,
NumberValue a, NumberValue b) {
AlgoIntegralFunctions algo = new AlgoIntegralFunctions(cons, label, f, g, a, b);
GeoNumeric num = algo.getIntegral();
return num;
}
/**
*
*/
final public GeoPoint [] PointsFromList(String [] labels, GeoList list) {
AlgoPointsFromList algo = new AlgoPointsFromList(cons, labels, true, list);
GeoPoint [] g = algo.getPoints();
return g;
}
/**
* all Roots of polynomial f (works only for polynomials and functions
* that can be simplified to factors of polynomials, e.g. sqrt(x) to x)
*/
final public GeoPoint [] Root(String [] labels, GeoFunction f) {
// allow functions that can be simplified to factors of polynomials
if (!f.isPolynomialFunction(true)) return null;
AlgoRootsPolynomial algo = new AlgoRootsPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* all Complex Roots of polynomial f (works only for polynomials)
*/
final public GeoPoint [] ComplexRoot(String [] labels, GeoFunction f) {
// allow functions that can be simplified to factors of polynomials
if (!f.isPolynomialFunction(true)) return null;
AlgoComplexRootsPolynomial algo = new AlgoComplexRootsPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* Root of a function f to given start value a (works only if first derivative of f exists)
*/
final public GeoPoint Root(String label, GeoFunction f, NumberValue a) {
AlgoRootNewton algo = new AlgoRootNewton(cons, label, f, a);
GeoPoint p = algo.getRootPoint();
return p;
}
/**
* Root of a function f in given interval [a, b]
*/
final public GeoPoint Root(String label, GeoFunction f, NumberValue a, NumberValue b) {
AlgoRootInterval algo = new AlgoRootInterval(cons, label, f, a, b);
GeoPoint p = algo.getRootPoint();
return p;
}
/**
* all Extrema of function f (works only for polynomials)
*/
final public GeoPoint [] Extremum(String [] labels, GeoFunction f) {
// check if this is a polynomial at the moment
if (!f.isPolynomialFunction(true)) return null;
AlgoExtremumPolynomial algo = new AlgoExtremumPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* all Turning points of function f (works only for polynomials)
*/
final public GeoPoint [] TurningPoint(String [] labels, GeoFunction f) {
// check if this is a polynomial at the moment
if (!f.isPolynomialFunction(true)) return null;
AlgoTurningPointPolynomial algo = new AlgoTurningPointPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* Victor Franco Espino 18-04-2007: New commands
*
* Calculate affine ratio: (A,B,C) = (t(C)-t(A)) : (t(C)-t(B))
*/
final public GeoNumeric AffineRatio(String label, GeoPoint A, GeoPoint B,
GeoPoint C) {
AlgoAffineRatio affine = new AlgoAffineRatio(cons, label, A, B, C);
GeoNumeric M = affine.getResult();
return M;
}
/**
* Calculate cross ratio: (A,B,C,D) = affineRatio(A, B, C) / affineRatio(A, B, D)
*/
final public GeoNumeric CrossRatio(String label,GeoPoint A,GeoPoint B,GeoPoint C,GeoPoint D){
AlgoCrossRatio cross = new AlgoCrossRatio(cons,label,A,B,C,D);
GeoNumeric M = cross.getResult();
return M;
}
/**
* Calculate Curvature Vector for function: c(x) = (1/T^4)*(-f'*f'',f''), T = sqrt(1+(f')^2)
*/
final public GeoVector CurvatureVector(String label,GeoPoint A,GeoFunction f){
AlgoCurvatureVector algo = new AlgoCurvatureVector(cons,label,A,f);
GeoVector v = algo.getVector();
return v;
}
/**
* Calculate Curvature Vector for curve: c(t) = ((a'(t)b''(t)-a''(t)b'(t))/T^4) * (-b'(t),a'(t))
* T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoVector CurvatureVectorCurve(String label,GeoPoint A,GeoCurveCartesian f){
AlgoCurvatureVectorCurve algo = new AlgoCurvatureVectorCurve(cons,label,A,f);
GeoVector v = algo.getVector();
return v;
}
/**
* Calculate Curvature for function: k(x) = f''/T^3, T = sqrt(1+(f')^2)
*/
final public GeoNumeric Curvature(String label,GeoPoint A,GeoFunction f){
AlgoCurvature algo = new AlgoCurvature(cons,label,A,f);
GeoNumeric k = algo.getResult();
return k;
}
/**
* Calculate Curvature for Curve: k(t) = (a'(t)b''(t)-a''(t)b'(t))/T^3, T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoNumeric CurvatureCurve(String label,GeoPoint A, GeoCurveCartesian f){
AlgoCurvatureCurve algo = new AlgoCurvatureCurve(cons,label,A,f);
GeoNumeric k = algo.getResult();
return k;
}
/**
* Osculating Circle of a function f in point A
*/
final public GeoConic OsculatingCircle(String label,GeoPoint A,GeoFunction f){
AlgoOsculatingCircle algo = new AlgoOsculatingCircle(cons,label,A,f);
GeoConic circle = algo.getCircle();
return circle;
}
/**
* Osculating Circle of a curve f in point A
*/
final public GeoConic OsculatingCircleCurve(String label,GeoPoint A,GeoCurveCartesian f){
AlgoOsculatingCircleCurve algo = new AlgoOsculatingCircleCurve(cons,label,A,f);
GeoConic circle = algo.getCircle();
return circle;
}
/**
* Calculate Function Length between the numbers A and B: integral from A to B on T = sqrt(1+(f')^2)
*/
final public GeoNumeric FunctionLength(String label,GeoFunction f,GeoNumeric A,GeoNumeric B){
AlgoLengthFunction algo = new AlgoLengthFunction(cons,label,f,A,B);
GeoNumeric length = algo.getLength();
return length;
}
/**
* Calculate Function Length between the points A and B: integral from A to B on T = sqrt(1+(f')^2)
*/
final public GeoNumeric FunctionLength2Points(String label,GeoFunction f,GeoPoint A,GeoPoint B){
AlgoLengthFunction2Points algo = new AlgoLengthFunction2Points(cons,label,f,A,B);
GeoNumeric length = algo.getLength();
return length;
}
/**
* Calculate Curve Length between the parameters t0 and t1: integral from t0 to t1 on T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoNumeric CurveLength(String label, GeoCurveCartesian c, GeoNumeric t0,GeoNumeric t1){
AlgoLengthCurve algo = new AlgoLengthCurve(cons,label,c,t0,t1);
GeoNumeric length = algo.getLength();
return length;
}
/**
* Calculate Curve Length between the points A and B: integral from t0 to t1 on T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoNumeric CurveLength2Points(String label, GeoCurveCartesian c, GeoPoint A,GeoPoint B){
AlgoLengthCurve2Points algo = new AlgoLengthCurve2Points(cons,label,c,A,B);
GeoNumeric length = algo.getLength();
return length;
}
/**
* tangent to Curve f in point P: (b'(t), -a'(t), a'(t)*b(t)-a(t)*b'(t))
*/
final public GeoLine Tangent(String label,GeoPoint P,GeoCurveCartesian f) {
AlgoTangentCurve algo = new AlgoTangentCurve(cons, label, P, f);
GeoLine t = algo.getTangent();
t.setToExplicit();
t.update();
notifyUpdate(t);
return t;
}
/**
* Victor Franco Espino 18-04-2007: End new commands
*/
/***********************************
* PACKAGE STUFF
***********************************/
/** if x is nearly zero, 0.0 is returned,
* else x is returned
*/
final public double chop(double x) {
if (isZero(x))
return 0.0d;
else
return x;
}
final public boolean isReal(Complex c) {
return isZero(c.getImaginary());
}
/** is abs(x) < epsilon ? */
final public static boolean isZero(double x) {
return -EPSILON < x && x < EPSILON;
}
final boolean isZero(double[] a) {
for (int i = 0; i < a.length; i++) {
if (!isZero(a[i]))
return false;
}
return true;
}
final public boolean isInteger(double x) {
if (x > 1E17)
return true;
else
return isEqual(x, Math.round(x));
}
/**
* Returns whether x is equal to y
* infinity == infinity returns true eg 1/0
* -infinity == infinity returns false eg -1/0
* -infinity == -infinity returns true
* undefined == undefined returns false eg 0/0
*/
final public static boolean isEqual(double x, double y) {
if (x == y) // handles infinity and NaN cases
return true;
else
return x - EPSILON <= y && y <= x + EPSILON;
}
final public static boolean isEqual(double x, double y, double eps) {
if (x == y) // handles infinity and NaN cases
return true;
else
return x - eps < y && y < x + eps;
}
/**
* Returns whether x is greater than y
*/
final public boolean isGreater(double x, double y) {
return x > y + EPSILON;
}
/**
* Returns whether x is greater than or equal to y
*/
final public boolean isGreaterEqual(double x, double y) {
return x + EPSILON > y;
}
// compares double arrays:
// yields true if (isEqual(a[i], b[i]) == true) for all i
final boolean isEqual(double[] a, double[] b) {
for (int i = 0; i < a.length; ++i) {
if (!isEqual(a[i], b[i]))
return false;
}
return true;
}
final public double convertToAngleValue(double val) {
if (val > EPSILON && val < PI_2) return val;
double value = val % PI_2;
if (isZero(value)) {
if (val < 1.0) value = 0.0;
else value = PI_2;
}
else if (value < 0.0) {
value += PI_2;
}
return value;
}
/*
// calc acos(x). returns 0 for x > 1 and pi for x < -1
final static double trimmedAcos(double x) {
if (Math.abs(x) <= 1.0d)
return Math.acos(x);
else if (x > 1.0d)
return 0.0d;
else if (x < -1.0d)
return Math.PI;
else
return Double.NaN;
}*/
/** returns max of abs(a[i]) */
final static double maxAbs(double[] a) {
double temp, max = Math.abs(a[0]);
for (int i = 1; i < a.length; i++) {
temp = Math.abs(a[i]);
if (temp > max)
max = temp;
}
return max;
}
// copy array a to array b
final static void copy(double[] a, double[] b) {
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
}
// change signs of double array values, write result to array b
final static void negative(double[] a, double[] b) {
for (int i = 0; i < a.length; i++) {
b[i] = -a[i];
}
}
// c[] = a[] / b
final static void divide(double[] a, double b, double[] c) {
for (int i = 0; i < a.length; i++) {
c[i] = a[i] / b;
}
}
// temp for buildEquation
private double[] temp;// = new double[6];
// lhs of implicit equation without constant coeff
final private StringBuilder buildImplicitVarPart(
double[] numbers,
String[] vars,
boolean KEEP_LEADING_SIGN,
boolean CANCEL_DOWN) {
temp = new double[numbers.length];
int leadingNonZero = -1;
sbBuildImplicitVarPart.setLength(0);
for (int i = 0; i < vars.length; i++) {
if (!isZero(numbers[i])) {
leadingNonZero = i;
break;
}
}
if (CANCEL_DOWN) {
// check if integers and divide through gcd
boolean allIntegers = true;
for (int i = 0; i < numbers.length; i++) {
allIntegers = allIntegers && isInteger(numbers[i]);
}
if (allIntegers) {
// divide by greates common divisor
divide(numbers, gcd(numbers), numbers);
}
}
// no left hand side
if (leadingNonZero == -1) {
sbBuildImplicitVarPart.append("0");
return sbBuildImplicitVarPart;
}
// don't change leading coefficient
if (KEEP_LEADING_SIGN) {
copy(numbers, temp);
} else {
if (numbers[leadingNonZero] < 0)
negative(numbers, temp);
else
copy(numbers, temp);
}
// BUILD EQUATION STRING
// valid left hand side
// leading coefficient
String strCoeff = formatCoeff(temp[leadingNonZero]);
sbBuildImplicitVarPart.append(strCoeff);
sbBuildImplicitVarPart.append(vars[leadingNonZero]);
// other coefficients on lhs
String sign;
double abs;
for (int i = leadingNonZero + 1; i < vars.length; i++) {
if (temp[i] < 0.0) {
sign = " - ";
abs = -temp[i];
} else {
sign = " + ";
abs = temp[i];
}
if (abs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildImplicitVarPart.append(sign);
sbBuildImplicitVarPart.append(formatCoeff(abs));
sbBuildImplicitVarPart.append(vars[i]);
}
}
return sbBuildImplicitVarPart;
}
private StringBuilder sbBuildImplicitVarPart = new StringBuilder(80);
public final StringBuilder buildImplicitEquation(
double[] numbers,
String[] vars,
boolean KEEP_LEADING_SIGN,
boolean CANCEL_DOWN,
char op) {
sbBuildImplicitEquation.setLength(0);
Application.debug("implicit");
sbBuildImplicitEquation.append(buildImplicitVarPart(numbers, vars, KEEP_LEADING_SIGN || (op == '='), CANCEL_DOWN));
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER) {
sbBuildImplicitEquation.append(" == ");
}
else
{
sbBuildImplicitEquation.append(' ');
sbBuildImplicitEquation.append(op);
sbBuildImplicitEquation.append(' ');
}
// temp is set by buildImplicitVarPart
sbBuildImplicitEquation.append(format(-temp[vars.length]));
return sbBuildImplicitEquation;
}
private StringBuilder sbBuildImplicitEquation = new StringBuilder(80);
// lhs of lhs = 0
final public StringBuilder buildLHS(double[] numbers, String[] vars, boolean KEEP_LEADING_SIGN, boolean CANCEL_DOWN) {
sbBuildLHS.setLength(0);
sbBuildLHS.append(buildImplicitVarPart(numbers, vars, KEEP_LEADING_SIGN, CANCEL_DOWN));
// add constant coeff
double coeff = temp[vars.length];
if (Math.abs(coeff) >= PRINT_PRECISION || useSignificantFigures) {
sbBuildLHS.append(' ');
sbBuildLHS.append(sign(coeff));
sbBuildLHS.append(' ');
sbBuildLHS.append(format(Math.abs(coeff)));
}
return sbBuildLHS;
}
private StringBuilder sbBuildLHS = new StringBuilder(80);
// form: y� = f(x) (coeff of y = 0)
final StringBuilder buildExplicitConicEquation(
double[] numbers,
String[] vars,
int pos,
boolean KEEP_LEADING_SIGN) {
// y�-coeff is 0
double d, dabs, q = numbers[pos];
// coeff of y� is 0 or coeff of y is not 0
if (isZero(q))
return buildImplicitEquation(numbers, vars, KEEP_LEADING_SIGN, true, '=');
int i, leadingNonZero = numbers.length;
for (i = 0; i < numbers.length; i++) {
if (i != pos
&& // except y� coefficient
(Math.abs(numbers[i]) >= PRINT_PRECISION || useSignificantFigures)) {
leadingNonZero = i;
break;
}
}
// BUILD EQUATION STRING
sbBuildExplicitConicEquation.setLength(0);
sbBuildExplicitConicEquation.append(vars[pos]);
sbBuildExplicitConicEquation.append(" = ");
if (leadingNonZero == numbers.length) {
sbBuildExplicitConicEquation.append("0");
return sbBuildExplicitConicEquation;
} else if (leadingNonZero == numbers.length - 1) {
// only constant coeff
d = -numbers[leadingNonZero] / q;
sbBuildExplicitConicEquation.append(format(d));
return sbBuildExplicitConicEquation;
} else {
// leading coeff
d = -numbers[leadingNonZero] / q;
sbBuildExplicitConicEquation.append(formatCoeff(d));
sbBuildExplicitConicEquation.append(vars[leadingNonZero]);
// other coeffs
for (i = leadingNonZero + 1; i < vars.length; i++) {
if (i != pos) {
d = -numbers[i] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(sign(d));
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(formatCoeff(dabs));
sbBuildExplicitConicEquation.append(vars[i]);
}
}
}
// constant coeff
d = -numbers[i] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(sign(d));
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(format(dabs));
}
//Application.debug(sbBuildExplicitConicEquation.toString());
return sbBuildExplicitConicEquation;
}
}
private StringBuilder sbBuildExplicitConicEquation = new StringBuilder(80);
// y = k x + d
final StringBuilder buildExplicitLineEquation(
double[] numbers,
String[] vars,
char op) {
double d, dabs, q = numbers[1];
sbBuildExplicitLineEquation.setLength(0);
// BUILD EQUATION STRING
// special case
// y-coeff is 0: form x = constant
if (isZero(q)) {
sbBuildExplicitLineEquation.append("x");
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER) {
sbBuildExplicitLineEquation.append(" == ");
}
else {
sbBuildExplicitLineEquation.append(' ');
if(numbers[0]<Kernel.MIN_PRECISION){
op = oppositeSign(op);
}
sbBuildExplicitLineEquation.append(op);
sbBuildExplicitLineEquation.append(' ');
}
sbBuildExplicitLineEquation.append(format(-numbers[2] / numbers[0]));
return sbBuildExplicitLineEquation;
}
// standard case: y-coeff not 0
sbBuildExplicitLineEquation.append("y");
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER) {
sbBuildExplicitLineEquation.append(" == ");
}
else {
sbBuildExplicitLineEquation.append(' ');
if(numbers[1] <Kernel.MIN_PRECISION){
op = oppositeSign(op);
}
sbBuildExplicitLineEquation.append(op);
sbBuildExplicitLineEquation.append(' ');
}
// x coeff
d = -numbers[0] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitLineEquation.append(formatCoeff(d));
sbBuildExplicitLineEquation.append('x');
// constant
d = -numbers[2] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitLineEquation.append(' ');
sbBuildExplicitLineEquation.append(sign(d));
sbBuildExplicitLineEquation.append(' ');
sbBuildExplicitLineEquation.append(format(dabs));
}
} else {
// only constant
sbBuildExplicitLineEquation.append(format(-numbers[2] / q));
}
return sbBuildExplicitLineEquation;
}
/**
* Inverts the > or < sign
- * @param op
+ * @param op =,<,>,\u2264 or \u2265
* @return opposite sign
*/
public static char oppositeSign(char op) {
switch(op) {
case '=':return '=';
case '<':return '>';
case '>':return '<';
- default: return '?';
+ case '\u2264': return '\u2265';
+ case '\u2265': return '\u2264';
+ default: return '?'; //should never happen
}
}
private StringBuilder sbBuildExplicitLineEquation = new StringBuilder(50);
/*
final private String formatAbs(double x) {
if (isZero(x))
return "0";
else
return formatNF(Math.abs(x));
}*/
/** doesn't show 1 or -1 */
final private String formatCoeff(double x) {
if (Math.abs(x) == 1.0) {
if (x > 0.0)
return "";
else
return "-";
} else {
String numberStr = format(x);
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER)
return numberStr + "*";
else {
// standard case
return numberStr;
}
}
}
////////////////////////////////////////////////
// FORMAT FOR NUMBERS
////////////////////////////////////////////////
public double axisNumberDistance(double units, NumberFormat numberFormat){
// calc number of digits
int exp = (int) Math.floor(Math.log(units) / Math.log(10));
int maxFractionDigtis = Math.max(-exp, getPrintDecimals());
// format the numbers
if (numberFormat instanceof DecimalFormat)
((DecimalFormat) numberFormat).applyPattern("###0.##");
numberFormat.setMaximumFractionDigits(maxFractionDigtis);
// calc the distance
double pot = Math.pow(10, exp);
double n = units / pot;
double distance;
if (n > 5) {
distance = 5 * pot;
} else if (n > 2) {
distance = 2 * pot;
} else {
distance = pot;
}
return distance;
}
private StringBuilder formatSB;
/**
* Formats the value of x using the currently set
* NumberFormat or ScientificFormat. This method also
* takes getCasPrintForm() into account.
*
* converts to localised digits if appropriate
*/
final public String format(double x) {
if (Application.unicodeZero != '0') {
String num = formatRaw(x);
return internationalizeDigits(num);
} else return formatRaw(x);
}
/*
* swaps the digits in num to the current locale's
*/
public String internationalizeDigits(String num) {
if (formatSB == null) formatSB = new StringBuilder(17);
else formatSB.setLength(0);
boolean reverseOrder = app.isRightToLeftDigits();
int length = num.length();
for (int i = 0 ; i < num.length() ; i++) {
char c = num.charAt(i);
//char c = reverseOrder ? num.charAt(length - 1 - i) : num.charAt(i);
if (c == '.') c = Application.unicodeDecimalPoint;
else if (c >= '0' && c <= '9') {
c += Application.unicodeZero - '0'; // convert to eg Arabic Numeral
}
// make sure the minus is treated as part of the number in eg Arabic
if ( reverseOrder && c=='-'){
formatSB.append(Unicode.RightToLeftMark);
formatSB.append(c);
formatSB.append(Unicode.RightToLeftMark);
}
else
formatSB.append(c);
}
return formatSB.toString();
}
/**
* Formats the value of x using the currently set
* NumberFormat or ScientificFormat. This method also
* takes getCasPrintForm() into account.
*/
final public String formatRaw(double x) {
switch (casPrintForm) {
// number formatting for XML string output
case ExpressionNode.STRING_TYPE_GEOGEBRA_XML:
return Double.toString(x);
// number formatting for CAS
case ExpressionNode.STRING_TYPE_MATH_PIPER:
case ExpressionNode.STRING_TYPE_JASYMCA:
case ExpressionNode.STRING_TYPE_MAXIMA:
if (Double.isNaN(x))
return " 1/0 ";
else if (Double.isInfinite(x)) {
if (casPrintForm == ExpressionNode.STRING_TYPE_MAXIMA) return (x<0) ? "-infinity" : "infinity";
return Double.toString(x); // "Infinity" or "-Infinity"
}
else {
double abs = Math.abs(x);
// number small enough that Double.toString() won't create E notation
if (abs >= 10E-3 && abs < 10E7) {
long round = Math.round(x);
if (x == round) {
return Long.toString(round);
} else {
return Double.toString(x);
}
}
// number would produce E notation with Double.toString()
else {
// convert scientific notation 1.0E-20 to 1*10^(-20)
String scientificStr = Double.toString(x);
StringBuilder sb = new StringBuilder(scientificStr.length() * 2);
boolean Efound = false;
for (int i=0; i < scientificStr.length(); i++) {
char ch = scientificStr.charAt(i);
if (ch == 'E') {
sb.append("*10^(");
Efound = true;
} else {
sb.append(ch);
}
}
if (Efound)
sb.append(")");
// TODO: remove
//Application.printStacktrace(sb.toString());
return sb.toString();
}
}
// number formatting for screen output
default:
if (Double.isNaN(x))
return "?";
else if (Double.isInfinite(x)) {
return (x > 0) ? "\u221e" : "-\u221e"; // infinity
}
else if (x == Math.PI) {
return casPrintFormPI;
}
// ROUNDING hack
// NumberFormat and SignificantFigures use ROUND_HALF_EVEN as
// default which is not changeable, so we need to hack this
// to get ROUND_HALF_UP like in schools: increase abs(x) slightly
// x = x * ROUND_HALF_UP_FACTOR;
// We don't do this for large numbers as
double abs = Math.abs(x);
if (abs < 10E7) {
// increase abs(x) slightly to round up
x = x * ROUND_HALF_UP_FACTOR;
}
if (useSignificantFigures) {
return formatSF(x);
} else {
return formatNF(x);
}
}
}
/**
* Uses current NumberFormat nf to format a number.
*/
final private String formatNF(double x) {
// "<=" catches -0.0000000000000005
// should be rounded to -0.000000000000001 (15 d.p.)
// but nf.format(x) returns "-0"
if (-PRINT_PRECISION / 2 <= x && x < PRINT_PRECISION / 2) {
// avoid output of "-0" for eg -0.0004
return "0";
} else {
// standard case
return nf.format(x);
}
}
/**
* Uses current ScientificFormat sf to format a number. Makes sure ".123" is
* returned as "0.123".
*/
final private String formatSF(double x) {
if (sbFormatSF == null)
sbFormatSF = new StringBuilder();
else
sbFormatSF.setLength(0);
// get scientific format
String absStr;
if (x == 0) {
// avoid output of "-0.00"
absStr = sf.format(0);
}
else if (x > 0) {
absStr = sf.format(x);
}
else {
sbFormatSF.append('-');
absStr = sf.format(-x);
}
// make sure ".123" is returned as "0.123".
if (absStr.charAt(0) == '.')
sbFormatSF.append('0');
sbFormatSF.append(absStr);
return sbFormatSF.toString();
}
private StringBuilder sbFormatSF;
/**
* calls formatPiERaw() and converts to localised digits if appropriate
*/
final public String formatPiE(double x, NumberFormat numF) {
if (Application.unicodeZero != '0') {
String num = formatPiERaw(x, numF);
return internationalizeDigits(num);
} else return formatPiERaw(x, numF);
}
final public String formatPiERaw(double x, NumberFormat numF) {
// PI
if (x == Math.PI) {
return casPrintFormPI;
}
// MULTIPLES OF PI/2
// i.e. x = a * pi/2
double a = 2*x / Math.PI;
int aint = (int) Math.round(a);
if (sbFormat == null)
sbFormat = new StringBuilder();
sbFormat.setLength(0);
if (isEqual(a, aint, STANDARD_PRECISION)) {
switch (aint) {
case 0:
return "0";
case 1: // pi/2
sbFormat.append(casPrintFormPI);
sbFormat.append("/2");
return sbFormat.toString();
case -1: // -pi/2
sbFormat.append('-');
sbFormat.append(casPrintFormPI);
sbFormat.append("/2");
return sbFormat.toString();
case 2: // 2pi/2 = pi
return casPrintFormPI;
case -2: // -2pi/2 = -pi
sbFormat.append('-');
sbFormat.append(casPrintFormPI);
return sbFormat.toString();
default:
// even
long half = aint / 2;
if (aint == 2 * half) {
// half * pi
sbFormat.append(half);
if (casPrintForm != ExpressionNode.STRING_TYPE_GEOGEBRA)
sbFormat.append("*");
sbFormat.append(casPrintFormPI);
return sbFormat.toString();
}
// odd
else {
// aint * pi/2
sbFormat.append(aint);
if (casPrintForm != ExpressionNode.STRING_TYPE_GEOGEBRA)
sbFormat.append("*");
sbFormat.append(casPrintFormPI);
sbFormat.append("/2");
return sbFormat.toString();
}
}
}
// STANDARD CASE
// use numberformat to get number string
// checkDecimalFraction() added to avoid 2.19999999999999 when set to 15dp
String str = numF.format(checkDecimalFraction(x));
sbFormat.append(str);
// if number is in scientific notation and ends with "E0", remove this
if (str.endsWith("E0"))
sbFormat.setLength(sbFormat.length() - 2);
return sbFormat.toString();
}
private StringBuilder sbFormat;
final public String formatSignedCoefficient(double x) {
if (x == -1.0)
return "- ";
if (x == 1.0)
return "+ ";
return formatSigned(x).toString();
}
final public StringBuilder formatSigned(double x) {
sbFormatSigned.setLength(0);
if (x >= 0.0d) {
sbFormatSigned.append("+ ");
sbFormatSigned.append( format(x));
return sbFormatSigned;
} else {
sbFormatSigned.append("- ");
sbFormatSigned.append( format(-x));
return sbFormatSigned;
}
}
private StringBuilder sbFormatSigned = new StringBuilder(40);
final public StringBuilder formatAngle(double phi) {
// STANDARD_PRECISION * 10 as we need a little leeway as we've converted from radians
return formatAngle(phi, 10);
}
final public StringBuilder formatAngle(double phi, double precision) {
sbFormatAngle.setLength(0);
switch (casPrintForm) {
case ExpressionNode.STRING_TYPE_MATH_PIPER:
case ExpressionNode.STRING_TYPE_JASYMCA:
if (angleUnit == ANGLE_DEGREE) {
sbFormatAngle.append("(");
// STANDARD_PRECISION * 10 as we need a little leeway as we've converted from radians
sbFormatAngle.append(format(checkDecimalFraction(Math.toDegrees(phi), precision)));
sbFormatAngle.append("*");
sbFormatAngle.append("\u00b0");
sbFormatAngle.append(")");
} else {
sbFormatAngle.append(format(phi));
}
return sbFormatAngle;
default:
// STRING_TYPE_GEOGEBRA_XML
// STRING_TYPE_GEOGEBRA
if (Double.isNaN(phi)) {
sbFormatAngle.append("?");
return sbFormatAngle;
}
if (angleUnit == ANGLE_DEGREE) {
phi = Math.toDegrees(phi);
if (phi < 0)
phi += 360;
else if (phi > 360)
phi = phi % 360;
// STANDARD_PRECISION * 10 as we need a little leeway as we've converted from radians
sbFormatAngle.append(format(checkDecimalFraction(phi, precision)));
if (casPrintForm == ExpressionNode.STRING_TYPE_GEOGEBRA_XML) {
sbFormatAngle.append("*");
}
sbFormatAngle.append('\u00b0');
return sbFormatAngle;
}
else {
// RADIANS
sbFormatAngle.append(format(phi));
if (casPrintForm != ExpressionNode.STRING_TYPE_GEOGEBRA_XML) {
sbFormatAngle.append(" rad");
}
return sbFormatAngle;
}
}
}
private StringBuilder sbFormatAngle = new StringBuilder(40);
final private static char sign(double x) {
if (x > 0)
return '+';
else
return '-';
}
/**
* greatest common divisor
*/
final public static long gcd(long m, long n) {
// Return the GCD of positive integers m and n.
if (m == 0 || n == 0)
return Math.max(Math.abs(m), Math.abs(n));
long p = m, q = n;
while (p % q != 0) {
long r = p % q;
p = q;
q = r;
}
return q;
}
/**
* Compute greatest common divisor of given doubles.
* Note: all double values are cast to long.
*/
final public static double gcd(double[] numbers) {
long gcd = (long) numbers[0];
for (int i = 0; i < numbers.length; i++) {
gcd = gcd((long) numbers[i], gcd);
}
return Math.abs(gcd);
}
/**
* Round a double to the given scale
* e.g. roundToScale(5.32, 1) = 5.0,
* roundToScale(5.32, 0.5) = 5.5,
* roundToScale(5.32, 0.25) = 5.25,
* roundToScale(5.32, 0.1) = 5.3
*/
final public static double roundToScale(double x, double scale) {
if (scale == 1.0)
return Math.round(x);
else {
return Math.round(x / scale) * scale;
}
}
/**
* Checks if x is close (Kernel.MIN_PRECISION) to a decimal fraction,
* eg 2.800000000000001. If it is, the decimal fraction eg 2.8 is returned,
* otherwise x is returned.
*/
/**
* Checks if x is close (Kernel.MIN_PRECISION) to a decimal fraction, eg
* 2.800000000000001. If it is, the decimal fraction eg 2.8 is returned,
* otherwise x is returned.
*/
final public double checkDecimalFraction(double x, double precision) {
//Application.debug(precision+" ");
precision = Math.pow(10, Math.floor(Math.log(Math.abs(precision))/Math.log(10)));
double fracVal = x * INV_MIN_PRECISION;
double roundVal = Math.round(fracVal);
//Application.debug(precision+" "+x+" "+fracVal+" "+roundVal+" "+isEqual(fracVal, roundVal, precision)+" "+roundVal / INV_MIN_PRECISION);
if (isEqual(fracVal, roundVal, STANDARD_PRECISION * precision))
return roundVal / INV_MIN_PRECISION;
else
return x;
}
final public double checkDecimalFraction(double x) {
return checkDecimalFraction(x, 1);
}
/**
* Checks if x is very close (1E-8) to an integer. If it is,
* the integer value is returned, otherwise x is returnd.
*/
final public double checkInteger(double x) {
double roundVal = Math.round(x);
if (Math.abs(x - roundVal) < EPSILON)
return roundVal;
else
return x;
}
/*******************************************************
* SAVING
*******************************************************/
private boolean isSaving;
public synchronized boolean isSaving() {
return isSaving;
}
public synchronized void setSaving(boolean saving) {
isSaving = saving;
}
/**
* Returns the kernel settings in XML format.
*/
public void getKernelXML(StringBuilder sb) {
// kernel settings
sb.append("<kernel>\n");
// continuity: true or false, since V3.0
sb.append("\t<continuous val=\"");
sb.append(isContinuous());
sb.append("\"/>\n");
if (useSignificantFigures) {
// significant figures
sb.append("\t<significantfigures val=\"");
sb.append(getPrintFigures());
sb.append("\"/>\n");
}
else
{
// decimal places
sb.append("\t<decimals val=\"");
sb.append(getPrintDecimals());
sb.append("\"/>\n");
}
// angle unit
sb.append("\t<angleUnit val=\"");
sb.append(angleUnit == Kernel.ANGLE_RADIANT ? "radiant" : "degree");
sb.append("\"/>\n");
// algebra style
sb.append("\t<algebraStyle val=\"");
sb.append(algebraStyle);
sb.append("\"/>\n");
// coord style
sb.append("\t<coordStyle val=\"");
sb.append(getCoordStyle());
sb.append("\"/>\n");
// animation
if (isAnimationRunning()) {
sb.append("\t<startAnimation val=\"");
sb.append(isAnimationRunning());
sb.append("\"/>\n");
}
sb.append("</kernel>\n");
}
public boolean isTranslateCommandName() {
return translateCommandName;
}
public void setTranslateCommandName(boolean b) {
translateCommandName = b;
}
/**
* States whether the continuity heuristic is active.
*/
final public boolean isContinuous() {
return continuous;
}
/**
* Turns the continuity heuristic on or off.
* Note: the macro kernel always turns continuity off.
*/
public void setContinuous(boolean continuous) {
this.continuous = continuous;
}
public final boolean isAllowVisibilitySideEffects() {
return allowVisibilitySideEffects;
}
public final void setAllowVisibilitySideEffects(
boolean allowVisibilitySideEffects) {
this.allowVisibilitySideEffects = allowVisibilitySideEffects;
}
public boolean isMacroKernel() {
return false;
}
private AnimationManager animationManager;
final public AnimationManager getAnimatonManager() {
if (animationManager == null) {
animationManager = new AnimationManager(this);
}
return animationManager;
}
final public boolean isAnimationRunning() {
return animationManager != null && animationManager.isRunning();
}
final public boolean isAnimationPaused() {
return animationManager != null && animationManager.isPaused();
}
final public boolean needToShowAnimationButton() {
return animationManager != null && animationManager.needToShowAnimationButton();
}
final public void udpateNeedToShowAnimationButton() {
if (animationManager != null)
animationManager.updateNeedToShowAnimationButton();
}
/**
* Turns silent mode on (true) or off (false). In silent mode, commands can
* be used to create objects without any side effects, i.e.
* no labels are created, algorithms are not added to the construction
* list and the views are not notified about new objects.
*/
public final void setSilentMode(boolean silentMode) {
this.silentMode = silentMode;
// no new labels, no adding to construction list
cons.setSuppressLabelCreation(silentMode);
// no notifying of views
//ggb3D - 2009-07-17
//removing :
//notifyViewsActive = !silentMode;
//(seems not to work with loading files)
//Application.printStacktrace(""+silentMode);
}
/**
* Returns whether silent mode is turned on.
* @see setSilentMode()
*/
public final boolean isSilentMode() {
return silentMode;
}
/**
* Sets whether unknown variables should be resolved as GeoDummyVariable objects.
*/
public final void setResolveUnkownVarsAsDummyGeos(boolean resolveUnkownVarsAsDummyGeos) {
this.resolveUnkownVarsAsDummyGeos = resolveUnkownVarsAsDummyGeos;
}
/**
* Returns whether unkown variables are resolved as GeoDummyVariable objects.
* @see setSilentMode()
*/
public final boolean isResolveUnkownVarsAsDummyGeos() {
return resolveUnkownVarsAsDummyGeos;
}
final public static String defaultLibraryJavaScript = "function ggbOnInit() {}";
String libraryJavaScript = defaultLibraryJavaScript;
public void setLibraryJavaScript(String str) {
Application.debug(str);
libraryJavaScript = str;
//libraryJavaScript = "function ggbOnInit() {ggbApplet.evalCommand('A=(1,2)');ggbApplet.registerObjectUpdateListener('A','listener');}function listener() {//java.lang.System.out.println('add listener called'); var x = ggbApplet.getXcoord('A');var y = ggbApplet.getYcoord('A');var len = Math.sqrt(x*x + y*y);if (len > 5) { x=x*5/len; y=y*5/len; }ggbApplet.unregisterObjectUpdateListener('A');ggbApplet.setCoords('A',x,y);ggbApplet.registerObjectUpdateListener('A','listener');}";
//libraryJavaScript = "function ggbOnInit() {ggbApplet.evalCommand('A=(1,2)');}";
}
//public String getLibraryJavaScriptXML() {
// return Util.encodeXML(libraryJavaScript);
//}
public String getLibraryJavaScript() {
return libraryJavaScript;
}
/** return all points of the current construction */
public TreeSet getPointSet(){
return getConstruction().getGeoSetLabelOrder(GeoElement.GEO_CLASS_POINT);
}
/**
* test kernel
*/
public static void mainx(String [] args) {
// create kernel with null application for testing
Kernel kernel = new Kernel(null);
Construction cons = kernel.getConstruction();
// create points A and B
GeoPoint A = new GeoPoint(cons, "A", 0, 1, 1);
GeoPoint B = new GeoPoint(cons, "B", 3, 4, 1);
// create line g through points A and B
GeoLine g = kernel.Line("g", A, B);
// print current objects
System.out.println(A);
System.out.println(B);
System.out.println(g);
// change B
B.setCoords(3, 2, 1);
B.updateCascade();
// print current objects
System.out.println("changed " +B);
System.out.println(g);
}
final public GeoNumeric convertIndexToNumber(String str) {
int i = 0;
char c;
while (i < str.length() && !Unicode.isSuperscriptDigit(str.charAt(i)))
i++;
//Application.debug(str.substring(i, str.length() - 1));
MyDouble md = new MyDouble(this, str.substring(i, str.length() - 1)); // strip off eg "sin" at start, "(" at end
GeoNumeric num = new GeoNumeric(getConstruction(), md.getDouble());
return num;
}
final public ExpressionNode handleTrigPower(String image, ExpressionNode en, int type) {
// sin^(-1)(x) -> ArcSin(x)
if (image.indexOf(Unicode.Superscript_Minus) > -1) {
//String check = ""+Unicode.Superscript_Minus + Unicode.Superscript_1 + '(';
if (image.substring(3, 6).equals(Unicode.superscriptMinusOneBracket)) {
switch (type) {
case ExpressionNode.SIN:
return new ExpressionNode(this, en, ExpressionNode.ARCSIN, null);
case ExpressionNode.COS:
return new ExpressionNode(this, en, ExpressionNode.ARCCOS, null);
case ExpressionNode.TAN:
return new ExpressionNode(this, en, ExpressionNode.ARCTAN, null);
default:
throw new Error("Inverse not supported for trig function"); // eg csc^-1(x)
}
}
else throw new Error("Bad index for trig function"); // eg sin^-2(x)
}
return new ExpressionNode(this, new ExpressionNode(this, en, type, null), ExpressionNode.POWER, convertIndexToNumber(image));
}
///////////////////////////////////////////
// CHANGING TYPE OF A GEO (mathieu)
///////////////////////////////////////////
/**
* @return possible alternatives for a given geo (e.g. number -> complex)
*/
public GeoElement[] getAlternatives(GeoElement geo){
return geo.getAlternatives();
}
}
| false | true | final public GeoElement If(String label,
GeoBoolean condition,
GeoElement geoIf, GeoElement geoElse) {
// check if geoIf and geoElse are of same type
/* if (geoElse == null ||
geoIf.isNumberValue() && geoElse.isNumberValue() ||
geoIf.getTypeString().equals(geoElse.getTypeString()))
{*/
AlgoIf algo = new AlgoIf(cons, label, condition, geoIf, geoElse);
return algo.getGeoElement();
/* }
else {
// incompatible types
Application.debug("if incompatible: " + geoIf + ", " + geoElse);
return null;
} */
}
/**
* If-then-else construct for functions.
* example: If[ x < 2, x^2, x + 2 ]
*/
final public GeoFunction If(String label,
GeoFunction boolFun,
GeoFunction ifFun, GeoFunction elseFun) {
AlgoIfFunction algo = new AlgoIfFunction(cons, label, boolFun, ifFun, elseFun);
return algo.getGeoFunction();
}
/**
* If-then-else construct for functions.
* example: If[ x < 2, x^2, x + 2 ]
*/
final public GeoNumeric CountIf(String label,
GeoFunction boolFun,
GeoList list) {
AlgoCountIf algo = new AlgoCountIf(cons, label, boolFun, list);
return algo.getResult();
}
/**
* Sequence command:
* Sequence[ <expression>, <number-var>, <from>, <to>, <step> ]
* @return array with GeoList object and its list items
*/
final public GeoElement [] Sequence(String label,
GeoElement expression, GeoNumeric localVar,
NumberValue from, NumberValue to, NumberValue step) {
AlgoSequence algo = new AlgoSequence(cons, label, expression, localVar, from, to, step);
return algo.getOutput();
}
/**
* Cartesian curve command:
* Curve[ <expression x-coord>, <expression x-coord>, <number-var>, <from>, <to> ]
*/
final public GeoCurveCartesian CurveCartesian(String label,
NumberValue xcoord, NumberValue ycoord,
GeoNumeric localVar, NumberValue from, NumberValue to)
{
AlgoCurveCartesian algo = new AlgoCurveCartesian(cons, label, new NumberValue[] {xcoord, ycoord} , localVar, from, to);
return (GeoCurveCartesian) algo.getCurve();
}
/**
* Converts a NumberValue object to an ExpressionNode object.
*/
public ExpressionNode convertNumberValueToExpressionNode(NumberValue nv) {
GeoElement geo = nv.toGeoElement();
AlgoElement algo = geo.getParentAlgorithm();
if (algo != null && algo instanceof AlgoDependentNumber) {
AlgoDependentNumber algoDep = (AlgoDependentNumber) algo;
return algoDep.getExpression().getCopy(this);
}
else {
return new ExpressionNode(this, geo);
}
}
/** Number dependent on arithmetic expression with variables,
* represented by a tree. e.g. t = 6z - 2
*/
final public GeoNumeric DependentNumber(
String label,
ExpressionNode root,
boolean isAngle) {
AlgoDependentNumber algo =
new AlgoDependentNumber(cons, label, root, isAngle);
GeoNumeric number = algo.getNumber();
return number;
}
/** Point dependent on arithmetic expression with variables,
* represented by a tree. e.g. P = (4t, 2s)
*/
final public GeoPoint DependentPoint(
String label,
ExpressionNode root, boolean complex) {
AlgoDependentPoint algo = new AlgoDependentPoint(cons, label, root, complex);
GeoPoint P = algo.getPoint();
return P;
}
/** Vector dependent on arithmetic expression with variables,
* represented by a tree. e.g. v = u + 3 w
*/
final public GeoVector DependentVector(
String label,
ExpressionNode root) {
AlgoDependentVector algo = new AlgoDependentVector(cons, label, root);
GeoVector v = algo.getVector();
return v;
}
/** Line dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. y = k x + d
*/
final public GeoLine DependentLine(String label, Equation equ) {
AlgoDependentLine algo = new AlgoDependentLine(cons, label, equ, false);
GeoLine line = algo.getLine();
return line;
}
/** Inequality dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. y < k x + d
*/
final public GeoLinearInequality DependentInequality(String label, Equation equ) {
AlgoDependentLine algo = new AlgoDependentLine(cons, label, equ, true);
GeoLine line = algo.getLine();
return (GeoLinearInequality)line;
}
/** Conic dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. y� = 2 p x
*/
final public GeoConic DependentConic(String label, Equation equ) {
AlgoDependentConic algo = new AlgoDependentConic(cons, label, equ);
GeoConic conic = algo.getConic();
return conic;
}
final public GeoImplicitPoly DependentImplicitPoly(String label, Equation equ) {
AlgoDependentImplicitPoly algo = new AlgoDependentImplicitPoly(cons, label, equ);
GeoImplicitPoly implicitPoly = algo.getImplicitPoly();
return implicitPoly;
}
/** Function dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. f(x) = a x� + b x�
*/
final public GeoFunction DependentFunction(
String label,
Function fun) {
AlgoDependentFunction algo = new AlgoDependentFunction(cons, label, fun);
GeoFunction f = algo.getFunction();
return f;
}
/** Multivariate Function depending on coefficients of arithmetic expressions with variables,
* e.g. f(x,y) = a x^2 + b y^2
*/
final public GeoFunctionNVar DependentFunctionNVar(
String label,
FunctionNVar fun) {
AlgoDependentFunctionNVar algo = new AlgoDependentFunctionNVar(cons, label, fun);
GeoFunctionNVar f = algo.getFunction();
return f;
}
/** Interval dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. x > a && x < b
*/
final public GeoFunction DependentInterval(
String label,
Function fun) {
AlgoDependentInterval algo = new AlgoDependentInterval(cons, label, fun);
GeoFunction f = algo.getFunction();
return f;
}
/** Text dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. text = "Radius: " + r
*/
final public GeoText DependentText(
String label,
ExpressionNode root) {
AlgoDependentText algo = new AlgoDependentText(cons, label, root);
GeoText t = algo.getGeoText();
return t;
}
/**
* Creates a dependent copy of origGeo with label
*/
final public GeoElement DependentGeoCopy(String label, ExpressionNode origGeoNode) {
AlgoDependentGeoCopy algo = new AlgoDependentGeoCopy(cons, label, origGeoNode);
return algo.getGeo();
}
/**
* Name of geo.
*/
final public GeoText Name(
String label,
GeoElement geo) {
AlgoName algo = new AlgoName(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* Object from name
*/
final public GeoElement Object(
String label,
GeoText text) {
AlgoObject algo = new AlgoObject(cons, label, text);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Spreadsheet Object from coords
*/
final public GeoElement Cell(
String label,
NumberValue a, NumberValue b) {
AlgoCell algo = new AlgoCell(cons, label, a, b);
GeoElement ret = algo.getResult();
return ret;
}
/**
* ColumnName[]
*/
final public GeoText ColumnName(
String label,
GeoElement geo) {
AlgoColumnName algo = new AlgoColumnName(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* LaTeX of geo.
*/
final public GeoText LaTeX(
String label,
GeoElement geo, GeoBoolean substituteVars) {
AlgoLaTeX algo = new AlgoLaTeX(cons, label, geo, substituteVars);
GeoText t = algo.getGeoText();
return t;
}
/**
* LaTeX of geo.
*/
final public GeoText LaTeX(
String label,
GeoElement geo) {
AlgoLaTeX algo = new AlgoLaTeX(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo) {
AlgoText algo = new AlgoText(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoBoolean substituteVars) {
AlgoText algo = new AlgoText(cons, label, geo, substituteVars);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoPoint p, GeoBoolean substituteVars) {
AlgoText algo = new AlgoText(cons, label, geo, p, substituteVars);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoPoint p, GeoBoolean substituteVars, GeoBoolean latex) {
AlgoText algo = new AlgoText(cons, label, geo, p, substituteVars, latex);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoPoint p) {
AlgoText algo = new AlgoText(cons, label, geo, p);
GeoText t = algo.getGeoText();
return t;
}
/**
* Row of geo.
*/
final public GeoNumeric Row(
String label,
GeoElement geo) {
AlgoRow algo = new AlgoRow(cons, label, geo);
GeoNumeric ret = algo.getResult();
return ret;
}
/**
* Column of geo.
*/
final public GeoNumeric Column(
String label,
GeoElement geo) {
AlgoColumn algo = new AlgoColumn(cons, label, geo);
GeoNumeric ret = algo.getResult();
return ret;
}
/**
* ToNumber
*/
final public GeoNumeric LetterToUnicode(
String label,
GeoText geo) {
AlgoLetterToUnicode algo = new AlgoLetterToUnicode(cons, label, geo);
GeoNumeric ret = algo.getResult();
return ret;
}
/**
* ToNumbers
*/
final public GeoList TextToUnicode(
String label,
GeoText geo) {
AlgoTextToUnicode algo = new AlgoTextToUnicode(cons, label, geo);
GeoList ret = algo.getResult();
return ret;
}
/**
* ToText(number)
*/
final public GeoText UnicodeToLetter(String label, NumberValue a) {
AlgoUnicodeToLetter algo = new AlgoUnicodeToLetter(cons, label, a);
GeoText text = algo.getResult();
return text;
}
/**
* ToText(list)
*/
final public GeoText UnicodeToText(
String label,
GeoList geo) {
AlgoUnicodeToText algo = new AlgoUnicodeToText(cons, label, geo);
GeoText ret = algo.getResult();
return ret;
}
/**
* returns the current x-axis step
* Michael Borcherds
*/
final public GeoNumeric AxisStepX(
String label) {
AlgoAxisStepX algo = new AlgoAxisStepX(cons, label);
GeoNumeric t = algo.getResult();
return t;
}
/**
* returns the current y-axis step
* Michael Borcherds
*/
final public GeoNumeric AxisStepY(
String label) {
AlgoAxisStepY algo = new AlgoAxisStepY(cons, label);
GeoNumeric t = algo.getResult();
return t;
}
/**
* returns the current construction protocol step
* Michael Borcherds 2008-05-15
*/
final public GeoNumeric ConstructionStep(
String label) {
AlgoConstructionStep algo = new AlgoConstructionStep(cons, label);
GeoNumeric t = algo.getResult();
return t;
}
/**
* returns current construction protocol step for an object
* Michael Borcherds 2008-05-15
*/
final public GeoNumeric ConstructionStep(
String label, GeoElement geo) {
AlgoStepObject algo = new AlgoStepObject(cons, label, geo);
GeoNumeric t = algo.getResult();
return t;
}
/**
* Text dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. c = a & b
*/
final public GeoBoolean DependentBoolean(
String label,
ExpressionNode root) {
AlgoDependentBoolean algo = new AlgoDependentBoolean(cons, label, root);
return algo.getGeoBoolean();
}
/** Point on path with cartesian coordinates (x,y) */
final public GeoPoint Point(String label, Path path, double x, double y, boolean addToConstruction) {
boolean oldMacroMode = false;
if (!addToConstruction) {
oldMacroMode = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
}
AlgoPointOnPath algo = new AlgoPointOnPath(cons, label, path, x, y);
GeoPoint p = algo.getP();
if (!addToConstruction) {
cons.setSuppressLabelCreation(oldMacroMode);
}
return p;
}
/** Point anywhere on path with */
final public GeoPoint Point(String label, Path path) {
// try (0,0)
AlgoPointOnPath algo = new AlgoPointOnPath(cons, label, path, 0, 0);
GeoPoint p = algo.getP();
// try (1,0)
if (!p.isDefined()) {
p.setCoords(1,0,1);
algo.update();
}
// try (random(),0)
if (!p.isDefined()) {
p.setCoords(Math.random(),0,1);
algo.update();
}
return p;
}
/** Point in region with cartesian coordinates (x,y) */
final public GeoPoint PointIn(String label, Region region, double x, double y) {
AlgoPointInRegion algo = new AlgoPointInRegion(cons, label, region, x, y);
Application.debug("PointIn - \n x="+x+"\n y="+y);
GeoPoint p = algo.getP();
return p;
}
/** Point in region */
final public GeoPoint PointIn(String label, Region region) {
return PointIn(label,region,0,0); //TODO do as for paths
}
/** Point P + v */
final public GeoPoint Point(String label, GeoPoint P, GeoVector v) {
AlgoPointVector algo = new AlgoPointVector(cons, label, P, v);
GeoPoint p = algo.getQ();
return p;
}
/**
* Returns the projected point of P on line g.
*/
final public GeoPoint ProjectedPoint(GeoPoint P, GeoLine g) {
boolean oldMacroMode = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
GeoLine perp = OrthogonalLine(null, P, g);
GeoPoint S = IntersectLines(null, perp, g);
cons.setSuppressLabelCreation(oldMacroMode);
return S;
}
/**
* Midpoint M = (P + Q)/2
*/
final public GeoPoint Midpoint(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoMidpoint algo = new AlgoMidpoint(cons, label, P, Q);
GeoPoint M = algo.getPoint();
return M;
}
/**
* Creates Midpoint M = (P + Q)/2 without label (for use as e.g. start point)
*/
final public GeoPoint Midpoint(
GeoPoint P,
GeoPoint Q) {
boolean oldValue = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
GeoPoint midPoint = Midpoint(null, P, Q);
cons.setSuppressLabelCreation(oldValue);
return midPoint;
}
/**
* Midpoint of segment
*/
final public GeoPoint Midpoint(
String label,
GeoSegment s) {
AlgoMidpointSegment algo = new AlgoMidpointSegment(cons, label, s);
GeoPoint M = algo.getPoint();
return M;
}
/**
* LineSegment named label from Point P to Point Q
*/
final public GeoSegment Segment(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoJoinPointsSegment algo = new AlgoJoinPointsSegment(cons, label, P, Q);
GeoSegment s = algo.getSegment();
return s;
}
/**
* Line named label through Points P and Q
*/
final public GeoLine Line(String label, GeoPoint P, GeoPoint Q) {
AlgoJoinPoints algo = new AlgoJoinPoints(cons, label, P, Q);
GeoLine g = algo.getLine();
return g;
}
/**
* Line named label through Point P with direction of vector v
*/
final public GeoLine Line(String label, GeoPoint P, GeoVector v) {
AlgoLinePointVector algo = new AlgoLinePointVector(cons, label, P, v);
GeoLine g = algo.getLine();
return g;
}
/**
* Ray named label through Points P and Q
*/
final public GeoRay Ray(String label, GeoPoint P, GeoPoint Q) {
AlgoJoinPointsRay algo = new AlgoJoinPointsRay(cons, label, P, Q);
return algo.getRay();
}
/**
* Ray named label through Point P with direction of vector v
*/
final public GeoRay Ray(String label, GeoPoint P, GeoVector v) {
AlgoRayPointVector algo = new AlgoRayPointVector(cons, label, P, v);
return algo.getRay();
}
/**
* Line named label through Point P parallel to Line l
*/
final public GeoLine Line(String label, GeoPoint P, GeoLine l) {
AlgoLinePointLine algo = new AlgoLinePointLine(cons, label, P, l);
GeoLine g = algo.getLine();
return g;
}
/**
* Line named label through Point P orthogonal to vector v
*/
final public GeoLine OrthogonalLine(
String label,
GeoPoint P,
GeoVector v) {
AlgoOrthoLinePointVector algo =
new AlgoOrthoLinePointVector(cons, label, P, v);
GeoLine g = algo.getLine();
return g;
}
/**
* Line named label through Point P orthogonal to line l
*/
final public GeoLine OrthogonalLine(
String label,
GeoPoint P,
GeoLine l) {
AlgoOrthoLinePointLine algo = new AlgoOrthoLinePointLine(cons, label, P, l);
GeoLine g = algo.getLine();
return g;
}
/**
* Line bisector of points A, B
*/
final public GeoLine LineBisector(
String label,
GeoPoint A,
GeoPoint B) {
AlgoLineBisector algo = new AlgoLineBisector(cons, label, A, B);
GeoLine g = algo.getLine();
return g;
}
/**
* Line bisector of segment s
*/
final public GeoLine LineBisector(String label, GeoSegment s) {
AlgoLineBisectorSegment algo = new AlgoLineBisectorSegment(cons, label, s);
GeoLine g = algo.getLine();
return g;
}
/**
* Angular bisector of points A, B, C
*/
final public GeoLine AngularBisector(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoAngularBisectorPoints algo =
new AlgoAngularBisectorPoints(cons, label, A, B, C);
GeoLine g = algo.getLine();
return g;
}
/**
* Angular bisectors of lines g, h
*/
final public GeoLine[] AngularBisector(
String[] labels,
GeoLine g,
GeoLine h) {
AlgoAngularBisectorLines algo =
new AlgoAngularBisectorLines(cons, labels, g, h);
GeoLine[] lines = algo.getLines();
return lines;
}
/**
* Vector named label from Point P to Q
*/
final public GeoVector Vector(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoVector algo = new AlgoVector(cons, label, P, Q);
GeoVector v = (GeoVector) algo.getVector();
v.setEuclidianVisible(true);
v.update();
notifyUpdate(v);
return v;
}
/**
* Vector (0,0) to P
*/
final public GeoVector Vector(String label, GeoPoint P) {
AlgoVectorPoint algo = new AlgoVectorPoint(cons, label, P);
GeoVector v = algo.getVector();
v.setEuclidianVisible(true);
v.update();
notifyUpdate(v);
return v;
}
/**
* Direction vector of line g
*/
final public GeoVector Direction(String label, GeoLine g) {
AlgoDirection algo = new AlgoDirection(cons, label, g);
GeoVector v = algo.getVector();
return v;
}
/**
* Slope of line g
*/
final public GeoNumeric Slope(String label, GeoLine g) {
AlgoSlope algo = new AlgoSlope(cons, label, g);
GeoNumeric slope = algo.getSlope();
return slope;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
NumberValue a, NumberValue b, GeoList list) {
AlgoBarChart algo = new AlgoBarChart(cons, label, a, b, list);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
GeoList list1, GeoList list2) {
AlgoBarChart algo = new AlgoBarChart(cons, label, list1, list2);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
GeoList list1, GeoList list2, NumberValue width) {
AlgoBarChart algo = new AlgoBarChart(cons, label, list1, list2, width);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
GeoList list, GeoNumeric a) {
AlgoBarChart algo = new AlgoBarChart(cons, label, list, a);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
NumberValue a, NumberValue b, GeoElement expression, GeoNumeric localVar,
NumberValue from, NumberValue to, NumberValue step) {
AlgoSequence seq = new AlgoSequence(cons, expression, localVar, from, to, step);
cons.removeFromConstructionList(seq);
AlgoBarChart algo = new AlgoBarChart(cons, label, a, b, (GeoList)seq.getOutput()[0]);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BoxPlot
*/
final public GeoNumeric BoxPlot(String label,
NumberValue a, NumberValue b, GeoList rawData) {
/*
AlgoListMin min = new AlgoListMin(cons,rawData);
cons.removeFromConstructionList(min);
AlgoQ1 Q1 = new AlgoQ1(cons,rawData);
cons.removeFromConstructionList(Q1);
AlgoMedian median = new AlgoMedian(cons,rawData);
cons.removeFromConstructionList(median);
AlgoQ3 Q3 = new AlgoQ3(cons,rawData);
cons.removeFromConstructionList(Q3);
AlgoListMax max = new AlgoListMax(cons,rawData);
cons.removeFromConstructionList(max);
AlgoBoxPlot algo = new AlgoBoxPlot(cons, label, a, b, (NumberValue)(min.getMin()),
(NumberValue)(Q1.getQ1()), (NumberValue)(median.getMedian()), (NumberValue)(Q3.getQ3()), (NumberValue)(max.getMax()));
*/
AlgoBoxPlot algo = new AlgoBoxPlot(cons, label, a, b, rawData);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BoxPlot
*/
final public GeoNumeric BoxPlot(String label,
NumberValue a, NumberValue b, NumberValue min, NumberValue Q1,
NumberValue median, NumberValue Q3, NumberValue max) {
AlgoBoxPlot algo = new AlgoBoxPlot(cons, label, a, b, min, Q1, median, Q3, max);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* Histogram
*/
final public GeoNumeric Histogram(String label,
GeoList list1, GeoList list2) {
AlgoHistogram algo = new AlgoHistogram(cons, label, list1, list2);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* DotPlot
* G.Sturr 2010-8-10
*/
final public GeoList DotPlot(String label, GeoList list) {
AlgoDotPlot algo = new AlgoDotPlot(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* UpperSum of function f
*/
final public GeoNumeric UpperSum(String label, GeoFunction f,
NumberValue a, NumberValue b, NumberValue n) {
AlgoSumUpper algo = new AlgoSumUpper(cons, label, f, a, b, n);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* TrapezoidalSum of function f
*/
final public GeoNumeric TrapezoidalSum(String label, GeoFunction f,
NumberValue a, NumberValue b, NumberValue n) {
AlgoSumTrapezoidal algo = new AlgoSumTrapezoidal(cons, label, f, a, b, n);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* LowerSum of function f
*/
final public GeoNumeric LowerSum(String label, GeoFunction f,
NumberValue a, NumberValue b, NumberValue n) {
AlgoSumLower algo = new AlgoSumLower(cons, label, f, a, b, n);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* SumSquaredErrors[<List of Points>,<Function>]
* Hans-Petter Ulven
* 2010-02-22
*/
final public GeoNumeric SumSquaredErrors(String label, GeoList list, GeoFunctionable function) {
AlgoSumSquaredErrors algo = new AlgoSumSquaredErrors(cons, label, list, function);
GeoNumeric sse=algo.getsse();
return sse;
}
/**
* RSquare[<List of Points>,<Function>]
*/
final public GeoNumeric RSquare(String label, GeoList list, GeoFunctionable function) {
AlgoRSquare algo = new AlgoRSquare(cons, label, list, function);
GeoNumeric r2=algo.getRSquare();
return r2;
}
/**
* unit vector of line g
*/
final public GeoVector UnitVector(String label, GeoLine g) {
AlgoUnitVectorLine algo = new AlgoUnitVectorLine(cons, label, g);
GeoVector v = algo.getVector();
return v;
}
/**
* unit vector of vector v
*/
final public GeoVector UnitVector(String label, GeoVector v) {
AlgoUnitVectorVector algo = new AlgoUnitVectorVector(cons, label, v);
GeoVector u = algo.getVector();
return u;
}
/**
* orthogonal vector of line g
*/
final public GeoVector OrthogonalVector(String label, GeoLine g) {
AlgoOrthoVectorLine algo = new AlgoOrthoVectorLine(cons, label, g);
GeoVector n = algo.getVector();
return n;
}
/**
* orthogonal vector of vector v
*/
final public GeoVector OrthogonalVector(String label, GeoVector v) {
AlgoOrthoVectorVector algo = new AlgoOrthoVectorVector(cons, label, v);
GeoVector n = algo.getVector();
return n;
}
/**
* unit orthogonal vector of line g
*/
final public GeoVector UnitOrthogonalVector(
String label,
GeoLine g) {
AlgoUnitOrthoVectorLine algo = new AlgoUnitOrthoVectorLine(cons, label, g);
GeoVector n = algo.getVector();
return n;
}
/**
* unit orthogonal vector of vector v
*/
final public GeoVector UnitOrthogonalVector(
String label,
GeoVector v) {
AlgoUnitOrthoVectorVector algo =
new AlgoUnitOrthoVectorVector(cons, label, v);
GeoVector n = algo.getVector();
return n;
}
/**
* Length named label of vector v
*/
final public GeoNumeric Length(String label, GeoVec3D v) {
AlgoLengthVector algo = new AlgoLengthVector(cons, label, v);
GeoNumeric num = algo.getLength();
return num;
}
/**
* Distance named label between points P and Q
*/
final public GeoNumeric Distance(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoDistancePoints algo = new AlgoDistancePoints(cons, label, P, Q);
GeoNumeric num = algo.getDistance();
return num;
}
/**
* Distance named label between point P and line g
*/
final public GeoNumeric Distance(
String label,
GeoPoint P,
GeoLine g) {
AlgoDistancePointLine algo = new AlgoDistancePointLine(cons, label, P, g);
GeoNumeric num = algo.getDistance();
return num;
}
/**
* Distance named label between line g and line h
*/
final public GeoNumeric Distance(
String label,
GeoLine g,
GeoLine h) {
AlgoDistanceLineLine algo = new AlgoDistanceLineLine(cons, label, g, h);
GeoNumeric num = algo.getDistance();
return num;
}
/**
* Area named label of P[0], ..., P[n]
*/
final public GeoNumeric Area(String label, GeoPoint [] P) {
AlgoAreaPoints algo = new AlgoAreaPoints(cons, label, P);
GeoNumeric num = algo.getArea();
return num;
}
/**
* Area named label of conic
*/
final public GeoNumeric Area(String label, GeoConic c) {
AlgoAreaConic algo = new AlgoAreaConic(cons, label, c);
GeoNumeric num = algo.getArea();
return num;
}
/**
* Mod[a, b]
*/
final public GeoNumeric Mod(String label, NumberValue a, NumberValue b) {
AlgoMod algo = new AlgoMod(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Div[a, b]
*/
final public GeoNumeric Div(String label, NumberValue a, NumberValue b) {
AlgoDiv algo = new AlgoDiv(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Mod[a, b] Polynomial remainder
*/
final public GeoFunction Mod(String label, GeoFunction a, GeoFunction b) {
AlgoPolynomialMod algo = new AlgoPolynomialMod(cons, label, a, b);
GeoFunction f = algo.getResult();
return f;
}
/**
* Div[a, b] Polynomial Division
*/
final public GeoFunction Div(String label, GeoFunction a, GeoFunction b) {
AlgoPolynomialDiv algo = new AlgoPolynomialDiv(cons, label, a, b);
GeoFunction f = algo.getResult();
return f;
}
/**
* Min[a, b]
*/
final public GeoNumeric Min(String label, NumberValue a, NumberValue b) {
AlgoMin algo = new AlgoMin(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Min[list]
*/
final public GeoNumeric Min(String label, GeoList list) {
AlgoListMin algo = new AlgoListMin(cons, label, list);
GeoNumeric num = algo.getMin();
return num;
}
/**
* Max[a, b]
*/
final public GeoNumeric Max(String label, NumberValue a, NumberValue b) {
AlgoMax algo = new AlgoMax(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Max[list]
*/
final public GeoNumeric Max(String label, GeoList list) {
AlgoListMax algo = new AlgoListMax(cons, label, list);
GeoNumeric num = algo.getMax();
return num;
}
/**
* LCM[a, b]
* Michael Borcherds
*/
final public GeoNumeric LCM(String label, NumberValue a, NumberValue b) {
AlgoLCM algo = new AlgoLCM(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* LCM[list]
* Michael Borcherds
*/
final public GeoNumeric LCM(String label, GeoList list) {
AlgoListLCM algo = new AlgoListLCM(cons, label, list);
GeoNumeric num = algo.getLCM();
return num;
}
/**
* GCD[a, b]
* Michael Borcherds
*/
final public GeoNumeric GCD(String label, NumberValue a, NumberValue b) {
AlgoGCD algo = new AlgoGCD(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* GCD[list]
* Michael Borcherds
*/
final public GeoNumeric GCD(String label, GeoList list) {
AlgoListGCD algo = new AlgoListGCD(cons, label, list);
GeoNumeric num = algo.getGCD();
return num;
}
/**
* SigmaXY[list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXY(String label, GeoList list) {
AlgoListSigmaXY algo = new AlgoListSigmaXY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaYY[list]
* Michael Borcherds
*/
final public GeoNumeric SigmaYY(String label, GeoList list) {
AlgoListSigmaYY algo = new AlgoListSigmaYY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Covariance[list]
* Michael Borcherds
*/
final public GeoNumeric Covariance(String label, GeoList list) {
AlgoListCovariance algo = new AlgoListCovariance(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SXX[list]
* Michael Borcherds
*/
final public GeoNumeric SXX(String label, GeoList list) {
GeoNumeric num;
GeoElement geo = list.get(0);
if (geo.isNumberValue())
{ // list of numbers
AlgoSXX algo = new AlgoSXX(cons, label, list);
num = algo.getResult();
}
else
{ // (probably) list of points
AlgoListSXX algo = new AlgoListSXX(cons, label, list);
num = algo.getResult();
}
return num;
}
/**
* SXY[list]
* Michael Borcherds
*/
final public GeoNumeric SXY(String label, GeoList list) {
AlgoListSXY algo = new AlgoListSXY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SYY[list]
* Michael Borcherds
*/
final public GeoNumeric SYY(String label, GeoList list) {
AlgoListSYY algo = new AlgoListSYY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* MeanX[list]
* Michael Borcherds
*/
final public GeoNumeric MeanX(String label, GeoList list) {
AlgoListMeanX algo = new AlgoListMeanX(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* MeanY[list]
* Michael Borcherds
*/
final public GeoNumeric MeanY(String label, GeoList list) {
AlgoListMeanY algo = new AlgoListMeanY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* PMCC[list]
* Michael Borcherds
*/
final public GeoNumeric PMCC(String label, GeoList list) {
AlgoListPMCC algo = new AlgoListPMCC(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaXY[list,list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXY(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSigmaXY algo = new AlgoDoubleListSigmaXY(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaXX[list,list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXX(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSigmaXX algo = new AlgoDoubleListSigmaXX(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaYY[list,list]
* Michael Borcherds
*/
final public GeoNumeric SigmaYY(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSigmaYY algo = new AlgoDoubleListSigmaYY(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Covariance[list,list]
* Michael Borcherds
*/
final public GeoNumeric Covariance(String label, GeoList listX, GeoList listY) {
AlgoDoubleListCovariance algo = new AlgoDoubleListCovariance(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SXX[list,list]
* Michael Borcherds
*/
final public GeoNumeric SXX(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSXX algo = new AlgoDoubleListSXX(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SXY[list,list]
* Michael Borcherds
*/
final public GeoNumeric SXY(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSXY algo = new AlgoDoubleListSXY(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* PMCC[list,list]
* Michael Borcherds
*/
final public GeoNumeric PMCC(String label, GeoList listX, GeoList listY) {
AlgoDoubleListPMCC algo = new AlgoDoubleListPMCC(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* FitLineY[list of coords]
* Michael Borcherds
*/
final public GeoLine FitLineY(String label, GeoList list) {
AlgoFitLineY algo = new AlgoFitLineY(cons, label, list);
GeoLine line = algo.getFitLineY();
return line;
}
/**
* FitLineX[list of coords]
* Michael Borcherds
*/
final public GeoLine FitLineX(String label, GeoList list) {
AlgoFitLineX algo = new AlgoFitLineX(cons, label, list);
GeoLine line = algo.getFitLineX();
return line;
}
final public GeoLocus Voronoi(String label, GeoList list) {
AlgoVoronoi algo = new AlgoVoronoi(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus Hull(String label, GeoList list, GeoNumeric percent) {
AlgoHull algo = new AlgoHull(cons, label, list, percent);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus TravelingSalesman(String label, GeoList list) {
AlgoTravelingSalesman algo = new AlgoTravelingSalesman(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus ConvexHull(String label, GeoList list) {
AlgoConvexHull algo = new AlgoConvexHull(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus MinimumSpanningTree(String label, GeoList list) {
AlgoMinimumSpanningTree algo = new AlgoMinimumSpanningTree(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus DelauneyTriangulation(String label, GeoList list) {
AlgoDelauneyTriangulation algo = new AlgoDelauneyTriangulation(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
/**
* FitPoly[list of coords,degree]
* Hans-Petter Ulven
*/
final public GeoFunction FitPoly(String label, GeoList list, NumberValue degree) {
AlgoFitPoly algo = new AlgoFitPoly(cons, label, list, degree);
GeoFunction function = algo.getFitPoly();
return function;
}
/**
* FitExp[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitExp(String label, GeoList list) {
AlgoFitExp algo = new AlgoFitExp(cons, label, list);
GeoFunction function = algo.getFitExp();
return function;
}
/**
* FitLog[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitLog(String label, GeoList list) {
AlgoFitLog algo = new AlgoFitLog(cons, label, list);
GeoFunction function = algo.getFitLog();
return function;
}
/**
* FitPow[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitPow(String label, GeoList list) {
AlgoFitPow algo = new AlgoFitPow(cons, label, list);
GeoFunction function = algo.getFitPow();
return function;
}
/**
* FitSin[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitSin(String label, GeoList list) {
AlgoFitSin algo = new AlgoFitSin(cons, label, list);
GeoFunction function = algo.getFitSin();
return function;
}
/**
* FitLogistic[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitLogistic(String label, GeoList list) {
AlgoFitLogistic algo = new AlgoFitLogistic(cons, label, list);
GeoFunction function = algo.getFitLogistic();
return function;
}
/**
* Fit[list of points,list of functions]
* Hans-Petter Ulven
*/
final public GeoFunction Fit(String label, GeoList ptslist,GeoList funclist) {
AlgoFit algo = new AlgoFit(cons, label, ptslist,funclist);
GeoFunction function = algo.getFit();
return function;
}
/**
* 'FitGrowth[<List of Points>]
* Hans-Petter Ulven
*/
final public GeoFunction FitGrowth(String label, GeoList list) {
AlgoFitGrowth algo = new AlgoFitGrowth(cons, label, list);
GeoFunction function=algo.getFitGrowth();
return function;
}
/**
* Binomial[n,r]
* Michael Borcherds
*/
final public GeoNumeric Binomial(String label, NumberValue a, NumberValue b) {
AlgoBinomial algo = new AlgoBinomial(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomNormal[mean,variance]
* Michael Borcherds
*/
final public GeoNumeric RandomNormal(String label, NumberValue a, NumberValue b) {
AlgoRandomNormal algo = new AlgoRandomNormal(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Random[max,min]
* Michael Borcherds
*/
final public GeoNumeric Random(String label, NumberValue a, NumberValue b) {
AlgoRandom algo = new AlgoRandom(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomUniform[max,min]
* Michael Borcherds
*/
final public GeoNumeric RandomUniform(String label, NumberValue a, NumberValue b) {
AlgoRandomUniform algo = new AlgoRandomUniform(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomBinomial[n,p]
* Michael Borcherds
*/
final public GeoNumeric RandomBinomial(String label, NumberValue a, NumberValue b) {
AlgoRandomBinomial algo = new AlgoRandomBinomial(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomPoisson[lambda]
* Michael Borcherds
*/
final public GeoNumeric RandomPoisson(String label, NumberValue a) {
AlgoRandomPoisson algo = new AlgoRandomPoisson(cons, label, a);
GeoNumeric num = algo.getResult();
return num;
}
/**
* InverseNormal[mean,variance,x]
* Michael Borcherds
*/
final public GeoNumeric InverseNormal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseNormal algo = new AlgoInverseNormal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Normal[mean,variance,x]
* Michael Borcherds
*/
final public GeoNumeric Normal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoNormal algo = new AlgoNormal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
/**
* TDistribution[degrees of freedom,x]
* Michael Borcherds
*/
final public GeoNumeric TDistribution(String label, NumberValue a, NumberValue b) {
AlgoTDistribution algo = new AlgoTDistribution(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseTDistribution(String label, NumberValue a, NumberValue b) {
AlgoInverseTDistribution algo = new AlgoInverseTDistribution(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric ChiSquared(String label, NumberValue a, NumberValue b) {
AlgoChiSquared algo = new AlgoChiSquared(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseChiSquared(String label, NumberValue a, NumberValue b) {
AlgoInverseChiSquared algo = new AlgoInverseChiSquared(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Exponential(String label, NumberValue a, NumberValue b) {
AlgoExponential algo = new AlgoExponential(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseExponential(String label, NumberValue a, NumberValue b) {
AlgoInverseExponential algo = new AlgoInverseExponential(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric FDistribution(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoFDistribution algo = new AlgoFDistribution(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseFDistribution(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseFDistribution algo = new AlgoInverseFDistribution(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Gamma(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoGamma algo = new AlgoGamma(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseGamma(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseGamma algo = new AlgoInverseGamma(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Cauchy(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoCauchy algo = new AlgoCauchy(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseCauchy(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseCauchy algo = new AlgoInverseCauchy(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Weibull(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoWeibull algo = new AlgoWeibull(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseWeibull(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseWeibull algo = new AlgoInverseWeibull(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Zipf(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoZipf algo = new AlgoZipf(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseZipf(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseZipf algo = new AlgoInverseZipf(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Pascal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoPascal algo = new AlgoPascal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InversePascal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInversePascal algo = new AlgoInversePascal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric HyperGeometric(String label, NumberValue a, NumberValue b, NumberValue c, NumberValue d) {
AlgoHyperGeometric algo = new AlgoHyperGeometric(cons, label, a, b, c, d);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseHyperGeometric(String label, NumberValue a, NumberValue b, NumberValue c, NumberValue d) {
AlgoInverseHyperGeometric algo = new AlgoInverseHyperGeometric(cons, label, a, b, c, d);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Sort[list]
* Michael Borcherds
*/
final public GeoList Sort(String label, GeoList list) {
AlgoSort algo = new AlgoSort(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Rank[list]
* Michael Borcherds
*/
final public GeoList Rank(String label, GeoList list) {
AlgoRank algo = new AlgoRank(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Shuffle[list]
* Michael Borcherds
*/
final public GeoList Shuffle(String label, GeoList list) {
AlgoShuffle algo = new AlgoShuffle(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* PointList[list]
* Michael Borcherds
*/
final public GeoList PointList(String label, GeoList list) {
AlgoPointList algo = new AlgoPointList(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* RootList[list]
* Michael Borcherds
*/
final public GeoList RootList(String label, GeoList list) {
AlgoRootList algo = new AlgoRootList(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* First[list,n]
* Michael Borcherds
*/
final public GeoList First(String label, GeoList list, GeoNumeric n) {
AlgoFirst algo = new AlgoFirst(cons, label, list, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* First[string,n]
* Michael Borcherds
*/
final public GeoText First(String label, GeoText list, GeoNumeric n) {
AlgoFirstString algo = new AlgoFirstString(cons, label, list, n);
GeoText list2 = algo.getResult();
return list2;
}
/**
* Last[string,n]
* Michael Borcherds
*/
final public GeoText Last(String label, GeoText list, GeoNumeric n) {
AlgoLastString algo = new AlgoLastString(cons, label, list, n);
GeoText list2 = algo.getResult();
return list2;
}
/**
* First[string,n]
* Michael Borcherds
*/
final public GeoText Take(String label, GeoText list, GeoNumeric m, GeoNumeric n) {
AlgoTakeString algo = new AlgoTakeString(cons, label, list, m, n);
GeoText list2 = algo.getResult();
return list2;
}
/**
* Last[list,n]
* Michael Borcherds
*/
final public GeoList Last(String label, GeoList list, GeoNumeric n) {
AlgoLast algo = new AlgoLast(cons, label, list, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Take[list,m,n]
* Michael Borcherds
*/
final public GeoList Take(String label, GeoList list, GeoNumeric m, GeoNumeric n) {
AlgoTake algo = new AlgoTake(cons, label, list, m, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Append[list,object]
* Michael Borcherds
*/
final public GeoList Append(String label, GeoList list, GeoElement geo) {
AlgoAppend algo = new AlgoAppend(cons, label, list, geo);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Append[object,list]
* Michael Borcherds
*/
final public GeoList Append(String label, GeoElement geo, GeoList list) {
AlgoAppend algo = new AlgoAppend(cons, label, geo, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Join[list,list]
* Michael Borcherds
*/
final public GeoList Join(String label, GeoList list) {
AlgoJoin algo = new AlgoJoin(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Union[list,list]
* Michael Borcherds
*/
final public GeoList Union(String label, GeoList list, GeoList list1) {
AlgoUnion algo = new AlgoUnion(cons, label, list, list1);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Intersection[list,list]
* Michael Borcherds
*/
final public GeoList Intersection(String label, GeoList list, GeoList list1) {
AlgoIntersection algo = new AlgoIntersection(cons, label, list, list1);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Insert[list,list,n]
* Michael Borcherds
*/
final public GeoList Insert(String label, GeoElement geo, GeoList list, GeoNumeric n) {
AlgoInsert algo = new AlgoInsert(cons, label, geo, list, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* RemoveUndefined[list]
* Michael Borcherds
*/
final public GeoList RemoveUndefined(String label, GeoList list) {
AlgoRemoveUndefined algo = new AlgoRemoveUndefined(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Keep[boolean condition, list]
* Michael Borcherds
*/
final public GeoList KeepIf(String label, GeoFunction boolFun, GeoList list) {
AlgoKeepIf algo = new AlgoKeepIf(cons, label, boolFun, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Defined[object]
* Michael Borcherds
*/
final public GeoBoolean Defined(String label, GeoElement geo) {
AlgoDefined algo = new AlgoDefined(cons, label, geo);
GeoBoolean result = algo.getResult();
return result;
}
/**
* IsInteger[number]
* Michael Borcherds
*/
final public GeoBoolean IsInteger(String label, GeoNumeric geo) {
AlgoIsInteger algo = new AlgoIsInteger(cons, label, geo);
GeoBoolean result = algo.getResult();
return result;
}
/**
* Mode[list]
* Michael Borcherds
*/
final public GeoList Mode(String label, GeoList list) {
AlgoMode algo = new AlgoMode(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Invert[matrix]
* Michael Borcherds
*/
final public GeoList Invert(String label, GeoList list) {
AlgoInvert algo = new AlgoInvert(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Transpose[matrix]
* Michael Borcherds
*/
final public GeoList Transpose(String label, GeoList list) {
AlgoTranspose algo = new AlgoTranspose(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Transpose[matrix]
* Michael Borcherds
*/
final public GeoList ReducedRowEchelonForm(String label, GeoList list) {
AlgoReducedRowEchelonForm algo = new AlgoReducedRowEchelonForm(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Transpose[matrix]
* Michael Borcherds
*/
final public GeoNumeric Determinant(String label, GeoList list) {
AlgoDeterminant algo = new AlgoDeterminant(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Reverse[list]
* Michael Borcherds
*/
final public GeoList Reverse(String label, GeoList list) {
AlgoReverse algo = new AlgoReverse(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Product[list]
* Michael Borcherds
*/
final public GeoNumeric Product(String label, GeoList list) {
AlgoProduct algo = new AlgoProduct(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Sum[list]
* Michael Borcherds
*/
final public GeoElement Sum(String label, GeoList list) {
AlgoSum algo = new AlgoSum(cons, label, list);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list,n]
* Michael Borcherds
*/
final public GeoElement Sum(String label, GeoList list, GeoNumeric n) {
AlgoSum algo = new AlgoSum(cons, label, list, n);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of functions]
* Michael Borcherds
*/
final public GeoElement SumFunctions(String label, GeoList list) {
AlgoSumFunctions algo = new AlgoSumFunctions(cons, label, list);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of functions,n]
* Michael Borcherds
*/
final public GeoElement SumFunctions(String label, GeoList list, GeoNumeric num) {
AlgoSumFunctions algo = new AlgoSumFunctions(cons, label, list, num);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of points]
* Michael Borcherds
*/
final public GeoElement SumPoints(String label, GeoList list) {
AlgoSumPoints algo = new AlgoSumPoints(cons, label, list);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of points,n]
* Michael Borcherds
*/
final public GeoElement SumPoints(String label, GeoList list, GeoNumeric num) {
AlgoSumPoints algo = new AlgoSumPoints(cons, label, list, num);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of points]
* Michael Borcherds
*/
final public GeoElement SumText(String label, GeoList list) {
AlgoSumText algo = new AlgoSumText(cons, label, list);
GeoText ret = algo.getResult();
return ret;
}
/**
* Sum[list of text,n]
* Michael Borcherds
*/
final public GeoElement SumText(String label, GeoList list, GeoNumeric num) {
AlgoSumText algo = new AlgoSumText(cons, label, list, num);
GeoText ret = algo.getResult();
return ret;
}
/**
* Sample[list,n]
* Michael Borcherds
*/
final public GeoElement Sample(String label, GeoList list, NumberValue n) {
AlgoSample algo = new AlgoSample(cons, label, list, n, null);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sample[list,n, withReplacement]
* Michael Borcherds
*/
final public GeoElement Sample(String label, GeoList list, NumberValue n, GeoBoolean withReplacement) {
AlgoSample algo = new AlgoSample(cons, label, list, n, withReplacement);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Table[list]
* Michael Borcherds
*/
final public GeoText TableText(String label, GeoList list, GeoText args) {
AlgoTableText algo = new AlgoTableText(cons, label, list, args);
GeoText text = algo.getResult();
return text;
}
/**
* StemPlot[list]
* Michael Borcherds
*/
final public GeoText StemPlot(String label, GeoList list) {
AlgoStemPlot algo = new AlgoStemPlot(cons, label, list, null);
GeoText text = algo.getResult();
return text;
}
/**
* StemPlot[list, number]
* Michael Borcherds
*/
final public GeoText StemPlot(String label, GeoList list, GeoNumeric num) {
AlgoStemPlot algo = new AlgoStemPlot(cons, label, list, num);
GeoText text = algo.getResult();
return text;
}
/**
* ToFraction[number]
* Michael Borcherds
*/
final public GeoText FractionText(String label, GeoNumeric num) {
AlgoFractionText algo = new AlgoFractionText(cons, label, num);
GeoText text = algo.getResult();
return text;
}
/**
* Mean[list]
* Michael Borcherds
*/
final public GeoNumeric Mean(String label, GeoList list) {
AlgoMean algo = new AlgoMean(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoText VerticalText(String label, GeoText args) {
AlgoVerticalText algo = new AlgoVerticalText(cons, label, args);
GeoText text = algo.getResult();
return text;
}
final public GeoText RotateText(String label, GeoText args, GeoNumeric angle) {
AlgoRotateText algo = new AlgoRotateText(cons, label, args, angle);
GeoText text = algo.getResult();
return text;
}
/**
* Variance[list]
* Michael Borcherds
*/
final public GeoNumeric Variance(String label, GeoList list) {
AlgoVariance algo = new AlgoVariance(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SampleVariance[list]
* Michael Borcherds
*/
final public GeoNumeric SampleVariance(String label, GeoList list) {
AlgoSampleVariance algo = new AlgoSampleVariance(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SD[list]
* Michael Borcherds
*/
final public GeoNumeric StandardDeviation(String label, GeoList list) {
AlgoStandardDeviation algo = new AlgoStandardDeviation(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SampleSD[list]
* Michael Borcherds
*/
final public GeoNumeric SampleStandardDeviation(String label, GeoList list) {
AlgoSampleStandardDeviation algo = new AlgoSampleStandardDeviation(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaXX[list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXX(String label, GeoList list) {
GeoNumeric num;
GeoElement geo = list.get(0);
if (geo.isNumberValue())
{ // list of numbers
AlgoSigmaXX algo = new AlgoSigmaXX(cons, label, list);
num = algo.getResult();
}
else
{ // (probably) list of points
AlgoListSigmaXX algo = new AlgoListSigmaXX(cons, label, list);
num = algo.getResult();
}
return num;
}
/**
* Median[list]
* Michael Borcherds
*/
final public GeoNumeric Median(String label, GeoList list) {
AlgoMedian algo = new AlgoMedian(cons, label, list);
GeoNumeric num = algo.getMedian();
return num;
}
/**
* Q1[list] lower quartile
* Michael Borcherds
*/
final public GeoNumeric Q1(String label, GeoList list) {
AlgoQ1 algo = new AlgoQ1(cons, label, list);
GeoNumeric num = algo.getQ1();
return num;
}
/**
* Q3[list] upper quartile
* Michael Borcherds
*/
final public GeoNumeric Q3(String label, GeoList list) {
AlgoQ3 algo = new AlgoQ3(cons, label, list);
GeoNumeric num = algo.getQ3();
return num;
}
/**
* Iteration[ f(x), x0, n ]
*/
final public GeoNumeric Iteration(String label, GeoFunction f, NumberValue start,
NumberValue n) {
AlgoIteration algo = new AlgoIteration(cons, label, f, start, n);
GeoNumeric num = algo.getResult();
return num;
}
/**
* IterationList[ f(x), x0, n ]
*/
final public GeoList IterationList(String label, GeoFunction f, NumberValue start,
NumberValue n) {
AlgoIterationList algo = new AlgoIterationList(cons, label, f, start, n);
return algo.getResult();
}
/**
* RandomElement[list]
*/
final public GeoElement RandomElement(String label, GeoList list) {
AlgoRandomElement algo = new AlgoRandomElement(cons, label, list);
GeoElement geo = algo.getElement();
return geo;
}
/**
* Element[list, number]
*/
final public GeoElement Element(String label, GeoList list, NumberValue n) {
AlgoListElement algo = new AlgoListElement(cons, label, list, n);
GeoElement geo = algo.getElement();
return geo;
}
/**
* SelectedElement[list]
*/
final public GeoElement SelectedElement(String label, GeoList list) {
AlgoSelectedElement algo = new AlgoSelectedElement(cons, label, list);
GeoElement geo = algo.getElement();
return geo;
}
/**
* SelectedElement[list]
*/
final public GeoElement SelectedIndex(String label, GeoList list) {
AlgoSelectedIndex algo = new AlgoSelectedIndex(cons, label, list);
GeoElement geo = algo.getElement();
return geo;
}
/**
* Element[list, number, number]
*/
final public GeoElement Element(String label, GeoList list, NumberValue n, NumberValue m) {
AlgoListElement algo = new AlgoListElement(cons, label, list, n, m);
GeoElement geo = algo.getElement();
return geo;
}
/**
* Length[list]
*/
final public GeoNumeric Length(String label, GeoList list) {
AlgoListLength algo = new AlgoListLength(cons, label, list);
return algo.getLength();
}
/**
* Element[text, number]
*/
final public GeoElement Element(String label, GeoText text, NumberValue n) {
AlgoTextElement algo = new AlgoTextElement(cons, label, text, n);
GeoElement geo = algo.getText();
return geo;
}
/**
* Length[text]
*/
final public GeoNumeric Length(String label, GeoText text) {
AlgoTextLength algo = new AlgoTextLength(cons, label, text);
return algo.getLength();
}
// PhilippWeissenbacher 2007-04-10
/**
* Perimeter named label of GeoPolygon
*/
final public GeoNumeric Perimeter(String label, GeoPolygon polygon) {
AlgoPerimeterPoly algo = new AlgoPerimeterPoly(cons, label, polygon);
return algo.getCircumference();
}
/**
* Circumference named label of GeoConic
*/
final public GeoNumeric Circumference(String label, GeoConic conic) {
AlgoCircumferenceConic algo = new AlgoCircumferenceConic(cons, label, conic);
return algo.getCircumference();
}
// PhilippWeissenbacher 2007-04-10
/**
* polygon P[0], ..., P[n-1]
* The labels name the polygon itself and its segments
*/
final public GeoElement [] Polygon(String [] labels, GeoPoint [] P) {
AlgoPolygon algo = new AlgoPolygon(cons, labels, P);
return algo.getOutput();
}
//G.Sturr 2010-3-14
/**
* Polygon with vertices from geolist
* Only the polygon is labeled, segments are not labeled
*/
final public GeoElement [] Polygon(String [] labels, GeoList pointList) {
AlgoPolygon algo = new AlgoPolygon(cons, labels, pointList);
return algo.getOutput();
}
//END G.Sturr
/**
* polygon P[0], ..., P[n-1]
* The labels name the polygon itself and its segments
*/
final public GeoElement [] PolyLine(String [] labels, GeoPoint [] P) {
AlgoPolyLine algo = new AlgoPolyLine(cons, labels, P);
return algo.getOutput();
}
/**
* Polygon with vertices from geolist
* Only the polygon is labeled, segments are not labeled
*/
final public GeoElement [] PolyLine(String [] labels, GeoList pointList) {
AlgoPolyLine algo = new AlgoPolyLine(cons, labels, pointList);
return algo.getOutput();
}
final public GeoElement [] RigidPolygon(String [] labels, GeoPoint [] points) {
boolean oldMacroMode = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
GeoConic circle = Circle(null, points[0], new MyDouble(this, points[0].distance(points[1])));
cons.setSuppressLabelCreation(oldMacroMode);
GeoPoint p = Point(null, (Path)circle, points[1].inhomX, points[1].inhomY, true);
try {
cons.replace(points[1], p);
points[1] = p;
} catch (Exception e) {
e.printStackTrace();
return null;
}
StringBuilder sb = new StringBuilder();
double xA = points[0].inhomX;
double yA = points[0].inhomY;
double xB = points[1].inhomX;
double yB = points[1].inhomY;
GeoVec2D a = new GeoVec2D(this, xB - xA, yB - yA ); // vector AB
GeoVec2D b = new GeoVec2D(this, yA - yB, xB - xA ); // perpendicular to AB
a.makeUnitVector();
b.makeUnitVector();
for (int i = 2; i < points.length ; i++) {
double xC = points[i].inhomX;
double yC = points[i].inhomY;
GeoVec2D d = new GeoVec2D(this, xC - xA, yC - yA ); // vector AC
setTemporaryPrintFigures(15);
// make string like this
// A+3.76UnitVector[Segment[A,B]]+-1.74UnitPerpendicularVector[Segment[A,B]]
sb.setLength(0);
sb.append(points[0].getLabel());
sb.append('+');
sb.append(format(a.inner(d)));
// use internal command name
sb.append("UnitVector[Segment[");
sb.append(points[0].getLabel());
sb.append(',');
sb.append(points[1].getLabel());
sb.append("]]+");
sb.append(format(b.inner(d)));
// use internal command name
sb.append("UnitOrthogonalVector[Segment[");
sb.append(points[0].getLabel());
sb.append(',');
sb.append(points[1].getLabel());
sb.append("]]");
restorePrintAccuracy();
//Application.debug(sb.toString());
GeoPoint pp = (GeoPoint)getAlgebraProcessor().evaluateToPoint(sb.toString());
try {
cons.replace(points[i], pp);
points[i] = pp;
points[i].setEuclidianVisible(false);
points[i].update();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Application.debug(kernel.format(a.inner(d))+" UnitVector[Segment[A,B]] + "+kernel.format(b.inner(d))+" UnitPerpendicularVector[Segment[A,B]]");
points[0].setEuclidianVisible(false);
points[0].update();
return Polygon(labels, points);
}
/**
* Regular polygon with vertices A and B and n total vertices.
* The labels name the polygon itself, its segments and points
*/
final public GeoElement [] RegularPolygon(String [] labels, GeoPoint A, GeoPoint B, NumberValue n) {
AlgoPolygonRegular algo = new AlgoPolygonRegular(cons, labels, A, B, n);
return algo.getOutput();
}
//G.Sturr 2010-3-14
/**
* Polygon formed by operation on two input polygons.
* Possible operations: addition, subtraction or intersection
* The labels name the polygon itself, its segments and points
*/
final public GeoElement [] PolygonOperation(String [] labels, GeoPolygon A, GeoPolygon B, NumberValue n) {
AlgoPolygonOperation algo = new AlgoPolygonOperation(cons, labels, A, B,n);
return algo.getOutput();
}
//END G.Sturr
/**
* Creates new point B with distance n from A and new segment AB
* The labels[0] is for the segment, labels[1] for the new point
*/
final public GeoElement [] Segment (String [] labels, GeoPoint A, NumberValue n) {
// this is actually a macro
String pointLabel = null, segmentLabel = null;
if (labels != null) {
switch (labels.length) {
case 2:
pointLabel = labels[1];
case 1:
segmentLabel = labels[0];
default:
}
}
// create a circle around A with radius n
AlgoCirclePointRadius algoCircle = new AlgoCirclePointRadius(cons, A, n);
cons.removeFromConstructionList(algoCircle);
// place the new point on the circle
AlgoPointOnPath algoPoint = new AlgoPointOnPath(cons, pointLabel, algoCircle.getCircle(), A.inhomX+ n.getDouble(), A.inhomY );
// return segment and new point
GeoElement [] ret = { Segment(segmentLabel, A, algoPoint.getP()),
algoPoint.getP() };
return ret;
}
/**
* Creates a new point C by rotating B around A using angle alpha and
* a new angle BAC.
* The labels[0] is for the angle, labels[1] for the new point
*/
final public GeoElement [] Angle (String [] labels, GeoPoint B, GeoPoint A, NumberValue alpha) {
return Angle(labels, B, A, alpha, true);
}
/**
* Creates a new point C by rotating B around A using angle alpha and
* a new angle BAC (for positive orientation) resp. angle CAB (for negative orientation).
* The labels[0] is for the angle, labels[1] for the new point
*/
final public GeoElement [] Angle (String [] labels, GeoPoint B, GeoPoint A, NumberValue alpha, boolean posOrientation) {
// this is actually a macro
String pointLabel = null, angleLabel = null;
if (labels != null) {
switch (labels.length) {
case 2:
pointLabel = labels[1];
case 1:
angleLabel = labels[0];
default:
}
}
// rotate B around A using angle alpha
GeoPoint C = (GeoPoint) Rotate(pointLabel, B, alpha, A)[0];
// create angle according to orientation
GeoAngle angle;
if (posOrientation) {
angle = Angle(angleLabel, B, A, C);
} else {
angle = Angle(angleLabel, C, A, B);
}
//return angle and new point
GeoElement [] ret = { angle, C };
return ret;
}
/**
* Angle named label between line g and line h
*/
final public GeoAngle Angle(String label, GeoLine g, GeoLine h) {
AlgoAngleLines algo = new AlgoAngleLines(cons, label, g, h);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* Angle named label between vector v and vector w
*/
final public GeoAngle Angle(
String label,
GeoVector v,
GeoVector w) {
AlgoAngleVectors algo = new AlgoAngleVectors(cons, label, v, w);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* Angle named label for a point or a vector
*/
final public GeoAngle Angle(
String label,
GeoVec3D v) {
AlgoAngleVector algo = new AlgoAngleVector(cons, label, v);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* Angle named label between three points
*/
final public GeoAngle Angle(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoAnglePoints algo = new AlgoAnglePoints(cons, label, A, B, C);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* all angles of given polygon
*/
final public GeoAngle [] Angles(String [] labels, GeoPolygon poly) {
AlgoAnglePolygon algo = new AlgoAnglePolygon(cons, labels, poly);
GeoAngle [] angles = algo.getAngles();
//for (int i=0; i < angles.length; i++) {
// angles[i].setAlphaValue(0.0f);
//}
return angles;
}
/**
* IntersectLines yields intersection point named label of lines g, h
*/
final public GeoPoint IntersectLines(
String label,
GeoLine g,
GeoLine h) {
AlgoIntersectLines algo = new AlgoIntersectLines(cons, label, g, h);
GeoPoint S = algo.getPoint();
return S;
}
/**
* yields intersection point named label of line g and polygon p
*/
final public GeoElement[] IntersectLinePolygon(
String[] labels,
GeoLine g,
GeoPolygon p) {
AlgoIntersectLinePolygon algo = new AlgoIntersectLinePolygon(cons, labels, g, p);
return algo.getOutput();
}
/**
* Intersects f and g using starting point A (with Newton's root finding)
*/
final public GeoPoint IntersectFunctions(
String label,
GeoFunction f,
GeoFunction g, GeoPoint A) {
AlgoIntersectFunctionsNewton algo = new AlgoIntersectFunctionsNewton(cons, label, f, g, A);
GeoPoint S = algo.getIntersectionPoint();
return S;
}
/**
* Intersects f and l using starting point A (with Newton's root finding)
*/
final public GeoPoint IntersectFunctionLine(
String label,
GeoFunction f,
GeoLine l, GeoPoint A) {
AlgoIntersectFunctionLineNewton algo = new AlgoIntersectFunctionLineNewton(cons, label, f, l, A);
GeoPoint S = algo.getIntersectionPoint();
return S;
}
/*********************************************
* CONIC PART
*********************************************/
/**
* circle with midpoint M and radius r
*/
final public GeoConic Circle(
String label,
GeoPoint M,
NumberValue r) {
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, M, r);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint M and radius BC
* Michael Borcherds 2008-03-14
*/
final public GeoConic Circle(
// this is actually a macro
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C, boolean dummy) {
AlgoJoinPointsSegment algoSegment = new AlgoJoinPointsSegment(cons, B, C, null);
cons.removeFromConstructionList(algoSegment);
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, A, algoSegment.getSegment(),true);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint A and radius the same as circle
* Michael Borcherds 2008-03-14
*/
final public GeoConic Circle(
// this is actually a macro
String label,
GeoPoint A,
GeoConic c) {
AlgoRadius radius = new AlgoRadius(cons, c);
cons.removeFromConstructionList(radius);
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, A, radius.getRadius());
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint M and radius segment
* Michael Borcherds 2008-03-15
*/
final public GeoConic Circle(
String label,
GeoPoint A,
GeoSegment segment) {
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, A, segment, true);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint M through point P
*/
final public GeoConic Circle(String label, GeoPoint M, GeoPoint P) {
AlgoCircleTwoPoints algo = new AlgoCircleTwoPoints(cons, label, M, P);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* semicircle with midpoint M through point P
*/
final public GeoConicPart Semicircle(String label, GeoPoint M, GeoPoint P) {
AlgoSemicircle algo = new AlgoSemicircle(cons, label, M, P);
return algo.getSemicircle();
}
/**
* locus line for Q dependent on P. Note: P must be a point
* on a path.
*/
final public GeoLocus Locus(String label, GeoPoint Q, GeoPoint P) {
if (P.getPath() == null ||
Q.getPath() != null ||
!P.isParentOf(Q)) return null;
AlgoLocus algo = new AlgoLocus(cons, label, Q, P);
return algo.getLocus();
}
/**
* circle with through points A, B, C
*/
final public GeoConic Circle(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoCircleThreePoints algo = new AlgoCircleThreePoints(cons, label, A, B, C);
GeoConic circle = (GeoConic) algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* conic arc from conic and parameters
*/
final public GeoConicPart ConicArc(String label, GeoConic conic, NumberValue a, NumberValue b) {
AlgoConicPartConicParameters algo = new AlgoConicPartConicParameters(cons, label, conic, a, b,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* conic sector from conic and points
*/
final public GeoConicPart ConicArc(String label, GeoConic conic, GeoPoint P, GeoPoint Q) {
AlgoConicPartConicPoints algo = new AlgoConicPartConicPoints(cons, label, conic, P, Q,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* conic sector from conic and parameters
*/
final public GeoConicPart ConicSector(String label, GeoConic conic, NumberValue a, NumberValue b) {
AlgoConicPartConicParameters algo = new AlgoConicPartConicParameters(cons, label, conic, a, b,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* conic sector from conic and points
*/
final public GeoConicPart ConicSector(String label, GeoConic conic, GeoPoint P, GeoPoint Q) {
AlgoConicPartConicPoints algo = new AlgoConicPartConicPoints(cons, label, conic, P, Q,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* circle arc from three points
*/
final public GeoConicPart CircumcircleArc(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircumcircle algo = new AlgoConicPartCircumcircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* circle sector from three points
*/
final public GeoConicPart CircumcircleSector(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircumcircle algo = new AlgoConicPartCircumcircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* circle arc from center and twho points on arc
*/
final public GeoConicPart CircleArc(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircle algo = new AlgoConicPartCircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* circle sector from center and twho points on arc
*/
final public GeoConicPart CircleSector(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircle algo = new AlgoConicPartCircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* Focuses of conic. returns 2 GeoPoints
*/
final public GeoPoint[] Focus(String[] labels, GeoConic c) {
AlgoFocus algo = new AlgoFocus(cons, labels, c);
GeoPoint[] focus = algo.getFocus();
return focus;
}
/**
* Vertices of conic. returns 4 GeoPoints
*/
final public GeoPoint[] Vertex(String[] labels, GeoConic c) {
AlgoVertex algo = new AlgoVertex(cons, labels, c);
GeoPoint[] vertex = algo.getVertex();
return vertex;
}
/**
* Vertices of polygon. returns 3+ GeoPoints
*/
final public GeoElement[] Vertex(String[] labels, GeoPolygon p) {
AlgoVertexPolygon algo = new AlgoVertexPolygon(cons, labels, p);
GeoElement[] vertex = algo.getVertex();
return vertex;
}
/**
* Center of conic
*/
final public GeoPoint Center(String label, GeoConic c) {
AlgoCenterConic algo = new AlgoCenterConic(cons, label, c);
GeoPoint midpoint = algo.getPoint();
return midpoint;
}
/**
* Centroid of a
*/
final public GeoPoint Centroid(String label, GeoPolygon p) {
AlgoCentroidPolygon algo = new AlgoCentroidPolygon(cons, label, p);
GeoPoint centroid = algo.getPoint();
return centroid;
}
/**
* Corner of image
*/
final public GeoPoint Corner(String label, GeoImage img, NumberValue number) {
AlgoImageCorner algo = new AlgoImageCorner(cons, label, img, number);
return algo.getCorner();
}
/**
* Corner of text Michael Borcherds 2007-11-26
*/
final public GeoPoint Corner(String label, GeoText txt, NumberValue number) {
AlgoTextCorner algo = new AlgoTextCorner(cons, label, txt, number);
return algo.getCorner();
}
/**
* Corner of Drawing Pad Michael Borcherds 2008-05-10
*/
final public GeoPoint CornerOfDrawingPad(String label, NumberValue number) {
AlgoDrawingPadCorner algo = new AlgoDrawingPadCorner(cons, label, number);
return algo.getCorner();
}
/**
* parabola with focus F and line l
*/
final public GeoConic Parabola(
String label,
GeoPoint F,
GeoLine l) {
AlgoParabolaPointLine algo = new AlgoParabolaPointLine(cons, label, F, l);
GeoConic parabola = algo.getParabola();
return parabola;
}
/**
* ellipse with foci A, B and length of first half axis a
*/
final public GeoConic Ellipse(
String label,
GeoPoint A,
GeoPoint B,
NumberValue a) {
AlgoEllipseFociLength algo = new AlgoEllipseFociLength(cons, label, A, B, a);
GeoConic ellipse = algo.getConic();
return ellipse;
}
/**
* ellipse with foci A, B passing thorugh C
* Michael Borcherds 2008-04-06
*/
final public GeoConic Ellipse(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoEllipseFociPoint algo = new AlgoEllipseFociPoint(cons, label, A, B, C);
GeoConic ellipse = algo.getEllipse();
return ellipse;
}
/**
* hyperbola with foci A, B and length of first half axis a
*/
final public GeoConic Hyperbola(
String label,
GeoPoint A,
GeoPoint B,
NumberValue a) {
AlgoHyperbolaFociLength algo =
new AlgoHyperbolaFociLength(cons, label, A, B, a);
GeoConic hyperbola = algo.getConic();
return hyperbola;
}
/**
* hyperbola with foci A, B passing thorugh C
* Michael Borcherds 2008-04-06
*/
final public GeoConic Hyperbola(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoHyperbolaFociPoint algo =
new AlgoHyperbolaFociPoint(cons, label, A, B, C);
GeoConic hyperbola = algo.getHyperbola();
return hyperbola;
}
/**
* conic through five points
*/
final public GeoConic Conic(String label, GeoPoint[] points) {
AlgoConicFivePoints algo = new AlgoConicFivePoints(cons, label, points);
GeoConic conic = algo.getConic();
return conic;
}
/**
* IntersectLineConic yields intersection points named label1, label2
* of line g and conic c
*/
final public GeoPoint[] IntersectLineConic(
String[] labels,
GeoLine g,
GeoConic c) {
AlgoIntersectLineConic algo = getIntersectionAlgorithm(g, c);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
GeoElement.setLabels(labels, points);
return points;
}
/**
* IntersectConics yields intersection points named label1, label2, label3, label4
* of conics c1, c2
*/
final public GeoPoint[] IntersectConics(
String[] labels,
GeoConic a,
GeoConic b) {
AlgoIntersectConics algo = getIntersectionAlgorithm(a, b);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
GeoElement.setLabels(labels, points);
return points;
}
/**
* IntersectPolynomials yields all intersection points
* of polynomials a, b
*/
final public GeoPoint[] IntersectPolynomials(String[] labels, GeoFunction a, GeoFunction b) {
if (!a.isPolynomialFunction(false) || !b.isPolynomialFunction(false)) {
// dummy point
GeoPoint A = new GeoPoint(cons);
A.setZero();
AlgoIntersectFunctionsNewton algo = new AlgoIntersectFunctionsNewton(cons, labels[0], a, b, A);
GeoPoint[] ret = {algo.getIntersectionPoint()};
return ret;
}
AlgoIntersectPolynomials algo = getIntersectionAlgorithm(a, b);
algo.setPrintedInXML(true);
algo.setLabels(labels);
GeoPoint[] points = algo.getIntersectionPoints();
return points;
}
/**
* get only one intersection point of two polynomials a, b
* that is near to the given location (xRW, yRW)
*/
final public GeoPoint IntersectPolynomialsSingle(
String label, GeoFunction a, GeoFunction b,
double xRW, double yRW)
{
if (!a.isPolynomialFunction(false) || !b.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomials algo = getIntersectionAlgorithm(a, b);
int index = algo.getClosestPointIndex(xRW, yRW);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two polynomials a, b
* with given index
*/
final public GeoPoint IntersectPolynomialsSingle(
String label,
GeoFunction a,
GeoFunction b, NumberValue index) {
if (!a.isPolynomialFunction(false) || !b.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomials algo = getIntersectionAlgorithm(a, b); // index - 1 to start at 0
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* IntersectPolyomialLine yields all intersection points
* of polynomial f and line l
*/
final public GeoPoint[] IntersectPolynomialLine(
String[] labels,
GeoFunction f,
GeoLine l) {
if (!f.isPolynomialFunction(false)) {
// dummy point
GeoPoint A = new GeoPoint(cons);
A.setZero();
AlgoIntersectFunctionLineNewton algo = new AlgoIntersectFunctionLineNewton(cons, labels[0], f, l, A);
GeoPoint[] ret = {algo.getIntersectionPoint()};
return ret;
}
AlgoIntersectPolynomialLine algo = getIntersectionAlgorithm(f, l);
algo.setPrintedInXML(true);
algo.setLabels(labels);
GeoPoint[] points = algo.getIntersectionPoints();
return points;
}
/**
* one intersection point of polynomial f and line l near to (xRW, yRW)
*/
final public GeoPoint IntersectPolynomialLineSingle(
String label,
GeoFunction f,
GeoLine l, double xRW, double yRW) {
if (!f.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomialLine algo = getIntersectionAlgorithm(f, l);
int index = algo.getClosestPointIndex(xRW, yRW);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of a line and a function
*/
final public GeoPoint IntersectPolynomialLineSingle(
String label,
GeoFunction f,
GeoLine l, NumberValue index) {
if (!f.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomialLine algo = getIntersectionAlgorithm(f, l);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two conics that is near to the given
* location (xRW, yRW)
*/
final public GeoPoint IntersectLineConicSingle(
String label,
GeoLine g,
GeoConic c, double xRW, double yRW) {
AlgoIntersectLineConic algo = getIntersectionAlgorithm(g, c);
int index = algo.getClosestPointIndex(xRW, yRW);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of a line and a conic
*/
final public GeoPoint IntersectLineConicSingle(
String label,
GeoLine g,
GeoConic c, NumberValue index) {
AlgoIntersectLineConic algo = getIntersectionAlgorithm(g, c); // index - 1 to start at 0
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two conics that is near to the given
* location (xRW, yRW)
*/
final public GeoPoint IntersectConicsSingle(
String label,
GeoConic a,
GeoConic b, double xRW, double yRW) {
AlgoIntersectConics algo = getIntersectionAlgorithm(a, b);
int index = algo.getClosestPointIndex(xRW, yRW) ;
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two conics
*/
final public GeoPoint IntersectConicsSingle(
String label, GeoConic a, GeoConic b, NumberValue index) {
AlgoIntersectConics algo = getIntersectionAlgorithm(a, b); // index - 1 to start at 0
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of a polynomial and a conic
*/
final public GeoPoint[] IntersectPolynomialConic(
String[] labels,
GeoFunction f,
GeoConic c) {
AlgoIntersectPolynomialConic algo = getIntersectionAlgorithm(f, c);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
// GeoElement.setLabels(labels, points);
algo.setLabels(labels);
return points;
}
final public GeoPoint IntersectPolynomialConicSingle(String label,
GeoFunction f, GeoConic c,NumberValue idx){
AlgoIntersect algo = getIntersectionAlgorithm(f, c);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
final public GeoPoint IntersectPolynomialConicSingle(String label,
GeoFunction f, GeoConic c,double x,double y){
AlgoIntersect algo = getIntersectionAlgorithm(f, c);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of a implicitPoly and a line
*/
final public GeoPoint[] IntersectImplicitpolyLine(
String[] labels,
GeoImplicitPoly p,
GeoLine l) {
AlgoIntersectImplicitpolyParametric algo = getIntersectionAlgorithm(p, l);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of a implicitPoly and a line
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolyLineSingle(
String label,
GeoImplicitPoly p,
GeoLine l,NumberValue idx) {
AlgoIntersect algo = getIntersectionAlgorithm(p, l);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of a implicitPoly and a line
*/
final public GeoPoint IntersectImplicitpolyLineSingle(
String label,
GeoImplicitPoly p,
GeoLine l,double x,double y) {
AlgoIntersect algo = getIntersectionAlgorithm(p, l);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of a implicitPoly and a polynomial
*/
final public GeoPoint[] IntersectImplicitpolyPolynomial(
String[] labels,
GeoImplicitPoly p,
GeoFunction f) {
if (!f.isPolynomialFunction(false))
return null;
AlgoIntersectImplicitpolyParametric algo = getIntersectionAlgorithm(p, f);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of a implicitPoly and a line
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolyPolynomialSingle(
String label,
GeoImplicitPoly p,
GeoFunction f,NumberValue idx) {
if (!f.isPolynomialFunction(false))
return null;
AlgoIntersect algo = getIntersectionAlgorithm(p, f);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of a implicitPoly and a line
*/
final public GeoPoint IntersectImplicitpolyPolynomialSingle(
String label,
GeoImplicitPoly p,
GeoFunction f,double x,double y) {
if (!f.isPolynomialFunction(false))
return null;
AlgoIntersect algo = getIntersectionAlgorithm(p, f);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of two implicitPolys
*/
final public GeoPoint[] IntersectImplicitpolys(
String[] labels,
GeoImplicitPoly p1,
GeoImplicitPoly p2) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, p2);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of two implicitPolys
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolysSingle(
String label,
GeoImplicitPoly p1,
GeoImplicitPoly p2,NumberValue idx) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, p2);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of two implicitPolys near given Point (x,y)
* @param x
* @param y
*/
final public GeoPoint IntersectImplicitpolysSingle(
String label,
GeoImplicitPoly p1,
GeoImplicitPoly p2,double x,double y) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, p2);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of implicitPoly and conic
*/
final public GeoPoint[] IntersectImplicitpolyConic(
String[] labels,
GeoImplicitPoly p1,
GeoConic c1) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, c1);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of implicitPoly and conic
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolyConicSingle(
String label,
GeoImplicitPoly p1,
GeoConic c1,NumberValue idx) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, c1);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of implicitPolys and conic near given Point (x,y)
* @param x
* @param y
*/
final public GeoPoint IntersectImplicitpolyConicSingle(
String label,
GeoImplicitPoly p1,
GeoConic c1,double x,double y) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, c1);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/*
* to avoid multiple calculations of the intersection points of the same
* two objects, we remember all the intersection algorithms created
*/
private ArrayList intersectionAlgos = new ArrayList();
// intersect polynomial and conic
AlgoIntersectPolynomialConic getIntersectionAlgorithm(GeoFunction f, GeoConic c) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(f, c);
if (existingAlgo != null) return (AlgoIntersectPolynomialConic) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectPolynomialConic algo = new AlgoIntersectPolynomialConic(cons, f, c);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersect line and conic
AlgoIntersectLineConic getIntersectionAlgorithm(GeoLine g, GeoConic c) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(g, c);
if (existingAlgo != null) return (AlgoIntersectLineConic) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectLineConic algo = new AlgoIntersectLineConic(cons, g, c);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersect conics
AlgoIntersectConics getIntersectionAlgorithm(GeoConic a, GeoConic b) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(a, b);
if (existingAlgo != null) return (AlgoIntersectConics) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectConics algo = new AlgoIntersectConics(cons, a, b);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of polynomials
AlgoIntersectPolynomials getIntersectionAlgorithm(GeoFunction a, GeoFunction b) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(a, b);
if (existingAlgo != null) return (AlgoIntersectPolynomials) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectPolynomials algo = new AlgoIntersectPolynomials(cons, a, b);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of polynomials
AlgoIntersectPolynomialLine getIntersectionAlgorithm(GeoFunction a, GeoLine l) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(a, l);
if (existingAlgo != null) return (AlgoIntersectPolynomialLine) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectPolynomialLine algo = new AlgoIntersectPolynomialLine(cons, a, l);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of GeoImplicitPoly, GeoLine
AlgoIntersectImplicitpolyParametric getIntersectionAlgorithm(GeoImplicitPoly p, GeoLine l) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p, l);
if (existingAlgo != null) return (AlgoIntersectImplicitpolyParametric) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolyParametric algo = new AlgoIntersectImplicitpolyParametric(cons, p, l);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of GeoImplicitPoly, polynomial
AlgoIntersectImplicitpolyParametric getIntersectionAlgorithm(GeoImplicitPoly p, GeoFunction f) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p, f);
if (existingAlgo != null) return (AlgoIntersectImplicitpolyParametric) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolyParametric algo = new AlgoIntersectImplicitpolyParametric(cons, p, f);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of two GeoImplicitPoly
AlgoIntersectImplicitpolys getIntersectionAlgorithm(GeoImplicitPoly p1, GeoImplicitPoly p2) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p1, p2);
if (existingAlgo != null) return (AlgoIntersectImplicitpolys) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolys algo = new AlgoIntersectImplicitpolys(cons, p1, p2);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
AlgoIntersectImplicitpolys getIntersectionAlgorithm(GeoImplicitPoly p1, GeoConic c1) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p1, c1);
if (existingAlgo != null) return (AlgoIntersectImplicitpolys) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolys algo = new AlgoIntersectImplicitpolys(cons, p1, c1);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
private AlgoElement findExistingIntersectionAlgorithm(GeoElement a, GeoElement b) {
int size = intersectionAlgos.size();
AlgoElement algo;
for (int i=0; i < size; i++) {
algo = (AlgoElement) intersectionAlgos.get(i);
GeoElement [] input = algo.getInput();
if (a == input[0] && b == input[1] ||
a == input[1] && b == input[0])
// we found an existing intersection algorithm
return algo;
}
return null;
}
void removeIntersectionAlgorithm(AlgoIntersect algo) {
intersectionAlgos.remove(algo);
}
/**
* polar line to P relativ to c
*/
final public GeoLine PolarLine(
String label,
GeoPoint P,
GeoConic c) {
AlgoPolarLine algo = new AlgoPolarLine(cons, label, c, P);
GeoLine polar = algo.getLine();
return polar;
}
/**
* diameter line conjugate to direction of g relative to c
*/
final public GeoLine DiameterLine(
String label,
GeoLine g,
GeoConic c) {
AlgoDiameterLine algo = new AlgoDiameterLine(cons, label, c, g);
GeoLine diameter = algo.getDiameter();
return diameter;
}
/**
* diameter line conjugate to v relative to c
*/
final public GeoLine DiameterLine(
String label,
GeoVector v,
GeoConic c) {
AlgoDiameterVector algo = new AlgoDiameterVector(cons, label, c, v);
GeoLine diameter = algo.getDiameter();
return diameter;
}
/**
* tangents to c through P
*/
final public GeoLine[] Tangent(
String[] labels,
GeoPoint P,
GeoConic c) {
AlgoTangentPoint algo = new AlgoTangentPoint(cons, labels, P, c);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* tangents to c parallel to g
*/
final public GeoLine[] Tangent(
String[] labels,
GeoLine g,
GeoConic c) {
AlgoTangentLine algo = new AlgoTangentLine(cons, labels, g, c);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* tangent to f in x = a
*/
final public GeoLine Tangent(
String label,
NumberValue a,
GeoFunction f) {
AlgoTangentFunctionNumber algo =
new AlgoTangentFunctionNumber(cons, label, a, f);
GeoLine t = algo.getTangent();
t.setToExplicit();
t.update();
notifyUpdate(t);
return t;
}
/**
* tangent to f in x = x(P)
*/
final public GeoLine Tangent(
String label,
GeoPoint P,
GeoFunction f) {
AlgoTangentFunctionPoint algo =
new AlgoTangentFunctionPoint(cons, label, P, f);
GeoLine t = algo.getTangent();
t.setToExplicit();
t.update();
notifyUpdate(t);
return t;
}
/**
* tangents to p through P
*/
final public GeoLine[] Tangent(
String[] labels,
GeoPoint R,
GeoImplicitPoly p) {
AlgoTangentImplicitpoly algo = new AlgoTangentImplicitpoly(cons, labels, p, R);
algo.setLabels(labels);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* tangents to p parallel to g
*/
final public GeoLine[] Tangent(
String[] labels,
GeoLine g,
GeoImplicitPoly p) {
AlgoTangentImplicitpoly algo = new AlgoTangentImplicitpoly(cons, labels, p, g);
algo.setLabels(labels);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* asymptotes to c
*/
final public GeoLine[] Asymptote(String[] labels, GeoConic c) {
AlgoAsymptote algo = new AlgoAsymptote(cons, labels, c);
GeoLine[] asymptotes = algo.getAsymptotes();
return asymptotes;
}
/**
* axes of c
*/
final public GeoLine[] Axes(String[] labels, GeoConic c) {
AlgoAxes algo = new AlgoAxes(cons, labels, c);
GeoLine[] axes = algo.getAxes();
return axes;
}
/**
* first axis of c
*/
final public GeoLine FirstAxis(String label, GeoConic c) {
AlgoAxisFirst algo = new AlgoAxisFirst(cons, label, c);
GeoLine axis = algo.getAxis();
return axis;
}
/**
* second axis of c
*/
final public GeoLine SecondAxis(String label, GeoConic c) {
AlgoAxisSecond algo = new AlgoAxisSecond(cons, label, c);
GeoLine axis = algo.getAxis();
return axis;
}
/**
* directrix of c
*/
final public GeoLine Directrix(String label, GeoConic c) {
AlgoDirectrix algo = new AlgoDirectrix(cons, label, c);
GeoLine directrix = algo.getDirectrix();
return directrix;
}
/**
* linear eccentricity of c
*/
final public GeoNumeric Excentricity(String label, GeoConic c) {
AlgoExcentricity algo = new AlgoExcentricity(cons, label, c);
GeoNumeric linearEccentricity = algo.getLinearEccentricity();
return linearEccentricity;
}
/**
* eccentricity of c
*/
final public GeoNumeric Eccentricity(String label, GeoConic c) {
AlgoEccentricity algo = new AlgoEccentricity(cons, label, c);
GeoNumeric eccentricity = algo.getEccentricity();
return eccentricity;
}
/**
* first axis' length of c
*/
final public GeoNumeric FirstAxisLength(String label, GeoConic c) {
AlgoAxisFirstLength algo = new AlgoAxisFirstLength(cons, label, c);
GeoNumeric length = algo.getLength();
return length;
}
/**
* second axis' length of c
*/
final public GeoNumeric SecondAxisLength(String label, GeoConic c) {
AlgoAxisSecondLength algo = new AlgoAxisSecondLength(cons, label, c);
GeoNumeric length = algo.getLength();
return length;
}
/**
* (parabola) parameter of c
*/
final public GeoNumeric Parameter(String label, GeoConic c) {
AlgoParabolaParameter algo = new AlgoParabolaParameter(cons, label, c);
GeoNumeric length = algo.getParameter();
return length;
}
/**
* (circle) radius of c
*/
final public GeoNumeric Radius(String label, GeoConic c) {
AlgoRadius algo = new AlgoRadius(cons, label, c);
GeoNumeric length = algo.getRadius();
return length;
}
/**
* angle of c (angle between first eigenvector and (1,0))
*/
final public GeoAngle Angle(String label, GeoConic c) {
AlgoAngleConic algo = new AlgoAngleConic(cons, label, c);
GeoAngle angle = algo.getAngle();
return angle;
}
/********************************************************************
* TRANSFORMATIONS
********************************************************************/
/**
* translate geoTrans by vector v
*/
final public GeoElement [] Translate(String label, GeoElement geoTrans, GeoVec3D v) {
Transform t = new TransformTranslate(v);
return t.transform(geoTrans, label);
}
/**
* translates vector v to point A. The resulting vector is equal
* to v and has A as startPoint
*/
final public GeoVector Translate(String label, GeoVec3D v, GeoPoint A) {
AlgoTranslateVector algo = new AlgoTranslateVector(cons, label, v, A);
GeoVector vec = algo.getTranslatedVector();
return vec;
}
/**
* rotate geoRot by angle phi around (0,0)
*/
final public GeoElement [] Rotate(String label, GeoElement geoRot, NumberValue phi) {
Transform t = new TransformRotate(phi);
return t.transform(geoRot, label);
}
/**
* rotate geoRot by angle phi around Q
*/
final public GeoElement [] Rotate(String label, GeoElement geoRot, NumberValue phi, GeoPoint Q) {
Transform t = new TransformRotate(phi,Q);
return t.transform(geoRot, label);
}
/**
* dilate geoRot by r from S
*/
final public GeoElement [] Dilate(String label, GeoElement geoDil, NumberValue r, GeoPoint S) {
Transform t = new TransformDilate(r,S);
return t.transform(geoDil, label);
}
/**
* dilate geoRot by r from origin
*/
final public GeoElement [] Dilate(String label, GeoElement geoDil, NumberValue r) {
Transform t = new TransformDilate(r);
return t.transform(geoDil, label);
}
/**
* mirror geoMir at point Q
*/
final public GeoElement [] Mirror(String label, GeoElement geoMir, GeoPoint Q) {
Transform t = new TransformMirror(Q);
return t.transform(geoMir, label);
}
/**
* mirror (invert) element Q in circle
* Michael Borcherds 2008-02-10
*/
final public GeoElement [] Mirror(String label, GeoElement Q, GeoConic conic) {
Transform t = new TransformMirror(conic);
return t.transform(Q, label);
}
/**
* apply matrix
* Michael Borcherds 2010-05-27
*/
final public GeoElement [] ApplyMatrix(String label, GeoElement Q, GeoList matrix) {
Transform t = new TransformApplyMatrix(matrix);
return t.transform(Q, label);
}
/**
* shear
*/
final public GeoElement [] Shear(String label, GeoElement Q, GeoVec3D l, GeoNumeric num) {
Transform t = new TransformShearOrStretch(l,num,true);
return t.transform(Q, label);
}
/**
* apply matrix
* Michael Borcherds 2010-05-27
*/
final public GeoElement [] Stretch(String label, GeoElement Q, GeoVec3D l, GeoNumeric num) {
Transform t = new TransformShearOrStretch(l,num,false);
return t.transform(Q, label);
}
/**
* mirror geoMir at line g
*/
final public GeoElement [] Mirror(String label, GeoElement geoMir, GeoLine g) {
Transform t = new TransformMirror(g);
return t.transform(geoMir, label);
}
static final int TRANSFORM_TRANSLATE = 0;
static final int TRANSFORM_MIRROR_AT_POINT = 1;
static final int TRANSFORM_MIRROR_AT_LINE = 2;
static final int TRANSFORM_ROTATE = 3;
static final int TRANSFORM_ROTATE_AROUND_POINT = 4;
static final int TRANSFORM_DILATE = 5;
public static boolean keepOrientationForTransformation(int transformationType) {
switch (transformationType) {
case TRANSFORM_MIRROR_AT_LINE:
return false;
default:
return true;
}
}
/***********************************
* CALCULUS
***********************************/
/** function limited to interval [a, b]
*/
final public GeoFunction Function(String label, GeoFunction f,
NumberValue a, NumberValue b) {
AlgoFunctionInterval algo = new AlgoFunctionInterval(cons, label, f, a, b);
GeoFunction g = algo.getFunction();
return g;
}
/**
* n-th derivative of multivariate function f
*/
final public GeoElement Derivative(
String label,
CasEvaluableFunction f, GeoNumeric var,
NumberValue n) {
AlgoCasDerivative algo = new AlgoCasDerivative(cons, label, f, var, n);
return algo.getResult();
}
/**
* Tries to expand a function f to a polynomial.
*/
final public GeoFunction PolynomialFunction(String label, GeoFunction f) {
AlgoPolynomialFromFunction algo = new AlgoPolynomialFromFunction(cons, label, f);
return algo.getPolynomial();
}
/**
* Fits a polynomial exactly to a list of coordinates
* Michael Borcherds 2008-01-22
*/
final public GeoFunction PolynomialFunction(String label, GeoList list) {
AlgoPolynomialFromCoordinates algo = new AlgoPolynomialFromCoordinates(cons, label, list);
return algo.getPolynomial();
}
final public GeoElement Expand(String label, CasEvaluableFunction func) {
AlgoCasExpand algo = new AlgoCasExpand(cons, label, func);
return algo.getResult();
}
final public GeoElement Simplify(String label, CasEvaluableFunction func) {
AlgoCasSimplify algo = new AlgoCasSimplify(cons, label, func);
return algo.getResult();
}
final public GeoElement SolveODE(String label, CasEvaluableFunction func) {
AlgoCasSolveODE algo = new AlgoCasSolveODE(cons, label, func);
return algo.getResult();
}
/**
* Simplify text, eg "+-x" to "-x"
* @author Michael Borcherds
*/
final public GeoElement Simplify(String label, GeoText text) {
AlgoSimplifyText algo = new AlgoSimplifyText(cons, label, text);
return algo.getGeoText();
}
final public GeoElement DynamicCoordinates(String label, GeoPoint geoPoint,
NumberValue num1, NumberValue num2) {
AlgoDynamicCoordinates algo = new AlgoDynamicCoordinates(cons, label, geoPoint, num1, num2);
return algo.getPoint();
}
final public GeoElement Factor(String label, CasEvaluableFunction func) {
AlgoCasFactor algo = new AlgoCasFactor(cons, label, func);
return algo.getResult();
}
/**
* Factors
* Michael Borcherds
*/
final public GeoList Factors(String label, GeoFunction func) {
AlgoFactors algo = new AlgoFactors(cons, label, func);
return algo.getResult();
}
final public GeoLocus SolveODE(String label, FunctionalNVar f, FunctionalNVar g, GeoNumeric x, GeoNumeric y, GeoNumeric end, GeoNumeric step) {
AlgoSolveODE algo = new AlgoSolveODE(cons, label, f, g, x, y, end, step);
return algo.getResult();
}
/*
* second order ODEs
*/
final public GeoLocus SolveODE2(String label, GeoFunctionable f, GeoFunctionable g, GeoFunctionable h, GeoNumeric x, GeoNumeric y, GeoNumeric yDot, GeoNumeric end, GeoNumeric step) {
AlgoSolveODE2 algo = new AlgoSolveODE2(cons, label, f, g, h, x, y, yDot, end, step);
return algo.getResult();
}
/**
* Asymptotes
* Michael Borcherds
*/
final public GeoList AsymptoteFunction(String label, GeoFunction func) {
AlgoAsymptoteFunction algo = new AlgoAsymptoteFunction(cons, label, func);
return algo.getResult();
}
/**
* Numerator
* Michael Borcherds
*/
final public GeoFunction Numerator(String label, GeoFunction func) {
AlgoNumerator algo = new AlgoNumerator(cons, label, func);
return algo.getResult();
}
/**
* Denominator
* Michael Borcherds
*/
final public GeoFunction Denominator(String label, GeoFunction func) {
AlgoDenominator algo = new AlgoDenominator(cons, label, func);
return algo.getResult();
}
/**
* Degree
* Michael Borcherds
*/
final public GeoNumeric Degree(String label, GeoFunction func) {
AlgoDegree algo = new AlgoDegree(cons, label, func);
return algo.getResult();
}
/**
* Limit
* Michael Borcherds
*/
final public GeoNumeric Limit(String label, GeoFunction func, NumberValue num) {
AlgoLimit algo = new AlgoLimit(cons, label, func, num);
return algo.getResult();
}
/**
* LimitBelow
* Michael Borcherds
*/
final public GeoNumeric LimitBelow(String label, GeoFunction func, NumberValue num) {
AlgoLimitBelow algo = new AlgoLimitBelow(cons, label, func, num);
return algo.getResult();
}
/**
* LimitAbove
* Michael Borcherds
*/
final public GeoNumeric LimitAbove(String label, GeoFunction func, NumberValue num) {
AlgoLimitAbove algo = new AlgoLimitAbove(cons, label, func, num);
return algo.getResult();
}
/**
* Partial Fractions
* Michael Borcherds
*/
final public GeoElement PartialFractions(String label, CasEvaluableFunction func) {
AlgoCasPartialFractions algo = new AlgoCasPartialFractions(cons, label, func);
return algo.getResult();
}
/**
* Coefficients
* Michael Borcherds 2008-04-04
*/
final public GeoList Coefficients(String label, GeoFunction func) {
AlgoCoefficients algo = new AlgoCoefficients(cons, label, func);
return algo.getResult();
}
/**
* Coefficients
* Michael Borcherds 2008-04-04
*/
final public GeoList Coefficients(String label, GeoConic func) {
AlgoConicCoefficients algo = new AlgoConicCoefficients(cons, label, func);
return algo.getResult();
}
/**
* Taylor series of function f about point x=a of order n
*/
final public GeoFunction TaylorSeries(
String label,
GeoFunction f,
NumberValue a,
NumberValue n) {
AlgoTaylorSeries algo = new AlgoTaylorSeries(cons, label, f, a, n);
return algo.getPolynomial();
}
/**
* Integral of function f
*/
final public GeoElement Integral(String label, CasEvaluableFunction f, GeoNumeric var) {
AlgoCasIntegral algo = new AlgoCasIntegral(cons, label, f, var);
return algo.getResult();
}
/**
* definite Integral of function f from x=a to x=b
*/
final public GeoNumeric Integral(String label, GeoFunction f, NumberValue a, NumberValue b) {
AlgoIntegralDefinite algo = new AlgoIntegralDefinite(cons, label, f, a, b);
GeoNumeric n = algo.getIntegral();
return n;
}
/**
* definite integral of function (f - g) in interval [a, b]
*/
final public GeoNumeric Integral(String label, GeoFunction f, GeoFunction g,
NumberValue a, NumberValue b) {
AlgoIntegralFunctions algo = new AlgoIntegralFunctions(cons, label, f, g, a, b);
GeoNumeric num = algo.getIntegral();
return num;
}
/**
*
*/
final public GeoPoint [] PointsFromList(String [] labels, GeoList list) {
AlgoPointsFromList algo = new AlgoPointsFromList(cons, labels, true, list);
GeoPoint [] g = algo.getPoints();
return g;
}
/**
* all Roots of polynomial f (works only for polynomials and functions
* that can be simplified to factors of polynomials, e.g. sqrt(x) to x)
*/
final public GeoPoint [] Root(String [] labels, GeoFunction f) {
// allow functions that can be simplified to factors of polynomials
if (!f.isPolynomialFunction(true)) return null;
AlgoRootsPolynomial algo = new AlgoRootsPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* all Complex Roots of polynomial f (works only for polynomials)
*/
final public GeoPoint [] ComplexRoot(String [] labels, GeoFunction f) {
// allow functions that can be simplified to factors of polynomials
if (!f.isPolynomialFunction(true)) return null;
AlgoComplexRootsPolynomial algo = new AlgoComplexRootsPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* Root of a function f to given start value a (works only if first derivative of f exists)
*/
final public GeoPoint Root(String label, GeoFunction f, NumberValue a) {
AlgoRootNewton algo = new AlgoRootNewton(cons, label, f, a);
GeoPoint p = algo.getRootPoint();
return p;
}
/**
* Root of a function f in given interval [a, b]
*/
final public GeoPoint Root(String label, GeoFunction f, NumberValue a, NumberValue b) {
AlgoRootInterval algo = new AlgoRootInterval(cons, label, f, a, b);
GeoPoint p = algo.getRootPoint();
return p;
}
/**
* all Extrema of function f (works only for polynomials)
*/
final public GeoPoint [] Extremum(String [] labels, GeoFunction f) {
// check if this is a polynomial at the moment
if (!f.isPolynomialFunction(true)) return null;
AlgoExtremumPolynomial algo = new AlgoExtremumPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* all Turning points of function f (works only for polynomials)
*/
final public GeoPoint [] TurningPoint(String [] labels, GeoFunction f) {
// check if this is a polynomial at the moment
if (!f.isPolynomialFunction(true)) return null;
AlgoTurningPointPolynomial algo = new AlgoTurningPointPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* Victor Franco Espino 18-04-2007: New commands
*
* Calculate affine ratio: (A,B,C) = (t(C)-t(A)) : (t(C)-t(B))
*/
final public GeoNumeric AffineRatio(String label, GeoPoint A, GeoPoint B,
GeoPoint C) {
AlgoAffineRatio affine = new AlgoAffineRatio(cons, label, A, B, C);
GeoNumeric M = affine.getResult();
return M;
}
/**
* Calculate cross ratio: (A,B,C,D) = affineRatio(A, B, C) / affineRatio(A, B, D)
*/
final public GeoNumeric CrossRatio(String label,GeoPoint A,GeoPoint B,GeoPoint C,GeoPoint D){
AlgoCrossRatio cross = new AlgoCrossRatio(cons,label,A,B,C,D);
GeoNumeric M = cross.getResult();
return M;
}
/**
* Calculate Curvature Vector for function: c(x) = (1/T^4)*(-f'*f'',f''), T = sqrt(1+(f')^2)
*/
final public GeoVector CurvatureVector(String label,GeoPoint A,GeoFunction f){
AlgoCurvatureVector algo = new AlgoCurvatureVector(cons,label,A,f);
GeoVector v = algo.getVector();
return v;
}
/**
* Calculate Curvature Vector for curve: c(t) = ((a'(t)b''(t)-a''(t)b'(t))/T^4) * (-b'(t),a'(t))
* T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoVector CurvatureVectorCurve(String label,GeoPoint A,GeoCurveCartesian f){
AlgoCurvatureVectorCurve algo = new AlgoCurvatureVectorCurve(cons,label,A,f);
GeoVector v = algo.getVector();
return v;
}
/**
* Calculate Curvature for function: k(x) = f''/T^3, T = sqrt(1+(f')^2)
*/
final public GeoNumeric Curvature(String label,GeoPoint A,GeoFunction f){
AlgoCurvature algo = new AlgoCurvature(cons,label,A,f);
GeoNumeric k = algo.getResult();
return k;
}
/**
* Calculate Curvature for Curve: k(t) = (a'(t)b''(t)-a''(t)b'(t))/T^3, T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoNumeric CurvatureCurve(String label,GeoPoint A, GeoCurveCartesian f){
AlgoCurvatureCurve algo = new AlgoCurvatureCurve(cons,label,A,f);
GeoNumeric k = algo.getResult();
return k;
}
/**
* Osculating Circle of a function f in point A
*/
final public GeoConic OsculatingCircle(String label,GeoPoint A,GeoFunction f){
AlgoOsculatingCircle algo = new AlgoOsculatingCircle(cons,label,A,f);
GeoConic circle = algo.getCircle();
return circle;
}
/**
* Osculating Circle of a curve f in point A
*/
final public GeoConic OsculatingCircleCurve(String label,GeoPoint A,GeoCurveCartesian f){
AlgoOsculatingCircleCurve algo = new AlgoOsculatingCircleCurve(cons,label,A,f);
GeoConic circle = algo.getCircle();
return circle;
}
/**
* Calculate Function Length between the numbers A and B: integral from A to B on T = sqrt(1+(f')^2)
*/
final public GeoNumeric FunctionLength(String label,GeoFunction f,GeoNumeric A,GeoNumeric B){
AlgoLengthFunction algo = new AlgoLengthFunction(cons,label,f,A,B);
GeoNumeric length = algo.getLength();
return length;
}
/**
* Calculate Function Length between the points A and B: integral from A to B on T = sqrt(1+(f')^2)
*/
final public GeoNumeric FunctionLength2Points(String label,GeoFunction f,GeoPoint A,GeoPoint B){
AlgoLengthFunction2Points algo = new AlgoLengthFunction2Points(cons,label,f,A,B);
GeoNumeric length = algo.getLength();
return length;
}
/**
* Calculate Curve Length between the parameters t0 and t1: integral from t0 to t1 on T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoNumeric CurveLength(String label, GeoCurveCartesian c, GeoNumeric t0,GeoNumeric t1){
AlgoLengthCurve algo = new AlgoLengthCurve(cons,label,c,t0,t1);
GeoNumeric length = algo.getLength();
return length;
}
/**
* Calculate Curve Length between the points A and B: integral from t0 to t1 on T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoNumeric CurveLength2Points(String label, GeoCurveCartesian c, GeoPoint A,GeoPoint B){
AlgoLengthCurve2Points algo = new AlgoLengthCurve2Points(cons,label,c,A,B);
GeoNumeric length = algo.getLength();
return length;
}
/**
* tangent to Curve f in point P: (b'(t), -a'(t), a'(t)*b(t)-a(t)*b'(t))
*/
final public GeoLine Tangent(String label,GeoPoint P,GeoCurveCartesian f) {
AlgoTangentCurve algo = new AlgoTangentCurve(cons, label, P, f);
GeoLine t = algo.getTangent();
t.setToExplicit();
t.update();
notifyUpdate(t);
return t;
}
/**
* Victor Franco Espino 18-04-2007: End new commands
*/
/***********************************
* PACKAGE STUFF
***********************************/
/** if x is nearly zero, 0.0 is returned,
* else x is returned
*/
final public double chop(double x) {
if (isZero(x))
return 0.0d;
else
return x;
}
final public boolean isReal(Complex c) {
return isZero(c.getImaginary());
}
/** is abs(x) < epsilon ? */
final public static boolean isZero(double x) {
return -EPSILON < x && x < EPSILON;
}
final boolean isZero(double[] a) {
for (int i = 0; i < a.length; i++) {
if (!isZero(a[i]))
return false;
}
return true;
}
final public boolean isInteger(double x) {
if (x > 1E17)
return true;
else
return isEqual(x, Math.round(x));
}
/**
* Returns whether x is equal to y
* infinity == infinity returns true eg 1/0
* -infinity == infinity returns false eg -1/0
* -infinity == -infinity returns true
* undefined == undefined returns false eg 0/0
*/
final public static boolean isEqual(double x, double y) {
if (x == y) // handles infinity and NaN cases
return true;
else
return x - EPSILON <= y && y <= x + EPSILON;
}
final public static boolean isEqual(double x, double y, double eps) {
if (x == y) // handles infinity and NaN cases
return true;
else
return x - eps < y && y < x + eps;
}
/**
* Returns whether x is greater than y
*/
final public boolean isGreater(double x, double y) {
return x > y + EPSILON;
}
/**
* Returns whether x is greater than or equal to y
*/
final public boolean isGreaterEqual(double x, double y) {
return x + EPSILON > y;
}
// compares double arrays:
// yields true if (isEqual(a[i], b[i]) == true) for all i
final boolean isEqual(double[] a, double[] b) {
for (int i = 0; i < a.length; ++i) {
if (!isEqual(a[i], b[i]))
return false;
}
return true;
}
final public double convertToAngleValue(double val) {
if (val > EPSILON && val < PI_2) return val;
double value = val % PI_2;
if (isZero(value)) {
if (val < 1.0) value = 0.0;
else value = PI_2;
}
else if (value < 0.0) {
value += PI_2;
}
return value;
}
/*
// calc acos(x). returns 0 for x > 1 and pi for x < -1
final static double trimmedAcos(double x) {
if (Math.abs(x) <= 1.0d)
return Math.acos(x);
else if (x > 1.0d)
return 0.0d;
else if (x < -1.0d)
return Math.PI;
else
return Double.NaN;
}*/
/** returns max of abs(a[i]) */
final static double maxAbs(double[] a) {
double temp, max = Math.abs(a[0]);
for (int i = 1; i < a.length; i++) {
temp = Math.abs(a[i]);
if (temp > max)
max = temp;
}
return max;
}
// copy array a to array b
final static void copy(double[] a, double[] b) {
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
}
// change signs of double array values, write result to array b
final static void negative(double[] a, double[] b) {
for (int i = 0; i < a.length; i++) {
b[i] = -a[i];
}
}
// c[] = a[] / b
final static void divide(double[] a, double b, double[] c) {
for (int i = 0; i < a.length; i++) {
c[i] = a[i] / b;
}
}
// temp for buildEquation
private double[] temp;// = new double[6];
// lhs of implicit equation without constant coeff
final private StringBuilder buildImplicitVarPart(
double[] numbers,
String[] vars,
boolean KEEP_LEADING_SIGN,
boolean CANCEL_DOWN) {
temp = new double[numbers.length];
int leadingNonZero = -1;
sbBuildImplicitVarPart.setLength(0);
for (int i = 0; i < vars.length; i++) {
if (!isZero(numbers[i])) {
leadingNonZero = i;
break;
}
}
if (CANCEL_DOWN) {
// check if integers and divide through gcd
boolean allIntegers = true;
for (int i = 0; i < numbers.length; i++) {
allIntegers = allIntegers && isInteger(numbers[i]);
}
if (allIntegers) {
// divide by greates common divisor
divide(numbers, gcd(numbers), numbers);
}
}
// no left hand side
if (leadingNonZero == -1) {
sbBuildImplicitVarPart.append("0");
return sbBuildImplicitVarPart;
}
// don't change leading coefficient
if (KEEP_LEADING_SIGN) {
copy(numbers, temp);
} else {
if (numbers[leadingNonZero] < 0)
negative(numbers, temp);
else
copy(numbers, temp);
}
// BUILD EQUATION STRING
// valid left hand side
// leading coefficient
String strCoeff = formatCoeff(temp[leadingNonZero]);
sbBuildImplicitVarPart.append(strCoeff);
sbBuildImplicitVarPart.append(vars[leadingNonZero]);
// other coefficients on lhs
String sign;
double abs;
for (int i = leadingNonZero + 1; i < vars.length; i++) {
if (temp[i] < 0.0) {
sign = " - ";
abs = -temp[i];
} else {
sign = " + ";
abs = temp[i];
}
if (abs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildImplicitVarPart.append(sign);
sbBuildImplicitVarPart.append(formatCoeff(abs));
sbBuildImplicitVarPart.append(vars[i]);
}
}
return sbBuildImplicitVarPart;
}
private StringBuilder sbBuildImplicitVarPart = new StringBuilder(80);
public final StringBuilder buildImplicitEquation(
double[] numbers,
String[] vars,
boolean KEEP_LEADING_SIGN,
boolean CANCEL_DOWN,
char op) {
sbBuildImplicitEquation.setLength(0);
Application.debug("implicit");
sbBuildImplicitEquation.append(buildImplicitVarPart(numbers, vars, KEEP_LEADING_SIGN || (op == '='), CANCEL_DOWN));
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER) {
sbBuildImplicitEquation.append(" == ");
}
else
{
sbBuildImplicitEquation.append(' ');
sbBuildImplicitEquation.append(op);
sbBuildImplicitEquation.append(' ');
}
// temp is set by buildImplicitVarPart
sbBuildImplicitEquation.append(format(-temp[vars.length]));
return sbBuildImplicitEquation;
}
private StringBuilder sbBuildImplicitEquation = new StringBuilder(80);
// lhs of lhs = 0
final public StringBuilder buildLHS(double[] numbers, String[] vars, boolean KEEP_LEADING_SIGN, boolean CANCEL_DOWN) {
sbBuildLHS.setLength(0);
sbBuildLHS.append(buildImplicitVarPart(numbers, vars, KEEP_LEADING_SIGN, CANCEL_DOWN));
// add constant coeff
double coeff = temp[vars.length];
if (Math.abs(coeff) >= PRINT_PRECISION || useSignificantFigures) {
sbBuildLHS.append(' ');
sbBuildLHS.append(sign(coeff));
sbBuildLHS.append(' ');
sbBuildLHS.append(format(Math.abs(coeff)));
}
return sbBuildLHS;
}
private StringBuilder sbBuildLHS = new StringBuilder(80);
// form: y� = f(x) (coeff of y = 0)
final StringBuilder buildExplicitConicEquation(
double[] numbers,
String[] vars,
int pos,
boolean KEEP_LEADING_SIGN) {
// y�-coeff is 0
double d, dabs, q = numbers[pos];
// coeff of y� is 0 or coeff of y is not 0
if (isZero(q))
return buildImplicitEquation(numbers, vars, KEEP_LEADING_SIGN, true, '=');
int i, leadingNonZero = numbers.length;
for (i = 0; i < numbers.length; i++) {
if (i != pos
&& // except y� coefficient
(Math.abs(numbers[i]) >= PRINT_PRECISION || useSignificantFigures)) {
leadingNonZero = i;
break;
}
}
// BUILD EQUATION STRING
sbBuildExplicitConicEquation.setLength(0);
sbBuildExplicitConicEquation.append(vars[pos]);
sbBuildExplicitConicEquation.append(" = ");
if (leadingNonZero == numbers.length) {
sbBuildExplicitConicEquation.append("0");
return sbBuildExplicitConicEquation;
} else if (leadingNonZero == numbers.length - 1) {
// only constant coeff
d = -numbers[leadingNonZero] / q;
sbBuildExplicitConicEquation.append(format(d));
return sbBuildExplicitConicEquation;
} else {
// leading coeff
d = -numbers[leadingNonZero] / q;
sbBuildExplicitConicEquation.append(formatCoeff(d));
sbBuildExplicitConicEquation.append(vars[leadingNonZero]);
// other coeffs
for (i = leadingNonZero + 1; i < vars.length; i++) {
if (i != pos) {
d = -numbers[i] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(sign(d));
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(formatCoeff(dabs));
sbBuildExplicitConicEquation.append(vars[i]);
}
}
}
// constant coeff
d = -numbers[i] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(sign(d));
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(format(dabs));
}
//Application.debug(sbBuildExplicitConicEquation.toString());
return sbBuildExplicitConicEquation;
}
}
private StringBuilder sbBuildExplicitConicEquation = new StringBuilder(80);
// y = k x + d
final StringBuilder buildExplicitLineEquation(
double[] numbers,
String[] vars,
char op) {
double d, dabs, q = numbers[1];
sbBuildExplicitLineEquation.setLength(0);
// BUILD EQUATION STRING
// special case
// y-coeff is 0: form x = constant
if (isZero(q)) {
sbBuildExplicitLineEquation.append("x");
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER) {
sbBuildExplicitLineEquation.append(" == ");
}
else {
sbBuildExplicitLineEquation.append(' ');
if(numbers[0]<Kernel.MIN_PRECISION){
op = oppositeSign(op);
}
sbBuildExplicitLineEquation.append(op);
sbBuildExplicitLineEquation.append(' ');
}
sbBuildExplicitLineEquation.append(format(-numbers[2] / numbers[0]));
return sbBuildExplicitLineEquation;
}
// standard case: y-coeff not 0
sbBuildExplicitLineEquation.append("y");
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER) {
sbBuildExplicitLineEquation.append(" == ");
}
else {
sbBuildExplicitLineEquation.append(' ');
if(numbers[1] <Kernel.MIN_PRECISION){
op = oppositeSign(op);
}
sbBuildExplicitLineEquation.append(op);
sbBuildExplicitLineEquation.append(' ');
}
// x coeff
d = -numbers[0] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitLineEquation.append(formatCoeff(d));
sbBuildExplicitLineEquation.append('x');
// constant
d = -numbers[2] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitLineEquation.append(' ');
sbBuildExplicitLineEquation.append(sign(d));
sbBuildExplicitLineEquation.append(' ');
sbBuildExplicitLineEquation.append(format(dabs));
}
} else {
// only constant
sbBuildExplicitLineEquation.append(format(-numbers[2] / q));
}
return sbBuildExplicitLineEquation;
}
/**
* Inverts the > or < sign
* @param op
* @return opposite sign
*/
public static char oppositeSign(char op) {
switch(op) {
case '=':return '=';
case '<':return '>';
case '>':return '<';
default: return '?';
}
}
private StringBuilder sbBuildExplicitLineEquation = new StringBuilder(50);
/*
final private String formatAbs(double x) {
if (isZero(x))
return "0";
else
return formatNF(Math.abs(x));
}*/
/** doesn't show 1 or -1 */
final private String formatCoeff(double x) {
if (Math.abs(x) == 1.0) {
if (x > 0.0)
return "";
else
return "-";
} else {
String numberStr = format(x);
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER)
return numberStr + "*";
else {
// standard case
return numberStr;
}
}
}
////////////////////////////////////////////////
// FORMAT FOR NUMBERS
////////////////////////////////////////////////
public double axisNumberDistance(double units, NumberFormat numberFormat){
// calc number of digits
int exp = (int) Math.floor(Math.log(units) / Math.log(10));
int maxFractionDigtis = Math.max(-exp, getPrintDecimals());
// format the numbers
if (numberFormat instanceof DecimalFormat)
((DecimalFormat) numberFormat).applyPattern("###0.##");
numberFormat.setMaximumFractionDigits(maxFractionDigtis);
// calc the distance
double pot = Math.pow(10, exp);
double n = units / pot;
double distance;
if (n > 5) {
distance = 5 * pot;
} else if (n > 2) {
distance = 2 * pot;
} else {
distance = pot;
}
return distance;
}
private StringBuilder formatSB;
/**
* Formats the value of x using the currently set
* NumberFormat or ScientificFormat. This method also
* takes getCasPrintForm() into account.
*
* converts to localised digits if appropriate
*/
final public String format(double x) {
if (Application.unicodeZero != '0') {
String num = formatRaw(x);
return internationalizeDigits(num);
} else return formatRaw(x);
}
/*
* swaps the digits in num to the current locale's
*/
public String internationalizeDigits(String num) {
if (formatSB == null) formatSB = new StringBuilder(17);
else formatSB.setLength(0);
boolean reverseOrder = app.isRightToLeftDigits();
int length = num.length();
for (int i = 0 ; i < num.length() ; i++) {
char c = num.charAt(i);
//char c = reverseOrder ? num.charAt(length - 1 - i) : num.charAt(i);
if (c == '.') c = Application.unicodeDecimalPoint;
else if (c >= '0' && c <= '9') {
c += Application.unicodeZero - '0'; // convert to eg Arabic Numeral
}
// make sure the minus is treated as part of the number in eg Arabic
if ( reverseOrder && c=='-'){
formatSB.append(Unicode.RightToLeftMark);
formatSB.append(c);
formatSB.append(Unicode.RightToLeftMark);
}
else
formatSB.append(c);
}
return formatSB.toString();
}
/**
* Formats the value of x using the currently set
* NumberFormat or ScientificFormat. This method also
* takes getCasPrintForm() into account.
*/
final public String formatRaw(double x) {
switch (casPrintForm) {
// number formatting for XML string output
case ExpressionNode.STRING_TYPE_GEOGEBRA_XML:
return Double.toString(x);
// number formatting for CAS
case ExpressionNode.STRING_TYPE_MATH_PIPER:
case ExpressionNode.STRING_TYPE_JASYMCA:
case ExpressionNode.STRING_TYPE_MAXIMA:
if (Double.isNaN(x))
return " 1/0 ";
else if (Double.isInfinite(x)) {
if (casPrintForm == ExpressionNode.STRING_TYPE_MAXIMA) return (x<0) ? "-infinity" : "infinity";
return Double.toString(x); // "Infinity" or "-Infinity"
}
else {
double abs = Math.abs(x);
// number small enough that Double.toString() won't create E notation
if (abs >= 10E-3 && abs < 10E7) {
long round = Math.round(x);
if (x == round) {
return Long.toString(round);
} else {
return Double.toString(x);
}
}
// number would produce E notation with Double.toString()
else {
// convert scientific notation 1.0E-20 to 1*10^(-20)
String scientificStr = Double.toString(x);
StringBuilder sb = new StringBuilder(scientificStr.length() * 2);
boolean Efound = false;
for (int i=0; i < scientificStr.length(); i++) {
char ch = scientificStr.charAt(i);
if (ch == 'E') {
sb.append("*10^(");
Efound = true;
} else {
sb.append(ch);
}
}
if (Efound)
sb.append(")");
// TODO: remove
//Application.printStacktrace(sb.toString());
return sb.toString();
}
}
// number formatting for screen output
default:
if (Double.isNaN(x))
return "?";
else if (Double.isInfinite(x)) {
return (x > 0) ? "\u221e" : "-\u221e"; // infinity
}
else if (x == Math.PI) {
return casPrintFormPI;
}
// ROUNDING hack
// NumberFormat and SignificantFigures use ROUND_HALF_EVEN as
// default which is not changeable, so we need to hack this
// to get ROUND_HALF_UP like in schools: increase abs(x) slightly
// x = x * ROUND_HALF_UP_FACTOR;
// We don't do this for large numbers as
double abs = Math.abs(x);
if (abs < 10E7) {
// increase abs(x) slightly to round up
x = x * ROUND_HALF_UP_FACTOR;
}
if (useSignificantFigures) {
return formatSF(x);
} else {
return formatNF(x);
}
}
}
/**
* Uses current NumberFormat nf to format a number.
*/
final private String formatNF(double x) {
// "<=" catches -0.0000000000000005
// should be rounded to -0.000000000000001 (15 d.p.)
// but nf.format(x) returns "-0"
if (-PRINT_PRECISION / 2 <= x && x < PRINT_PRECISION / 2) {
// avoid output of "-0" for eg -0.0004
return "0";
} else {
// standard case
return nf.format(x);
}
}
/**
* Uses current ScientificFormat sf to format a number. Makes sure ".123" is
* returned as "0.123".
*/
final private String formatSF(double x) {
if (sbFormatSF == null)
sbFormatSF = new StringBuilder();
else
sbFormatSF.setLength(0);
// get scientific format
String absStr;
if (x == 0) {
// avoid output of "-0.00"
absStr = sf.format(0);
}
else if (x > 0) {
absStr = sf.format(x);
}
else {
sbFormatSF.append('-');
absStr = sf.format(-x);
}
// make sure ".123" is returned as "0.123".
if (absStr.charAt(0) == '.')
sbFormatSF.append('0');
sbFormatSF.append(absStr);
return sbFormatSF.toString();
}
private StringBuilder sbFormatSF;
/**
* calls formatPiERaw() and converts to localised digits if appropriate
*/
final public String formatPiE(double x, NumberFormat numF) {
if (Application.unicodeZero != '0') {
String num = formatPiERaw(x, numF);
return internationalizeDigits(num);
} else return formatPiERaw(x, numF);
}
final public String formatPiERaw(double x, NumberFormat numF) {
// PI
if (x == Math.PI) {
return casPrintFormPI;
}
// MULTIPLES OF PI/2
// i.e. x = a * pi/2
double a = 2*x / Math.PI;
int aint = (int) Math.round(a);
if (sbFormat == null)
sbFormat = new StringBuilder();
sbFormat.setLength(0);
if (isEqual(a, aint, STANDARD_PRECISION)) {
switch (aint) {
case 0:
return "0";
case 1: // pi/2
sbFormat.append(casPrintFormPI);
sbFormat.append("/2");
return sbFormat.toString();
case -1: // -pi/2
sbFormat.append('-');
sbFormat.append(casPrintFormPI);
sbFormat.append("/2");
return sbFormat.toString();
case 2: // 2pi/2 = pi
return casPrintFormPI;
case -2: // -2pi/2 = -pi
sbFormat.append('-');
sbFormat.append(casPrintFormPI);
return sbFormat.toString();
default:
// even
long half = aint / 2;
if (aint == 2 * half) {
// half * pi
sbFormat.append(half);
if (casPrintForm != ExpressionNode.STRING_TYPE_GEOGEBRA)
sbFormat.append("*");
sbFormat.append(casPrintFormPI);
return sbFormat.toString();
}
// odd
else {
// aint * pi/2
sbFormat.append(aint);
if (casPrintForm != ExpressionNode.STRING_TYPE_GEOGEBRA)
sbFormat.append("*");
sbFormat.append(casPrintFormPI);
sbFormat.append("/2");
return sbFormat.toString();
}
}
}
// STANDARD CASE
// use numberformat to get number string
// checkDecimalFraction() added to avoid 2.19999999999999 when set to 15dp
String str = numF.format(checkDecimalFraction(x));
sbFormat.append(str);
// if number is in scientific notation and ends with "E0", remove this
if (str.endsWith("E0"))
sbFormat.setLength(sbFormat.length() - 2);
return sbFormat.toString();
}
private StringBuilder sbFormat;
final public String formatSignedCoefficient(double x) {
if (x == -1.0)
return "- ";
if (x == 1.0)
return "+ ";
return formatSigned(x).toString();
}
final public StringBuilder formatSigned(double x) {
sbFormatSigned.setLength(0);
if (x >= 0.0d) {
sbFormatSigned.append("+ ");
sbFormatSigned.append( format(x));
return sbFormatSigned;
} else {
sbFormatSigned.append("- ");
sbFormatSigned.append( format(-x));
return sbFormatSigned;
}
}
private StringBuilder sbFormatSigned = new StringBuilder(40);
final public StringBuilder formatAngle(double phi) {
// STANDARD_PRECISION * 10 as we need a little leeway as we've converted from radians
return formatAngle(phi, 10);
}
final public StringBuilder formatAngle(double phi, double precision) {
sbFormatAngle.setLength(0);
switch (casPrintForm) {
case ExpressionNode.STRING_TYPE_MATH_PIPER:
case ExpressionNode.STRING_TYPE_JASYMCA:
if (angleUnit == ANGLE_DEGREE) {
sbFormatAngle.append("(");
// STANDARD_PRECISION * 10 as we need a little leeway as we've converted from radians
sbFormatAngle.append(format(checkDecimalFraction(Math.toDegrees(phi), precision)));
sbFormatAngle.append("*");
sbFormatAngle.append("\u00b0");
sbFormatAngle.append(")");
} else {
sbFormatAngle.append(format(phi));
}
return sbFormatAngle;
default:
// STRING_TYPE_GEOGEBRA_XML
// STRING_TYPE_GEOGEBRA
if (Double.isNaN(phi)) {
sbFormatAngle.append("?");
return sbFormatAngle;
}
if (angleUnit == ANGLE_DEGREE) {
phi = Math.toDegrees(phi);
if (phi < 0)
phi += 360;
else if (phi > 360)
phi = phi % 360;
// STANDARD_PRECISION * 10 as we need a little leeway as we've converted from radians
sbFormatAngle.append(format(checkDecimalFraction(phi, precision)));
if (casPrintForm == ExpressionNode.STRING_TYPE_GEOGEBRA_XML) {
sbFormatAngle.append("*");
}
sbFormatAngle.append('\u00b0');
return sbFormatAngle;
}
else {
// RADIANS
sbFormatAngle.append(format(phi));
if (casPrintForm != ExpressionNode.STRING_TYPE_GEOGEBRA_XML) {
sbFormatAngle.append(" rad");
}
return sbFormatAngle;
}
}
}
private StringBuilder sbFormatAngle = new StringBuilder(40);
final private static char sign(double x) {
if (x > 0)
return '+';
else
return '-';
}
/**
* greatest common divisor
*/
final public static long gcd(long m, long n) {
// Return the GCD of positive integers m and n.
if (m == 0 || n == 0)
return Math.max(Math.abs(m), Math.abs(n));
long p = m, q = n;
while (p % q != 0) {
long r = p % q;
p = q;
q = r;
}
return q;
}
/**
* Compute greatest common divisor of given doubles.
* Note: all double values are cast to long.
*/
final public static double gcd(double[] numbers) {
long gcd = (long) numbers[0];
for (int i = 0; i < numbers.length; i++) {
gcd = gcd((long) numbers[i], gcd);
}
return Math.abs(gcd);
}
/**
* Round a double to the given scale
* e.g. roundToScale(5.32, 1) = 5.0,
* roundToScale(5.32, 0.5) = 5.5,
* roundToScale(5.32, 0.25) = 5.25,
* roundToScale(5.32, 0.1) = 5.3
*/
final public static double roundToScale(double x, double scale) {
if (scale == 1.0)
return Math.round(x);
else {
return Math.round(x / scale) * scale;
}
}
/**
* Checks if x is close (Kernel.MIN_PRECISION) to a decimal fraction,
* eg 2.800000000000001. If it is, the decimal fraction eg 2.8 is returned,
* otherwise x is returned.
*/
/**
* Checks if x is close (Kernel.MIN_PRECISION) to a decimal fraction, eg
* 2.800000000000001. If it is, the decimal fraction eg 2.8 is returned,
* otherwise x is returned.
*/
final public double checkDecimalFraction(double x, double precision) {
//Application.debug(precision+" ");
precision = Math.pow(10, Math.floor(Math.log(Math.abs(precision))/Math.log(10)));
double fracVal = x * INV_MIN_PRECISION;
double roundVal = Math.round(fracVal);
//Application.debug(precision+" "+x+" "+fracVal+" "+roundVal+" "+isEqual(fracVal, roundVal, precision)+" "+roundVal / INV_MIN_PRECISION);
if (isEqual(fracVal, roundVal, STANDARD_PRECISION * precision))
return roundVal / INV_MIN_PRECISION;
else
return x;
}
final public double checkDecimalFraction(double x) {
return checkDecimalFraction(x, 1);
}
/**
* Checks if x is very close (1E-8) to an integer. If it is,
* the integer value is returned, otherwise x is returnd.
*/
final public double checkInteger(double x) {
double roundVal = Math.round(x);
if (Math.abs(x - roundVal) < EPSILON)
return roundVal;
else
return x;
}
/*******************************************************
* SAVING
*******************************************************/
private boolean isSaving;
public synchronized boolean isSaving() {
return isSaving;
}
public synchronized void setSaving(boolean saving) {
isSaving = saving;
}
/**
* Returns the kernel settings in XML format.
*/
public void getKernelXML(StringBuilder sb) {
// kernel settings
sb.append("<kernel>\n");
// continuity: true or false, since V3.0
sb.append("\t<continuous val=\"");
sb.append(isContinuous());
sb.append("\"/>\n");
if (useSignificantFigures) {
// significant figures
sb.append("\t<significantfigures val=\"");
sb.append(getPrintFigures());
sb.append("\"/>\n");
}
else
{
// decimal places
sb.append("\t<decimals val=\"");
sb.append(getPrintDecimals());
sb.append("\"/>\n");
}
// angle unit
sb.append("\t<angleUnit val=\"");
sb.append(angleUnit == Kernel.ANGLE_RADIANT ? "radiant" : "degree");
sb.append("\"/>\n");
// algebra style
sb.append("\t<algebraStyle val=\"");
sb.append(algebraStyle);
sb.append("\"/>\n");
// coord style
sb.append("\t<coordStyle val=\"");
sb.append(getCoordStyle());
sb.append("\"/>\n");
// animation
if (isAnimationRunning()) {
sb.append("\t<startAnimation val=\"");
sb.append(isAnimationRunning());
sb.append("\"/>\n");
}
sb.append("</kernel>\n");
}
public boolean isTranslateCommandName() {
return translateCommandName;
}
public void setTranslateCommandName(boolean b) {
translateCommandName = b;
}
/**
* States whether the continuity heuristic is active.
*/
final public boolean isContinuous() {
return continuous;
}
/**
* Turns the continuity heuristic on or off.
* Note: the macro kernel always turns continuity off.
*/
public void setContinuous(boolean continuous) {
this.continuous = continuous;
}
public final boolean isAllowVisibilitySideEffects() {
return allowVisibilitySideEffects;
}
public final void setAllowVisibilitySideEffects(
boolean allowVisibilitySideEffects) {
this.allowVisibilitySideEffects = allowVisibilitySideEffects;
}
public boolean isMacroKernel() {
return false;
}
private AnimationManager animationManager;
final public AnimationManager getAnimatonManager() {
if (animationManager == null) {
animationManager = new AnimationManager(this);
}
return animationManager;
}
final public boolean isAnimationRunning() {
return animationManager != null && animationManager.isRunning();
}
final public boolean isAnimationPaused() {
return animationManager != null && animationManager.isPaused();
}
final public boolean needToShowAnimationButton() {
return animationManager != null && animationManager.needToShowAnimationButton();
}
final public void udpateNeedToShowAnimationButton() {
if (animationManager != null)
animationManager.updateNeedToShowAnimationButton();
}
/**
* Turns silent mode on (true) or off (false). In silent mode, commands can
* be used to create objects without any side effects, i.e.
* no labels are created, algorithms are not added to the construction
* list and the views are not notified about new objects.
*/
public final void setSilentMode(boolean silentMode) {
this.silentMode = silentMode;
// no new labels, no adding to construction list
cons.setSuppressLabelCreation(silentMode);
// no notifying of views
//ggb3D - 2009-07-17
//removing :
//notifyViewsActive = !silentMode;
//(seems not to work with loading files)
//Application.printStacktrace(""+silentMode);
}
/**
* Returns whether silent mode is turned on.
* @see setSilentMode()
*/
public final boolean isSilentMode() {
return silentMode;
}
/**
* Sets whether unknown variables should be resolved as GeoDummyVariable objects.
*/
public final void setResolveUnkownVarsAsDummyGeos(boolean resolveUnkownVarsAsDummyGeos) {
this.resolveUnkownVarsAsDummyGeos = resolveUnkownVarsAsDummyGeos;
}
/**
* Returns whether unkown variables are resolved as GeoDummyVariable objects.
* @see setSilentMode()
*/
public final boolean isResolveUnkownVarsAsDummyGeos() {
return resolveUnkownVarsAsDummyGeos;
}
final public static String defaultLibraryJavaScript = "function ggbOnInit() {}";
String libraryJavaScript = defaultLibraryJavaScript;
public void setLibraryJavaScript(String str) {
Application.debug(str);
libraryJavaScript = str;
//libraryJavaScript = "function ggbOnInit() {ggbApplet.evalCommand('A=(1,2)');ggbApplet.registerObjectUpdateListener('A','listener');}function listener() {//java.lang.System.out.println('add listener called'); var x = ggbApplet.getXcoord('A');var y = ggbApplet.getYcoord('A');var len = Math.sqrt(x*x + y*y);if (len > 5) { x=x*5/len; y=y*5/len; }ggbApplet.unregisterObjectUpdateListener('A');ggbApplet.setCoords('A',x,y);ggbApplet.registerObjectUpdateListener('A','listener');}";
//libraryJavaScript = "function ggbOnInit() {ggbApplet.evalCommand('A=(1,2)');}";
}
//public String getLibraryJavaScriptXML() {
// return Util.encodeXML(libraryJavaScript);
//}
public String getLibraryJavaScript() {
return libraryJavaScript;
}
/** return all points of the current construction */
public TreeSet getPointSet(){
return getConstruction().getGeoSetLabelOrder(GeoElement.GEO_CLASS_POINT);
}
/**
* test kernel
*/
public static void mainx(String [] args) {
// create kernel with null application for testing
Kernel kernel = new Kernel(null);
Construction cons = kernel.getConstruction();
// create points A and B
GeoPoint A = new GeoPoint(cons, "A", 0, 1, 1);
GeoPoint B = new GeoPoint(cons, "B", 3, 4, 1);
// create line g through points A and B
GeoLine g = kernel.Line("g", A, B);
// print current objects
System.out.println(A);
System.out.println(B);
System.out.println(g);
// change B
B.setCoords(3, 2, 1);
B.updateCascade();
// print current objects
System.out.println("changed " +B);
System.out.println(g);
}
final public GeoNumeric convertIndexToNumber(String str) {
int i = 0;
char c;
while (i < str.length() && !Unicode.isSuperscriptDigit(str.charAt(i)))
i++;
//Application.debug(str.substring(i, str.length() - 1));
MyDouble md = new MyDouble(this, str.substring(i, str.length() - 1)); // strip off eg "sin" at start, "(" at end
GeoNumeric num = new GeoNumeric(getConstruction(), md.getDouble());
return num;
}
final public ExpressionNode handleTrigPower(String image, ExpressionNode en, int type) {
// sin^(-1)(x) -> ArcSin(x)
if (image.indexOf(Unicode.Superscript_Minus) > -1) {
//String check = ""+Unicode.Superscript_Minus + Unicode.Superscript_1 + '(';
if (image.substring(3, 6).equals(Unicode.superscriptMinusOneBracket)) {
switch (type) {
case ExpressionNode.SIN:
return new ExpressionNode(this, en, ExpressionNode.ARCSIN, null);
case ExpressionNode.COS:
return new ExpressionNode(this, en, ExpressionNode.ARCCOS, null);
case ExpressionNode.TAN:
return new ExpressionNode(this, en, ExpressionNode.ARCTAN, null);
default:
throw new Error("Inverse not supported for trig function"); // eg csc^-1(x)
}
}
else throw new Error("Bad index for trig function"); // eg sin^-2(x)
}
return new ExpressionNode(this, new ExpressionNode(this, en, type, null), ExpressionNode.POWER, convertIndexToNumber(image));
}
///////////////////////////////////////////
// CHANGING TYPE OF A GEO (mathieu)
///////////////////////////////////////////
/**
* @return possible alternatives for a given geo (e.g. number -> complex)
*/
public GeoElement[] getAlternatives(GeoElement geo){
return geo.getAlternatives();
}
}
| final public GeoElement If(String label,
GeoBoolean condition,
GeoElement geoIf, GeoElement geoElse) {
// check if geoIf and geoElse are of same type
/* if (geoElse == null ||
geoIf.isNumberValue() && geoElse.isNumberValue() ||
geoIf.getTypeString().equals(geoElse.getTypeString()))
{*/
AlgoIf algo = new AlgoIf(cons, label, condition, geoIf, geoElse);
return algo.getGeoElement();
/* }
else {
// incompatible types
Application.debug("if incompatible: " + geoIf + ", " + geoElse);
return null;
} */
}
/**
* If-then-else construct for functions.
* example: If[ x < 2, x^2, x + 2 ]
*/
final public GeoFunction If(String label,
GeoFunction boolFun,
GeoFunction ifFun, GeoFunction elseFun) {
AlgoIfFunction algo = new AlgoIfFunction(cons, label, boolFun, ifFun, elseFun);
return algo.getGeoFunction();
}
/**
* If-then-else construct for functions.
* example: If[ x < 2, x^2, x + 2 ]
*/
final public GeoNumeric CountIf(String label,
GeoFunction boolFun,
GeoList list) {
AlgoCountIf algo = new AlgoCountIf(cons, label, boolFun, list);
return algo.getResult();
}
/**
* Sequence command:
* Sequence[ <expression>, <number-var>, <from>, <to>, <step> ]
* @return array with GeoList object and its list items
*/
final public GeoElement [] Sequence(String label,
GeoElement expression, GeoNumeric localVar,
NumberValue from, NumberValue to, NumberValue step) {
AlgoSequence algo = new AlgoSequence(cons, label, expression, localVar, from, to, step);
return algo.getOutput();
}
/**
* Cartesian curve command:
* Curve[ <expression x-coord>, <expression x-coord>, <number-var>, <from>, <to> ]
*/
final public GeoCurveCartesian CurveCartesian(String label,
NumberValue xcoord, NumberValue ycoord,
GeoNumeric localVar, NumberValue from, NumberValue to)
{
AlgoCurveCartesian algo = new AlgoCurveCartesian(cons, label, new NumberValue[] {xcoord, ycoord} , localVar, from, to);
return (GeoCurveCartesian) algo.getCurve();
}
/**
* Converts a NumberValue object to an ExpressionNode object.
*/
public ExpressionNode convertNumberValueToExpressionNode(NumberValue nv) {
GeoElement geo = nv.toGeoElement();
AlgoElement algo = geo.getParentAlgorithm();
if (algo != null && algo instanceof AlgoDependentNumber) {
AlgoDependentNumber algoDep = (AlgoDependentNumber) algo;
return algoDep.getExpression().getCopy(this);
}
else {
return new ExpressionNode(this, geo);
}
}
/** Number dependent on arithmetic expression with variables,
* represented by a tree. e.g. t = 6z - 2
*/
final public GeoNumeric DependentNumber(
String label,
ExpressionNode root,
boolean isAngle) {
AlgoDependentNumber algo =
new AlgoDependentNumber(cons, label, root, isAngle);
GeoNumeric number = algo.getNumber();
return number;
}
/** Point dependent on arithmetic expression with variables,
* represented by a tree. e.g. P = (4t, 2s)
*/
final public GeoPoint DependentPoint(
String label,
ExpressionNode root, boolean complex) {
AlgoDependentPoint algo = new AlgoDependentPoint(cons, label, root, complex);
GeoPoint P = algo.getPoint();
return P;
}
/** Vector dependent on arithmetic expression with variables,
* represented by a tree. e.g. v = u + 3 w
*/
final public GeoVector DependentVector(
String label,
ExpressionNode root) {
AlgoDependentVector algo = new AlgoDependentVector(cons, label, root);
GeoVector v = algo.getVector();
return v;
}
/** Line dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. y = k x + d
*/
final public GeoLine DependentLine(String label, Equation equ) {
AlgoDependentLine algo = new AlgoDependentLine(cons, label, equ, false);
GeoLine line = algo.getLine();
return line;
}
/** Inequality dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. y < k x + d
*/
final public GeoLinearInequality DependentInequality(String label, Equation equ) {
AlgoDependentLine algo = new AlgoDependentLine(cons, label, equ, true);
GeoLine line = algo.getLine();
return (GeoLinearInequality)line;
}
/** Conic dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. y� = 2 p x
*/
final public GeoConic DependentConic(String label, Equation equ) {
AlgoDependentConic algo = new AlgoDependentConic(cons, label, equ);
GeoConic conic = algo.getConic();
return conic;
}
final public GeoImplicitPoly DependentImplicitPoly(String label, Equation equ) {
AlgoDependentImplicitPoly algo = new AlgoDependentImplicitPoly(cons, label, equ);
GeoImplicitPoly implicitPoly = algo.getImplicitPoly();
return implicitPoly;
}
/** Function dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. f(x) = a x� + b x�
*/
final public GeoFunction DependentFunction(
String label,
Function fun) {
AlgoDependentFunction algo = new AlgoDependentFunction(cons, label, fun);
GeoFunction f = algo.getFunction();
return f;
}
/** Multivariate Function depending on coefficients of arithmetic expressions with variables,
* e.g. f(x,y) = a x^2 + b y^2
*/
final public GeoFunctionNVar DependentFunctionNVar(
String label,
FunctionNVar fun) {
AlgoDependentFunctionNVar algo = new AlgoDependentFunctionNVar(cons, label, fun);
GeoFunctionNVar f = algo.getFunction();
return f;
}
/** Interval dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. x > a && x < b
*/
final public GeoFunction DependentInterval(
String label,
Function fun) {
AlgoDependentInterval algo = new AlgoDependentInterval(cons, label, fun);
GeoFunction f = algo.getFunction();
return f;
}
/** Text dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. text = "Radius: " + r
*/
final public GeoText DependentText(
String label,
ExpressionNode root) {
AlgoDependentText algo = new AlgoDependentText(cons, label, root);
GeoText t = algo.getGeoText();
return t;
}
/**
* Creates a dependent copy of origGeo with label
*/
final public GeoElement DependentGeoCopy(String label, ExpressionNode origGeoNode) {
AlgoDependentGeoCopy algo = new AlgoDependentGeoCopy(cons, label, origGeoNode);
return algo.getGeo();
}
/**
* Name of geo.
*/
final public GeoText Name(
String label,
GeoElement geo) {
AlgoName algo = new AlgoName(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* Object from name
*/
final public GeoElement Object(
String label,
GeoText text) {
AlgoObject algo = new AlgoObject(cons, label, text);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Spreadsheet Object from coords
*/
final public GeoElement Cell(
String label,
NumberValue a, NumberValue b) {
AlgoCell algo = new AlgoCell(cons, label, a, b);
GeoElement ret = algo.getResult();
return ret;
}
/**
* ColumnName[]
*/
final public GeoText ColumnName(
String label,
GeoElement geo) {
AlgoColumnName algo = new AlgoColumnName(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* LaTeX of geo.
*/
final public GeoText LaTeX(
String label,
GeoElement geo, GeoBoolean substituteVars) {
AlgoLaTeX algo = new AlgoLaTeX(cons, label, geo, substituteVars);
GeoText t = algo.getGeoText();
return t;
}
/**
* LaTeX of geo.
*/
final public GeoText LaTeX(
String label,
GeoElement geo) {
AlgoLaTeX algo = new AlgoLaTeX(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo) {
AlgoText algo = new AlgoText(cons, label, geo);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoBoolean substituteVars) {
AlgoText algo = new AlgoText(cons, label, geo, substituteVars);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoPoint p, GeoBoolean substituteVars) {
AlgoText algo = new AlgoText(cons, label, geo, p, substituteVars);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoPoint p, GeoBoolean substituteVars, GeoBoolean latex) {
AlgoText algo = new AlgoText(cons, label, geo, p, substituteVars, latex);
GeoText t = algo.getGeoText();
return t;
}
/**
* Text of geo.
*/
final public GeoText Text(
String label,
GeoElement geo, GeoPoint p) {
AlgoText algo = new AlgoText(cons, label, geo, p);
GeoText t = algo.getGeoText();
return t;
}
/**
* Row of geo.
*/
final public GeoNumeric Row(
String label,
GeoElement geo) {
AlgoRow algo = new AlgoRow(cons, label, geo);
GeoNumeric ret = algo.getResult();
return ret;
}
/**
* Column of geo.
*/
final public GeoNumeric Column(
String label,
GeoElement geo) {
AlgoColumn algo = new AlgoColumn(cons, label, geo);
GeoNumeric ret = algo.getResult();
return ret;
}
/**
* ToNumber
*/
final public GeoNumeric LetterToUnicode(
String label,
GeoText geo) {
AlgoLetterToUnicode algo = new AlgoLetterToUnicode(cons, label, geo);
GeoNumeric ret = algo.getResult();
return ret;
}
/**
* ToNumbers
*/
final public GeoList TextToUnicode(
String label,
GeoText geo) {
AlgoTextToUnicode algo = new AlgoTextToUnicode(cons, label, geo);
GeoList ret = algo.getResult();
return ret;
}
/**
* ToText(number)
*/
final public GeoText UnicodeToLetter(String label, NumberValue a) {
AlgoUnicodeToLetter algo = new AlgoUnicodeToLetter(cons, label, a);
GeoText text = algo.getResult();
return text;
}
/**
* ToText(list)
*/
final public GeoText UnicodeToText(
String label,
GeoList geo) {
AlgoUnicodeToText algo = new AlgoUnicodeToText(cons, label, geo);
GeoText ret = algo.getResult();
return ret;
}
/**
* returns the current x-axis step
* Michael Borcherds
*/
final public GeoNumeric AxisStepX(
String label) {
AlgoAxisStepX algo = new AlgoAxisStepX(cons, label);
GeoNumeric t = algo.getResult();
return t;
}
/**
* returns the current y-axis step
* Michael Borcherds
*/
final public GeoNumeric AxisStepY(
String label) {
AlgoAxisStepY algo = new AlgoAxisStepY(cons, label);
GeoNumeric t = algo.getResult();
return t;
}
/**
* returns the current construction protocol step
* Michael Borcherds 2008-05-15
*/
final public GeoNumeric ConstructionStep(
String label) {
AlgoConstructionStep algo = new AlgoConstructionStep(cons, label);
GeoNumeric t = algo.getResult();
return t;
}
/**
* returns current construction protocol step for an object
* Michael Borcherds 2008-05-15
*/
final public GeoNumeric ConstructionStep(
String label, GeoElement geo) {
AlgoStepObject algo = new AlgoStepObject(cons, label, geo);
GeoNumeric t = algo.getResult();
return t;
}
/**
* Text dependent on coefficients of arithmetic expressions with variables,
* represented by trees. e.g. c = a & b
*/
final public GeoBoolean DependentBoolean(
String label,
ExpressionNode root) {
AlgoDependentBoolean algo = new AlgoDependentBoolean(cons, label, root);
return algo.getGeoBoolean();
}
/** Point on path with cartesian coordinates (x,y) */
final public GeoPoint Point(String label, Path path, double x, double y, boolean addToConstruction) {
boolean oldMacroMode = false;
if (!addToConstruction) {
oldMacroMode = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
}
AlgoPointOnPath algo = new AlgoPointOnPath(cons, label, path, x, y);
GeoPoint p = algo.getP();
if (!addToConstruction) {
cons.setSuppressLabelCreation(oldMacroMode);
}
return p;
}
/** Point anywhere on path with */
final public GeoPoint Point(String label, Path path) {
// try (0,0)
AlgoPointOnPath algo = new AlgoPointOnPath(cons, label, path, 0, 0);
GeoPoint p = algo.getP();
// try (1,0)
if (!p.isDefined()) {
p.setCoords(1,0,1);
algo.update();
}
// try (random(),0)
if (!p.isDefined()) {
p.setCoords(Math.random(),0,1);
algo.update();
}
return p;
}
/** Point in region with cartesian coordinates (x,y) */
final public GeoPoint PointIn(String label, Region region, double x, double y) {
AlgoPointInRegion algo = new AlgoPointInRegion(cons, label, region, x, y);
Application.debug("PointIn - \n x="+x+"\n y="+y);
GeoPoint p = algo.getP();
return p;
}
/** Point in region */
final public GeoPoint PointIn(String label, Region region) {
return PointIn(label,region,0,0); //TODO do as for paths
}
/** Point P + v */
final public GeoPoint Point(String label, GeoPoint P, GeoVector v) {
AlgoPointVector algo = new AlgoPointVector(cons, label, P, v);
GeoPoint p = algo.getQ();
return p;
}
/**
* Returns the projected point of P on line g.
*/
final public GeoPoint ProjectedPoint(GeoPoint P, GeoLine g) {
boolean oldMacroMode = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
GeoLine perp = OrthogonalLine(null, P, g);
GeoPoint S = IntersectLines(null, perp, g);
cons.setSuppressLabelCreation(oldMacroMode);
return S;
}
/**
* Midpoint M = (P + Q)/2
*/
final public GeoPoint Midpoint(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoMidpoint algo = new AlgoMidpoint(cons, label, P, Q);
GeoPoint M = algo.getPoint();
return M;
}
/**
* Creates Midpoint M = (P + Q)/2 without label (for use as e.g. start point)
*/
final public GeoPoint Midpoint(
GeoPoint P,
GeoPoint Q) {
boolean oldValue = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
GeoPoint midPoint = Midpoint(null, P, Q);
cons.setSuppressLabelCreation(oldValue);
return midPoint;
}
/**
* Midpoint of segment
*/
final public GeoPoint Midpoint(
String label,
GeoSegment s) {
AlgoMidpointSegment algo = new AlgoMidpointSegment(cons, label, s);
GeoPoint M = algo.getPoint();
return M;
}
/**
* LineSegment named label from Point P to Point Q
*/
final public GeoSegment Segment(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoJoinPointsSegment algo = new AlgoJoinPointsSegment(cons, label, P, Q);
GeoSegment s = algo.getSegment();
return s;
}
/**
* Line named label through Points P and Q
*/
final public GeoLine Line(String label, GeoPoint P, GeoPoint Q) {
AlgoJoinPoints algo = new AlgoJoinPoints(cons, label, P, Q);
GeoLine g = algo.getLine();
return g;
}
/**
* Line named label through Point P with direction of vector v
*/
final public GeoLine Line(String label, GeoPoint P, GeoVector v) {
AlgoLinePointVector algo = new AlgoLinePointVector(cons, label, P, v);
GeoLine g = algo.getLine();
return g;
}
/**
* Ray named label through Points P and Q
*/
final public GeoRay Ray(String label, GeoPoint P, GeoPoint Q) {
AlgoJoinPointsRay algo = new AlgoJoinPointsRay(cons, label, P, Q);
return algo.getRay();
}
/**
* Ray named label through Point P with direction of vector v
*/
final public GeoRay Ray(String label, GeoPoint P, GeoVector v) {
AlgoRayPointVector algo = new AlgoRayPointVector(cons, label, P, v);
return algo.getRay();
}
/**
* Line named label through Point P parallel to Line l
*/
final public GeoLine Line(String label, GeoPoint P, GeoLine l) {
AlgoLinePointLine algo = new AlgoLinePointLine(cons, label, P, l);
GeoLine g = algo.getLine();
return g;
}
/**
* Line named label through Point P orthogonal to vector v
*/
final public GeoLine OrthogonalLine(
String label,
GeoPoint P,
GeoVector v) {
AlgoOrthoLinePointVector algo =
new AlgoOrthoLinePointVector(cons, label, P, v);
GeoLine g = algo.getLine();
return g;
}
/**
* Line named label through Point P orthogonal to line l
*/
final public GeoLine OrthogonalLine(
String label,
GeoPoint P,
GeoLine l) {
AlgoOrthoLinePointLine algo = new AlgoOrthoLinePointLine(cons, label, P, l);
GeoLine g = algo.getLine();
return g;
}
/**
* Line bisector of points A, B
*/
final public GeoLine LineBisector(
String label,
GeoPoint A,
GeoPoint B) {
AlgoLineBisector algo = new AlgoLineBisector(cons, label, A, B);
GeoLine g = algo.getLine();
return g;
}
/**
* Line bisector of segment s
*/
final public GeoLine LineBisector(String label, GeoSegment s) {
AlgoLineBisectorSegment algo = new AlgoLineBisectorSegment(cons, label, s);
GeoLine g = algo.getLine();
return g;
}
/**
* Angular bisector of points A, B, C
*/
final public GeoLine AngularBisector(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoAngularBisectorPoints algo =
new AlgoAngularBisectorPoints(cons, label, A, B, C);
GeoLine g = algo.getLine();
return g;
}
/**
* Angular bisectors of lines g, h
*/
final public GeoLine[] AngularBisector(
String[] labels,
GeoLine g,
GeoLine h) {
AlgoAngularBisectorLines algo =
new AlgoAngularBisectorLines(cons, labels, g, h);
GeoLine[] lines = algo.getLines();
return lines;
}
/**
* Vector named label from Point P to Q
*/
final public GeoVector Vector(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoVector algo = new AlgoVector(cons, label, P, Q);
GeoVector v = (GeoVector) algo.getVector();
v.setEuclidianVisible(true);
v.update();
notifyUpdate(v);
return v;
}
/**
* Vector (0,0) to P
*/
final public GeoVector Vector(String label, GeoPoint P) {
AlgoVectorPoint algo = new AlgoVectorPoint(cons, label, P);
GeoVector v = algo.getVector();
v.setEuclidianVisible(true);
v.update();
notifyUpdate(v);
return v;
}
/**
* Direction vector of line g
*/
final public GeoVector Direction(String label, GeoLine g) {
AlgoDirection algo = new AlgoDirection(cons, label, g);
GeoVector v = algo.getVector();
return v;
}
/**
* Slope of line g
*/
final public GeoNumeric Slope(String label, GeoLine g) {
AlgoSlope algo = new AlgoSlope(cons, label, g);
GeoNumeric slope = algo.getSlope();
return slope;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
NumberValue a, NumberValue b, GeoList list) {
AlgoBarChart algo = new AlgoBarChart(cons, label, a, b, list);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
GeoList list1, GeoList list2) {
AlgoBarChart algo = new AlgoBarChart(cons, label, list1, list2);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
GeoList list1, GeoList list2, NumberValue width) {
AlgoBarChart algo = new AlgoBarChart(cons, label, list1, list2, width);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
GeoList list, GeoNumeric a) {
AlgoBarChart algo = new AlgoBarChart(cons, label, list, a);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BarChart
*/
final public GeoNumeric BarChart(String label,
NumberValue a, NumberValue b, GeoElement expression, GeoNumeric localVar,
NumberValue from, NumberValue to, NumberValue step) {
AlgoSequence seq = new AlgoSequence(cons, expression, localVar, from, to, step);
cons.removeFromConstructionList(seq);
AlgoBarChart algo = new AlgoBarChart(cons, label, a, b, (GeoList)seq.getOutput()[0]);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BoxPlot
*/
final public GeoNumeric BoxPlot(String label,
NumberValue a, NumberValue b, GeoList rawData) {
/*
AlgoListMin min = new AlgoListMin(cons,rawData);
cons.removeFromConstructionList(min);
AlgoQ1 Q1 = new AlgoQ1(cons,rawData);
cons.removeFromConstructionList(Q1);
AlgoMedian median = new AlgoMedian(cons,rawData);
cons.removeFromConstructionList(median);
AlgoQ3 Q3 = new AlgoQ3(cons,rawData);
cons.removeFromConstructionList(Q3);
AlgoListMax max = new AlgoListMax(cons,rawData);
cons.removeFromConstructionList(max);
AlgoBoxPlot algo = new AlgoBoxPlot(cons, label, a, b, (NumberValue)(min.getMin()),
(NumberValue)(Q1.getQ1()), (NumberValue)(median.getMedian()), (NumberValue)(Q3.getQ3()), (NumberValue)(max.getMax()));
*/
AlgoBoxPlot algo = new AlgoBoxPlot(cons, label, a, b, rawData);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* BoxPlot
*/
final public GeoNumeric BoxPlot(String label,
NumberValue a, NumberValue b, NumberValue min, NumberValue Q1,
NumberValue median, NumberValue Q3, NumberValue max) {
AlgoBoxPlot algo = new AlgoBoxPlot(cons, label, a, b, min, Q1, median, Q3, max);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* Histogram
*/
final public GeoNumeric Histogram(String label,
GeoList list1, GeoList list2) {
AlgoHistogram algo = new AlgoHistogram(cons, label, list1, list2);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* DotPlot
* G.Sturr 2010-8-10
*/
final public GeoList DotPlot(String label, GeoList list) {
AlgoDotPlot algo = new AlgoDotPlot(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* UpperSum of function f
*/
final public GeoNumeric UpperSum(String label, GeoFunction f,
NumberValue a, NumberValue b, NumberValue n) {
AlgoSumUpper algo = new AlgoSumUpper(cons, label, f, a, b, n);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* TrapezoidalSum of function f
*/
final public GeoNumeric TrapezoidalSum(String label, GeoFunction f,
NumberValue a, NumberValue b, NumberValue n) {
AlgoSumTrapezoidal algo = new AlgoSumTrapezoidal(cons, label, f, a, b, n);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* LowerSum of function f
*/
final public GeoNumeric LowerSum(String label, GeoFunction f,
NumberValue a, NumberValue b, NumberValue n) {
AlgoSumLower algo = new AlgoSumLower(cons, label, f, a, b, n);
GeoNumeric sum = algo.getSum();
return sum;
}
/**
* SumSquaredErrors[<List of Points>,<Function>]
* Hans-Petter Ulven
* 2010-02-22
*/
final public GeoNumeric SumSquaredErrors(String label, GeoList list, GeoFunctionable function) {
AlgoSumSquaredErrors algo = new AlgoSumSquaredErrors(cons, label, list, function);
GeoNumeric sse=algo.getsse();
return sse;
}
/**
* RSquare[<List of Points>,<Function>]
*/
final public GeoNumeric RSquare(String label, GeoList list, GeoFunctionable function) {
AlgoRSquare algo = new AlgoRSquare(cons, label, list, function);
GeoNumeric r2=algo.getRSquare();
return r2;
}
/**
* unit vector of line g
*/
final public GeoVector UnitVector(String label, GeoLine g) {
AlgoUnitVectorLine algo = new AlgoUnitVectorLine(cons, label, g);
GeoVector v = algo.getVector();
return v;
}
/**
* unit vector of vector v
*/
final public GeoVector UnitVector(String label, GeoVector v) {
AlgoUnitVectorVector algo = new AlgoUnitVectorVector(cons, label, v);
GeoVector u = algo.getVector();
return u;
}
/**
* orthogonal vector of line g
*/
final public GeoVector OrthogonalVector(String label, GeoLine g) {
AlgoOrthoVectorLine algo = new AlgoOrthoVectorLine(cons, label, g);
GeoVector n = algo.getVector();
return n;
}
/**
* orthogonal vector of vector v
*/
final public GeoVector OrthogonalVector(String label, GeoVector v) {
AlgoOrthoVectorVector algo = new AlgoOrthoVectorVector(cons, label, v);
GeoVector n = algo.getVector();
return n;
}
/**
* unit orthogonal vector of line g
*/
final public GeoVector UnitOrthogonalVector(
String label,
GeoLine g) {
AlgoUnitOrthoVectorLine algo = new AlgoUnitOrthoVectorLine(cons, label, g);
GeoVector n = algo.getVector();
return n;
}
/**
* unit orthogonal vector of vector v
*/
final public GeoVector UnitOrthogonalVector(
String label,
GeoVector v) {
AlgoUnitOrthoVectorVector algo =
new AlgoUnitOrthoVectorVector(cons, label, v);
GeoVector n = algo.getVector();
return n;
}
/**
* Length named label of vector v
*/
final public GeoNumeric Length(String label, GeoVec3D v) {
AlgoLengthVector algo = new AlgoLengthVector(cons, label, v);
GeoNumeric num = algo.getLength();
return num;
}
/**
* Distance named label between points P and Q
*/
final public GeoNumeric Distance(
String label,
GeoPoint P,
GeoPoint Q) {
AlgoDistancePoints algo = new AlgoDistancePoints(cons, label, P, Q);
GeoNumeric num = algo.getDistance();
return num;
}
/**
* Distance named label between point P and line g
*/
final public GeoNumeric Distance(
String label,
GeoPoint P,
GeoLine g) {
AlgoDistancePointLine algo = new AlgoDistancePointLine(cons, label, P, g);
GeoNumeric num = algo.getDistance();
return num;
}
/**
* Distance named label between line g and line h
*/
final public GeoNumeric Distance(
String label,
GeoLine g,
GeoLine h) {
AlgoDistanceLineLine algo = new AlgoDistanceLineLine(cons, label, g, h);
GeoNumeric num = algo.getDistance();
return num;
}
/**
* Area named label of P[0], ..., P[n]
*/
final public GeoNumeric Area(String label, GeoPoint [] P) {
AlgoAreaPoints algo = new AlgoAreaPoints(cons, label, P);
GeoNumeric num = algo.getArea();
return num;
}
/**
* Area named label of conic
*/
final public GeoNumeric Area(String label, GeoConic c) {
AlgoAreaConic algo = new AlgoAreaConic(cons, label, c);
GeoNumeric num = algo.getArea();
return num;
}
/**
* Mod[a, b]
*/
final public GeoNumeric Mod(String label, NumberValue a, NumberValue b) {
AlgoMod algo = new AlgoMod(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Div[a, b]
*/
final public GeoNumeric Div(String label, NumberValue a, NumberValue b) {
AlgoDiv algo = new AlgoDiv(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Mod[a, b] Polynomial remainder
*/
final public GeoFunction Mod(String label, GeoFunction a, GeoFunction b) {
AlgoPolynomialMod algo = new AlgoPolynomialMod(cons, label, a, b);
GeoFunction f = algo.getResult();
return f;
}
/**
* Div[a, b] Polynomial Division
*/
final public GeoFunction Div(String label, GeoFunction a, GeoFunction b) {
AlgoPolynomialDiv algo = new AlgoPolynomialDiv(cons, label, a, b);
GeoFunction f = algo.getResult();
return f;
}
/**
* Min[a, b]
*/
final public GeoNumeric Min(String label, NumberValue a, NumberValue b) {
AlgoMin algo = new AlgoMin(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Min[list]
*/
final public GeoNumeric Min(String label, GeoList list) {
AlgoListMin algo = new AlgoListMin(cons, label, list);
GeoNumeric num = algo.getMin();
return num;
}
/**
* Max[a, b]
*/
final public GeoNumeric Max(String label, NumberValue a, NumberValue b) {
AlgoMax algo = new AlgoMax(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Max[list]
*/
final public GeoNumeric Max(String label, GeoList list) {
AlgoListMax algo = new AlgoListMax(cons, label, list);
GeoNumeric num = algo.getMax();
return num;
}
/**
* LCM[a, b]
* Michael Borcherds
*/
final public GeoNumeric LCM(String label, NumberValue a, NumberValue b) {
AlgoLCM algo = new AlgoLCM(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* LCM[list]
* Michael Borcherds
*/
final public GeoNumeric LCM(String label, GeoList list) {
AlgoListLCM algo = new AlgoListLCM(cons, label, list);
GeoNumeric num = algo.getLCM();
return num;
}
/**
* GCD[a, b]
* Michael Borcherds
*/
final public GeoNumeric GCD(String label, NumberValue a, NumberValue b) {
AlgoGCD algo = new AlgoGCD(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* GCD[list]
* Michael Borcherds
*/
final public GeoNumeric GCD(String label, GeoList list) {
AlgoListGCD algo = new AlgoListGCD(cons, label, list);
GeoNumeric num = algo.getGCD();
return num;
}
/**
* SigmaXY[list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXY(String label, GeoList list) {
AlgoListSigmaXY algo = new AlgoListSigmaXY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaYY[list]
* Michael Borcherds
*/
final public GeoNumeric SigmaYY(String label, GeoList list) {
AlgoListSigmaYY algo = new AlgoListSigmaYY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Covariance[list]
* Michael Borcherds
*/
final public GeoNumeric Covariance(String label, GeoList list) {
AlgoListCovariance algo = new AlgoListCovariance(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SXX[list]
* Michael Borcherds
*/
final public GeoNumeric SXX(String label, GeoList list) {
GeoNumeric num;
GeoElement geo = list.get(0);
if (geo.isNumberValue())
{ // list of numbers
AlgoSXX algo = new AlgoSXX(cons, label, list);
num = algo.getResult();
}
else
{ // (probably) list of points
AlgoListSXX algo = new AlgoListSXX(cons, label, list);
num = algo.getResult();
}
return num;
}
/**
* SXY[list]
* Michael Borcherds
*/
final public GeoNumeric SXY(String label, GeoList list) {
AlgoListSXY algo = new AlgoListSXY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SYY[list]
* Michael Borcherds
*/
final public GeoNumeric SYY(String label, GeoList list) {
AlgoListSYY algo = new AlgoListSYY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* MeanX[list]
* Michael Borcherds
*/
final public GeoNumeric MeanX(String label, GeoList list) {
AlgoListMeanX algo = new AlgoListMeanX(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* MeanY[list]
* Michael Borcherds
*/
final public GeoNumeric MeanY(String label, GeoList list) {
AlgoListMeanY algo = new AlgoListMeanY(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* PMCC[list]
* Michael Borcherds
*/
final public GeoNumeric PMCC(String label, GeoList list) {
AlgoListPMCC algo = new AlgoListPMCC(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaXY[list,list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXY(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSigmaXY algo = new AlgoDoubleListSigmaXY(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaXX[list,list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXX(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSigmaXX algo = new AlgoDoubleListSigmaXX(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaYY[list,list]
* Michael Borcherds
*/
final public GeoNumeric SigmaYY(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSigmaYY algo = new AlgoDoubleListSigmaYY(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Covariance[list,list]
* Michael Borcherds
*/
final public GeoNumeric Covariance(String label, GeoList listX, GeoList listY) {
AlgoDoubleListCovariance algo = new AlgoDoubleListCovariance(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SXX[list,list]
* Michael Borcherds
*/
final public GeoNumeric SXX(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSXX algo = new AlgoDoubleListSXX(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SXY[list,list]
* Michael Borcherds
*/
final public GeoNumeric SXY(String label, GeoList listX, GeoList listY) {
AlgoDoubleListSXY algo = new AlgoDoubleListSXY(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* PMCC[list,list]
* Michael Borcherds
*/
final public GeoNumeric PMCC(String label, GeoList listX, GeoList listY) {
AlgoDoubleListPMCC algo = new AlgoDoubleListPMCC(cons, label, listX, listY);
GeoNumeric num = algo.getResult();
return num;
}
/**
* FitLineY[list of coords]
* Michael Borcherds
*/
final public GeoLine FitLineY(String label, GeoList list) {
AlgoFitLineY algo = new AlgoFitLineY(cons, label, list);
GeoLine line = algo.getFitLineY();
return line;
}
/**
* FitLineX[list of coords]
* Michael Borcherds
*/
final public GeoLine FitLineX(String label, GeoList list) {
AlgoFitLineX algo = new AlgoFitLineX(cons, label, list);
GeoLine line = algo.getFitLineX();
return line;
}
final public GeoLocus Voronoi(String label, GeoList list) {
AlgoVoronoi algo = new AlgoVoronoi(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus Hull(String label, GeoList list, GeoNumeric percent) {
AlgoHull algo = new AlgoHull(cons, label, list, percent);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus TravelingSalesman(String label, GeoList list) {
AlgoTravelingSalesman algo = new AlgoTravelingSalesman(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus ConvexHull(String label, GeoList list) {
AlgoConvexHull algo = new AlgoConvexHull(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus MinimumSpanningTree(String label, GeoList list) {
AlgoMinimumSpanningTree algo = new AlgoMinimumSpanningTree(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
final public GeoLocus DelauneyTriangulation(String label, GeoList list) {
AlgoDelauneyTriangulation algo = new AlgoDelauneyTriangulation(cons, label, list);
GeoLocus ret = algo.getResult();
return ret;
}
/**
* FitPoly[list of coords,degree]
* Hans-Petter Ulven
*/
final public GeoFunction FitPoly(String label, GeoList list, NumberValue degree) {
AlgoFitPoly algo = new AlgoFitPoly(cons, label, list, degree);
GeoFunction function = algo.getFitPoly();
return function;
}
/**
* FitExp[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitExp(String label, GeoList list) {
AlgoFitExp algo = new AlgoFitExp(cons, label, list);
GeoFunction function = algo.getFitExp();
return function;
}
/**
* FitLog[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitLog(String label, GeoList list) {
AlgoFitLog algo = new AlgoFitLog(cons, label, list);
GeoFunction function = algo.getFitLog();
return function;
}
/**
* FitPow[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitPow(String label, GeoList list) {
AlgoFitPow algo = new AlgoFitPow(cons, label, list);
GeoFunction function = algo.getFitPow();
return function;
}
/**
* FitSin[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitSin(String label, GeoList list) {
AlgoFitSin algo = new AlgoFitSin(cons, label, list);
GeoFunction function = algo.getFitSin();
return function;
}
/**
* FitLogistic[list of coords]
* Hans-Petter Ulven
*/
final public GeoFunction FitLogistic(String label, GeoList list) {
AlgoFitLogistic algo = new AlgoFitLogistic(cons, label, list);
GeoFunction function = algo.getFitLogistic();
return function;
}
/**
* Fit[list of points,list of functions]
* Hans-Petter Ulven
*/
final public GeoFunction Fit(String label, GeoList ptslist,GeoList funclist) {
AlgoFit algo = new AlgoFit(cons, label, ptslist,funclist);
GeoFunction function = algo.getFit();
return function;
}
/**
* 'FitGrowth[<List of Points>]
* Hans-Petter Ulven
*/
final public GeoFunction FitGrowth(String label, GeoList list) {
AlgoFitGrowth algo = new AlgoFitGrowth(cons, label, list);
GeoFunction function=algo.getFitGrowth();
return function;
}
/**
* Binomial[n,r]
* Michael Borcherds
*/
final public GeoNumeric Binomial(String label, NumberValue a, NumberValue b) {
AlgoBinomial algo = new AlgoBinomial(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomNormal[mean,variance]
* Michael Borcherds
*/
final public GeoNumeric RandomNormal(String label, NumberValue a, NumberValue b) {
AlgoRandomNormal algo = new AlgoRandomNormal(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Random[max,min]
* Michael Borcherds
*/
final public GeoNumeric Random(String label, NumberValue a, NumberValue b) {
AlgoRandom algo = new AlgoRandom(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomUniform[max,min]
* Michael Borcherds
*/
final public GeoNumeric RandomUniform(String label, NumberValue a, NumberValue b) {
AlgoRandomUniform algo = new AlgoRandomUniform(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomBinomial[n,p]
* Michael Borcherds
*/
final public GeoNumeric RandomBinomial(String label, NumberValue a, NumberValue b) {
AlgoRandomBinomial algo = new AlgoRandomBinomial(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
/**
* RandomPoisson[lambda]
* Michael Borcherds
*/
final public GeoNumeric RandomPoisson(String label, NumberValue a) {
AlgoRandomPoisson algo = new AlgoRandomPoisson(cons, label, a);
GeoNumeric num = algo.getResult();
return num;
}
/**
* InverseNormal[mean,variance,x]
* Michael Borcherds
*/
final public GeoNumeric InverseNormal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseNormal algo = new AlgoInverseNormal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Normal[mean,variance,x]
* Michael Borcherds
*/
final public GeoNumeric Normal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoNormal algo = new AlgoNormal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
/**
* TDistribution[degrees of freedom,x]
* Michael Borcherds
*/
final public GeoNumeric TDistribution(String label, NumberValue a, NumberValue b) {
AlgoTDistribution algo = new AlgoTDistribution(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseTDistribution(String label, NumberValue a, NumberValue b) {
AlgoInverseTDistribution algo = new AlgoInverseTDistribution(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric ChiSquared(String label, NumberValue a, NumberValue b) {
AlgoChiSquared algo = new AlgoChiSquared(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseChiSquared(String label, NumberValue a, NumberValue b) {
AlgoInverseChiSquared algo = new AlgoInverseChiSquared(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Exponential(String label, NumberValue a, NumberValue b) {
AlgoExponential algo = new AlgoExponential(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseExponential(String label, NumberValue a, NumberValue b) {
AlgoInverseExponential algo = new AlgoInverseExponential(cons, label, a, b);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric FDistribution(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoFDistribution algo = new AlgoFDistribution(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseFDistribution(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseFDistribution algo = new AlgoInverseFDistribution(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Gamma(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoGamma algo = new AlgoGamma(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseGamma(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseGamma algo = new AlgoInverseGamma(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Cauchy(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoCauchy algo = new AlgoCauchy(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseCauchy(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseCauchy algo = new AlgoInverseCauchy(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Weibull(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoWeibull algo = new AlgoWeibull(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseWeibull(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseWeibull algo = new AlgoInverseWeibull(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Zipf(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoZipf algo = new AlgoZipf(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseZipf(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInverseZipf algo = new AlgoInverseZipf(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric Pascal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoPascal algo = new AlgoPascal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InversePascal(String label, NumberValue a, NumberValue b, NumberValue c) {
AlgoInversePascal algo = new AlgoInversePascal(cons, label, a, b, c);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric HyperGeometric(String label, NumberValue a, NumberValue b, NumberValue c, NumberValue d) {
AlgoHyperGeometric algo = new AlgoHyperGeometric(cons, label, a, b, c, d);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoNumeric InverseHyperGeometric(String label, NumberValue a, NumberValue b, NumberValue c, NumberValue d) {
AlgoInverseHyperGeometric algo = new AlgoInverseHyperGeometric(cons, label, a, b, c, d);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Sort[list]
* Michael Borcherds
*/
final public GeoList Sort(String label, GeoList list) {
AlgoSort algo = new AlgoSort(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Rank[list]
* Michael Borcherds
*/
final public GeoList Rank(String label, GeoList list) {
AlgoRank algo = new AlgoRank(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Shuffle[list]
* Michael Borcherds
*/
final public GeoList Shuffle(String label, GeoList list) {
AlgoShuffle algo = new AlgoShuffle(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* PointList[list]
* Michael Borcherds
*/
final public GeoList PointList(String label, GeoList list) {
AlgoPointList algo = new AlgoPointList(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* RootList[list]
* Michael Borcherds
*/
final public GeoList RootList(String label, GeoList list) {
AlgoRootList algo = new AlgoRootList(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* First[list,n]
* Michael Borcherds
*/
final public GeoList First(String label, GeoList list, GeoNumeric n) {
AlgoFirst algo = new AlgoFirst(cons, label, list, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* First[string,n]
* Michael Borcherds
*/
final public GeoText First(String label, GeoText list, GeoNumeric n) {
AlgoFirstString algo = new AlgoFirstString(cons, label, list, n);
GeoText list2 = algo.getResult();
return list2;
}
/**
* Last[string,n]
* Michael Borcherds
*/
final public GeoText Last(String label, GeoText list, GeoNumeric n) {
AlgoLastString algo = new AlgoLastString(cons, label, list, n);
GeoText list2 = algo.getResult();
return list2;
}
/**
* First[string,n]
* Michael Borcherds
*/
final public GeoText Take(String label, GeoText list, GeoNumeric m, GeoNumeric n) {
AlgoTakeString algo = new AlgoTakeString(cons, label, list, m, n);
GeoText list2 = algo.getResult();
return list2;
}
/**
* Last[list,n]
* Michael Borcherds
*/
final public GeoList Last(String label, GeoList list, GeoNumeric n) {
AlgoLast algo = new AlgoLast(cons, label, list, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Take[list,m,n]
* Michael Borcherds
*/
final public GeoList Take(String label, GeoList list, GeoNumeric m, GeoNumeric n) {
AlgoTake algo = new AlgoTake(cons, label, list, m, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Append[list,object]
* Michael Borcherds
*/
final public GeoList Append(String label, GeoList list, GeoElement geo) {
AlgoAppend algo = new AlgoAppend(cons, label, list, geo);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Append[object,list]
* Michael Borcherds
*/
final public GeoList Append(String label, GeoElement geo, GeoList list) {
AlgoAppend algo = new AlgoAppend(cons, label, geo, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Join[list,list]
* Michael Borcherds
*/
final public GeoList Join(String label, GeoList list) {
AlgoJoin algo = new AlgoJoin(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Union[list,list]
* Michael Borcherds
*/
final public GeoList Union(String label, GeoList list, GeoList list1) {
AlgoUnion algo = new AlgoUnion(cons, label, list, list1);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Intersection[list,list]
* Michael Borcherds
*/
final public GeoList Intersection(String label, GeoList list, GeoList list1) {
AlgoIntersection algo = new AlgoIntersection(cons, label, list, list1);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Insert[list,list,n]
* Michael Borcherds
*/
final public GeoList Insert(String label, GeoElement geo, GeoList list, GeoNumeric n) {
AlgoInsert algo = new AlgoInsert(cons, label, geo, list, n);
GeoList list2 = algo.getResult();
return list2;
}
/**
* RemoveUndefined[list]
* Michael Borcherds
*/
final public GeoList RemoveUndefined(String label, GeoList list) {
AlgoRemoveUndefined algo = new AlgoRemoveUndefined(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Keep[boolean condition, list]
* Michael Borcherds
*/
final public GeoList KeepIf(String label, GeoFunction boolFun, GeoList list) {
AlgoKeepIf algo = new AlgoKeepIf(cons, label, boolFun, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Defined[object]
* Michael Borcherds
*/
final public GeoBoolean Defined(String label, GeoElement geo) {
AlgoDefined algo = new AlgoDefined(cons, label, geo);
GeoBoolean result = algo.getResult();
return result;
}
/**
* IsInteger[number]
* Michael Borcherds
*/
final public GeoBoolean IsInteger(String label, GeoNumeric geo) {
AlgoIsInteger algo = new AlgoIsInteger(cons, label, geo);
GeoBoolean result = algo.getResult();
return result;
}
/**
* Mode[list]
* Michael Borcherds
*/
final public GeoList Mode(String label, GeoList list) {
AlgoMode algo = new AlgoMode(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Invert[matrix]
* Michael Borcherds
*/
final public GeoList Invert(String label, GeoList list) {
AlgoInvert algo = new AlgoInvert(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Transpose[matrix]
* Michael Borcherds
*/
final public GeoList Transpose(String label, GeoList list) {
AlgoTranspose algo = new AlgoTranspose(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Transpose[matrix]
* Michael Borcherds
*/
final public GeoList ReducedRowEchelonForm(String label, GeoList list) {
AlgoReducedRowEchelonForm algo = new AlgoReducedRowEchelonForm(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Transpose[matrix]
* Michael Borcherds
*/
final public GeoNumeric Determinant(String label, GeoList list) {
AlgoDeterminant algo = new AlgoDeterminant(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Reverse[list]
* Michael Borcherds
*/
final public GeoList Reverse(String label, GeoList list) {
AlgoReverse algo = new AlgoReverse(cons, label, list);
GeoList list2 = algo.getResult();
return list2;
}
/**
* Product[list]
* Michael Borcherds
*/
final public GeoNumeric Product(String label, GeoList list) {
AlgoProduct algo = new AlgoProduct(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* Sum[list]
* Michael Borcherds
*/
final public GeoElement Sum(String label, GeoList list) {
AlgoSum algo = new AlgoSum(cons, label, list);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list,n]
* Michael Borcherds
*/
final public GeoElement Sum(String label, GeoList list, GeoNumeric n) {
AlgoSum algo = new AlgoSum(cons, label, list, n);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of functions]
* Michael Borcherds
*/
final public GeoElement SumFunctions(String label, GeoList list) {
AlgoSumFunctions algo = new AlgoSumFunctions(cons, label, list);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of functions,n]
* Michael Borcherds
*/
final public GeoElement SumFunctions(String label, GeoList list, GeoNumeric num) {
AlgoSumFunctions algo = new AlgoSumFunctions(cons, label, list, num);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of points]
* Michael Borcherds
*/
final public GeoElement SumPoints(String label, GeoList list) {
AlgoSumPoints algo = new AlgoSumPoints(cons, label, list);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of points,n]
* Michael Borcherds
*/
final public GeoElement SumPoints(String label, GeoList list, GeoNumeric num) {
AlgoSumPoints algo = new AlgoSumPoints(cons, label, list, num);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sum[list of points]
* Michael Borcherds
*/
final public GeoElement SumText(String label, GeoList list) {
AlgoSumText algo = new AlgoSumText(cons, label, list);
GeoText ret = algo.getResult();
return ret;
}
/**
* Sum[list of text,n]
* Michael Borcherds
*/
final public GeoElement SumText(String label, GeoList list, GeoNumeric num) {
AlgoSumText algo = new AlgoSumText(cons, label, list, num);
GeoText ret = algo.getResult();
return ret;
}
/**
* Sample[list,n]
* Michael Borcherds
*/
final public GeoElement Sample(String label, GeoList list, NumberValue n) {
AlgoSample algo = new AlgoSample(cons, label, list, n, null);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Sample[list,n, withReplacement]
* Michael Borcherds
*/
final public GeoElement Sample(String label, GeoList list, NumberValue n, GeoBoolean withReplacement) {
AlgoSample algo = new AlgoSample(cons, label, list, n, withReplacement);
GeoElement ret = algo.getResult();
return ret;
}
/**
* Table[list]
* Michael Borcherds
*/
final public GeoText TableText(String label, GeoList list, GeoText args) {
AlgoTableText algo = new AlgoTableText(cons, label, list, args);
GeoText text = algo.getResult();
return text;
}
/**
* StemPlot[list]
* Michael Borcherds
*/
final public GeoText StemPlot(String label, GeoList list) {
AlgoStemPlot algo = new AlgoStemPlot(cons, label, list, null);
GeoText text = algo.getResult();
return text;
}
/**
* StemPlot[list, number]
* Michael Borcherds
*/
final public GeoText StemPlot(String label, GeoList list, GeoNumeric num) {
AlgoStemPlot algo = new AlgoStemPlot(cons, label, list, num);
GeoText text = algo.getResult();
return text;
}
/**
* ToFraction[number]
* Michael Borcherds
*/
final public GeoText FractionText(String label, GeoNumeric num) {
AlgoFractionText algo = new AlgoFractionText(cons, label, num);
GeoText text = algo.getResult();
return text;
}
/**
* Mean[list]
* Michael Borcherds
*/
final public GeoNumeric Mean(String label, GeoList list) {
AlgoMean algo = new AlgoMean(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
final public GeoText VerticalText(String label, GeoText args) {
AlgoVerticalText algo = new AlgoVerticalText(cons, label, args);
GeoText text = algo.getResult();
return text;
}
final public GeoText RotateText(String label, GeoText args, GeoNumeric angle) {
AlgoRotateText algo = new AlgoRotateText(cons, label, args, angle);
GeoText text = algo.getResult();
return text;
}
/**
* Variance[list]
* Michael Borcherds
*/
final public GeoNumeric Variance(String label, GeoList list) {
AlgoVariance algo = new AlgoVariance(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SampleVariance[list]
* Michael Borcherds
*/
final public GeoNumeric SampleVariance(String label, GeoList list) {
AlgoSampleVariance algo = new AlgoSampleVariance(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SD[list]
* Michael Borcherds
*/
final public GeoNumeric StandardDeviation(String label, GeoList list) {
AlgoStandardDeviation algo = new AlgoStandardDeviation(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SampleSD[list]
* Michael Borcherds
*/
final public GeoNumeric SampleStandardDeviation(String label, GeoList list) {
AlgoSampleStandardDeviation algo = new AlgoSampleStandardDeviation(cons, label, list);
GeoNumeric num = algo.getResult();
return num;
}
/**
* SigmaXX[list]
* Michael Borcherds
*/
final public GeoNumeric SigmaXX(String label, GeoList list) {
GeoNumeric num;
GeoElement geo = list.get(0);
if (geo.isNumberValue())
{ // list of numbers
AlgoSigmaXX algo = new AlgoSigmaXX(cons, label, list);
num = algo.getResult();
}
else
{ // (probably) list of points
AlgoListSigmaXX algo = new AlgoListSigmaXX(cons, label, list);
num = algo.getResult();
}
return num;
}
/**
* Median[list]
* Michael Borcherds
*/
final public GeoNumeric Median(String label, GeoList list) {
AlgoMedian algo = new AlgoMedian(cons, label, list);
GeoNumeric num = algo.getMedian();
return num;
}
/**
* Q1[list] lower quartile
* Michael Borcherds
*/
final public GeoNumeric Q1(String label, GeoList list) {
AlgoQ1 algo = new AlgoQ1(cons, label, list);
GeoNumeric num = algo.getQ1();
return num;
}
/**
* Q3[list] upper quartile
* Michael Borcherds
*/
final public GeoNumeric Q3(String label, GeoList list) {
AlgoQ3 algo = new AlgoQ3(cons, label, list);
GeoNumeric num = algo.getQ3();
return num;
}
/**
* Iteration[ f(x), x0, n ]
*/
final public GeoNumeric Iteration(String label, GeoFunction f, NumberValue start,
NumberValue n) {
AlgoIteration algo = new AlgoIteration(cons, label, f, start, n);
GeoNumeric num = algo.getResult();
return num;
}
/**
* IterationList[ f(x), x0, n ]
*/
final public GeoList IterationList(String label, GeoFunction f, NumberValue start,
NumberValue n) {
AlgoIterationList algo = new AlgoIterationList(cons, label, f, start, n);
return algo.getResult();
}
/**
* RandomElement[list]
*/
final public GeoElement RandomElement(String label, GeoList list) {
AlgoRandomElement algo = new AlgoRandomElement(cons, label, list);
GeoElement geo = algo.getElement();
return geo;
}
/**
* Element[list, number]
*/
final public GeoElement Element(String label, GeoList list, NumberValue n) {
AlgoListElement algo = new AlgoListElement(cons, label, list, n);
GeoElement geo = algo.getElement();
return geo;
}
/**
* SelectedElement[list]
*/
final public GeoElement SelectedElement(String label, GeoList list) {
AlgoSelectedElement algo = new AlgoSelectedElement(cons, label, list);
GeoElement geo = algo.getElement();
return geo;
}
/**
* SelectedElement[list]
*/
final public GeoElement SelectedIndex(String label, GeoList list) {
AlgoSelectedIndex algo = new AlgoSelectedIndex(cons, label, list);
GeoElement geo = algo.getElement();
return geo;
}
/**
* Element[list, number, number]
*/
final public GeoElement Element(String label, GeoList list, NumberValue n, NumberValue m) {
AlgoListElement algo = new AlgoListElement(cons, label, list, n, m);
GeoElement geo = algo.getElement();
return geo;
}
/**
* Length[list]
*/
final public GeoNumeric Length(String label, GeoList list) {
AlgoListLength algo = new AlgoListLength(cons, label, list);
return algo.getLength();
}
/**
* Element[text, number]
*/
final public GeoElement Element(String label, GeoText text, NumberValue n) {
AlgoTextElement algo = new AlgoTextElement(cons, label, text, n);
GeoElement geo = algo.getText();
return geo;
}
/**
* Length[text]
*/
final public GeoNumeric Length(String label, GeoText text) {
AlgoTextLength algo = new AlgoTextLength(cons, label, text);
return algo.getLength();
}
// PhilippWeissenbacher 2007-04-10
/**
* Perimeter named label of GeoPolygon
*/
final public GeoNumeric Perimeter(String label, GeoPolygon polygon) {
AlgoPerimeterPoly algo = new AlgoPerimeterPoly(cons, label, polygon);
return algo.getCircumference();
}
/**
* Circumference named label of GeoConic
*/
final public GeoNumeric Circumference(String label, GeoConic conic) {
AlgoCircumferenceConic algo = new AlgoCircumferenceConic(cons, label, conic);
return algo.getCircumference();
}
// PhilippWeissenbacher 2007-04-10
/**
* polygon P[0], ..., P[n-1]
* The labels name the polygon itself and its segments
*/
final public GeoElement [] Polygon(String [] labels, GeoPoint [] P) {
AlgoPolygon algo = new AlgoPolygon(cons, labels, P);
return algo.getOutput();
}
//G.Sturr 2010-3-14
/**
* Polygon with vertices from geolist
* Only the polygon is labeled, segments are not labeled
*/
final public GeoElement [] Polygon(String [] labels, GeoList pointList) {
AlgoPolygon algo = new AlgoPolygon(cons, labels, pointList);
return algo.getOutput();
}
//END G.Sturr
/**
* polygon P[0], ..., P[n-1]
* The labels name the polygon itself and its segments
*/
final public GeoElement [] PolyLine(String [] labels, GeoPoint [] P) {
AlgoPolyLine algo = new AlgoPolyLine(cons, labels, P);
return algo.getOutput();
}
/**
* Polygon with vertices from geolist
* Only the polygon is labeled, segments are not labeled
*/
final public GeoElement [] PolyLine(String [] labels, GeoList pointList) {
AlgoPolyLine algo = new AlgoPolyLine(cons, labels, pointList);
return algo.getOutput();
}
final public GeoElement [] RigidPolygon(String [] labels, GeoPoint [] points) {
boolean oldMacroMode = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
GeoConic circle = Circle(null, points[0], new MyDouble(this, points[0].distance(points[1])));
cons.setSuppressLabelCreation(oldMacroMode);
GeoPoint p = Point(null, (Path)circle, points[1].inhomX, points[1].inhomY, true);
try {
cons.replace(points[1], p);
points[1] = p;
} catch (Exception e) {
e.printStackTrace();
return null;
}
StringBuilder sb = new StringBuilder();
double xA = points[0].inhomX;
double yA = points[0].inhomY;
double xB = points[1].inhomX;
double yB = points[1].inhomY;
GeoVec2D a = new GeoVec2D(this, xB - xA, yB - yA ); // vector AB
GeoVec2D b = new GeoVec2D(this, yA - yB, xB - xA ); // perpendicular to AB
a.makeUnitVector();
b.makeUnitVector();
for (int i = 2; i < points.length ; i++) {
double xC = points[i].inhomX;
double yC = points[i].inhomY;
GeoVec2D d = new GeoVec2D(this, xC - xA, yC - yA ); // vector AC
setTemporaryPrintFigures(15);
// make string like this
// A+3.76UnitVector[Segment[A,B]]+-1.74UnitPerpendicularVector[Segment[A,B]]
sb.setLength(0);
sb.append(points[0].getLabel());
sb.append('+');
sb.append(format(a.inner(d)));
// use internal command name
sb.append("UnitVector[Segment[");
sb.append(points[0].getLabel());
sb.append(',');
sb.append(points[1].getLabel());
sb.append("]]+");
sb.append(format(b.inner(d)));
// use internal command name
sb.append("UnitOrthogonalVector[Segment[");
sb.append(points[0].getLabel());
sb.append(',');
sb.append(points[1].getLabel());
sb.append("]]");
restorePrintAccuracy();
//Application.debug(sb.toString());
GeoPoint pp = (GeoPoint)getAlgebraProcessor().evaluateToPoint(sb.toString());
try {
cons.replace(points[i], pp);
points[i] = pp;
points[i].setEuclidianVisible(false);
points[i].update();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Application.debug(kernel.format(a.inner(d))+" UnitVector[Segment[A,B]] + "+kernel.format(b.inner(d))+" UnitPerpendicularVector[Segment[A,B]]");
points[0].setEuclidianVisible(false);
points[0].update();
return Polygon(labels, points);
}
/**
* Regular polygon with vertices A and B and n total vertices.
* The labels name the polygon itself, its segments and points
*/
final public GeoElement [] RegularPolygon(String [] labels, GeoPoint A, GeoPoint B, NumberValue n) {
AlgoPolygonRegular algo = new AlgoPolygonRegular(cons, labels, A, B, n);
return algo.getOutput();
}
//G.Sturr 2010-3-14
/**
* Polygon formed by operation on two input polygons.
* Possible operations: addition, subtraction or intersection
* The labels name the polygon itself, its segments and points
*/
final public GeoElement [] PolygonOperation(String [] labels, GeoPolygon A, GeoPolygon B, NumberValue n) {
AlgoPolygonOperation algo = new AlgoPolygonOperation(cons, labels, A, B,n);
return algo.getOutput();
}
//END G.Sturr
/**
* Creates new point B with distance n from A and new segment AB
* The labels[0] is for the segment, labels[1] for the new point
*/
final public GeoElement [] Segment (String [] labels, GeoPoint A, NumberValue n) {
// this is actually a macro
String pointLabel = null, segmentLabel = null;
if (labels != null) {
switch (labels.length) {
case 2:
pointLabel = labels[1];
case 1:
segmentLabel = labels[0];
default:
}
}
// create a circle around A with radius n
AlgoCirclePointRadius algoCircle = new AlgoCirclePointRadius(cons, A, n);
cons.removeFromConstructionList(algoCircle);
// place the new point on the circle
AlgoPointOnPath algoPoint = new AlgoPointOnPath(cons, pointLabel, algoCircle.getCircle(), A.inhomX+ n.getDouble(), A.inhomY );
// return segment and new point
GeoElement [] ret = { Segment(segmentLabel, A, algoPoint.getP()),
algoPoint.getP() };
return ret;
}
/**
* Creates a new point C by rotating B around A using angle alpha and
* a new angle BAC.
* The labels[0] is for the angle, labels[1] for the new point
*/
final public GeoElement [] Angle (String [] labels, GeoPoint B, GeoPoint A, NumberValue alpha) {
return Angle(labels, B, A, alpha, true);
}
/**
* Creates a new point C by rotating B around A using angle alpha and
* a new angle BAC (for positive orientation) resp. angle CAB (for negative orientation).
* The labels[0] is for the angle, labels[1] for the new point
*/
final public GeoElement [] Angle (String [] labels, GeoPoint B, GeoPoint A, NumberValue alpha, boolean posOrientation) {
// this is actually a macro
String pointLabel = null, angleLabel = null;
if (labels != null) {
switch (labels.length) {
case 2:
pointLabel = labels[1];
case 1:
angleLabel = labels[0];
default:
}
}
// rotate B around A using angle alpha
GeoPoint C = (GeoPoint) Rotate(pointLabel, B, alpha, A)[0];
// create angle according to orientation
GeoAngle angle;
if (posOrientation) {
angle = Angle(angleLabel, B, A, C);
} else {
angle = Angle(angleLabel, C, A, B);
}
//return angle and new point
GeoElement [] ret = { angle, C };
return ret;
}
/**
* Angle named label between line g and line h
*/
final public GeoAngle Angle(String label, GeoLine g, GeoLine h) {
AlgoAngleLines algo = new AlgoAngleLines(cons, label, g, h);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* Angle named label between vector v and vector w
*/
final public GeoAngle Angle(
String label,
GeoVector v,
GeoVector w) {
AlgoAngleVectors algo = new AlgoAngleVectors(cons, label, v, w);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* Angle named label for a point or a vector
*/
final public GeoAngle Angle(
String label,
GeoVec3D v) {
AlgoAngleVector algo = new AlgoAngleVector(cons, label, v);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* Angle named label between three points
*/
final public GeoAngle Angle(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoAnglePoints algo = new AlgoAnglePoints(cons, label, A, B, C);
GeoAngle angle = algo.getAngle();
return angle;
}
/**
* all angles of given polygon
*/
final public GeoAngle [] Angles(String [] labels, GeoPolygon poly) {
AlgoAnglePolygon algo = new AlgoAnglePolygon(cons, labels, poly);
GeoAngle [] angles = algo.getAngles();
//for (int i=0; i < angles.length; i++) {
// angles[i].setAlphaValue(0.0f);
//}
return angles;
}
/**
* IntersectLines yields intersection point named label of lines g, h
*/
final public GeoPoint IntersectLines(
String label,
GeoLine g,
GeoLine h) {
AlgoIntersectLines algo = new AlgoIntersectLines(cons, label, g, h);
GeoPoint S = algo.getPoint();
return S;
}
/**
* yields intersection point named label of line g and polygon p
*/
final public GeoElement[] IntersectLinePolygon(
String[] labels,
GeoLine g,
GeoPolygon p) {
AlgoIntersectLinePolygon algo = new AlgoIntersectLinePolygon(cons, labels, g, p);
return algo.getOutput();
}
/**
* Intersects f and g using starting point A (with Newton's root finding)
*/
final public GeoPoint IntersectFunctions(
String label,
GeoFunction f,
GeoFunction g, GeoPoint A) {
AlgoIntersectFunctionsNewton algo = new AlgoIntersectFunctionsNewton(cons, label, f, g, A);
GeoPoint S = algo.getIntersectionPoint();
return S;
}
/**
* Intersects f and l using starting point A (with Newton's root finding)
*/
final public GeoPoint IntersectFunctionLine(
String label,
GeoFunction f,
GeoLine l, GeoPoint A) {
AlgoIntersectFunctionLineNewton algo = new AlgoIntersectFunctionLineNewton(cons, label, f, l, A);
GeoPoint S = algo.getIntersectionPoint();
return S;
}
/*********************************************
* CONIC PART
*********************************************/
/**
* circle with midpoint M and radius r
*/
final public GeoConic Circle(
String label,
GeoPoint M,
NumberValue r) {
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, M, r);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint M and radius BC
* Michael Borcherds 2008-03-14
*/
final public GeoConic Circle(
// this is actually a macro
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C, boolean dummy) {
AlgoJoinPointsSegment algoSegment = new AlgoJoinPointsSegment(cons, B, C, null);
cons.removeFromConstructionList(algoSegment);
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, A, algoSegment.getSegment(),true);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint A and radius the same as circle
* Michael Borcherds 2008-03-14
*/
final public GeoConic Circle(
// this is actually a macro
String label,
GeoPoint A,
GeoConic c) {
AlgoRadius radius = new AlgoRadius(cons, c);
cons.removeFromConstructionList(radius);
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, A, radius.getRadius());
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint M and radius segment
* Michael Borcherds 2008-03-15
*/
final public GeoConic Circle(
String label,
GeoPoint A,
GeoSegment segment) {
AlgoCirclePointRadius algo = new AlgoCirclePointRadius(cons, label, A, segment, true);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* circle with midpoint M through point P
*/
final public GeoConic Circle(String label, GeoPoint M, GeoPoint P) {
AlgoCircleTwoPoints algo = new AlgoCircleTwoPoints(cons, label, M, P);
GeoConic circle = algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* semicircle with midpoint M through point P
*/
final public GeoConicPart Semicircle(String label, GeoPoint M, GeoPoint P) {
AlgoSemicircle algo = new AlgoSemicircle(cons, label, M, P);
return algo.getSemicircle();
}
/**
* locus line for Q dependent on P. Note: P must be a point
* on a path.
*/
final public GeoLocus Locus(String label, GeoPoint Q, GeoPoint P) {
if (P.getPath() == null ||
Q.getPath() != null ||
!P.isParentOf(Q)) return null;
AlgoLocus algo = new AlgoLocus(cons, label, Q, P);
return algo.getLocus();
}
/**
* circle with through points A, B, C
*/
final public GeoConic Circle(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoCircleThreePoints algo = new AlgoCircleThreePoints(cons, label, A, B, C);
GeoConic circle = (GeoConic) algo.getCircle();
circle.setToSpecific();
circle.update();
notifyUpdate(circle);
return circle;
}
/**
* conic arc from conic and parameters
*/
final public GeoConicPart ConicArc(String label, GeoConic conic, NumberValue a, NumberValue b) {
AlgoConicPartConicParameters algo = new AlgoConicPartConicParameters(cons, label, conic, a, b,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* conic sector from conic and points
*/
final public GeoConicPart ConicArc(String label, GeoConic conic, GeoPoint P, GeoPoint Q) {
AlgoConicPartConicPoints algo = new AlgoConicPartConicPoints(cons, label, conic, P, Q,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* conic sector from conic and parameters
*/
final public GeoConicPart ConicSector(String label, GeoConic conic, NumberValue a, NumberValue b) {
AlgoConicPartConicParameters algo = new AlgoConicPartConicParameters(cons, label, conic, a, b,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* conic sector from conic and points
*/
final public GeoConicPart ConicSector(String label, GeoConic conic, GeoPoint P, GeoPoint Q) {
AlgoConicPartConicPoints algo = new AlgoConicPartConicPoints(cons, label, conic, P, Q,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* circle arc from three points
*/
final public GeoConicPart CircumcircleArc(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircumcircle algo = new AlgoConicPartCircumcircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* circle sector from three points
*/
final public GeoConicPart CircumcircleSector(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircumcircle algo = new AlgoConicPartCircumcircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* circle arc from center and twho points on arc
*/
final public GeoConicPart CircleArc(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircle algo = new AlgoConicPartCircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_ARC);
return algo.getConicPart();
}
/**
* circle sector from center and twho points on arc
*/
final public GeoConicPart CircleSector(String label, GeoPoint A, GeoPoint B, GeoPoint C) {
AlgoConicPartCircle algo = new AlgoConicPartCircle(cons, label, A,B, C,
GeoConicPart.CONIC_PART_SECTOR);
return algo.getConicPart();
}
/**
* Focuses of conic. returns 2 GeoPoints
*/
final public GeoPoint[] Focus(String[] labels, GeoConic c) {
AlgoFocus algo = new AlgoFocus(cons, labels, c);
GeoPoint[] focus = algo.getFocus();
return focus;
}
/**
* Vertices of conic. returns 4 GeoPoints
*/
final public GeoPoint[] Vertex(String[] labels, GeoConic c) {
AlgoVertex algo = new AlgoVertex(cons, labels, c);
GeoPoint[] vertex = algo.getVertex();
return vertex;
}
/**
* Vertices of polygon. returns 3+ GeoPoints
*/
final public GeoElement[] Vertex(String[] labels, GeoPolygon p) {
AlgoVertexPolygon algo = new AlgoVertexPolygon(cons, labels, p);
GeoElement[] vertex = algo.getVertex();
return vertex;
}
/**
* Center of conic
*/
final public GeoPoint Center(String label, GeoConic c) {
AlgoCenterConic algo = new AlgoCenterConic(cons, label, c);
GeoPoint midpoint = algo.getPoint();
return midpoint;
}
/**
* Centroid of a
*/
final public GeoPoint Centroid(String label, GeoPolygon p) {
AlgoCentroidPolygon algo = new AlgoCentroidPolygon(cons, label, p);
GeoPoint centroid = algo.getPoint();
return centroid;
}
/**
* Corner of image
*/
final public GeoPoint Corner(String label, GeoImage img, NumberValue number) {
AlgoImageCorner algo = new AlgoImageCorner(cons, label, img, number);
return algo.getCorner();
}
/**
* Corner of text Michael Borcherds 2007-11-26
*/
final public GeoPoint Corner(String label, GeoText txt, NumberValue number) {
AlgoTextCorner algo = new AlgoTextCorner(cons, label, txt, number);
return algo.getCorner();
}
/**
* Corner of Drawing Pad Michael Borcherds 2008-05-10
*/
final public GeoPoint CornerOfDrawingPad(String label, NumberValue number) {
AlgoDrawingPadCorner algo = new AlgoDrawingPadCorner(cons, label, number);
return algo.getCorner();
}
/**
* parabola with focus F and line l
*/
final public GeoConic Parabola(
String label,
GeoPoint F,
GeoLine l) {
AlgoParabolaPointLine algo = new AlgoParabolaPointLine(cons, label, F, l);
GeoConic parabola = algo.getParabola();
return parabola;
}
/**
* ellipse with foci A, B and length of first half axis a
*/
final public GeoConic Ellipse(
String label,
GeoPoint A,
GeoPoint B,
NumberValue a) {
AlgoEllipseFociLength algo = new AlgoEllipseFociLength(cons, label, A, B, a);
GeoConic ellipse = algo.getConic();
return ellipse;
}
/**
* ellipse with foci A, B passing thorugh C
* Michael Borcherds 2008-04-06
*/
final public GeoConic Ellipse(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoEllipseFociPoint algo = new AlgoEllipseFociPoint(cons, label, A, B, C);
GeoConic ellipse = algo.getEllipse();
return ellipse;
}
/**
* hyperbola with foci A, B and length of first half axis a
*/
final public GeoConic Hyperbola(
String label,
GeoPoint A,
GeoPoint B,
NumberValue a) {
AlgoHyperbolaFociLength algo =
new AlgoHyperbolaFociLength(cons, label, A, B, a);
GeoConic hyperbola = algo.getConic();
return hyperbola;
}
/**
* hyperbola with foci A, B passing thorugh C
* Michael Borcherds 2008-04-06
*/
final public GeoConic Hyperbola(
String label,
GeoPoint A,
GeoPoint B,
GeoPoint C) {
AlgoHyperbolaFociPoint algo =
new AlgoHyperbolaFociPoint(cons, label, A, B, C);
GeoConic hyperbola = algo.getHyperbola();
return hyperbola;
}
/**
* conic through five points
*/
final public GeoConic Conic(String label, GeoPoint[] points) {
AlgoConicFivePoints algo = new AlgoConicFivePoints(cons, label, points);
GeoConic conic = algo.getConic();
return conic;
}
/**
* IntersectLineConic yields intersection points named label1, label2
* of line g and conic c
*/
final public GeoPoint[] IntersectLineConic(
String[] labels,
GeoLine g,
GeoConic c) {
AlgoIntersectLineConic algo = getIntersectionAlgorithm(g, c);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
GeoElement.setLabels(labels, points);
return points;
}
/**
* IntersectConics yields intersection points named label1, label2, label3, label4
* of conics c1, c2
*/
final public GeoPoint[] IntersectConics(
String[] labels,
GeoConic a,
GeoConic b) {
AlgoIntersectConics algo = getIntersectionAlgorithm(a, b);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
GeoElement.setLabels(labels, points);
return points;
}
/**
* IntersectPolynomials yields all intersection points
* of polynomials a, b
*/
final public GeoPoint[] IntersectPolynomials(String[] labels, GeoFunction a, GeoFunction b) {
if (!a.isPolynomialFunction(false) || !b.isPolynomialFunction(false)) {
// dummy point
GeoPoint A = new GeoPoint(cons);
A.setZero();
AlgoIntersectFunctionsNewton algo = new AlgoIntersectFunctionsNewton(cons, labels[0], a, b, A);
GeoPoint[] ret = {algo.getIntersectionPoint()};
return ret;
}
AlgoIntersectPolynomials algo = getIntersectionAlgorithm(a, b);
algo.setPrintedInXML(true);
algo.setLabels(labels);
GeoPoint[] points = algo.getIntersectionPoints();
return points;
}
/**
* get only one intersection point of two polynomials a, b
* that is near to the given location (xRW, yRW)
*/
final public GeoPoint IntersectPolynomialsSingle(
String label, GeoFunction a, GeoFunction b,
double xRW, double yRW)
{
if (!a.isPolynomialFunction(false) || !b.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomials algo = getIntersectionAlgorithm(a, b);
int index = algo.getClosestPointIndex(xRW, yRW);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two polynomials a, b
* with given index
*/
final public GeoPoint IntersectPolynomialsSingle(
String label,
GeoFunction a,
GeoFunction b, NumberValue index) {
if (!a.isPolynomialFunction(false) || !b.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomials algo = getIntersectionAlgorithm(a, b); // index - 1 to start at 0
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* IntersectPolyomialLine yields all intersection points
* of polynomial f and line l
*/
final public GeoPoint[] IntersectPolynomialLine(
String[] labels,
GeoFunction f,
GeoLine l) {
if (!f.isPolynomialFunction(false)) {
// dummy point
GeoPoint A = new GeoPoint(cons);
A.setZero();
AlgoIntersectFunctionLineNewton algo = new AlgoIntersectFunctionLineNewton(cons, labels[0], f, l, A);
GeoPoint[] ret = {algo.getIntersectionPoint()};
return ret;
}
AlgoIntersectPolynomialLine algo = getIntersectionAlgorithm(f, l);
algo.setPrintedInXML(true);
algo.setLabels(labels);
GeoPoint[] points = algo.getIntersectionPoints();
return points;
}
/**
* one intersection point of polynomial f and line l near to (xRW, yRW)
*/
final public GeoPoint IntersectPolynomialLineSingle(
String label,
GeoFunction f,
GeoLine l, double xRW, double yRW) {
if (!f.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomialLine algo = getIntersectionAlgorithm(f, l);
int index = algo.getClosestPointIndex(xRW, yRW);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of a line and a function
*/
final public GeoPoint IntersectPolynomialLineSingle(
String label,
GeoFunction f,
GeoLine l, NumberValue index) {
if (!f.isPolynomialFunction(false)) return null;
AlgoIntersectPolynomialLine algo = getIntersectionAlgorithm(f, l);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two conics that is near to the given
* location (xRW, yRW)
*/
final public GeoPoint IntersectLineConicSingle(
String label,
GeoLine g,
GeoConic c, double xRW, double yRW) {
AlgoIntersectLineConic algo = getIntersectionAlgorithm(g, c);
int index = algo.getClosestPointIndex(xRW, yRW);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of a line and a conic
*/
final public GeoPoint IntersectLineConicSingle(
String label,
GeoLine g,
GeoConic c, NumberValue index) {
AlgoIntersectLineConic algo = getIntersectionAlgorithm(g, c); // index - 1 to start at 0
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two conics that is near to the given
* location (xRW, yRW)
*/
final public GeoPoint IntersectConicsSingle(
String label,
GeoConic a,
GeoConic b, double xRW, double yRW) {
AlgoIntersectConics algo = getIntersectionAlgorithm(a, b);
int index = algo.getClosestPointIndex(xRW, yRW) ;
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, index);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get only one intersection point of two conics
*/
final public GeoPoint IntersectConicsSingle(
String label, GeoConic a, GeoConic b, NumberValue index) {
AlgoIntersectConics algo = getIntersectionAlgorithm(a, b); // index - 1 to start at 0
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) index.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of a polynomial and a conic
*/
final public GeoPoint[] IntersectPolynomialConic(
String[] labels,
GeoFunction f,
GeoConic c) {
AlgoIntersectPolynomialConic algo = getIntersectionAlgorithm(f, c);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
// GeoElement.setLabels(labels, points);
algo.setLabels(labels);
return points;
}
final public GeoPoint IntersectPolynomialConicSingle(String label,
GeoFunction f, GeoConic c,NumberValue idx){
AlgoIntersect algo = getIntersectionAlgorithm(f, c);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
final public GeoPoint IntersectPolynomialConicSingle(String label,
GeoFunction f, GeoConic c,double x,double y){
AlgoIntersect algo = getIntersectionAlgorithm(f, c);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of a implicitPoly and a line
*/
final public GeoPoint[] IntersectImplicitpolyLine(
String[] labels,
GeoImplicitPoly p,
GeoLine l) {
AlgoIntersectImplicitpolyParametric algo = getIntersectionAlgorithm(p, l);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of a implicitPoly and a line
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolyLineSingle(
String label,
GeoImplicitPoly p,
GeoLine l,NumberValue idx) {
AlgoIntersect algo = getIntersectionAlgorithm(p, l);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of a implicitPoly and a line
*/
final public GeoPoint IntersectImplicitpolyLineSingle(
String label,
GeoImplicitPoly p,
GeoLine l,double x,double y) {
AlgoIntersect algo = getIntersectionAlgorithm(p, l);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of a implicitPoly and a polynomial
*/
final public GeoPoint[] IntersectImplicitpolyPolynomial(
String[] labels,
GeoImplicitPoly p,
GeoFunction f) {
if (!f.isPolynomialFunction(false))
return null;
AlgoIntersectImplicitpolyParametric algo = getIntersectionAlgorithm(p, f);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of a implicitPoly and a line
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolyPolynomialSingle(
String label,
GeoImplicitPoly p,
GeoFunction f,NumberValue idx) {
if (!f.isPolynomialFunction(false))
return null;
AlgoIntersect algo = getIntersectionAlgorithm(p, f);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of a implicitPoly and a line
*/
final public GeoPoint IntersectImplicitpolyPolynomialSingle(
String label,
GeoImplicitPoly p,
GeoFunction f,double x,double y) {
if (!f.isPolynomialFunction(false))
return null;
AlgoIntersect algo = getIntersectionAlgorithm(p, f);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of two implicitPolys
*/
final public GeoPoint[] IntersectImplicitpolys(
String[] labels,
GeoImplicitPoly p1,
GeoImplicitPoly p2) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, p2);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of two implicitPolys
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolysSingle(
String label,
GeoImplicitPoly p1,
GeoImplicitPoly p2,NumberValue idx) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, p2);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of two implicitPolys near given Point (x,y)
* @param x
* @param y
*/
final public GeoPoint IntersectImplicitpolysSingle(
String label,
GeoImplicitPoly p1,
GeoImplicitPoly p2,double x,double y) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, p2);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get intersection points of implicitPoly and conic
*/
final public GeoPoint[] IntersectImplicitpolyConic(
String[] labels,
GeoImplicitPoly p1,
GeoConic c1) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, c1);
algo.setPrintedInXML(true);
GeoPoint[] points = algo.getIntersectionPoints();
algo.setLabels(labels);
return points;
}
/**
* get single intersection points of implicitPoly and conic
* @param idx index of choosen point
*/
final public GeoPoint IntersectImplicitpolyConicSingle(
String label,
GeoImplicitPoly p1,
GeoConic c1,NumberValue idx) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, c1);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, (int) idx.getDouble() - 1);
GeoPoint point = salgo.getPoint();
return point;
}
/**
* get single intersection points of implicitPolys and conic near given Point (x,y)
* @param x
* @param y
*/
final public GeoPoint IntersectImplicitpolyConicSingle(
String label,
GeoImplicitPoly p1,
GeoConic c1,double x,double y) {
AlgoIntersectImplicitpolys algo = getIntersectionAlgorithm(p1, c1);
int idx=algo.getClosestPointIndex(x, y);
AlgoIntersectSingle salgo = new AlgoIntersectSingle(label, algo, idx);
GeoPoint point = salgo.getPoint();
return point;
}
/*
* to avoid multiple calculations of the intersection points of the same
* two objects, we remember all the intersection algorithms created
*/
private ArrayList intersectionAlgos = new ArrayList();
// intersect polynomial and conic
AlgoIntersectPolynomialConic getIntersectionAlgorithm(GeoFunction f, GeoConic c) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(f, c);
if (existingAlgo != null) return (AlgoIntersectPolynomialConic) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectPolynomialConic algo = new AlgoIntersectPolynomialConic(cons, f, c);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersect line and conic
AlgoIntersectLineConic getIntersectionAlgorithm(GeoLine g, GeoConic c) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(g, c);
if (existingAlgo != null) return (AlgoIntersectLineConic) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectLineConic algo = new AlgoIntersectLineConic(cons, g, c);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersect conics
AlgoIntersectConics getIntersectionAlgorithm(GeoConic a, GeoConic b) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(a, b);
if (existingAlgo != null) return (AlgoIntersectConics) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectConics algo = new AlgoIntersectConics(cons, a, b);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of polynomials
AlgoIntersectPolynomials getIntersectionAlgorithm(GeoFunction a, GeoFunction b) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(a, b);
if (existingAlgo != null) return (AlgoIntersectPolynomials) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectPolynomials algo = new AlgoIntersectPolynomials(cons, a, b);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of polynomials
AlgoIntersectPolynomialLine getIntersectionAlgorithm(GeoFunction a, GeoLine l) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(a, l);
if (existingAlgo != null) return (AlgoIntersectPolynomialLine) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectPolynomialLine algo = new AlgoIntersectPolynomialLine(cons, a, l);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of GeoImplicitPoly, GeoLine
AlgoIntersectImplicitpolyParametric getIntersectionAlgorithm(GeoImplicitPoly p, GeoLine l) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p, l);
if (existingAlgo != null) return (AlgoIntersectImplicitpolyParametric) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolyParametric algo = new AlgoIntersectImplicitpolyParametric(cons, p, l);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of GeoImplicitPoly, polynomial
AlgoIntersectImplicitpolyParametric getIntersectionAlgorithm(GeoImplicitPoly p, GeoFunction f) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p, f);
if (existingAlgo != null) return (AlgoIntersectImplicitpolyParametric) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolyParametric algo = new AlgoIntersectImplicitpolyParametric(cons, p, f);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
// intersection of two GeoImplicitPoly
AlgoIntersectImplicitpolys getIntersectionAlgorithm(GeoImplicitPoly p1, GeoImplicitPoly p2) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p1, p2);
if (existingAlgo != null) return (AlgoIntersectImplicitpolys) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolys algo = new AlgoIntersectImplicitpolys(cons, p1, p2);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
AlgoIntersectImplicitpolys getIntersectionAlgorithm(GeoImplicitPoly p1, GeoConic c1) {
AlgoElement existingAlgo = findExistingIntersectionAlgorithm(p1, c1);
if (existingAlgo != null) return (AlgoIntersectImplicitpolys) existingAlgo;
// we didn't find a matching algorithm, so create a new one
AlgoIntersectImplicitpolys algo = new AlgoIntersectImplicitpolys(cons, p1, c1);
algo.setPrintedInXML(false);
intersectionAlgos.add(algo); // remember this algorithm
return algo;
}
private AlgoElement findExistingIntersectionAlgorithm(GeoElement a, GeoElement b) {
int size = intersectionAlgos.size();
AlgoElement algo;
for (int i=0; i < size; i++) {
algo = (AlgoElement) intersectionAlgos.get(i);
GeoElement [] input = algo.getInput();
if (a == input[0] && b == input[1] ||
a == input[1] && b == input[0])
// we found an existing intersection algorithm
return algo;
}
return null;
}
void removeIntersectionAlgorithm(AlgoIntersect algo) {
intersectionAlgos.remove(algo);
}
/**
* polar line to P relativ to c
*/
final public GeoLine PolarLine(
String label,
GeoPoint P,
GeoConic c) {
AlgoPolarLine algo = new AlgoPolarLine(cons, label, c, P);
GeoLine polar = algo.getLine();
return polar;
}
/**
* diameter line conjugate to direction of g relative to c
*/
final public GeoLine DiameterLine(
String label,
GeoLine g,
GeoConic c) {
AlgoDiameterLine algo = new AlgoDiameterLine(cons, label, c, g);
GeoLine diameter = algo.getDiameter();
return diameter;
}
/**
* diameter line conjugate to v relative to c
*/
final public GeoLine DiameterLine(
String label,
GeoVector v,
GeoConic c) {
AlgoDiameterVector algo = new AlgoDiameterVector(cons, label, c, v);
GeoLine diameter = algo.getDiameter();
return diameter;
}
/**
* tangents to c through P
*/
final public GeoLine[] Tangent(
String[] labels,
GeoPoint P,
GeoConic c) {
AlgoTangentPoint algo = new AlgoTangentPoint(cons, labels, P, c);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* tangents to c parallel to g
*/
final public GeoLine[] Tangent(
String[] labels,
GeoLine g,
GeoConic c) {
AlgoTangentLine algo = new AlgoTangentLine(cons, labels, g, c);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* tangent to f in x = a
*/
final public GeoLine Tangent(
String label,
NumberValue a,
GeoFunction f) {
AlgoTangentFunctionNumber algo =
new AlgoTangentFunctionNumber(cons, label, a, f);
GeoLine t = algo.getTangent();
t.setToExplicit();
t.update();
notifyUpdate(t);
return t;
}
/**
* tangent to f in x = x(P)
*/
final public GeoLine Tangent(
String label,
GeoPoint P,
GeoFunction f) {
AlgoTangentFunctionPoint algo =
new AlgoTangentFunctionPoint(cons, label, P, f);
GeoLine t = algo.getTangent();
t.setToExplicit();
t.update();
notifyUpdate(t);
return t;
}
/**
* tangents to p through P
*/
final public GeoLine[] Tangent(
String[] labels,
GeoPoint R,
GeoImplicitPoly p) {
AlgoTangentImplicitpoly algo = new AlgoTangentImplicitpoly(cons, labels, p, R);
algo.setLabels(labels);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* tangents to p parallel to g
*/
final public GeoLine[] Tangent(
String[] labels,
GeoLine g,
GeoImplicitPoly p) {
AlgoTangentImplicitpoly algo = new AlgoTangentImplicitpoly(cons, labels, p, g);
algo.setLabels(labels);
GeoLine[] tangents = algo.getTangents();
return tangents;
}
/**
* asymptotes to c
*/
final public GeoLine[] Asymptote(String[] labels, GeoConic c) {
AlgoAsymptote algo = new AlgoAsymptote(cons, labels, c);
GeoLine[] asymptotes = algo.getAsymptotes();
return asymptotes;
}
/**
* axes of c
*/
final public GeoLine[] Axes(String[] labels, GeoConic c) {
AlgoAxes algo = new AlgoAxes(cons, labels, c);
GeoLine[] axes = algo.getAxes();
return axes;
}
/**
* first axis of c
*/
final public GeoLine FirstAxis(String label, GeoConic c) {
AlgoAxisFirst algo = new AlgoAxisFirst(cons, label, c);
GeoLine axis = algo.getAxis();
return axis;
}
/**
* second axis of c
*/
final public GeoLine SecondAxis(String label, GeoConic c) {
AlgoAxisSecond algo = new AlgoAxisSecond(cons, label, c);
GeoLine axis = algo.getAxis();
return axis;
}
/**
* directrix of c
*/
final public GeoLine Directrix(String label, GeoConic c) {
AlgoDirectrix algo = new AlgoDirectrix(cons, label, c);
GeoLine directrix = algo.getDirectrix();
return directrix;
}
/**
* linear eccentricity of c
*/
final public GeoNumeric Excentricity(String label, GeoConic c) {
AlgoExcentricity algo = new AlgoExcentricity(cons, label, c);
GeoNumeric linearEccentricity = algo.getLinearEccentricity();
return linearEccentricity;
}
/**
* eccentricity of c
*/
final public GeoNumeric Eccentricity(String label, GeoConic c) {
AlgoEccentricity algo = new AlgoEccentricity(cons, label, c);
GeoNumeric eccentricity = algo.getEccentricity();
return eccentricity;
}
/**
* first axis' length of c
*/
final public GeoNumeric FirstAxisLength(String label, GeoConic c) {
AlgoAxisFirstLength algo = new AlgoAxisFirstLength(cons, label, c);
GeoNumeric length = algo.getLength();
return length;
}
/**
* second axis' length of c
*/
final public GeoNumeric SecondAxisLength(String label, GeoConic c) {
AlgoAxisSecondLength algo = new AlgoAxisSecondLength(cons, label, c);
GeoNumeric length = algo.getLength();
return length;
}
/**
* (parabola) parameter of c
*/
final public GeoNumeric Parameter(String label, GeoConic c) {
AlgoParabolaParameter algo = new AlgoParabolaParameter(cons, label, c);
GeoNumeric length = algo.getParameter();
return length;
}
/**
* (circle) radius of c
*/
final public GeoNumeric Radius(String label, GeoConic c) {
AlgoRadius algo = new AlgoRadius(cons, label, c);
GeoNumeric length = algo.getRadius();
return length;
}
/**
* angle of c (angle between first eigenvector and (1,0))
*/
final public GeoAngle Angle(String label, GeoConic c) {
AlgoAngleConic algo = new AlgoAngleConic(cons, label, c);
GeoAngle angle = algo.getAngle();
return angle;
}
/********************************************************************
* TRANSFORMATIONS
********************************************************************/
/**
* translate geoTrans by vector v
*/
final public GeoElement [] Translate(String label, GeoElement geoTrans, GeoVec3D v) {
Transform t = new TransformTranslate(v);
return t.transform(geoTrans, label);
}
/**
* translates vector v to point A. The resulting vector is equal
* to v and has A as startPoint
*/
final public GeoVector Translate(String label, GeoVec3D v, GeoPoint A) {
AlgoTranslateVector algo = new AlgoTranslateVector(cons, label, v, A);
GeoVector vec = algo.getTranslatedVector();
return vec;
}
/**
* rotate geoRot by angle phi around (0,0)
*/
final public GeoElement [] Rotate(String label, GeoElement geoRot, NumberValue phi) {
Transform t = new TransformRotate(phi);
return t.transform(geoRot, label);
}
/**
* rotate geoRot by angle phi around Q
*/
final public GeoElement [] Rotate(String label, GeoElement geoRot, NumberValue phi, GeoPoint Q) {
Transform t = new TransformRotate(phi,Q);
return t.transform(geoRot, label);
}
/**
* dilate geoRot by r from S
*/
final public GeoElement [] Dilate(String label, GeoElement geoDil, NumberValue r, GeoPoint S) {
Transform t = new TransformDilate(r,S);
return t.transform(geoDil, label);
}
/**
* dilate geoRot by r from origin
*/
final public GeoElement [] Dilate(String label, GeoElement geoDil, NumberValue r) {
Transform t = new TransformDilate(r);
return t.transform(geoDil, label);
}
/**
* mirror geoMir at point Q
*/
final public GeoElement [] Mirror(String label, GeoElement geoMir, GeoPoint Q) {
Transform t = new TransformMirror(Q);
return t.transform(geoMir, label);
}
/**
* mirror (invert) element Q in circle
* Michael Borcherds 2008-02-10
*/
final public GeoElement [] Mirror(String label, GeoElement Q, GeoConic conic) {
Transform t = new TransformMirror(conic);
return t.transform(Q, label);
}
/**
* apply matrix
* Michael Borcherds 2010-05-27
*/
final public GeoElement [] ApplyMatrix(String label, GeoElement Q, GeoList matrix) {
Transform t = new TransformApplyMatrix(matrix);
return t.transform(Q, label);
}
/**
* shear
*/
final public GeoElement [] Shear(String label, GeoElement Q, GeoVec3D l, GeoNumeric num) {
Transform t = new TransformShearOrStretch(l,num,true);
return t.transform(Q, label);
}
/**
* apply matrix
* Michael Borcherds 2010-05-27
*/
final public GeoElement [] Stretch(String label, GeoElement Q, GeoVec3D l, GeoNumeric num) {
Transform t = new TransformShearOrStretch(l,num,false);
return t.transform(Q, label);
}
/**
* mirror geoMir at line g
*/
final public GeoElement [] Mirror(String label, GeoElement geoMir, GeoLine g) {
Transform t = new TransformMirror(g);
return t.transform(geoMir, label);
}
static final int TRANSFORM_TRANSLATE = 0;
static final int TRANSFORM_MIRROR_AT_POINT = 1;
static final int TRANSFORM_MIRROR_AT_LINE = 2;
static final int TRANSFORM_ROTATE = 3;
static final int TRANSFORM_ROTATE_AROUND_POINT = 4;
static final int TRANSFORM_DILATE = 5;
public static boolean keepOrientationForTransformation(int transformationType) {
switch (transformationType) {
case TRANSFORM_MIRROR_AT_LINE:
return false;
default:
return true;
}
}
/***********************************
* CALCULUS
***********************************/
/** function limited to interval [a, b]
*/
final public GeoFunction Function(String label, GeoFunction f,
NumberValue a, NumberValue b) {
AlgoFunctionInterval algo = new AlgoFunctionInterval(cons, label, f, a, b);
GeoFunction g = algo.getFunction();
return g;
}
/**
* n-th derivative of multivariate function f
*/
final public GeoElement Derivative(
String label,
CasEvaluableFunction f, GeoNumeric var,
NumberValue n) {
AlgoCasDerivative algo = new AlgoCasDerivative(cons, label, f, var, n);
return algo.getResult();
}
/**
* Tries to expand a function f to a polynomial.
*/
final public GeoFunction PolynomialFunction(String label, GeoFunction f) {
AlgoPolynomialFromFunction algo = new AlgoPolynomialFromFunction(cons, label, f);
return algo.getPolynomial();
}
/**
* Fits a polynomial exactly to a list of coordinates
* Michael Borcherds 2008-01-22
*/
final public GeoFunction PolynomialFunction(String label, GeoList list) {
AlgoPolynomialFromCoordinates algo = new AlgoPolynomialFromCoordinates(cons, label, list);
return algo.getPolynomial();
}
final public GeoElement Expand(String label, CasEvaluableFunction func) {
AlgoCasExpand algo = new AlgoCasExpand(cons, label, func);
return algo.getResult();
}
final public GeoElement Simplify(String label, CasEvaluableFunction func) {
AlgoCasSimplify algo = new AlgoCasSimplify(cons, label, func);
return algo.getResult();
}
final public GeoElement SolveODE(String label, CasEvaluableFunction func) {
AlgoCasSolveODE algo = new AlgoCasSolveODE(cons, label, func);
return algo.getResult();
}
/**
* Simplify text, eg "+-x" to "-x"
* @author Michael Borcherds
*/
final public GeoElement Simplify(String label, GeoText text) {
AlgoSimplifyText algo = new AlgoSimplifyText(cons, label, text);
return algo.getGeoText();
}
final public GeoElement DynamicCoordinates(String label, GeoPoint geoPoint,
NumberValue num1, NumberValue num2) {
AlgoDynamicCoordinates algo = new AlgoDynamicCoordinates(cons, label, geoPoint, num1, num2);
return algo.getPoint();
}
final public GeoElement Factor(String label, CasEvaluableFunction func) {
AlgoCasFactor algo = new AlgoCasFactor(cons, label, func);
return algo.getResult();
}
/**
* Factors
* Michael Borcherds
*/
final public GeoList Factors(String label, GeoFunction func) {
AlgoFactors algo = new AlgoFactors(cons, label, func);
return algo.getResult();
}
final public GeoLocus SolveODE(String label, FunctionalNVar f, FunctionalNVar g, GeoNumeric x, GeoNumeric y, GeoNumeric end, GeoNumeric step) {
AlgoSolveODE algo = new AlgoSolveODE(cons, label, f, g, x, y, end, step);
return algo.getResult();
}
/*
* second order ODEs
*/
final public GeoLocus SolveODE2(String label, GeoFunctionable f, GeoFunctionable g, GeoFunctionable h, GeoNumeric x, GeoNumeric y, GeoNumeric yDot, GeoNumeric end, GeoNumeric step) {
AlgoSolveODE2 algo = new AlgoSolveODE2(cons, label, f, g, h, x, y, yDot, end, step);
return algo.getResult();
}
/**
* Asymptotes
* Michael Borcherds
*/
final public GeoList AsymptoteFunction(String label, GeoFunction func) {
AlgoAsymptoteFunction algo = new AlgoAsymptoteFunction(cons, label, func);
return algo.getResult();
}
/**
* Numerator
* Michael Borcherds
*/
final public GeoFunction Numerator(String label, GeoFunction func) {
AlgoNumerator algo = new AlgoNumerator(cons, label, func);
return algo.getResult();
}
/**
* Denominator
* Michael Borcherds
*/
final public GeoFunction Denominator(String label, GeoFunction func) {
AlgoDenominator algo = new AlgoDenominator(cons, label, func);
return algo.getResult();
}
/**
* Degree
* Michael Borcherds
*/
final public GeoNumeric Degree(String label, GeoFunction func) {
AlgoDegree algo = new AlgoDegree(cons, label, func);
return algo.getResult();
}
/**
* Limit
* Michael Borcherds
*/
final public GeoNumeric Limit(String label, GeoFunction func, NumberValue num) {
AlgoLimit algo = new AlgoLimit(cons, label, func, num);
return algo.getResult();
}
/**
* LimitBelow
* Michael Borcherds
*/
final public GeoNumeric LimitBelow(String label, GeoFunction func, NumberValue num) {
AlgoLimitBelow algo = new AlgoLimitBelow(cons, label, func, num);
return algo.getResult();
}
/**
* LimitAbove
* Michael Borcherds
*/
final public GeoNumeric LimitAbove(String label, GeoFunction func, NumberValue num) {
AlgoLimitAbove algo = new AlgoLimitAbove(cons, label, func, num);
return algo.getResult();
}
/**
* Partial Fractions
* Michael Borcherds
*/
final public GeoElement PartialFractions(String label, CasEvaluableFunction func) {
AlgoCasPartialFractions algo = new AlgoCasPartialFractions(cons, label, func);
return algo.getResult();
}
/**
* Coefficients
* Michael Borcherds 2008-04-04
*/
final public GeoList Coefficients(String label, GeoFunction func) {
AlgoCoefficients algo = new AlgoCoefficients(cons, label, func);
return algo.getResult();
}
/**
* Coefficients
* Michael Borcherds 2008-04-04
*/
final public GeoList Coefficients(String label, GeoConic func) {
AlgoConicCoefficients algo = new AlgoConicCoefficients(cons, label, func);
return algo.getResult();
}
/**
* Taylor series of function f about point x=a of order n
*/
final public GeoFunction TaylorSeries(
String label,
GeoFunction f,
NumberValue a,
NumberValue n) {
AlgoTaylorSeries algo = new AlgoTaylorSeries(cons, label, f, a, n);
return algo.getPolynomial();
}
/**
* Integral of function f
*/
final public GeoElement Integral(String label, CasEvaluableFunction f, GeoNumeric var) {
AlgoCasIntegral algo = new AlgoCasIntegral(cons, label, f, var);
return algo.getResult();
}
/**
* definite Integral of function f from x=a to x=b
*/
final public GeoNumeric Integral(String label, GeoFunction f, NumberValue a, NumberValue b) {
AlgoIntegralDefinite algo = new AlgoIntegralDefinite(cons, label, f, a, b);
GeoNumeric n = algo.getIntegral();
return n;
}
/**
* definite integral of function (f - g) in interval [a, b]
*/
final public GeoNumeric Integral(String label, GeoFunction f, GeoFunction g,
NumberValue a, NumberValue b) {
AlgoIntegralFunctions algo = new AlgoIntegralFunctions(cons, label, f, g, a, b);
GeoNumeric num = algo.getIntegral();
return num;
}
/**
*
*/
final public GeoPoint [] PointsFromList(String [] labels, GeoList list) {
AlgoPointsFromList algo = new AlgoPointsFromList(cons, labels, true, list);
GeoPoint [] g = algo.getPoints();
return g;
}
/**
* all Roots of polynomial f (works only for polynomials and functions
* that can be simplified to factors of polynomials, e.g. sqrt(x) to x)
*/
final public GeoPoint [] Root(String [] labels, GeoFunction f) {
// allow functions that can be simplified to factors of polynomials
if (!f.isPolynomialFunction(true)) return null;
AlgoRootsPolynomial algo = new AlgoRootsPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* all Complex Roots of polynomial f (works only for polynomials)
*/
final public GeoPoint [] ComplexRoot(String [] labels, GeoFunction f) {
// allow functions that can be simplified to factors of polynomials
if (!f.isPolynomialFunction(true)) return null;
AlgoComplexRootsPolynomial algo = new AlgoComplexRootsPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* Root of a function f to given start value a (works only if first derivative of f exists)
*/
final public GeoPoint Root(String label, GeoFunction f, NumberValue a) {
AlgoRootNewton algo = new AlgoRootNewton(cons, label, f, a);
GeoPoint p = algo.getRootPoint();
return p;
}
/**
* Root of a function f in given interval [a, b]
*/
final public GeoPoint Root(String label, GeoFunction f, NumberValue a, NumberValue b) {
AlgoRootInterval algo = new AlgoRootInterval(cons, label, f, a, b);
GeoPoint p = algo.getRootPoint();
return p;
}
/**
* all Extrema of function f (works only for polynomials)
*/
final public GeoPoint [] Extremum(String [] labels, GeoFunction f) {
// check if this is a polynomial at the moment
if (!f.isPolynomialFunction(true)) return null;
AlgoExtremumPolynomial algo = new AlgoExtremumPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* all Turning points of function f (works only for polynomials)
*/
final public GeoPoint [] TurningPoint(String [] labels, GeoFunction f) {
// check if this is a polynomial at the moment
if (!f.isPolynomialFunction(true)) return null;
AlgoTurningPointPolynomial algo = new AlgoTurningPointPolynomial(cons, labels, f);
GeoPoint [] g = algo.getRootPoints();
return g;
}
/**
* Victor Franco Espino 18-04-2007: New commands
*
* Calculate affine ratio: (A,B,C) = (t(C)-t(A)) : (t(C)-t(B))
*/
final public GeoNumeric AffineRatio(String label, GeoPoint A, GeoPoint B,
GeoPoint C) {
AlgoAffineRatio affine = new AlgoAffineRatio(cons, label, A, B, C);
GeoNumeric M = affine.getResult();
return M;
}
/**
* Calculate cross ratio: (A,B,C,D) = affineRatio(A, B, C) / affineRatio(A, B, D)
*/
final public GeoNumeric CrossRatio(String label,GeoPoint A,GeoPoint B,GeoPoint C,GeoPoint D){
AlgoCrossRatio cross = new AlgoCrossRatio(cons,label,A,B,C,D);
GeoNumeric M = cross.getResult();
return M;
}
/**
* Calculate Curvature Vector for function: c(x) = (1/T^4)*(-f'*f'',f''), T = sqrt(1+(f')^2)
*/
final public GeoVector CurvatureVector(String label,GeoPoint A,GeoFunction f){
AlgoCurvatureVector algo = new AlgoCurvatureVector(cons,label,A,f);
GeoVector v = algo.getVector();
return v;
}
/**
* Calculate Curvature Vector for curve: c(t) = ((a'(t)b''(t)-a''(t)b'(t))/T^4) * (-b'(t),a'(t))
* T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoVector CurvatureVectorCurve(String label,GeoPoint A,GeoCurveCartesian f){
AlgoCurvatureVectorCurve algo = new AlgoCurvatureVectorCurve(cons,label,A,f);
GeoVector v = algo.getVector();
return v;
}
/**
* Calculate Curvature for function: k(x) = f''/T^3, T = sqrt(1+(f')^2)
*/
final public GeoNumeric Curvature(String label,GeoPoint A,GeoFunction f){
AlgoCurvature algo = new AlgoCurvature(cons,label,A,f);
GeoNumeric k = algo.getResult();
return k;
}
/**
* Calculate Curvature for Curve: k(t) = (a'(t)b''(t)-a''(t)b'(t))/T^3, T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoNumeric CurvatureCurve(String label,GeoPoint A, GeoCurveCartesian f){
AlgoCurvatureCurve algo = new AlgoCurvatureCurve(cons,label,A,f);
GeoNumeric k = algo.getResult();
return k;
}
/**
* Osculating Circle of a function f in point A
*/
final public GeoConic OsculatingCircle(String label,GeoPoint A,GeoFunction f){
AlgoOsculatingCircle algo = new AlgoOsculatingCircle(cons,label,A,f);
GeoConic circle = algo.getCircle();
return circle;
}
/**
* Osculating Circle of a curve f in point A
*/
final public GeoConic OsculatingCircleCurve(String label,GeoPoint A,GeoCurveCartesian f){
AlgoOsculatingCircleCurve algo = new AlgoOsculatingCircleCurve(cons,label,A,f);
GeoConic circle = algo.getCircle();
return circle;
}
/**
* Calculate Function Length between the numbers A and B: integral from A to B on T = sqrt(1+(f')^2)
*/
final public GeoNumeric FunctionLength(String label,GeoFunction f,GeoNumeric A,GeoNumeric B){
AlgoLengthFunction algo = new AlgoLengthFunction(cons,label,f,A,B);
GeoNumeric length = algo.getLength();
return length;
}
/**
* Calculate Function Length between the points A and B: integral from A to B on T = sqrt(1+(f')^2)
*/
final public GeoNumeric FunctionLength2Points(String label,GeoFunction f,GeoPoint A,GeoPoint B){
AlgoLengthFunction2Points algo = new AlgoLengthFunction2Points(cons,label,f,A,B);
GeoNumeric length = algo.getLength();
return length;
}
/**
* Calculate Curve Length between the parameters t0 and t1: integral from t0 to t1 on T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoNumeric CurveLength(String label, GeoCurveCartesian c, GeoNumeric t0,GeoNumeric t1){
AlgoLengthCurve algo = new AlgoLengthCurve(cons,label,c,t0,t1);
GeoNumeric length = algo.getLength();
return length;
}
/**
* Calculate Curve Length between the points A and B: integral from t0 to t1 on T = sqrt(a'(t)^2+b'(t)^2)
*/
final public GeoNumeric CurveLength2Points(String label, GeoCurveCartesian c, GeoPoint A,GeoPoint B){
AlgoLengthCurve2Points algo = new AlgoLengthCurve2Points(cons,label,c,A,B);
GeoNumeric length = algo.getLength();
return length;
}
/**
* tangent to Curve f in point P: (b'(t), -a'(t), a'(t)*b(t)-a(t)*b'(t))
*/
final public GeoLine Tangent(String label,GeoPoint P,GeoCurveCartesian f) {
AlgoTangentCurve algo = new AlgoTangentCurve(cons, label, P, f);
GeoLine t = algo.getTangent();
t.setToExplicit();
t.update();
notifyUpdate(t);
return t;
}
/**
* Victor Franco Espino 18-04-2007: End new commands
*/
/***********************************
* PACKAGE STUFF
***********************************/
/** if x is nearly zero, 0.0 is returned,
* else x is returned
*/
final public double chop(double x) {
if (isZero(x))
return 0.0d;
else
return x;
}
final public boolean isReal(Complex c) {
return isZero(c.getImaginary());
}
/** is abs(x) < epsilon ? */
final public static boolean isZero(double x) {
return -EPSILON < x && x < EPSILON;
}
final boolean isZero(double[] a) {
for (int i = 0; i < a.length; i++) {
if (!isZero(a[i]))
return false;
}
return true;
}
final public boolean isInteger(double x) {
if (x > 1E17)
return true;
else
return isEqual(x, Math.round(x));
}
/**
* Returns whether x is equal to y
* infinity == infinity returns true eg 1/0
* -infinity == infinity returns false eg -1/0
* -infinity == -infinity returns true
* undefined == undefined returns false eg 0/0
*/
final public static boolean isEqual(double x, double y) {
if (x == y) // handles infinity and NaN cases
return true;
else
return x - EPSILON <= y && y <= x + EPSILON;
}
final public static boolean isEqual(double x, double y, double eps) {
if (x == y) // handles infinity and NaN cases
return true;
else
return x - eps < y && y < x + eps;
}
/**
* Returns whether x is greater than y
*/
final public boolean isGreater(double x, double y) {
return x > y + EPSILON;
}
/**
* Returns whether x is greater than or equal to y
*/
final public boolean isGreaterEqual(double x, double y) {
return x + EPSILON > y;
}
// compares double arrays:
// yields true if (isEqual(a[i], b[i]) == true) for all i
final boolean isEqual(double[] a, double[] b) {
for (int i = 0; i < a.length; ++i) {
if (!isEqual(a[i], b[i]))
return false;
}
return true;
}
final public double convertToAngleValue(double val) {
if (val > EPSILON && val < PI_2) return val;
double value = val % PI_2;
if (isZero(value)) {
if (val < 1.0) value = 0.0;
else value = PI_2;
}
else if (value < 0.0) {
value += PI_2;
}
return value;
}
/*
// calc acos(x). returns 0 for x > 1 and pi for x < -1
final static double trimmedAcos(double x) {
if (Math.abs(x) <= 1.0d)
return Math.acos(x);
else if (x > 1.0d)
return 0.0d;
else if (x < -1.0d)
return Math.PI;
else
return Double.NaN;
}*/
/** returns max of abs(a[i]) */
final static double maxAbs(double[] a) {
double temp, max = Math.abs(a[0]);
for (int i = 1; i < a.length; i++) {
temp = Math.abs(a[i]);
if (temp > max)
max = temp;
}
return max;
}
// copy array a to array b
final static void copy(double[] a, double[] b) {
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
}
// change signs of double array values, write result to array b
final static void negative(double[] a, double[] b) {
for (int i = 0; i < a.length; i++) {
b[i] = -a[i];
}
}
// c[] = a[] / b
final static void divide(double[] a, double b, double[] c) {
for (int i = 0; i < a.length; i++) {
c[i] = a[i] / b;
}
}
// temp for buildEquation
private double[] temp;// = new double[6];
// lhs of implicit equation without constant coeff
final private StringBuilder buildImplicitVarPart(
double[] numbers,
String[] vars,
boolean KEEP_LEADING_SIGN,
boolean CANCEL_DOWN) {
temp = new double[numbers.length];
int leadingNonZero = -1;
sbBuildImplicitVarPart.setLength(0);
for (int i = 0; i < vars.length; i++) {
if (!isZero(numbers[i])) {
leadingNonZero = i;
break;
}
}
if (CANCEL_DOWN) {
// check if integers and divide through gcd
boolean allIntegers = true;
for (int i = 0; i < numbers.length; i++) {
allIntegers = allIntegers && isInteger(numbers[i]);
}
if (allIntegers) {
// divide by greates common divisor
divide(numbers, gcd(numbers), numbers);
}
}
// no left hand side
if (leadingNonZero == -1) {
sbBuildImplicitVarPart.append("0");
return sbBuildImplicitVarPart;
}
// don't change leading coefficient
if (KEEP_LEADING_SIGN) {
copy(numbers, temp);
} else {
if (numbers[leadingNonZero] < 0)
negative(numbers, temp);
else
copy(numbers, temp);
}
// BUILD EQUATION STRING
// valid left hand side
// leading coefficient
String strCoeff = formatCoeff(temp[leadingNonZero]);
sbBuildImplicitVarPart.append(strCoeff);
sbBuildImplicitVarPart.append(vars[leadingNonZero]);
// other coefficients on lhs
String sign;
double abs;
for (int i = leadingNonZero + 1; i < vars.length; i++) {
if (temp[i] < 0.0) {
sign = " - ";
abs = -temp[i];
} else {
sign = " + ";
abs = temp[i];
}
if (abs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildImplicitVarPart.append(sign);
sbBuildImplicitVarPart.append(formatCoeff(abs));
sbBuildImplicitVarPart.append(vars[i]);
}
}
return sbBuildImplicitVarPart;
}
private StringBuilder sbBuildImplicitVarPart = new StringBuilder(80);
public final StringBuilder buildImplicitEquation(
double[] numbers,
String[] vars,
boolean KEEP_LEADING_SIGN,
boolean CANCEL_DOWN,
char op) {
sbBuildImplicitEquation.setLength(0);
Application.debug("implicit");
sbBuildImplicitEquation.append(buildImplicitVarPart(numbers, vars, KEEP_LEADING_SIGN || (op == '='), CANCEL_DOWN));
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER) {
sbBuildImplicitEquation.append(" == ");
}
else
{
sbBuildImplicitEquation.append(' ');
sbBuildImplicitEquation.append(op);
sbBuildImplicitEquation.append(' ');
}
// temp is set by buildImplicitVarPart
sbBuildImplicitEquation.append(format(-temp[vars.length]));
return sbBuildImplicitEquation;
}
private StringBuilder sbBuildImplicitEquation = new StringBuilder(80);
// lhs of lhs = 0
final public StringBuilder buildLHS(double[] numbers, String[] vars, boolean KEEP_LEADING_SIGN, boolean CANCEL_DOWN) {
sbBuildLHS.setLength(0);
sbBuildLHS.append(buildImplicitVarPart(numbers, vars, KEEP_LEADING_SIGN, CANCEL_DOWN));
// add constant coeff
double coeff = temp[vars.length];
if (Math.abs(coeff) >= PRINT_PRECISION || useSignificantFigures) {
sbBuildLHS.append(' ');
sbBuildLHS.append(sign(coeff));
sbBuildLHS.append(' ');
sbBuildLHS.append(format(Math.abs(coeff)));
}
return sbBuildLHS;
}
private StringBuilder sbBuildLHS = new StringBuilder(80);
// form: y� = f(x) (coeff of y = 0)
final StringBuilder buildExplicitConicEquation(
double[] numbers,
String[] vars,
int pos,
boolean KEEP_LEADING_SIGN) {
// y�-coeff is 0
double d, dabs, q = numbers[pos];
// coeff of y� is 0 or coeff of y is not 0
if (isZero(q))
return buildImplicitEquation(numbers, vars, KEEP_LEADING_SIGN, true, '=');
int i, leadingNonZero = numbers.length;
for (i = 0; i < numbers.length; i++) {
if (i != pos
&& // except y� coefficient
(Math.abs(numbers[i]) >= PRINT_PRECISION || useSignificantFigures)) {
leadingNonZero = i;
break;
}
}
// BUILD EQUATION STRING
sbBuildExplicitConicEquation.setLength(0);
sbBuildExplicitConicEquation.append(vars[pos]);
sbBuildExplicitConicEquation.append(" = ");
if (leadingNonZero == numbers.length) {
sbBuildExplicitConicEquation.append("0");
return sbBuildExplicitConicEquation;
} else if (leadingNonZero == numbers.length - 1) {
// only constant coeff
d = -numbers[leadingNonZero] / q;
sbBuildExplicitConicEquation.append(format(d));
return sbBuildExplicitConicEquation;
} else {
// leading coeff
d = -numbers[leadingNonZero] / q;
sbBuildExplicitConicEquation.append(formatCoeff(d));
sbBuildExplicitConicEquation.append(vars[leadingNonZero]);
// other coeffs
for (i = leadingNonZero + 1; i < vars.length; i++) {
if (i != pos) {
d = -numbers[i] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(sign(d));
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(formatCoeff(dabs));
sbBuildExplicitConicEquation.append(vars[i]);
}
}
}
// constant coeff
d = -numbers[i] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(sign(d));
sbBuildExplicitConicEquation.append(' ');
sbBuildExplicitConicEquation.append(format(dabs));
}
//Application.debug(sbBuildExplicitConicEquation.toString());
return sbBuildExplicitConicEquation;
}
}
private StringBuilder sbBuildExplicitConicEquation = new StringBuilder(80);
// y = k x + d
final StringBuilder buildExplicitLineEquation(
double[] numbers,
String[] vars,
char op) {
double d, dabs, q = numbers[1];
sbBuildExplicitLineEquation.setLength(0);
// BUILD EQUATION STRING
// special case
// y-coeff is 0: form x = constant
if (isZero(q)) {
sbBuildExplicitLineEquation.append("x");
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER) {
sbBuildExplicitLineEquation.append(" == ");
}
else {
sbBuildExplicitLineEquation.append(' ');
if(numbers[0]<Kernel.MIN_PRECISION){
op = oppositeSign(op);
}
sbBuildExplicitLineEquation.append(op);
sbBuildExplicitLineEquation.append(' ');
}
sbBuildExplicitLineEquation.append(format(-numbers[2] / numbers[0]));
return sbBuildExplicitLineEquation;
}
// standard case: y-coeff not 0
sbBuildExplicitLineEquation.append("y");
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER) {
sbBuildExplicitLineEquation.append(" == ");
}
else {
sbBuildExplicitLineEquation.append(' ');
if(numbers[1] <Kernel.MIN_PRECISION){
op = oppositeSign(op);
}
sbBuildExplicitLineEquation.append(op);
sbBuildExplicitLineEquation.append(' ');
}
// x coeff
d = -numbers[0] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitLineEquation.append(formatCoeff(d));
sbBuildExplicitLineEquation.append('x');
// constant
d = -numbers[2] / q;
dabs = Math.abs(d);
if (dabs >= PRINT_PRECISION || useSignificantFigures) {
sbBuildExplicitLineEquation.append(' ');
sbBuildExplicitLineEquation.append(sign(d));
sbBuildExplicitLineEquation.append(' ');
sbBuildExplicitLineEquation.append(format(dabs));
}
} else {
// only constant
sbBuildExplicitLineEquation.append(format(-numbers[2] / q));
}
return sbBuildExplicitLineEquation;
}
/**
* Inverts the > or < sign
* @param op =,<,>,\u2264 or \u2265
* @return opposite sign
*/
public static char oppositeSign(char op) {
switch(op) {
case '=':return '=';
case '<':return '>';
case '>':return '<';
case '\u2264': return '\u2265';
case '\u2265': return '\u2264';
default: return '?'; //should never happen
}
}
private StringBuilder sbBuildExplicitLineEquation = new StringBuilder(50);
/*
final private String formatAbs(double x) {
if (isZero(x))
return "0";
else
return formatNF(Math.abs(x));
}*/
/** doesn't show 1 or -1 */
final private String formatCoeff(double x) {
if (Math.abs(x) == 1.0) {
if (x > 0.0)
return "";
else
return "-";
} else {
String numberStr = format(x);
if (casPrintForm == ExpressionNode.STRING_TYPE_MATH_PIPER)
return numberStr + "*";
else {
// standard case
return numberStr;
}
}
}
////////////////////////////////////////////////
// FORMAT FOR NUMBERS
////////////////////////////////////////////////
public double axisNumberDistance(double units, NumberFormat numberFormat){
// calc number of digits
int exp = (int) Math.floor(Math.log(units) / Math.log(10));
int maxFractionDigtis = Math.max(-exp, getPrintDecimals());
// format the numbers
if (numberFormat instanceof DecimalFormat)
((DecimalFormat) numberFormat).applyPattern("###0.##");
numberFormat.setMaximumFractionDigits(maxFractionDigtis);
// calc the distance
double pot = Math.pow(10, exp);
double n = units / pot;
double distance;
if (n > 5) {
distance = 5 * pot;
} else if (n > 2) {
distance = 2 * pot;
} else {
distance = pot;
}
return distance;
}
private StringBuilder formatSB;
/**
* Formats the value of x using the currently set
* NumberFormat or ScientificFormat. This method also
* takes getCasPrintForm() into account.
*
* converts to localised digits if appropriate
*/
final public String format(double x) {
if (Application.unicodeZero != '0') {
String num = formatRaw(x);
return internationalizeDigits(num);
} else return formatRaw(x);
}
/*
* swaps the digits in num to the current locale's
*/
public String internationalizeDigits(String num) {
if (formatSB == null) formatSB = new StringBuilder(17);
else formatSB.setLength(0);
boolean reverseOrder = app.isRightToLeftDigits();
int length = num.length();
for (int i = 0 ; i < num.length() ; i++) {
char c = num.charAt(i);
//char c = reverseOrder ? num.charAt(length - 1 - i) : num.charAt(i);
if (c == '.') c = Application.unicodeDecimalPoint;
else if (c >= '0' && c <= '9') {
c += Application.unicodeZero - '0'; // convert to eg Arabic Numeral
}
// make sure the minus is treated as part of the number in eg Arabic
if ( reverseOrder && c=='-'){
formatSB.append(Unicode.RightToLeftMark);
formatSB.append(c);
formatSB.append(Unicode.RightToLeftMark);
}
else
formatSB.append(c);
}
return formatSB.toString();
}
/**
* Formats the value of x using the currently set
* NumberFormat or ScientificFormat. This method also
* takes getCasPrintForm() into account.
*/
final public String formatRaw(double x) {
switch (casPrintForm) {
// number formatting for XML string output
case ExpressionNode.STRING_TYPE_GEOGEBRA_XML:
return Double.toString(x);
// number formatting for CAS
case ExpressionNode.STRING_TYPE_MATH_PIPER:
case ExpressionNode.STRING_TYPE_JASYMCA:
case ExpressionNode.STRING_TYPE_MAXIMA:
if (Double.isNaN(x))
return " 1/0 ";
else if (Double.isInfinite(x)) {
if (casPrintForm == ExpressionNode.STRING_TYPE_MAXIMA) return (x<0) ? "-infinity" : "infinity";
return Double.toString(x); // "Infinity" or "-Infinity"
}
else {
double abs = Math.abs(x);
// number small enough that Double.toString() won't create E notation
if (abs >= 10E-3 && abs < 10E7) {
long round = Math.round(x);
if (x == round) {
return Long.toString(round);
} else {
return Double.toString(x);
}
}
// number would produce E notation with Double.toString()
else {
// convert scientific notation 1.0E-20 to 1*10^(-20)
String scientificStr = Double.toString(x);
StringBuilder sb = new StringBuilder(scientificStr.length() * 2);
boolean Efound = false;
for (int i=0; i < scientificStr.length(); i++) {
char ch = scientificStr.charAt(i);
if (ch == 'E') {
sb.append("*10^(");
Efound = true;
} else {
sb.append(ch);
}
}
if (Efound)
sb.append(")");
// TODO: remove
//Application.printStacktrace(sb.toString());
return sb.toString();
}
}
// number formatting for screen output
default:
if (Double.isNaN(x))
return "?";
else if (Double.isInfinite(x)) {
return (x > 0) ? "\u221e" : "-\u221e"; // infinity
}
else if (x == Math.PI) {
return casPrintFormPI;
}
// ROUNDING hack
// NumberFormat and SignificantFigures use ROUND_HALF_EVEN as
// default which is not changeable, so we need to hack this
// to get ROUND_HALF_UP like in schools: increase abs(x) slightly
// x = x * ROUND_HALF_UP_FACTOR;
// We don't do this for large numbers as
double abs = Math.abs(x);
if (abs < 10E7) {
// increase abs(x) slightly to round up
x = x * ROUND_HALF_UP_FACTOR;
}
if (useSignificantFigures) {
return formatSF(x);
} else {
return formatNF(x);
}
}
}
/**
* Uses current NumberFormat nf to format a number.
*/
final private String formatNF(double x) {
// "<=" catches -0.0000000000000005
// should be rounded to -0.000000000000001 (15 d.p.)
// but nf.format(x) returns "-0"
if (-PRINT_PRECISION / 2 <= x && x < PRINT_PRECISION / 2) {
// avoid output of "-0" for eg -0.0004
return "0";
} else {
// standard case
return nf.format(x);
}
}
/**
* Uses current ScientificFormat sf to format a number. Makes sure ".123" is
* returned as "0.123".
*/
final private String formatSF(double x) {
if (sbFormatSF == null)
sbFormatSF = new StringBuilder();
else
sbFormatSF.setLength(0);
// get scientific format
String absStr;
if (x == 0) {
// avoid output of "-0.00"
absStr = sf.format(0);
}
else if (x > 0) {
absStr = sf.format(x);
}
else {
sbFormatSF.append('-');
absStr = sf.format(-x);
}
// make sure ".123" is returned as "0.123".
if (absStr.charAt(0) == '.')
sbFormatSF.append('0');
sbFormatSF.append(absStr);
return sbFormatSF.toString();
}
private StringBuilder sbFormatSF;
/**
* calls formatPiERaw() and converts to localised digits if appropriate
*/
final public String formatPiE(double x, NumberFormat numF) {
if (Application.unicodeZero != '0') {
String num = formatPiERaw(x, numF);
return internationalizeDigits(num);
} else return formatPiERaw(x, numF);
}
final public String formatPiERaw(double x, NumberFormat numF) {
// PI
if (x == Math.PI) {
return casPrintFormPI;
}
// MULTIPLES OF PI/2
// i.e. x = a * pi/2
double a = 2*x / Math.PI;
int aint = (int) Math.round(a);
if (sbFormat == null)
sbFormat = new StringBuilder();
sbFormat.setLength(0);
if (isEqual(a, aint, STANDARD_PRECISION)) {
switch (aint) {
case 0:
return "0";
case 1: // pi/2
sbFormat.append(casPrintFormPI);
sbFormat.append("/2");
return sbFormat.toString();
case -1: // -pi/2
sbFormat.append('-');
sbFormat.append(casPrintFormPI);
sbFormat.append("/2");
return sbFormat.toString();
case 2: // 2pi/2 = pi
return casPrintFormPI;
case -2: // -2pi/2 = -pi
sbFormat.append('-');
sbFormat.append(casPrintFormPI);
return sbFormat.toString();
default:
// even
long half = aint / 2;
if (aint == 2 * half) {
// half * pi
sbFormat.append(half);
if (casPrintForm != ExpressionNode.STRING_TYPE_GEOGEBRA)
sbFormat.append("*");
sbFormat.append(casPrintFormPI);
return sbFormat.toString();
}
// odd
else {
// aint * pi/2
sbFormat.append(aint);
if (casPrintForm != ExpressionNode.STRING_TYPE_GEOGEBRA)
sbFormat.append("*");
sbFormat.append(casPrintFormPI);
sbFormat.append("/2");
return sbFormat.toString();
}
}
}
// STANDARD CASE
// use numberformat to get number string
// checkDecimalFraction() added to avoid 2.19999999999999 when set to 15dp
String str = numF.format(checkDecimalFraction(x));
sbFormat.append(str);
// if number is in scientific notation and ends with "E0", remove this
if (str.endsWith("E0"))
sbFormat.setLength(sbFormat.length() - 2);
return sbFormat.toString();
}
private StringBuilder sbFormat;
final public String formatSignedCoefficient(double x) {
if (x == -1.0)
return "- ";
if (x == 1.0)
return "+ ";
return formatSigned(x).toString();
}
final public StringBuilder formatSigned(double x) {
sbFormatSigned.setLength(0);
if (x >= 0.0d) {
sbFormatSigned.append("+ ");
sbFormatSigned.append( format(x));
return sbFormatSigned;
} else {
sbFormatSigned.append("- ");
sbFormatSigned.append( format(-x));
return sbFormatSigned;
}
}
private StringBuilder sbFormatSigned = new StringBuilder(40);
final public StringBuilder formatAngle(double phi) {
// STANDARD_PRECISION * 10 as we need a little leeway as we've converted from radians
return formatAngle(phi, 10);
}
final public StringBuilder formatAngle(double phi, double precision) {
sbFormatAngle.setLength(0);
switch (casPrintForm) {
case ExpressionNode.STRING_TYPE_MATH_PIPER:
case ExpressionNode.STRING_TYPE_JASYMCA:
if (angleUnit == ANGLE_DEGREE) {
sbFormatAngle.append("(");
// STANDARD_PRECISION * 10 as we need a little leeway as we've converted from radians
sbFormatAngle.append(format(checkDecimalFraction(Math.toDegrees(phi), precision)));
sbFormatAngle.append("*");
sbFormatAngle.append("\u00b0");
sbFormatAngle.append(")");
} else {
sbFormatAngle.append(format(phi));
}
return sbFormatAngle;
default:
// STRING_TYPE_GEOGEBRA_XML
// STRING_TYPE_GEOGEBRA
if (Double.isNaN(phi)) {
sbFormatAngle.append("?");
return sbFormatAngle;
}
if (angleUnit == ANGLE_DEGREE) {
phi = Math.toDegrees(phi);
if (phi < 0)
phi += 360;
else if (phi > 360)
phi = phi % 360;
// STANDARD_PRECISION * 10 as we need a little leeway as we've converted from radians
sbFormatAngle.append(format(checkDecimalFraction(phi, precision)));
if (casPrintForm == ExpressionNode.STRING_TYPE_GEOGEBRA_XML) {
sbFormatAngle.append("*");
}
sbFormatAngle.append('\u00b0');
return sbFormatAngle;
}
else {
// RADIANS
sbFormatAngle.append(format(phi));
if (casPrintForm != ExpressionNode.STRING_TYPE_GEOGEBRA_XML) {
sbFormatAngle.append(" rad");
}
return sbFormatAngle;
}
}
}
private StringBuilder sbFormatAngle = new StringBuilder(40);
final private static char sign(double x) {
if (x > 0)
return '+';
else
return '-';
}
/**
* greatest common divisor
*/
final public static long gcd(long m, long n) {
// Return the GCD of positive integers m and n.
if (m == 0 || n == 0)
return Math.max(Math.abs(m), Math.abs(n));
long p = m, q = n;
while (p % q != 0) {
long r = p % q;
p = q;
q = r;
}
return q;
}
/**
* Compute greatest common divisor of given doubles.
* Note: all double values are cast to long.
*/
final public static double gcd(double[] numbers) {
long gcd = (long) numbers[0];
for (int i = 0; i < numbers.length; i++) {
gcd = gcd((long) numbers[i], gcd);
}
return Math.abs(gcd);
}
/**
* Round a double to the given scale
* e.g. roundToScale(5.32, 1) = 5.0,
* roundToScale(5.32, 0.5) = 5.5,
* roundToScale(5.32, 0.25) = 5.25,
* roundToScale(5.32, 0.1) = 5.3
*/
final public static double roundToScale(double x, double scale) {
if (scale == 1.0)
return Math.round(x);
else {
return Math.round(x / scale) * scale;
}
}
/**
* Checks if x is close (Kernel.MIN_PRECISION) to a decimal fraction,
* eg 2.800000000000001. If it is, the decimal fraction eg 2.8 is returned,
* otherwise x is returned.
*/
/**
* Checks if x is close (Kernel.MIN_PRECISION) to a decimal fraction, eg
* 2.800000000000001. If it is, the decimal fraction eg 2.8 is returned,
* otherwise x is returned.
*/
final public double checkDecimalFraction(double x, double precision) {
//Application.debug(precision+" ");
precision = Math.pow(10, Math.floor(Math.log(Math.abs(precision))/Math.log(10)));
double fracVal = x * INV_MIN_PRECISION;
double roundVal = Math.round(fracVal);
//Application.debug(precision+" "+x+" "+fracVal+" "+roundVal+" "+isEqual(fracVal, roundVal, precision)+" "+roundVal / INV_MIN_PRECISION);
if (isEqual(fracVal, roundVal, STANDARD_PRECISION * precision))
return roundVal / INV_MIN_PRECISION;
else
return x;
}
final public double checkDecimalFraction(double x) {
return checkDecimalFraction(x, 1);
}
/**
* Checks if x is very close (1E-8) to an integer. If it is,
* the integer value is returned, otherwise x is returnd.
*/
final public double checkInteger(double x) {
double roundVal = Math.round(x);
if (Math.abs(x - roundVal) < EPSILON)
return roundVal;
else
return x;
}
/*******************************************************
* SAVING
*******************************************************/
private boolean isSaving;
public synchronized boolean isSaving() {
return isSaving;
}
public synchronized void setSaving(boolean saving) {
isSaving = saving;
}
/**
* Returns the kernel settings in XML format.
*/
public void getKernelXML(StringBuilder sb) {
// kernel settings
sb.append("<kernel>\n");
// continuity: true or false, since V3.0
sb.append("\t<continuous val=\"");
sb.append(isContinuous());
sb.append("\"/>\n");
if (useSignificantFigures) {
// significant figures
sb.append("\t<significantfigures val=\"");
sb.append(getPrintFigures());
sb.append("\"/>\n");
}
else
{
// decimal places
sb.append("\t<decimals val=\"");
sb.append(getPrintDecimals());
sb.append("\"/>\n");
}
// angle unit
sb.append("\t<angleUnit val=\"");
sb.append(angleUnit == Kernel.ANGLE_RADIANT ? "radiant" : "degree");
sb.append("\"/>\n");
// algebra style
sb.append("\t<algebraStyle val=\"");
sb.append(algebraStyle);
sb.append("\"/>\n");
// coord style
sb.append("\t<coordStyle val=\"");
sb.append(getCoordStyle());
sb.append("\"/>\n");
// animation
if (isAnimationRunning()) {
sb.append("\t<startAnimation val=\"");
sb.append(isAnimationRunning());
sb.append("\"/>\n");
}
sb.append("</kernel>\n");
}
public boolean isTranslateCommandName() {
return translateCommandName;
}
public void setTranslateCommandName(boolean b) {
translateCommandName = b;
}
/**
* States whether the continuity heuristic is active.
*/
final public boolean isContinuous() {
return continuous;
}
/**
* Turns the continuity heuristic on or off.
* Note: the macro kernel always turns continuity off.
*/
public void setContinuous(boolean continuous) {
this.continuous = continuous;
}
public final boolean isAllowVisibilitySideEffects() {
return allowVisibilitySideEffects;
}
public final void setAllowVisibilitySideEffects(
boolean allowVisibilitySideEffects) {
this.allowVisibilitySideEffects = allowVisibilitySideEffects;
}
public boolean isMacroKernel() {
return false;
}
private AnimationManager animationManager;
final public AnimationManager getAnimatonManager() {
if (animationManager == null) {
animationManager = new AnimationManager(this);
}
return animationManager;
}
final public boolean isAnimationRunning() {
return animationManager != null && animationManager.isRunning();
}
final public boolean isAnimationPaused() {
return animationManager != null && animationManager.isPaused();
}
final public boolean needToShowAnimationButton() {
return animationManager != null && animationManager.needToShowAnimationButton();
}
final public void udpateNeedToShowAnimationButton() {
if (animationManager != null)
animationManager.updateNeedToShowAnimationButton();
}
/**
* Turns silent mode on (true) or off (false). In silent mode, commands can
* be used to create objects without any side effects, i.e.
* no labels are created, algorithms are not added to the construction
* list and the views are not notified about new objects.
*/
public final void setSilentMode(boolean silentMode) {
this.silentMode = silentMode;
// no new labels, no adding to construction list
cons.setSuppressLabelCreation(silentMode);
// no notifying of views
//ggb3D - 2009-07-17
//removing :
//notifyViewsActive = !silentMode;
//(seems not to work with loading files)
//Application.printStacktrace(""+silentMode);
}
/**
* Returns whether silent mode is turned on.
* @see setSilentMode()
*/
public final boolean isSilentMode() {
return silentMode;
}
/**
* Sets whether unknown variables should be resolved as GeoDummyVariable objects.
*/
public final void setResolveUnkownVarsAsDummyGeos(boolean resolveUnkownVarsAsDummyGeos) {
this.resolveUnkownVarsAsDummyGeos = resolveUnkownVarsAsDummyGeos;
}
/**
* Returns whether unkown variables are resolved as GeoDummyVariable objects.
* @see setSilentMode()
*/
public final boolean isResolveUnkownVarsAsDummyGeos() {
return resolveUnkownVarsAsDummyGeos;
}
final public static String defaultLibraryJavaScript = "function ggbOnInit() {}";
String libraryJavaScript = defaultLibraryJavaScript;
public void setLibraryJavaScript(String str) {
Application.debug(str);
libraryJavaScript = str;
//libraryJavaScript = "function ggbOnInit() {ggbApplet.evalCommand('A=(1,2)');ggbApplet.registerObjectUpdateListener('A','listener');}function listener() {//java.lang.System.out.println('add listener called'); var x = ggbApplet.getXcoord('A');var y = ggbApplet.getYcoord('A');var len = Math.sqrt(x*x + y*y);if (len > 5) { x=x*5/len; y=y*5/len; }ggbApplet.unregisterObjectUpdateListener('A');ggbApplet.setCoords('A',x,y);ggbApplet.registerObjectUpdateListener('A','listener');}";
//libraryJavaScript = "function ggbOnInit() {ggbApplet.evalCommand('A=(1,2)');}";
}
//public String getLibraryJavaScriptXML() {
// return Util.encodeXML(libraryJavaScript);
//}
public String getLibraryJavaScript() {
return libraryJavaScript;
}
/** return all points of the current construction */
public TreeSet getPointSet(){
return getConstruction().getGeoSetLabelOrder(GeoElement.GEO_CLASS_POINT);
}
/**
* test kernel
*/
public static void mainx(String [] args) {
// create kernel with null application for testing
Kernel kernel = new Kernel(null);
Construction cons = kernel.getConstruction();
// create points A and B
GeoPoint A = new GeoPoint(cons, "A", 0, 1, 1);
GeoPoint B = new GeoPoint(cons, "B", 3, 4, 1);
// create line g through points A and B
GeoLine g = kernel.Line("g", A, B);
// print current objects
System.out.println(A);
System.out.println(B);
System.out.println(g);
// change B
B.setCoords(3, 2, 1);
B.updateCascade();
// print current objects
System.out.println("changed " +B);
System.out.println(g);
}
final public GeoNumeric convertIndexToNumber(String str) {
int i = 0;
char c;
while (i < str.length() && !Unicode.isSuperscriptDigit(str.charAt(i)))
i++;
//Application.debug(str.substring(i, str.length() - 1));
MyDouble md = new MyDouble(this, str.substring(i, str.length() - 1)); // strip off eg "sin" at start, "(" at end
GeoNumeric num = new GeoNumeric(getConstruction(), md.getDouble());
return num;
}
final public ExpressionNode handleTrigPower(String image, ExpressionNode en, int type) {
// sin^(-1)(x) -> ArcSin(x)
if (image.indexOf(Unicode.Superscript_Minus) > -1) {
//String check = ""+Unicode.Superscript_Minus + Unicode.Superscript_1 + '(';
if (image.substring(3, 6).equals(Unicode.superscriptMinusOneBracket)) {
switch (type) {
case ExpressionNode.SIN:
return new ExpressionNode(this, en, ExpressionNode.ARCSIN, null);
case ExpressionNode.COS:
return new ExpressionNode(this, en, ExpressionNode.ARCCOS, null);
case ExpressionNode.TAN:
return new ExpressionNode(this, en, ExpressionNode.ARCTAN, null);
default:
throw new Error("Inverse not supported for trig function"); // eg csc^-1(x)
}
}
else throw new Error("Bad index for trig function"); // eg sin^-2(x)
}
return new ExpressionNode(this, new ExpressionNode(this, en, type, null), ExpressionNode.POWER, convertIndexToNumber(image));
}
///////////////////////////////////////////
// CHANGING TYPE OF A GEO (mathieu)
///////////////////////////////////////////
/**
* @return possible alternatives for a given geo (e.g. number -> complex)
*/
public GeoElement[] getAlternatives(GeoElement geo){
return geo.getAlternatives();
}
}
|
diff --git a/src/engine/render/Shader.java b/src/engine/render/Shader.java
index c2a7f02..8ec1276 100644
--- a/src/engine/render/Shader.java
+++ b/src/engine/render/Shader.java
@@ -1,304 +1,304 @@
package engine.render;
import engine.resource.Resource;
import engine.utils.DomTools;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBFragmentShader;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.ARBVertexShader;
import com.bulletphysics.linearmath.Transform;
import engine.entity.Entity;
import engine.render.ubos.Light;
import engine.render.ubos.TransformationMatrices;
import engine.render.ubos.UBOInterface;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class Shader implements Resource{
/*
* if the shaders are setup ok we can use shaders, otherwise we just
* use default settings
*/
private boolean useShader=false;
/*
* program shader, to which is attached a vertex and fragment shaders.
* They are set to 0 as a check because GL will assign unique int
* values to each
*/
private int shader=0;
private int vertShader=0;
private int fragShader=0;
private HashMap<String, UBO> ubo_interfaces;
private FloatBuffer buf;
public Shader() {
}
public Shader(Shader shader) {
this.vertShader = shader.vertShader;
this.fragShader = shader.fragShader;
this.shader = shader.shader;
this.useShader = shader.useShader;
}
public void addUBO(UBOInterface ubo_data) {
//create a UBO from our ubo interface
UBO ubo = new UBO(this, ubo_data);
//put it in the ubo array for usage later
ubo_interfaces.put(ubo_data.getName(), ubo);
}
/*
* With the exception of syntax, setting up vertex and fragment shaders
* is the same.
* @param the name and path to the vertex shader
*/
private int createVertShader(Document dom){
//vertShader will be non zero if successfully created
vertShader=ARBShaderObjects.glCreateShaderObjectARB(ARBVertexShader.GL_VERTEX_SHADER_ARB);
//if created, convert the vertex shader code to a String
String vertexCode;
if(vertShader==0){return 0;}
vertexCode = DomTools.findChildrenByName(dom.getDocumentElement(), "vertex").get(0).getTextContent();
/*
* associate the vertex code String with the created vertex shader
* and compile
*/
ARBShaderObjects.glShaderSourceARB(vertShader, vertexCode);
ARBShaderObjects.glCompileShaderARB(vertShader);
//if there was a problem compiling, reset vertShader to zero
if(!printLogInfo(vertShader)){
System.out.println("ERROR [vertshader id:" + vertShader + "]:\n" + vertexCode);
vertShader=0;
}
//if zero we won't be using the shader
return vertShader;
}
//same as per the vertex shader except for method syntax
private int createFragShader(Document dom){
//fragShader will be non zero if successfully created
fragShader=ARBShaderObjects.glCreateShaderObjectARB(ARBFragmentShader.GL_FRAGMENT_SHADER_ARB);
//if created, convert the vertex shader code to a String
String fragCode;
if(fragShader==0){return 0;}
fragCode = DomTools.findChildrenByName(dom.getDocumentElement(), "fragment").get(0).getTextContent();
/*
* associate the vertex code String with the created vertex shader
* and compile
*/
ARBShaderObjects.glShaderSourceARB(fragShader, fragCode);
ARBShaderObjects.glCompileShaderARB(fragShader);
//if there was a problem compiling, reset vertShader to zero
if(!printLogInfo(fragShader)){
System.out.println("ERROR [fragshader id:" + fragShader + "]:\n" + fragCode);
fragShader=0;
}
//if zero we won't be using the shader
return fragShader;
}
/*
* If the shader was setup successfully, we use the shader. Otherwise
* we run normal drawing code.
*/
public void startShader(int vbo_id, Entity ent){
if(useShader) {
//Adjust the position and rotation of the object from physics
Transform transform_matrix = new Transform();
transform_matrix = ent.getCollisionObject().getWorldTransform(new Transform());
float[] body_matrix = new float[16];
transform_matrix.getOpenGLMatrix(body_matrix);
buf.put(body_matrix);
buf.flip();
//*****UBO setup*****//
//world space transform
ARBShaderObjects.glUseProgramObjectARB(shader);
int transform = ARBShaderObjects.glGetUniformLocationARB(shader, "transform");
ARBShaderObjects.glUniformMatrix4ARB(transform, false, buf);
//world space scale op
buf.clear();
Vector3f scalevec = ent.getCollisionObject().getCollisionShape().getLocalScaling(new Vector3f());
buf.put(scalevec.x);
buf.put(scalevec.y);
buf.put(scalevec.z);
buf.put(1.0f);
buf.flip();
int scale = ARBShaderObjects.glGetUniformLocationARB(shader, "scale");
ARBShaderObjects.glUniform4ARB(scale, buf);
//parse material and light uniforms
for(UBO ubo: ubo_interfaces.values()) {
ubo.bufferData(shader);
}
buf.clear();
}
}
public void stopShader() {
if(useShader) {
//release the shader
ARBShaderObjects.glUseProgramObjectARB(0);
}
}
/*
* oddly enough, checking the success when setting up the shaders is
* verbose upon success. If the reference iVal becomes greater
* than 1, the setup being examined (obj) has been successful, the
* information gets printed to System.out, and true is returned.
*/
private static boolean printLogInfo(int obj){
IntBuffer iVal = BufferUtils.createIntBuffer(1);
ARBShaderObjects.glGetObjectParameterARB(
obj,
ARBShaderObjects.GL_OBJECT_INFO_LOG_LENGTH_ARB,
iVal
);
int length = iVal.get();
// We have some info we need to output.
if(length == 1) {
return true;
} else {
ByteBuffer infoLog = BufferUtils.createByteBuffer(length);
iVal.flip();
ARBShaderObjects.glGetInfoLogARB(obj, iVal, infoLog);
byte[] infoBytes = new byte[length];
infoLog.get(infoBytes);
String out = new String(infoBytes);
System.out.println("Info log:\n"+out);
return false;
}
}
protected String getShaderText(InputStream in, String tag_name) {
String vertexCode="";
String line;
try{
InputStreamReader is = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(is);
while((line=reader.readLine())!=null){
vertexCode+=line + "\n";
}
}catch(Exception e){
System.out.println("Failed to read " + tag_name + " shading code: " + in.toString());
return "";
}
return vertexCode;
}
public int getShaderID() {
return shader;
}
@Override
public void loadFromFile(InputStream is) throws Exception {
ubo_interfaces = new HashMap<String, UBO>();
/*
* create the shader program. If OK, create vertex
* and fragment shaders
*/
shader=ARBShaderObjects.glCreateProgramObjectARB();
if(shader!=0){
Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// Create Dom Structure
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(is);
vertShader=createVertShader(dom);
fragShader=createFragShader(dom);
} else {
useShader=false;
}
/*
* if the vertex and fragment shaders setup sucessfully,
* attach them to the shader program, link the shader program
* (into the GL context I suppose), and validate
*/
if(vertShader != 0 && fragShader != 0){
ARBShaderObjects.glAttachObjectARB(shader, vertShader);
ARBShaderObjects.glAttachObjectARB(shader, fragShader);
ARBShaderObjects.glLinkProgramARB(shader);
ARBShaderObjects.glValidateProgramARB(shader);
useShader=printLogInfo(shader);
buf = BufferUtils.createFloatBuffer(16);
} else {
useShader=false;
System.out.println("Failed to create shader");
System.out.println("\tvertShader: " + vertShader + " && fragShader: " + fragShader);
}
UBO light = new UBO(
this,
new Light(
new Vector4f(0.0f,10.0f,0.0f,1.0f),
- new Vector4f(100.0f,100.0f,100.0f,255.0f),
- new Vector4f(30.0f,30.0f,30.0f,255.0f),
- new Vector4f(30.0f,30.0f,30.0f,255.0f),
- 0.1f,
- 0.1f,
+ new Vector4f(50.0f,50.0f,50.0f,255.0f),
+ new Vector4f(255.0f,0.0f,0.0f,255.0f),
+ new Vector4f(255.0f,0.0f,0.0f,255.0f),
+ 1.0f,
+ 1.0f,
1.0f,
new Vector3f(0.0f,-1.0f,0.0f),
- 1000.0f,
+ 10.0f,
1.0f
)
);
ubo_interfaces.put("light",light);
UBO transformation_matrices = new UBO(
this,
new TransformationMatrices(
45f,
1f,
0.1f,
1000f,
new Vector3f(0,0,-25),
new Vector3f(0,0,0),
new Vector3f(0,1,0)
)
);
ubo_interfaces.put("projection",transformation_matrices);
}
@Override
public String toXML() {
// TODO Auto-generated method stub
return null;
}
}
| false | true | public void loadFromFile(InputStream is) throws Exception {
ubo_interfaces = new HashMap<String, UBO>();
/*
* create the shader program. If OK, create vertex
* and fragment shaders
*/
shader=ARBShaderObjects.glCreateProgramObjectARB();
if(shader!=0){
Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// Create Dom Structure
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(is);
vertShader=createVertShader(dom);
fragShader=createFragShader(dom);
} else {
useShader=false;
}
/*
* if the vertex and fragment shaders setup sucessfully,
* attach them to the shader program, link the shader program
* (into the GL context I suppose), and validate
*/
if(vertShader != 0 && fragShader != 0){
ARBShaderObjects.glAttachObjectARB(shader, vertShader);
ARBShaderObjects.glAttachObjectARB(shader, fragShader);
ARBShaderObjects.glLinkProgramARB(shader);
ARBShaderObjects.glValidateProgramARB(shader);
useShader=printLogInfo(shader);
buf = BufferUtils.createFloatBuffer(16);
} else {
useShader=false;
System.out.println("Failed to create shader");
System.out.println("\tvertShader: " + vertShader + " && fragShader: " + fragShader);
}
UBO light = new UBO(
this,
new Light(
new Vector4f(0.0f,10.0f,0.0f,1.0f),
new Vector4f(100.0f,100.0f,100.0f,255.0f),
new Vector4f(30.0f,30.0f,30.0f,255.0f),
new Vector4f(30.0f,30.0f,30.0f,255.0f),
0.1f,
0.1f,
1.0f,
new Vector3f(0.0f,-1.0f,0.0f),
1000.0f,
1.0f
)
);
ubo_interfaces.put("light",light);
UBO transformation_matrices = new UBO(
this,
new TransformationMatrices(
45f,
1f,
0.1f,
1000f,
new Vector3f(0,0,-25),
new Vector3f(0,0,0),
new Vector3f(0,1,0)
)
);
ubo_interfaces.put("projection",transformation_matrices);
}
| public void loadFromFile(InputStream is) throws Exception {
ubo_interfaces = new HashMap<String, UBO>();
/*
* create the shader program. If OK, create vertex
* and fragment shaders
*/
shader=ARBShaderObjects.glCreateProgramObjectARB();
if(shader!=0){
Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// Create Dom Structure
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(is);
vertShader=createVertShader(dom);
fragShader=createFragShader(dom);
} else {
useShader=false;
}
/*
* if the vertex and fragment shaders setup sucessfully,
* attach them to the shader program, link the shader program
* (into the GL context I suppose), and validate
*/
if(vertShader != 0 && fragShader != 0){
ARBShaderObjects.glAttachObjectARB(shader, vertShader);
ARBShaderObjects.glAttachObjectARB(shader, fragShader);
ARBShaderObjects.glLinkProgramARB(shader);
ARBShaderObjects.glValidateProgramARB(shader);
useShader=printLogInfo(shader);
buf = BufferUtils.createFloatBuffer(16);
} else {
useShader=false;
System.out.println("Failed to create shader");
System.out.println("\tvertShader: " + vertShader + " && fragShader: " + fragShader);
}
UBO light = new UBO(
this,
new Light(
new Vector4f(0.0f,10.0f,0.0f,1.0f),
new Vector4f(50.0f,50.0f,50.0f,255.0f),
new Vector4f(255.0f,0.0f,0.0f,255.0f),
new Vector4f(255.0f,0.0f,0.0f,255.0f),
1.0f,
1.0f,
1.0f,
new Vector3f(0.0f,-1.0f,0.0f),
10.0f,
1.0f
)
);
ubo_interfaces.put("light",light);
UBO transformation_matrices = new UBO(
this,
new TransformationMatrices(
45f,
1f,
0.1f,
1000f,
new Vector3f(0,0,-25),
new Vector3f(0,0,0),
new Vector3f(0,1,0)
)
);
ubo_interfaces.put("projection",transformation_matrices);
}
|
diff --git a/src/org/ohmage/service/UploadService.java b/src/org/ohmage/service/UploadService.java
index 0a89ff8..3b4a7e3 100644
--- a/src/org/ohmage/service/UploadService.java
+++ b/src/org/ohmage/service/UploadService.java
@@ -1,487 +1,487 @@
package org.ohmage.service;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import edu.ucla.cens.mobility.glue.MobilityInterface;
import edu.ucla.cens.systemlog.Analytics;
import edu.ucla.cens.systemlog.Analytics.Status;
import edu.ucla.cens.systemlog.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ohmage.Config;
import org.ohmage.NotificationHelper;
import org.ohmage.OhmageApi;
import org.ohmage.OhmageApi.Result;
import org.ohmage.SharedPreferencesHelper;
import org.ohmage.Utilities;
import org.ohmage.db.DbContract.Campaigns;
import org.ohmage.db.DbContract.PromptResponses;
import org.ohmage.db.DbContract.Responses;
import org.ohmage.db.DbContract.SurveyPrompts;
import org.ohmage.db.DbHelper;
import org.ohmage.db.DbHelper.Tables;
import org.ohmage.db.Models.Response;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class UploadService extends WakefulIntentService {
/** Extra to tell the upload service to upload mobility points */
public static final String EXTRA_UPLOAD_MOBILITY = "upload_mobility";
/** Extra to tell the upload service to upload surveys */
public static final String EXTRA_UPLOAD_SURVEYS = "upload_surveys";
/** Extra to tell the upload service if it is running in the background */
public static final String EXTRA_BACKGROUND = "is_background";
private static final String TAG = "UploadService";
public static final String MOBILITY_UPLOAD_STARTED = "org.ohmage.MOBILITY_UPLOAD_STARTED";
public static final String MOBILITY_UPLOAD_FINISHED = "org.ohmage.MOBILITY_UPLOAD_FINISHED";
private OhmageApi mApi;
public UploadService() {
super(TAG);
}
@Override
public void onCreate() {
super.onCreate();
Analytics.service(this, Status.ON);
}
@Override
public void onDestroy() {
super.onDestroy();
Analytics.service(this, Status.OFF);
}
@Override
protected void doWakefulWork(Intent intent) {
if(mApi == null)
setOhmageApi(new OhmageApi(this));
if (intent.getBooleanExtra(EXTRA_UPLOAD_SURVEYS, false)) {
uploadSurveyResponses(intent);
}
if (intent.getBooleanExtra(EXTRA_UPLOAD_MOBILITY, false)) {
uploadMobility(intent);
}
}
public void setOhmageApi(OhmageApi api) {
mApi = api;
}
private void uploadSurveyResponses(Intent intent) {
String serverUrl = Config.DEFAULT_SERVER_URL;
SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
String username = helper.getUsername();
String hashedPassword = helper.getHashedPassword();
boolean isBackground = intent.getBooleanExtra(EXTRA_BACKGROUND, false);
boolean uploadErrorOccurred = false;
boolean authErrorOccurred = false;
DbHelper dbHelper = new DbHelper(this);
Uri dataUri = intent.getData();
if(!Responses.isResponseUri(dataUri)) {
Log.e(TAG, "Upload service can only be called with a response URI");
return;
}
ContentResolver cr = getContentResolver();
String [] projection = new String [] {
Tables.RESPONSES + "." + Responses._ID,
Responses.RESPONSE_UUID,
Responses.RESPONSE_DATE,
Responses.RESPONSE_TIME,
Responses.RESPONSE_TIMEZONE,
Responses.RESPONSE_LOCATION_STATUS,
Responses.RESPONSE_LOCATION_LATITUDE,
Responses.RESPONSE_LOCATION_LONGITUDE,
Responses.RESPONSE_LOCATION_PROVIDER,
Responses.RESPONSE_LOCATION_ACCURACY,
Responses.RESPONSE_LOCATION_TIME,
Tables.RESPONSES + "." + Responses.SURVEY_ID,
Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT,
Responses.RESPONSE_JSON,
Tables.RESPONSES + "." + Responses.CAMPAIGN_URN,
Campaigns.CAMPAIGN_CREATED};
String select = Responses.RESPONSE_STATUS + "!=" + Response.STATUS_DOWNLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_UPLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_WAITING_FOR_LOCATION;
Cursor cursor = cr.query(dataUri, projection, select, null, null);
// If there is no data we should just return
if(cursor == null || !cursor.moveToFirst())
return;
ContentValues cv = new ContentValues();
cv.put(Responses.RESPONSE_STATUS, Response.STATUS_QUEUED);
cr.update(dataUri, cv, select, null);
for (int i = 0; i < cursor.getCount(); i++) {
long responseId = cursor.getLong(cursor.getColumnIndex(Responses._ID));
ContentValues values = new ContentValues();
values.put(Responses.RESPONSE_STATUS, Response.STATUS_UPLOADING);
cr.update(Responses.buildResponseUri(responseId), values, null, null);
// cr.update(Responses.CONTENT_URI, values, Tables.RESPONSES + "." + Responses._ID + "=" + responseId, null);
JSONArray responsesJsonArray = new JSONArray();
JSONObject responseJson = new JSONObject();
final ArrayList<String> photoUUIDs = new ArrayList<String>();
try {
responseJson.put("survey_key", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_UUID)));
responseJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIME)));
responseJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
String locationStatus = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_STATUS));
responseJson.put("location_status", locationStatus);
if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) {
JSONObject locationJson = new JSONObject();
locationJson.put("latitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LATITUDE)));
locationJson.put("longitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LONGITUDE)));
String provider = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_PROVIDER));
locationJson.put("provider", provider);
Log.i(TAG, "Response uploaded with " + provider + " location");
locationJson.put("accuracy", cursor.getFloat(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_ACCURACY)));
locationJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_TIME)));
- locationJson.put("timezone", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
+ locationJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
responseJson.put("location", locationJson);
} else {
Log.w(TAG, "Response uploaded without a location");
}
responseJson.put("survey_id", cursor.getString(cursor.getColumnIndex(Responses.SURVEY_ID)));
responseJson.put("survey_launch_context", new JSONObject(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT))));
responseJson.put("responses", new JSONArray(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_JSON))));
ContentResolver cr2 = getContentResolver();
Cursor promptsCursor = cr2.query(Responses.buildPromptResponsesUri(responseId), new String [] {PromptResponses.PROMPT_RESPONSE_VALUE, SurveyPrompts.SURVEY_PROMPT_TYPE}, SurveyPrompts.SURVEY_PROMPT_TYPE + "='photo'", null, null);
while (promptsCursor.moveToNext()) {
photoUUIDs.add(promptsCursor.getString(promptsCursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE)));
}
promptsCursor.close();
} catch (JSONException e) {
throw new RuntimeException(e);
}
responsesJsonArray.put(responseJson);
String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN));
String campaignCreationTimestamp = cursor.getString(cursor.getColumnIndex(Campaigns.CAMPAIGN_CREATED));
File [] photos = Response.getResponseImageUploadDir(this).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (photoUUIDs.contains(filename.split("\\.")[0])) {
return true;
}
return false;
}
});
OhmageApi.UploadResponse response = mApi.surveyUpload(serverUrl, username, hashedPassword, SharedPreferencesHelper.CLIENT_STRING, campaignUrn, campaignCreationTimestamp, responsesJsonArray.toString(), photos);
int responseStatus = Response.STATUS_UPLOADED;
if (response.getResult() == Result.SUCCESS) {
NotificationHelper.hideUploadErrorNotification(this);
NotificationHelper.hideAuthNotification(this);
} else {
responseStatus = Response.STATUS_ERROR_OTHER;
switch (response.getResult()) {
case FAILURE:
Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", "));
uploadErrorOccurred = true;
boolean isAuthenticationError = false;
boolean isUserDisabled = false;
String errorCode = null;
for (String code : response.getErrorCodes()) {
if (code.charAt(1) == '2') {
authErrorOccurred = true;
isAuthenticationError = true;
if (code.equals("0201")) {
isUserDisabled = true;
}
}
if (code.equals("0700") || code.equals("0707") || code.equals("0703") || code.equals("0710")) {
errorCode = code;
break;
}
}
if (isUserDisabled) {
new SharedPreferencesHelper(this).setUserDisabled(true);
}
if (isAuthenticationError) {
responseStatus = Response.STATUS_ERROR_AUTHENTICATION;
} else if ("0700".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_CAMPAIGN_NO_EXIST;
} else if ("0707".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_INVALID_USER_ROLE;
} else if ("0703".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_CAMPAIGN_STOPPED;
} else if ("0710".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE;
} else {
responseStatus = Response.STATUS_ERROR_OTHER;
}
break;
case INTERNAL_ERROR:
uploadErrorOccurred = true;
responseStatus = Response.STATUS_ERROR_OTHER;
break;
case HTTP_ERROR:
responseStatus = Response.STATUS_ERROR_HTTP;
break;
}
}
ContentValues cv2 = new ContentValues();
cv2.put(Responses.RESPONSE_STATUS, responseStatus);
cr.update(Responses.buildResponseUri(responseId), cv2, null, null);
cursor.moveToNext();
}
cursor.close();
if (isBackground) {
if (authErrorOccurred) {
NotificationHelper.showAuthNotification(this);
} else if (uploadErrorOccurred) {
NotificationHelper.showUploadErrorNotification(this);
}
}
}
private void uploadMobility(Intent intent) {
sendBroadcast(new Intent(UploadService.MOBILITY_UPLOAD_STARTED));
boolean uploadSensorData = true;
SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
String username = helper.getUsername();
String hashedPassword = helper.getHashedPassword();
long uploadAfterTimestamp = helper.getLastMobilityUploadTimestamp();
if (uploadAfterTimestamp == 0) {
uploadAfterTimestamp = helper.getLoginTimestamp();
}
Long now = System.currentTimeMillis();
Cursor c = MobilityInterface.getMobilityCursor(this, uploadAfterTimestamp);
OhmageApi.UploadResponse response = new OhmageApi.UploadResponse(OhmageApi.Result.SUCCESS, null);
if (c != null && c.getCount() > 0) {
Log.i(TAG, "There are " + String.valueOf(c.getCount()) + " mobility points to upload.");
c.moveToFirst();
int remainingCount = c.getCount();
int limit = 60;
while (remainingCount > 0) {
if (remainingCount < limit) {
limit = remainingCount;
}
Log.i(TAG, "Attempting to upload a batch with " + String.valueOf(limit) + " mobility points.");
JSONArray mobilityJsonArray = new JSONArray();
for (int i = 0; i < limit; i++) {
JSONObject mobilityPointJson = new JSONObject();
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Long time = Long.parseLong(c.getString(c.getColumnIndex(MobilityInterface.KEY_TIME)));
if (i == limit - 1) {
uploadAfterTimestamp = time;
}
mobilityPointJson.put("id", c.getString(c.getColumnIndex(MobilityInterface.KEY_ID)));
mobilityPointJson.put("time", time);
mobilityPointJson.put("timezone", c.getString(c.getColumnIndex(MobilityInterface.KEY_TIMEZONE)));
if (uploadSensorData) {
mobilityPointJson.put("subtype", "sensor_data");
JSONObject dataJson = new JSONObject();
dataJson.put("mode", c.getString(c.getColumnIndex(MobilityInterface.KEY_MODE)));
try {
dataJson.put("speed", Float.parseFloat(c.getString(c.getColumnIndex(MobilityInterface.KEY_SPEED))));
} catch (NumberFormatException e) {
dataJson.put("speed", "NaN");
} catch (JSONException e) {
dataJson.put("speed", "NaN");
}
String accelDataString = c.getString(c.getColumnIndex(MobilityInterface.KEY_ACCELDATA));
if (accelDataString == null || accelDataString.equals("")) {
accelDataString = "[]";
}
dataJson.put("accel_data", new JSONArray(accelDataString));
String wifiDataString = c.getString(c.getColumnIndex(MobilityInterface.KEY_WIFIDATA));
if (wifiDataString == null || wifiDataString.equals("")) {
wifiDataString = "{}";
}
dataJson.put("wifi_data", new JSONObject(wifiDataString));
mobilityPointJson.put("data", dataJson);
} else {
mobilityPointJson.put("subtype", "mode_only");
mobilityPointJson.put("mode", c.getString(c.getColumnIndex(MobilityInterface.KEY_MODE)));
}
String locationStatus = c.getString(c.getColumnIndex(MobilityInterface.KEY_STATUS));
mobilityPointJson.put("location_status", locationStatus);
if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) {
JSONObject locationJson = new JSONObject();
try {
locationJson.put("latitude", Double.parseDouble(c.getString(c.getColumnIndex(MobilityInterface.KEY_LATITUDE))));
} catch (NumberFormatException e) {
locationJson.put("latitude", "NaN");
} catch (JSONException e) {
locationJson.put("latitude", "NaN");
}
try {
locationJson.put("longitude", Double.parseDouble(c.getString(c.getColumnIndex(MobilityInterface.KEY_LONGITUDE))));
} catch (NumberFormatException e) {
locationJson.put("longitude", "NaN");
} catch (JSONException e) {
locationJson.put("longitude", "NaN");
}
locationJson.put("provider", c.getString(c.getColumnIndex(MobilityInterface.KEY_PROVIDER)));
try {
locationJson.put("accuracy", Float.parseFloat(c.getString(c.getColumnIndex(MobilityInterface.KEY_ACCURACY))));
} catch (NumberFormatException e) {
locationJson.put("accuracy", "NaN");
} catch (JSONException e) {
locationJson.put("accuracy", "NaN");
}
locationJson.put("time", Long.parseLong(c.getString(c.getColumnIndex(MobilityInterface.KEY_LOC_TIMESTAMP))));
locationJson.put("timezone", c.getString(c.getColumnIndex(MobilityInterface.KEY_TIMEZONE)));
mobilityPointJson.put("location", locationJson);
}
} catch (JSONException e) {
Log.e(TAG, "error creating mobility json", e);
NotificationHelper.showMobilityErrorNotification(this);
throw new RuntimeException(e);
}
mobilityJsonArray.put(mobilityPointJson);
c.moveToNext();
}
response = mApi.mobilityUpload(Config.DEFAULT_SERVER_URL, username, hashedPassword, SharedPreferencesHelper.CLIENT_STRING, mobilityJsonArray.toString());
if (response.getResult().equals(OhmageApi.Result.SUCCESS)) {
Log.i(TAG, "Successfully uploaded " + String.valueOf(limit) + " mobility points.");
helper.putLastMobilityUploadTimestamp(uploadAfterTimestamp);
remainingCount -= limit;
Log.i(TAG, "There are " + String.valueOf(remainingCount) + " mobility points remaining to be uploaded.");
NotificationHelper.hideMobilityErrorNotification(this);
} else {
Log.e(TAG, "Failed to upload mobility points. Cancelling current round of mobility uploads.");
switch (response.getResult()) {
case FAILURE:
Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", "));
boolean isAuthenticationError = false;
boolean isUserDisabled = false;
for (String code : response.getErrorCodes()) {
if (code.charAt(1) == '2') {
isAuthenticationError = true;
if (code.equals("0201")) {
isUserDisabled = true;
}
}
}
if (isUserDisabled) {
new SharedPreferencesHelper(this).setUserDisabled(true);
}
if (isAuthenticationError) {
NotificationHelper.showAuthNotification(this);
} else {
NotificationHelper.showMobilityErrorNotification(this);
}
break;
case INTERNAL_ERROR:
Log.e(TAG, "Upload failed due to unknown internal error");
NotificationHelper.showMobilityErrorNotification(this);
break;
case HTTP_ERROR:
Log.e(TAG, "Upload failed due to network error");
break;
}
break;
}
}
c.close();
} else {
Log.i(TAG, "No mobility points to upload.");
}
sendBroadcast(new Intent(UploadService.MOBILITY_UPLOAD_FINISHED));
}
}
| true | true | private void uploadSurveyResponses(Intent intent) {
String serverUrl = Config.DEFAULT_SERVER_URL;
SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
String username = helper.getUsername();
String hashedPassword = helper.getHashedPassword();
boolean isBackground = intent.getBooleanExtra(EXTRA_BACKGROUND, false);
boolean uploadErrorOccurred = false;
boolean authErrorOccurred = false;
DbHelper dbHelper = new DbHelper(this);
Uri dataUri = intent.getData();
if(!Responses.isResponseUri(dataUri)) {
Log.e(TAG, "Upload service can only be called with a response URI");
return;
}
ContentResolver cr = getContentResolver();
String [] projection = new String [] {
Tables.RESPONSES + "." + Responses._ID,
Responses.RESPONSE_UUID,
Responses.RESPONSE_DATE,
Responses.RESPONSE_TIME,
Responses.RESPONSE_TIMEZONE,
Responses.RESPONSE_LOCATION_STATUS,
Responses.RESPONSE_LOCATION_LATITUDE,
Responses.RESPONSE_LOCATION_LONGITUDE,
Responses.RESPONSE_LOCATION_PROVIDER,
Responses.RESPONSE_LOCATION_ACCURACY,
Responses.RESPONSE_LOCATION_TIME,
Tables.RESPONSES + "." + Responses.SURVEY_ID,
Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT,
Responses.RESPONSE_JSON,
Tables.RESPONSES + "." + Responses.CAMPAIGN_URN,
Campaigns.CAMPAIGN_CREATED};
String select = Responses.RESPONSE_STATUS + "!=" + Response.STATUS_DOWNLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_UPLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_WAITING_FOR_LOCATION;
Cursor cursor = cr.query(dataUri, projection, select, null, null);
// If there is no data we should just return
if(cursor == null || !cursor.moveToFirst())
return;
ContentValues cv = new ContentValues();
cv.put(Responses.RESPONSE_STATUS, Response.STATUS_QUEUED);
cr.update(dataUri, cv, select, null);
for (int i = 0; i < cursor.getCount(); i++) {
long responseId = cursor.getLong(cursor.getColumnIndex(Responses._ID));
ContentValues values = new ContentValues();
values.put(Responses.RESPONSE_STATUS, Response.STATUS_UPLOADING);
cr.update(Responses.buildResponseUri(responseId), values, null, null);
// cr.update(Responses.CONTENT_URI, values, Tables.RESPONSES + "." + Responses._ID + "=" + responseId, null);
JSONArray responsesJsonArray = new JSONArray();
JSONObject responseJson = new JSONObject();
final ArrayList<String> photoUUIDs = new ArrayList<String>();
try {
responseJson.put("survey_key", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_UUID)));
responseJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIME)));
responseJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
String locationStatus = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_STATUS));
responseJson.put("location_status", locationStatus);
if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) {
JSONObject locationJson = new JSONObject();
locationJson.put("latitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LATITUDE)));
locationJson.put("longitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LONGITUDE)));
String provider = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_PROVIDER));
locationJson.put("provider", provider);
Log.i(TAG, "Response uploaded with " + provider + " location");
locationJson.put("accuracy", cursor.getFloat(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_ACCURACY)));
locationJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_TIME)));
locationJson.put("timezone", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
responseJson.put("location", locationJson);
} else {
Log.w(TAG, "Response uploaded without a location");
}
responseJson.put("survey_id", cursor.getString(cursor.getColumnIndex(Responses.SURVEY_ID)));
responseJson.put("survey_launch_context", new JSONObject(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT))));
responseJson.put("responses", new JSONArray(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_JSON))));
ContentResolver cr2 = getContentResolver();
Cursor promptsCursor = cr2.query(Responses.buildPromptResponsesUri(responseId), new String [] {PromptResponses.PROMPT_RESPONSE_VALUE, SurveyPrompts.SURVEY_PROMPT_TYPE}, SurveyPrompts.SURVEY_PROMPT_TYPE + "='photo'", null, null);
while (promptsCursor.moveToNext()) {
photoUUIDs.add(promptsCursor.getString(promptsCursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE)));
}
promptsCursor.close();
} catch (JSONException e) {
throw new RuntimeException(e);
}
responsesJsonArray.put(responseJson);
String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN));
String campaignCreationTimestamp = cursor.getString(cursor.getColumnIndex(Campaigns.CAMPAIGN_CREATED));
File [] photos = Response.getResponseImageUploadDir(this).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (photoUUIDs.contains(filename.split("\\.")[0])) {
return true;
}
return false;
}
});
OhmageApi.UploadResponse response = mApi.surveyUpload(serverUrl, username, hashedPassword, SharedPreferencesHelper.CLIENT_STRING, campaignUrn, campaignCreationTimestamp, responsesJsonArray.toString(), photos);
int responseStatus = Response.STATUS_UPLOADED;
if (response.getResult() == Result.SUCCESS) {
NotificationHelper.hideUploadErrorNotification(this);
NotificationHelper.hideAuthNotification(this);
} else {
responseStatus = Response.STATUS_ERROR_OTHER;
switch (response.getResult()) {
case FAILURE:
Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", "));
uploadErrorOccurred = true;
boolean isAuthenticationError = false;
boolean isUserDisabled = false;
String errorCode = null;
for (String code : response.getErrorCodes()) {
if (code.charAt(1) == '2') {
authErrorOccurred = true;
isAuthenticationError = true;
if (code.equals("0201")) {
isUserDisabled = true;
}
}
if (code.equals("0700") || code.equals("0707") || code.equals("0703") || code.equals("0710")) {
errorCode = code;
break;
}
}
if (isUserDisabled) {
new SharedPreferencesHelper(this).setUserDisabled(true);
}
if (isAuthenticationError) {
responseStatus = Response.STATUS_ERROR_AUTHENTICATION;
} else if ("0700".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_CAMPAIGN_NO_EXIST;
} else if ("0707".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_INVALID_USER_ROLE;
} else if ("0703".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_CAMPAIGN_STOPPED;
} else if ("0710".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE;
} else {
responseStatus = Response.STATUS_ERROR_OTHER;
}
break;
case INTERNAL_ERROR:
uploadErrorOccurred = true;
responseStatus = Response.STATUS_ERROR_OTHER;
break;
case HTTP_ERROR:
responseStatus = Response.STATUS_ERROR_HTTP;
break;
}
}
ContentValues cv2 = new ContentValues();
cv2.put(Responses.RESPONSE_STATUS, responseStatus);
cr.update(Responses.buildResponseUri(responseId), cv2, null, null);
cursor.moveToNext();
}
cursor.close();
if (isBackground) {
if (authErrorOccurred) {
NotificationHelper.showAuthNotification(this);
} else if (uploadErrorOccurred) {
NotificationHelper.showUploadErrorNotification(this);
}
}
}
| private void uploadSurveyResponses(Intent intent) {
String serverUrl = Config.DEFAULT_SERVER_URL;
SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
String username = helper.getUsername();
String hashedPassword = helper.getHashedPassword();
boolean isBackground = intent.getBooleanExtra(EXTRA_BACKGROUND, false);
boolean uploadErrorOccurred = false;
boolean authErrorOccurred = false;
DbHelper dbHelper = new DbHelper(this);
Uri dataUri = intent.getData();
if(!Responses.isResponseUri(dataUri)) {
Log.e(TAG, "Upload service can only be called with a response URI");
return;
}
ContentResolver cr = getContentResolver();
String [] projection = new String [] {
Tables.RESPONSES + "." + Responses._ID,
Responses.RESPONSE_UUID,
Responses.RESPONSE_DATE,
Responses.RESPONSE_TIME,
Responses.RESPONSE_TIMEZONE,
Responses.RESPONSE_LOCATION_STATUS,
Responses.RESPONSE_LOCATION_LATITUDE,
Responses.RESPONSE_LOCATION_LONGITUDE,
Responses.RESPONSE_LOCATION_PROVIDER,
Responses.RESPONSE_LOCATION_ACCURACY,
Responses.RESPONSE_LOCATION_TIME,
Tables.RESPONSES + "." + Responses.SURVEY_ID,
Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT,
Responses.RESPONSE_JSON,
Tables.RESPONSES + "." + Responses.CAMPAIGN_URN,
Campaigns.CAMPAIGN_CREATED};
String select = Responses.RESPONSE_STATUS + "!=" + Response.STATUS_DOWNLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_UPLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_WAITING_FOR_LOCATION;
Cursor cursor = cr.query(dataUri, projection, select, null, null);
// If there is no data we should just return
if(cursor == null || !cursor.moveToFirst())
return;
ContentValues cv = new ContentValues();
cv.put(Responses.RESPONSE_STATUS, Response.STATUS_QUEUED);
cr.update(dataUri, cv, select, null);
for (int i = 0; i < cursor.getCount(); i++) {
long responseId = cursor.getLong(cursor.getColumnIndex(Responses._ID));
ContentValues values = new ContentValues();
values.put(Responses.RESPONSE_STATUS, Response.STATUS_UPLOADING);
cr.update(Responses.buildResponseUri(responseId), values, null, null);
// cr.update(Responses.CONTENT_URI, values, Tables.RESPONSES + "." + Responses._ID + "=" + responseId, null);
JSONArray responsesJsonArray = new JSONArray();
JSONObject responseJson = new JSONObject();
final ArrayList<String> photoUUIDs = new ArrayList<String>();
try {
responseJson.put("survey_key", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_UUID)));
responseJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIME)));
responseJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
String locationStatus = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_STATUS));
responseJson.put("location_status", locationStatus);
if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) {
JSONObject locationJson = new JSONObject();
locationJson.put("latitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LATITUDE)));
locationJson.put("longitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LONGITUDE)));
String provider = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_PROVIDER));
locationJson.put("provider", provider);
Log.i(TAG, "Response uploaded with " + provider + " location");
locationJson.put("accuracy", cursor.getFloat(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_ACCURACY)));
locationJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_TIME)));
locationJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
responseJson.put("location", locationJson);
} else {
Log.w(TAG, "Response uploaded without a location");
}
responseJson.put("survey_id", cursor.getString(cursor.getColumnIndex(Responses.SURVEY_ID)));
responseJson.put("survey_launch_context", new JSONObject(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT))));
responseJson.put("responses", new JSONArray(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_JSON))));
ContentResolver cr2 = getContentResolver();
Cursor promptsCursor = cr2.query(Responses.buildPromptResponsesUri(responseId), new String [] {PromptResponses.PROMPT_RESPONSE_VALUE, SurveyPrompts.SURVEY_PROMPT_TYPE}, SurveyPrompts.SURVEY_PROMPT_TYPE + "='photo'", null, null);
while (promptsCursor.moveToNext()) {
photoUUIDs.add(promptsCursor.getString(promptsCursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE)));
}
promptsCursor.close();
} catch (JSONException e) {
throw new RuntimeException(e);
}
responsesJsonArray.put(responseJson);
String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN));
String campaignCreationTimestamp = cursor.getString(cursor.getColumnIndex(Campaigns.CAMPAIGN_CREATED));
File [] photos = Response.getResponseImageUploadDir(this).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (photoUUIDs.contains(filename.split("\\.")[0])) {
return true;
}
return false;
}
});
OhmageApi.UploadResponse response = mApi.surveyUpload(serverUrl, username, hashedPassword, SharedPreferencesHelper.CLIENT_STRING, campaignUrn, campaignCreationTimestamp, responsesJsonArray.toString(), photos);
int responseStatus = Response.STATUS_UPLOADED;
if (response.getResult() == Result.SUCCESS) {
NotificationHelper.hideUploadErrorNotification(this);
NotificationHelper.hideAuthNotification(this);
} else {
responseStatus = Response.STATUS_ERROR_OTHER;
switch (response.getResult()) {
case FAILURE:
Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", "));
uploadErrorOccurred = true;
boolean isAuthenticationError = false;
boolean isUserDisabled = false;
String errorCode = null;
for (String code : response.getErrorCodes()) {
if (code.charAt(1) == '2') {
authErrorOccurred = true;
isAuthenticationError = true;
if (code.equals("0201")) {
isUserDisabled = true;
}
}
if (code.equals("0700") || code.equals("0707") || code.equals("0703") || code.equals("0710")) {
errorCode = code;
break;
}
}
if (isUserDisabled) {
new SharedPreferencesHelper(this).setUserDisabled(true);
}
if (isAuthenticationError) {
responseStatus = Response.STATUS_ERROR_AUTHENTICATION;
} else if ("0700".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_CAMPAIGN_NO_EXIST;
} else if ("0707".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_INVALID_USER_ROLE;
} else if ("0703".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_CAMPAIGN_STOPPED;
} else if ("0710".equals(errorCode)) {
responseStatus = Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE;
} else {
responseStatus = Response.STATUS_ERROR_OTHER;
}
break;
case INTERNAL_ERROR:
uploadErrorOccurred = true;
responseStatus = Response.STATUS_ERROR_OTHER;
break;
case HTTP_ERROR:
responseStatus = Response.STATUS_ERROR_HTTP;
break;
}
}
ContentValues cv2 = new ContentValues();
cv2.put(Responses.RESPONSE_STATUS, responseStatus);
cr.update(Responses.buildResponseUri(responseId), cv2, null, null);
cursor.moveToNext();
}
cursor.close();
if (isBackground) {
if (authErrorOccurred) {
NotificationHelper.showAuthNotification(this);
} else if (uploadErrorOccurred) {
NotificationHelper.showUploadErrorNotification(this);
}
}
}
|
diff --git a/src/com/android/exchange/adapter/FolderSyncParser.java b/src/com/android/exchange/adapter/FolderSyncParser.java
index f2e5d618..2f7cdd0c 100644
--- a/src/com/android/exchange/adapter/FolderSyncParser.java
+++ b/src/com/android/exchange/adapter/FolderSyncParser.java
@@ -1,428 +1,428 @@
/*
* Copyright (C) 2008-2009 Marc Blank
* Licensed to 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.exchange.adapter;
import com.android.email.Email;
import com.android.email.provider.AttachmentProvider;
import com.android.email.provider.EmailContent;
import com.android.email.provider.EmailProvider;
import com.android.email.provider.EmailContent.Account;
import com.android.email.provider.EmailContent.AccountColumns;
import com.android.email.provider.EmailContent.Mailbox;
import com.android.email.provider.EmailContent.MailboxColumns;
import com.android.exchange.Eas;
import com.android.exchange.MockParserStream;
import com.android.exchange.SyncManager;
import android.content.ContentProviderOperation;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.Calendar.Calendars;
import android.text.format.Time;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Parse the result of a FolderSync command
*
* Handles the addition, deletion, and changes to folders in the user's Exchange account.
**/
public class FolderSyncParser extends AbstractSyncParser {
public static final String TAG = "FolderSyncParser";
// These are defined by the EAS protocol
public static final int USER_FOLDER_TYPE = 1;
public static final int INBOX_TYPE = 2;
public static final int DRAFTS_TYPE = 3;
public static final int DELETED_TYPE = 4;
public static final int SENT_TYPE = 5;
public static final int OUTBOX_TYPE = 6;
public static final int TASKS_TYPE = 7;
public static final int CALENDAR_TYPE = 8;
public static final int CONTACTS_TYPE = 9;
public static final int NOTES_TYPE = 10;
public static final int JOURNAL_TYPE = 11;
public static final int USER_MAILBOX_TYPE = 12;
public static final List<Integer> mValidFolderTypes = Arrays.asList(INBOX_TYPE, DRAFTS_TYPE,
DELETED_TYPE, SENT_TYPE, OUTBOX_TYPE, USER_MAILBOX_TYPE, CALENDAR_TYPE, CONTACTS_TYPE);
public static final String ALL_BUT_ACCOUNT_MAILBOX = MailboxColumns.ACCOUNT_KEY + "=? and " +
MailboxColumns.TYPE + "!=" + Mailbox.TYPE_EAS_ACCOUNT_MAILBOX;
private static final String WHERE_SERVER_ID_AND_ACCOUNT = MailboxColumns.SERVER_ID + "=? and " +
MailboxColumns.ACCOUNT_KEY + "=?";
private static final String WHERE_DISPLAY_NAME_AND_ACCOUNT = MailboxColumns.DISPLAY_NAME +
"=? and " + MailboxColumns.ACCOUNT_KEY + "=?";
private static final String WHERE_PARENT_SERVER_ID_AND_ACCOUNT =
MailboxColumns.PARENT_SERVER_ID +"=? and " + MailboxColumns.ACCOUNT_KEY + "=?";
private static final String[] MAILBOX_ID_COLUMNS_PROJECTION =
new String[] {MailboxColumns.ID, MailboxColumns.SERVER_ID};
private long mAccountId;
private String mAccountIdAsString;
private MockParserStream mMock = null;
private String[] mBindArguments = new String[2];
public FolderSyncParser(InputStream in, AbstractSyncAdapter adapter) throws IOException {
super(in, adapter);
mAccountId = mAccount.mId;
mAccountIdAsString = Long.toString(mAccountId);
if (in instanceof MockParserStream) {
mMock = (MockParserStream)in;
}
}
@Override
public boolean parse() throws IOException {
int status;
boolean res = false;
boolean resetFolders = false;
if (nextTag(START_DOCUMENT) != Tags.FOLDER_FOLDER_SYNC)
throw new EasParserException();
while (nextTag(START_DOCUMENT) != END_DOCUMENT) {
if (tag == Tags.FOLDER_STATUS) {
status = getValueInt();
if (status != Eas.FOLDER_STATUS_OK) {
mService.errorLog("FolderSync failed: " + status);
if (status == Eas.FOLDER_STATUS_INVALID_KEY) {
mAccount.mSyncKey = "0";
mService.errorLog("Bad sync key; RESET and delete all folders");
mContentResolver.delete(Mailbox.CONTENT_URI, ALL_BUT_ACCOUNT_MAILBOX,
new String[] {Long.toString(mAccountId)});
// Stop existing syncs and reconstruct _main
SyncManager.folderListReloaded(mAccountId);
res = true;
resetFolders = true;
} else {
// Other errors are at the server, so let's throw an error that will
// cause this sync to be retried at a later time
mService.errorLog("Throwing IOException; will retry later");
throw new EasParserException("Folder status error");
}
}
} else if (tag == Tags.FOLDER_SYNC_KEY) {
mAccount.mSyncKey = getValue();
userLog("New Account SyncKey: ", mAccount.mSyncKey);
} else if (tag == Tags.FOLDER_CHANGES) {
changesParser();
} else
skipTag();
}
synchronized (mService.getSynchronizer()) {
if (!mService.isStopped() || resetFolders) {
ContentValues cv = new ContentValues();
cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey);
mAccount.update(mContext, cv);
userLog("Leaving FolderSyncParser with Account syncKey=", mAccount.mSyncKey);
}
}
return res;
}
private Cursor getServerIdCursor(String serverId) {
mBindArguments[0] = serverId;
mBindArguments[1] = mAccountIdAsString;
return mContentResolver.query(Mailbox.CONTENT_URI, EmailContent.ID_PROJECTION,
WHERE_SERVER_ID_AND_ACCOUNT, mBindArguments, null);
}
public void deleteParser(ArrayList<ContentProviderOperation> ops) throws IOException {
while (nextTag(Tags.FOLDER_DELETE) != END) {
switch (tag) {
case Tags.FOLDER_SERVER_ID:
String serverId = getValue();
// Find the mailbox in this account with the given serverId
Cursor c = getServerIdCursor(serverId);
try {
if (c.moveToFirst()) {
userLog("Deleting ", serverId);
ops.add(ContentProviderOperation.newDelete(
ContentUris.withAppendedId(Mailbox.CONTENT_URI,
c.getLong(0))).build());
AttachmentProvider.deleteAllMailboxAttachmentFiles(mContext,
mAccountId, mMailbox.mId);
}
} finally {
c.close();
}
break;
default:
skipTag();
}
}
}
public void addParser(ArrayList<ContentProviderOperation> ops) throws IOException {
String name = null;
String serverId = null;
String parentId = null;
int type = 0;
while (nextTag(Tags.FOLDER_ADD) != END) {
switch (tag) {
case Tags.FOLDER_DISPLAY_NAME: {
name = getValue();
break;
}
case Tags.FOLDER_TYPE: {
type = getValueInt();
break;
}
case Tags.FOLDER_PARENT_ID: {
parentId = getValue();
break;
}
case Tags.FOLDER_SERVER_ID: {
serverId = getValue();
break;
}
default:
skipTag();
}
}
if (mValidFolderTypes.contains(type)) {
Mailbox m = new Mailbox();
m.mDisplayName = name;
m.mServerId = serverId;
m.mAccountKey = mAccountId;
m.mType = Mailbox.TYPE_MAIL;
// Note that all mailboxes default to checking "never" (i.e. manual sync only)
// We set specific intervals for inbox, contacts, and (eventually) calendar
m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
switch (type) {
case INBOX_TYPE:
m.mType = Mailbox.TYPE_INBOX;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case CONTACTS_TYPE:
m.mType = Mailbox.TYPE_CONTACTS;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case OUTBOX_TYPE:
// TYPE_OUTBOX mailboxes are known by SyncManager to sync whenever they aren't
// empty. The value of mSyncFrequency is ignored for this kind of mailbox.
m.mType = Mailbox.TYPE_OUTBOX;
break;
case SENT_TYPE:
m.mType = Mailbox.TYPE_SENT;
break;
case DRAFTS_TYPE:
m.mType = Mailbox.TYPE_DRAFTS;
break;
case DELETED_TYPE:
m.mType = Mailbox.TYPE_TRASH;
break;
case CALENDAR_TYPE:
m.mType = Mailbox.TYPE_CALENDAR;
m.mSyncInterval = mAccount.mSyncInterval;
// Create a Calendar object
ContentValues cv = new ContentValues();
// TODO How will this change if the user changes his account display name?
cv.put(Calendars.DISPLAY_NAME, mAccount.mDisplayName);
cv.put(Calendars._SYNC_ACCOUNT, mAccount.mEmailAddress);
cv.put(Calendars._SYNC_ACCOUNT_TYPE, Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cv.put(Calendars.SYNC_EVENTS, 1);
cv.put(Calendars.SELECTED, 1);
cv.put(Calendars.HIDDEN, 0);
// TODO Find out how to set color!!
- cv.put(Calendars.COLOR, Email.getAccountColor(mAccountId));
+ cv.put(Calendars.COLOR, 0xFF000000 | Email.getAccountColor(mAccountId));
cv.put(Calendars.TIMEZONE, Time.getCurrentTimezone());
cv.put(Calendars.ACCESS_LEVEL, Calendars.OWNER_ACCESS);
cv.put(Calendars.OWNER_ACCOUNT, mAccount.mEmailAddress);
Uri uri = mService.mContentResolver.insert(Calendars.CONTENT_URI, cv);
// We save the id of the calendar into mSyncStatus
if (uri != null) {
m.mSyncStatus = uri.getPathSegments().get(1);
}
break;
}
// Make boxes like Contacts and Calendar invisible in the folder list
m.mFlagVisible = (m.mType < Mailbox.TYPE_NOT_EMAIL);
if (!parentId.equals("0")) {
m.mParentServerId = parentId;
}
userLog("Adding mailbox: ", m.mDisplayName);
ops.add(ContentProviderOperation
.newInsert(Mailbox.CONTENT_URI).withValues(m.toContentValues()).build());
}
return;
}
public void updateParser(ArrayList<ContentProviderOperation> ops) throws IOException {
String serverId = null;
String displayName = null;
String parentId = null;
while (nextTag(Tags.FOLDER_UPDATE) != END) {
switch (tag) {
case Tags.FOLDER_SERVER_ID:
serverId = getValue();
break;
case Tags.FOLDER_DISPLAY_NAME:
displayName = getValue();
break;
case Tags.FOLDER_PARENT_ID:
parentId = getValue();
break;
default:
skipTag();
break;
}
}
// We'll make a change if one of parentId or displayName are specified
// serverId is required, but let's be careful just the same
if (serverId != null && (displayName != null || parentId != null)) {
Cursor c = getServerIdCursor(serverId);
try {
// If we find the mailbox (using serverId), make the change
if (c.moveToFirst()) {
userLog("Updating ", serverId);
ContentValues cv = new ContentValues();
if (displayName != null) {
cv.put(Mailbox.DISPLAY_NAME, displayName);
}
if (parentId != null) {
cv.put(Mailbox.PARENT_SERVER_ID, parentId);
}
ops.add(ContentProviderOperation.newUpdate(
ContentUris.withAppendedId(Mailbox.CONTENT_URI,
c.getLong(0))).withValues(cv).build());
}
} finally {
c.close();
}
}
}
public void changesParser() throws IOException {
// Keep track of new boxes, deleted boxes, updated boxes
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
while (nextTag(Tags.FOLDER_CHANGES) != END) {
if (tag == Tags.FOLDER_ADD) {
addParser(ops);
} else if (tag == Tags.FOLDER_DELETE) {
deleteParser(ops);
} else if (tag == Tags.FOLDER_UPDATE) {
updateParser(ops);
} else if (tag == Tags.FOLDER_COUNT) {
getValueInt();
} else
skipTag();
}
// The mock stream is used for junit tests, so that the parsing code can be tested
// separately from the provider code.
// TODO Change tests to not require this; remove references to the mock stream
if (mMock != null) {
mMock.setResult(null);
return;
}
// Create the new mailboxes in a single batch operation
// Don't save any data if the service has been stopped
synchronized (mService.getSynchronizer()) {
if (!ops.isEmpty() && !mService.isStopped()) {
userLog("Applying ", ops.size(), " mailbox operations.");
// Then, we create an update for the account (most importantly, updating the syncKey)
ops.add(ContentProviderOperation.newUpdate(
ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId)).withValues(
mAccount.toContentValues()).build());
// Finally, we execute the batch
try {
mContentResolver.applyBatch(EmailProvider.EMAIL_AUTHORITY, ops);
userLog("New Account SyncKey: ", mAccount.mSyncKey);
} catch (RemoteException e) {
// There is nothing to be done here; fail by returning null
} catch (OperationApplicationException e) {
// There is nothing to be done here; fail by returning null
}
// Look for sync issues and its children and delete them
// I'm not aware of any other way to deal with this properly
mBindArguments[0] = "Sync Issues";
mBindArguments[1] = mAccountIdAsString;
Cursor c = mContentResolver.query(Mailbox.CONTENT_URI,
MAILBOX_ID_COLUMNS_PROJECTION, WHERE_DISPLAY_NAME_AND_ACCOUNT,
mBindArguments, null);
String parentServerId = null;
long id = 0;
try {
if (c.moveToFirst()) {
id = c.getLong(0);
parentServerId = c.getString(1);
}
} finally {
c.close();
}
if (parentServerId != null) {
mContentResolver.delete(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id),
null, null);
mBindArguments[0] = parentServerId;
mContentResolver.delete(Mailbox.CONTENT_URI, WHERE_PARENT_SERVER_ID_AND_ACCOUNT,
mBindArguments);
}
}
}
}
/**
* Not needed for FolderSync parsing; everything is done within changesParser
*/
@Override
public void commandsParser() throws IOException {
}
/**
* We don't need to implement commit() because all operations take place atomically within
* changesParser
*/
@Override
public void commit() throws IOException {
}
@Override
public void wipe() {
}
@Override
public void responsesParser() throws IOException {
}
}
| true | true | public void addParser(ArrayList<ContentProviderOperation> ops) throws IOException {
String name = null;
String serverId = null;
String parentId = null;
int type = 0;
while (nextTag(Tags.FOLDER_ADD) != END) {
switch (tag) {
case Tags.FOLDER_DISPLAY_NAME: {
name = getValue();
break;
}
case Tags.FOLDER_TYPE: {
type = getValueInt();
break;
}
case Tags.FOLDER_PARENT_ID: {
parentId = getValue();
break;
}
case Tags.FOLDER_SERVER_ID: {
serverId = getValue();
break;
}
default:
skipTag();
}
}
if (mValidFolderTypes.contains(type)) {
Mailbox m = new Mailbox();
m.mDisplayName = name;
m.mServerId = serverId;
m.mAccountKey = mAccountId;
m.mType = Mailbox.TYPE_MAIL;
// Note that all mailboxes default to checking "never" (i.e. manual sync only)
// We set specific intervals for inbox, contacts, and (eventually) calendar
m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
switch (type) {
case INBOX_TYPE:
m.mType = Mailbox.TYPE_INBOX;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case CONTACTS_TYPE:
m.mType = Mailbox.TYPE_CONTACTS;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case OUTBOX_TYPE:
// TYPE_OUTBOX mailboxes are known by SyncManager to sync whenever they aren't
// empty. The value of mSyncFrequency is ignored for this kind of mailbox.
m.mType = Mailbox.TYPE_OUTBOX;
break;
case SENT_TYPE:
m.mType = Mailbox.TYPE_SENT;
break;
case DRAFTS_TYPE:
m.mType = Mailbox.TYPE_DRAFTS;
break;
case DELETED_TYPE:
m.mType = Mailbox.TYPE_TRASH;
break;
case CALENDAR_TYPE:
m.mType = Mailbox.TYPE_CALENDAR;
m.mSyncInterval = mAccount.mSyncInterval;
// Create a Calendar object
ContentValues cv = new ContentValues();
// TODO How will this change if the user changes his account display name?
cv.put(Calendars.DISPLAY_NAME, mAccount.mDisplayName);
cv.put(Calendars._SYNC_ACCOUNT, mAccount.mEmailAddress);
cv.put(Calendars._SYNC_ACCOUNT_TYPE, Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cv.put(Calendars.SYNC_EVENTS, 1);
cv.put(Calendars.SELECTED, 1);
cv.put(Calendars.HIDDEN, 0);
// TODO Find out how to set color!!
cv.put(Calendars.COLOR, Email.getAccountColor(mAccountId));
cv.put(Calendars.TIMEZONE, Time.getCurrentTimezone());
cv.put(Calendars.ACCESS_LEVEL, Calendars.OWNER_ACCESS);
cv.put(Calendars.OWNER_ACCOUNT, mAccount.mEmailAddress);
Uri uri = mService.mContentResolver.insert(Calendars.CONTENT_URI, cv);
// We save the id of the calendar into mSyncStatus
if (uri != null) {
m.mSyncStatus = uri.getPathSegments().get(1);
}
break;
}
// Make boxes like Contacts and Calendar invisible in the folder list
m.mFlagVisible = (m.mType < Mailbox.TYPE_NOT_EMAIL);
if (!parentId.equals("0")) {
m.mParentServerId = parentId;
}
userLog("Adding mailbox: ", m.mDisplayName);
ops.add(ContentProviderOperation
.newInsert(Mailbox.CONTENT_URI).withValues(m.toContentValues()).build());
}
return;
}
| public void addParser(ArrayList<ContentProviderOperation> ops) throws IOException {
String name = null;
String serverId = null;
String parentId = null;
int type = 0;
while (nextTag(Tags.FOLDER_ADD) != END) {
switch (tag) {
case Tags.FOLDER_DISPLAY_NAME: {
name = getValue();
break;
}
case Tags.FOLDER_TYPE: {
type = getValueInt();
break;
}
case Tags.FOLDER_PARENT_ID: {
parentId = getValue();
break;
}
case Tags.FOLDER_SERVER_ID: {
serverId = getValue();
break;
}
default:
skipTag();
}
}
if (mValidFolderTypes.contains(type)) {
Mailbox m = new Mailbox();
m.mDisplayName = name;
m.mServerId = serverId;
m.mAccountKey = mAccountId;
m.mType = Mailbox.TYPE_MAIL;
// Note that all mailboxes default to checking "never" (i.e. manual sync only)
// We set specific intervals for inbox, contacts, and (eventually) calendar
m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
switch (type) {
case INBOX_TYPE:
m.mType = Mailbox.TYPE_INBOX;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case CONTACTS_TYPE:
m.mType = Mailbox.TYPE_CONTACTS;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case OUTBOX_TYPE:
// TYPE_OUTBOX mailboxes are known by SyncManager to sync whenever they aren't
// empty. The value of mSyncFrequency is ignored for this kind of mailbox.
m.mType = Mailbox.TYPE_OUTBOX;
break;
case SENT_TYPE:
m.mType = Mailbox.TYPE_SENT;
break;
case DRAFTS_TYPE:
m.mType = Mailbox.TYPE_DRAFTS;
break;
case DELETED_TYPE:
m.mType = Mailbox.TYPE_TRASH;
break;
case CALENDAR_TYPE:
m.mType = Mailbox.TYPE_CALENDAR;
m.mSyncInterval = mAccount.mSyncInterval;
// Create a Calendar object
ContentValues cv = new ContentValues();
// TODO How will this change if the user changes his account display name?
cv.put(Calendars.DISPLAY_NAME, mAccount.mDisplayName);
cv.put(Calendars._SYNC_ACCOUNT, mAccount.mEmailAddress);
cv.put(Calendars._SYNC_ACCOUNT_TYPE, Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cv.put(Calendars.SYNC_EVENTS, 1);
cv.put(Calendars.SELECTED, 1);
cv.put(Calendars.HIDDEN, 0);
// TODO Find out how to set color!!
cv.put(Calendars.COLOR, 0xFF000000 | Email.getAccountColor(mAccountId));
cv.put(Calendars.TIMEZONE, Time.getCurrentTimezone());
cv.put(Calendars.ACCESS_LEVEL, Calendars.OWNER_ACCESS);
cv.put(Calendars.OWNER_ACCOUNT, mAccount.mEmailAddress);
Uri uri = mService.mContentResolver.insert(Calendars.CONTENT_URI, cv);
// We save the id of the calendar into mSyncStatus
if (uri != null) {
m.mSyncStatus = uri.getPathSegments().get(1);
}
break;
}
// Make boxes like Contacts and Calendar invisible in the folder list
m.mFlagVisible = (m.mType < Mailbox.TYPE_NOT_EMAIL);
if (!parentId.equals("0")) {
m.mParentServerId = parentId;
}
userLog("Adding mailbox: ", m.mDisplayName);
ops.add(ContentProviderOperation
.newInsert(Mailbox.CONTENT_URI).withValues(m.toContentValues()).build());
}
return;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.