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/src/main/java/de/hpi/fgis/yql/YQLApiJSON.java b/src/main/java/de/hpi/fgis/yql/YQLApiJSON.java
index f94f3a5..906aee4 100644
--- a/src/main/java/de/hpi/fgis/yql/YQLApiJSON.java
+++ b/src/main/java/de/hpi/fgis/yql/YQLApiJSON.java
@@ -1,49 +1,53 @@
package de.hpi.fgis.yql;
import java.io.InputStream;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import com.mongodb.util.JSONParseException;
/**
* this class provides the possibility to access the <a
* href="http://developer.yahoo.com/yql/">Yahoo! Query Language (YQL)</a>
* web-interface using the JSON serialization.
*
* @author tonigr
*
*/
public class YQLApiJSON extends YQLApi {
/**
* create a new YQL API access instance that uses JSON serialization and the public YQL endpoint
*/
public YQLApiJSON() {
super();
}
/*
* (non-Javadoc)
* @see de.hpi.fgis.yql.YQLApi#format()
*/
@Override
protected String format() {
return "json";
}
/*
* (non-Javadoc)
* @see de.hpi.fgis.yql.YQLApi#parse(java.io.InputStream)
*/
@Override
protected DBObject parse(InputStream jsonIn) {
String data = convertStreamToString(jsonIn, "UTF-8");
try {
+ if(data==null || !data.matches("^\\s*{")) {
+ // log the erroneous data
+ return null;
+ }
return (DBObject) JSON.parse(data);
} catch (JSONParseException e) {
System.out.println(data);
throw e;
}
}
}
| true | true | protected DBObject parse(InputStream jsonIn) {
String data = convertStreamToString(jsonIn, "UTF-8");
try {
return (DBObject) JSON.parse(data);
} catch (JSONParseException e) {
System.out.println(data);
throw e;
}
}
| protected DBObject parse(InputStream jsonIn) {
String data = convertStreamToString(jsonIn, "UTF-8");
try {
if(data==null || !data.matches("^\\s*{")) {
// log the erroneous data
return null;
}
return (DBObject) JSON.parse(data);
} catch (JSONParseException e) {
System.out.println(data);
throw e;
}
}
|
diff --git a/src/com/tactfactory/harmony/parser/ClassCompletor.java b/src/com/tactfactory/harmony/parser/ClassCompletor.java
index 984af306..47bca1ad 100644
--- a/src/com/tactfactory/harmony/parser/ClassCompletor.java
+++ b/src/com/tactfactory/harmony/parser/ClassCompletor.java
@@ -1,295 +1,295 @@
/**
* This file is part of the Harmony package.
*
* (c) Mickael Gaillard <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.tactfactory.harmony.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.tactfactory.harmony.meta.ApplicationMetadata;
import com.tactfactory.harmony.meta.EntityMetadata;
import com.tactfactory.harmony.meta.FieldMetadata;
import com.tactfactory.harmony.meta.RelationMetadata;
import com.tactfactory.harmony.utils.ConsoleUtils;
import com.tactfactory.harmony.utils.MetadataUtils;
/** The class ClassCompletor will complete all ClassMetadatas
* with the information it needs from the others ClassMetadatas. */
public class ClassCompletor {
/** Integer literal. */
private static final String TYPE_INTEGER = "integer";
/** Class metadata. */
private Map<String, EntityMetadata> metas;
/** Newly created class metadata. */
private final Map<String, EntityMetadata> newMetas =
new HashMap<String, EntityMetadata>();
/**
* Constructor.
* @param entities Entities map.
*/
public ClassCompletor(final Map<String, EntityMetadata> entities) {
this.metas = entities;
}
/**
* Complete classes.
*/
public final void execute() {
for (final EntityMetadata classMeta : this.metas.values()) {
this.updateInheritedIds(classMeta);
this.updateRelations(classMeta);
}
for (final EntityMetadata classMeta : this.newMetas.values()) {
this.metas.put(
classMeta.getName(),
classMeta);
ApplicationMetadata.INSTANCE.getClasses().put(
classMeta.getName(),
classMeta);
}
}
/**
* Update all the relations in a class.
* (actually sets the referenced columns for the target entities)
* @param cm The class owning the relations
*/
private void updateRelations(final EntityMetadata cm) {
final ArrayList<FieldMetadata> newFields =
new ArrayList<FieldMetadata>();
// For each relation in the class
for (final FieldMetadata fieldMeta : cm.getRelations().values()) {
boolean isRecursive = false;
final RelationMetadata rel = fieldMeta.getRelation();
final String targetEntity = rel.getEntityRef();
if (targetEntity.equals(cm.getName())) {
isRecursive = true;
}
this.checkRelationIntegrity(fieldMeta);
if (rel.getFieldRef().isEmpty()) {
final EntityMetadata cmRef = this.metas.get(targetEntity);
final ArrayList<FieldMetadata> ids =
new ArrayList<FieldMetadata>(cmRef.getIds().values());
for (int i = 0; i < ids.size(); i++) {
rel.getFieldRef().add(ids.get(i).getName());
}
if (!ids.isEmpty()) {
fieldMeta.setColumnDefinition(ids.get(0).getType());
} else {
ConsoleUtils.displayError(new Exception(
"Error while updating relations : "
+ " Your entity " + cm.getName()
+ " refers the entity " + cmRef.getName()
+ " which has no ID defined."
+ " Please add the @Id annotation "
+ "to one of the fields of " + cmRef.getName()));
System.exit(-1);
}
}
ConsoleUtils.displayDebug("Relation " + rel.getType()
+ " on field " + rel.getField()
+ " targets " + rel.getEntityRef()
+ "(" + rel.getFieldRef().get(0) + ")");
// set inverse relation if it doesn't exists
if ("OneToMany".equals(rel.getType())) {
// Check if relation ManyToOne exists in target entity
final EntityMetadata entityRef =
this.metas.get(rel.getEntityRef());
// if it doesn't :
if (rel.getMappedBy() == null) {
// Create it
- final FieldMetadata newField = new FieldMetadata(cm);
+ final FieldMetadata newField = new FieldMetadata(entityRef);
newField.setColumnDefinition(TYPE_INTEGER);
newField.setHidden(true);
newField.setNullable(fieldMeta.isNullable());
newField.setInternal(true);
newField.setName(cm.getName() + fieldMeta.getName() + "_Internal");
newField.setColumnName(
cm.getName() + "_" + fieldMeta.getName() + "_internal");
newField.setType(cm.getName());
newField.setHarmonyType(TYPE_INTEGER);
newField.setRelation(new RelationMetadata());
newField.getRelation().setEntityRef(cm.getName());
for (final FieldMetadata idField : cm.getIds().values()) {
newField.getRelation().getFieldRef().add(
idField.getName());
}
newField.getRelation().setField(newField.getName());
newField.getRelation().setType("ManyToOne");
newField.getRelation().setInversedBy(fieldMeta.getName());
fieldMeta.getRelation().setInversedBy(newField.getName());
if (isRecursive) {
newFields.add(newField);
} else {
entityRef.getFields().put(newField.getName(), newField);
entityRef.getRelations().put(
newField.getName(), newField);
}
rel.setMappedBy(newField.getName());
} else { // Set inversedBy in mapping field
final FieldMetadata mappFm =
entityRef.getFields().get(rel.getMappedBy());
mappFm.getRelation().setInversedBy(fieldMeta.getName());
}
}
if ("ManyToMany".equals(rel.getType())) {
if (rel.getJoinTable() == null
|| rel.getJoinTable().isEmpty()) {
// Name JoinTable AtoB where A and B
// are the entities names ordered by alphabetic order
if (cm.getName().compareTo(rel.getEntityRef()) > 0) {
rel.setJoinTable(
cm.getName() + "to" + rel.getEntityRef());
} else {
rel.setJoinTable(
rel.getEntityRef() + "to" + cm.getName());
}
}
// If jointable doesn't exist yet, create it
if (!this.metas.containsKey(rel.getJoinTable())
&& !this.newMetas.containsKey(rel.getJoinTable())) {
ConsoleUtils.displayDebug(
"Association Table => " + rel.getJoinTable());
final EntityMetadata classMeta = new EntityMetadata();
classMeta.setName(rel.getJoinTable());
classMeta.setInternal(true);
classMeta.setSpace(cm.getSpace());
final FieldMetadata idField = new FieldMetadata(classMeta);
idField.setColumnDefinition(TYPE_INTEGER);
idField.setType(TYPE_INTEGER);
idField.setHarmonyType(TYPE_INTEGER);
idField.setName("id");
idField.setColumnName(idField.getName());
idField.setId(true);
classMeta.getIds().put("id", idField);
classMeta.getFields().put("id", idField);
final FieldMetadata ref1 =
- generateRefField(cm.getName(), cm);
+ generateRefField(cm.getName(), classMeta);
final RelationMetadata rel1 = new RelationMetadata();
rel1.setEntityRef(cm.getName());
for (final FieldMetadata cmid : cm.getIds().values()) {
rel1.getFieldRef().add(cmid.getName());
}
rel1.setInversedBy(fieldMeta.getName());
rel1.setType("ManyToOne");
ref1.setRelation(rel1);
classMeta.getFields().put(ref1.getName(), ref1);
classMeta.getRelations().put(ref1.getName(), ref1);
final FieldMetadata ref2 =
- generateRefField(rel.getEntityRef(), cm);
+ generateRefField(rel.getEntityRef(), classMeta);
final RelationMetadata rel2 = new RelationMetadata();
rel2.setEntityRef(rel.getEntityRef());
rel2.setFieldRef(rel.getFieldRef());
//rel2.inversedBy = rel.inversedBy;
rel2.setType("ManyToOne");
ref2.setRelation(rel2);
classMeta.getFields().put(ref2.getName(), ref2);
classMeta.getRelations().put(ref2.getName(), ref2);
this.newMetas.put(classMeta.getName(), classMeta);
// Complete it !
} else if (this.newMetas.containsKey(rel.getJoinTable())) {
final EntityMetadata jtable =
this.newMetas.get(rel.getJoinTable());
final FieldMetadata relation =
jtable.getRelations()
.get(cm.getName().toLowerCase() + "_id");
relation.getRelation().setInversedBy(fieldMeta.getName());
}
}
}
// Add internal recursive relations
for (final FieldMetadata newField : newFields) {
cm.getFields().put(newField.getName(), newField);
cm.getRelations().put(newField.getName(), newField);
}
}
/**
* Generate a reference field for relations.
* @param name referenced field name.
* @param owner New field owner.
* @return The newly created field.
*/
private static FieldMetadata generateRefField(final String name,
final EntityMetadata owner) {
final FieldMetadata idField = new FieldMetadata(owner);
idField.setColumnDefinition(TYPE_INTEGER);
idField.setType(TYPE_INTEGER);
idField.setHarmonyType(TYPE_INTEGER);
idField.setName(name.toLowerCase() + "_id");
idField.setColumnName(idField.getName());
return idField;
}
/**
* Check if field relation is valid.
* @param fm The field metadata of the relation.
*/
private void checkRelationIntegrity(final FieldMetadata fieldMeta) {
if (!this.metas.containsKey(fieldMeta.getRelation().getEntityRef())) {
ConsoleUtils.displayError(new ConstraintException(
"Entity "
+ fieldMeta.getName()
+ " refers to the non Entity class "
+ fieldMeta.getRelation().getEntityRef()));
}
}
/**
* Relation Constraint Exception.
*/
@SuppressWarnings("serial")
public static class ConstraintException extends Exception {
/**
* Constructor.
* @param msg The exception message.
*/
public ConstraintException(final String msg) {
super(msg);
}
}
private void updateInheritedIds(final EntityMetadata cm) {
// If entity has a mother
if (cm.getExtendType() != null) {
EntityMetadata mother = MetadataUtils.getTopMostMother(cm,
ApplicationMetadata.INSTANCE);
for (String idName : mother.getIds().keySet()) {
FieldMetadata id = mother.getIds().get(idName);
cm.getIds().put(idName, id);
cm.getFields().put(idName, id);
}
} else {
}
}
}
| false | true | private void updateRelations(final EntityMetadata cm) {
final ArrayList<FieldMetadata> newFields =
new ArrayList<FieldMetadata>();
// For each relation in the class
for (final FieldMetadata fieldMeta : cm.getRelations().values()) {
boolean isRecursive = false;
final RelationMetadata rel = fieldMeta.getRelation();
final String targetEntity = rel.getEntityRef();
if (targetEntity.equals(cm.getName())) {
isRecursive = true;
}
this.checkRelationIntegrity(fieldMeta);
if (rel.getFieldRef().isEmpty()) {
final EntityMetadata cmRef = this.metas.get(targetEntity);
final ArrayList<FieldMetadata> ids =
new ArrayList<FieldMetadata>(cmRef.getIds().values());
for (int i = 0; i < ids.size(); i++) {
rel.getFieldRef().add(ids.get(i).getName());
}
if (!ids.isEmpty()) {
fieldMeta.setColumnDefinition(ids.get(0).getType());
} else {
ConsoleUtils.displayError(new Exception(
"Error while updating relations : "
+ " Your entity " + cm.getName()
+ " refers the entity " + cmRef.getName()
+ " which has no ID defined."
+ " Please add the @Id annotation "
+ "to one of the fields of " + cmRef.getName()));
System.exit(-1);
}
}
ConsoleUtils.displayDebug("Relation " + rel.getType()
+ " on field " + rel.getField()
+ " targets " + rel.getEntityRef()
+ "(" + rel.getFieldRef().get(0) + ")");
// set inverse relation if it doesn't exists
if ("OneToMany".equals(rel.getType())) {
// Check if relation ManyToOne exists in target entity
final EntityMetadata entityRef =
this.metas.get(rel.getEntityRef());
// if it doesn't :
if (rel.getMappedBy() == null) {
// Create it
final FieldMetadata newField = new FieldMetadata(cm);
newField.setColumnDefinition(TYPE_INTEGER);
newField.setHidden(true);
newField.setNullable(fieldMeta.isNullable());
newField.setInternal(true);
newField.setName(cm.getName() + fieldMeta.getName() + "_Internal");
newField.setColumnName(
cm.getName() + "_" + fieldMeta.getName() + "_internal");
newField.setType(cm.getName());
newField.setHarmonyType(TYPE_INTEGER);
newField.setRelation(new RelationMetadata());
newField.getRelation().setEntityRef(cm.getName());
for (final FieldMetadata idField : cm.getIds().values()) {
newField.getRelation().getFieldRef().add(
idField.getName());
}
newField.getRelation().setField(newField.getName());
newField.getRelation().setType("ManyToOne");
newField.getRelation().setInversedBy(fieldMeta.getName());
fieldMeta.getRelation().setInversedBy(newField.getName());
if (isRecursive) {
newFields.add(newField);
} else {
entityRef.getFields().put(newField.getName(), newField);
entityRef.getRelations().put(
newField.getName(), newField);
}
rel.setMappedBy(newField.getName());
} else { // Set inversedBy in mapping field
final FieldMetadata mappFm =
entityRef.getFields().get(rel.getMappedBy());
mappFm.getRelation().setInversedBy(fieldMeta.getName());
}
}
if ("ManyToMany".equals(rel.getType())) {
if (rel.getJoinTable() == null
|| rel.getJoinTable().isEmpty()) {
// Name JoinTable AtoB where A and B
// are the entities names ordered by alphabetic order
if (cm.getName().compareTo(rel.getEntityRef()) > 0) {
rel.setJoinTable(
cm.getName() + "to" + rel.getEntityRef());
} else {
rel.setJoinTable(
rel.getEntityRef() + "to" + cm.getName());
}
}
// If jointable doesn't exist yet, create it
if (!this.metas.containsKey(rel.getJoinTable())
&& !this.newMetas.containsKey(rel.getJoinTable())) {
ConsoleUtils.displayDebug(
"Association Table => " + rel.getJoinTable());
final EntityMetadata classMeta = new EntityMetadata();
classMeta.setName(rel.getJoinTable());
classMeta.setInternal(true);
classMeta.setSpace(cm.getSpace());
final FieldMetadata idField = new FieldMetadata(classMeta);
idField.setColumnDefinition(TYPE_INTEGER);
idField.setType(TYPE_INTEGER);
idField.setHarmonyType(TYPE_INTEGER);
idField.setName("id");
idField.setColumnName(idField.getName());
idField.setId(true);
classMeta.getIds().put("id", idField);
classMeta.getFields().put("id", idField);
final FieldMetadata ref1 =
generateRefField(cm.getName(), cm);
final RelationMetadata rel1 = new RelationMetadata();
rel1.setEntityRef(cm.getName());
for (final FieldMetadata cmid : cm.getIds().values()) {
rel1.getFieldRef().add(cmid.getName());
}
rel1.setInversedBy(fieldMeta.getName());
rel1.setType("ManyToOne");
ref1.setRelation(rel1);
classMeta.getFields().put(ref1.getName(), ref1);
classMeta.getRelations().put(ref1.getName(), ref1);
final FieldMetadata ref2 =
generateRefField(rel.getEntityRef(), cm);
final RelationMetadata rel2 = new RelationMetadata();
rel2.setEntityRef(rel.getEntityRef());
rel2.setFieldRef(rel.getFieldRef());
//rel2.inversedBy = rel.inversedBy;
rel2.setType("ManyToOne");
ref2.setRelation(rel2);
classMeta.getFields().put(ref2.getName(), ref2);
classMeta.getRelations().put(ref2.getName(), ref2);
this.newMetas.put(classMeta.getName(), classMeta);
// Complete it !
} else if (this.newMetas.containsKey(rel.getJoinTable())) {
final EntityMetadata jtable =
this.newMetas.get(rel.getJoinTable());
final FieldMetadata relation =
jtable.getRelations()
.get(cm.getName().toLowerCase() + "_id");
relation.getRelation().setInversedBy(fieldMeta.getName());
}
}
}
// Add internal recursive relations
for (final FieldMetadata newField : newFields) {
cm.getFields().put(newField.getName(), newField);
cm.getRelations().put(newField.getName(), newField);
}
}
| private void updateRelations(final EntityMetadata cm) {
final ArrayList<FieldMetadata> newFields =
new ArrayList<FieldMetadata>();
// For each relation in the class
for (final FieldMetadata fieldMeta : cm.getRelations().values()) {
boolean isRecursive = false;
final RelationMetadata rel = fieldMeta.getRelation();
final String targetEntity = rel.getEntityRef();
if (targetEntity.equals(cm.getName())) {
isRecursive = true;
}
this.checkRelationIntegrity(fieldMeta);
if (rel.getFieldRef().isEmpty()) {
final EntityMetadata cmRef = this.metas.get(targetEntity);
final ArrayList<FieldMetadata> ids =
new ArrayList<FieldMetadata>(cmRef.getIds().values());
for (int i = 0; i < ids.size(); i++) {
rel.getFieldRef().add(ids.get(i).getName());
}
if (!ids.isEmpty()) {
fieldMeta.setColumnDefinition(ids.get(0).getType());
} else {
ConsoleUtils.displayError(new Exception(
"Error while updating relations : "
+ " Your entity " + cm.getName()
+ " refers the entity " + cmRef.getName()
+ " which has no ID defined."
+ " Please add the @Id annotation "
+ "to one of the fields of " + cmRef.getName()));
System.exit(-1);
}
}
ConsoleUtils.displayDebug("Relation " + rel.getType()
+ " on field " + rel.getField()
+ " targets " + rel.getEntityRef()
+ "(" + rel.getFieldRef().get(0) + ")");
// set inverse relation if it doesn't exists
if ("OneToMany".equals(rel.getType())) {
// Check if relation ManyToOne exists in target entity
final EntityMetadata entityRef =
this.metas.get(rel.getEntityRef());
// if it doesn't :
if (rel.getMappedBy() == null) {
// Create it
final FieldMetadata newField = new FieldMetadata(entityRef);
newField.setColumnDefinition(TYPE_INTEGER);
newField.setHidden(true);
newField.setNullable(fieldMeta.isNullable());
newField.setInternal(true);
newField.setName(cm.getName() + fieldMeta.getName() + "_Internal");
newField.setColumnName(
cm.getName() + "_" + fieldMeta.getName() + "_internal");
newField.setType(cm.getName());
newField.setHarmonyType(TYPE_INTEGER);
newField.setRelation(new RelationMetadata());
newField.getRelation().setEntityRef(cm.getName());
for (final FieldMetadata idField : cm.getIds().values()) {
newField.getRelation().getFieldRef().add(
idField.getName());
}
newField.getRelation().setField(newField.getName());
newField.getRelation().setType("ManyToOne");
newField.getRelation().setInversedBy(fieldMeta.getName());
fieldMeta.getRelation().setInversedBy(newField.getName());
if (isRecursive) {
newFields.add(newField);
} else {
entityRef.getFields().put(newField.getName(), newField);
entityRef.getRelations().put(
newField.getName(), newField);
}
rel.setMappedBy(newField.getName());
} else { // Set inversedBy in mapping field
final FieldMetadata mappFm =
entityRef.getFields().get(rel.getMappedBy());
mappFm.getRelation().setInversedBy(fieldMeta.getName());
}
}
if ("ManyToMany".equals(rel.getType())) {
if (rel.getJoinTable() == null
|| rel.getJoinTable().isEmpty()) {
// Name JoinTable AtoB where A and B
// are the entities names ordered by alphabetic order
if (cm.getName().compareTo(rel.getEntityRef()) > 0) {
rel.setJoinTable(
cm.getName() + "to" + rel.getEntityRef());
} else {
rel.setJoinTable(
rel.getEntityRef() + "to" + cm.getName());
}
}
// If jointable doesn't exist yet, create it
if (!this.metas.containsKey(rel.getJoinTable())
&& !this.newMetas.containsKey(rel.getJoinTable())) {
ConsoleUtils.displayDebug(
"Association Table => " + rel.getJoinTable());
final EntityMetadata classMeta = new EntityMetadata();
classMeta.setName(rel.getJoinTable());
classMeta.setInternal(true);
classMeta.setSpace(cm.getSpace());
final FieldMetadata idField = new FieldMetadata(classMeta);
idField.setColumnDefinition(TYPE_INTEGER);
idField.setType(TYPE_INTEGER);
idField.setHarmonyType(TYPE_INTEGER);
idField.setName("id");
idField.setColumnName(idField.getName());
idField.setId(true);
classMeta.getIds().put("id", idField);
classMeta.getFields().put("id", idField);
final FieldMetadata ref1 =
generateRefField(cm.getName(), classMeta);
final RelationMetadata rel1 = new RelationMetadata();
rel1.setEntityRef(cm.getName());
for (final FieldMetadata cmid : cm.getIds().values()) {
rel1.getFieldRef().add(cmid.getName());
}
rel1.setInversedBy(fieldMeta.getName());
rel1.setType("ManyToOne");
ref1.setRelation(rel1);
classMeta.getFields().put(ref1.getName(), ref1);
classMeta.getRelations().put(ref1.getName(), ref1);
final FieldMetadata ref2 =
generateRefField(rel.getEntityRef(), classMeta);
final RelationMetadata rel2 = new RelationMetadata();
rel2.setEntityRef(rel.getEntityRef());
rel2.setFieldRef(rel.getFieldRef());
//rel2.inversedBy = rel.inversedBy;
rel2.setType("ManyToOne");
ref2.setRelation(rel2);
classMeta.getFields().put(ref2.getName(), ref2);
classMeta.getRelations().put(ref2.getName(), ref2);
this.newMetas.put(classMeta.getName(), classMeta);
// Complete it !
} else if (this.newMetas.containsKey(rel.getJoinTable())) {
final EntityMetadata jtable =
this.newMetas.get(rel.getJoinTable());
final FieldMetadata relation =
jtable.getRelations()
.get(cm.getName().toLowerCase() + "_id");
relation.getRelation().setInversedBy(fieldMeta.getName());
}
}
}
// Add internal recursive relations
for (final FieldMetadata newField : newFields) {
cm.getFields().put(newField.getName(), newField);
cm.getRelations().put(newField.getName(), newField);
}
}
|
diff --git a/src/minecraft/co/uk/flansmods/client/tmt/ModelRendererTurbo.java b/src/minecraft/co/uk/flansmods/client/tmt/ModelRendererTurbo.java
index 95ae6760..8e116593 100644
--- a/src/minecraft/co/uk/flansmods/client/tmt/ModelRendererTurbo.java
+++ b/src/minecraft/co/uk/flansmods/client/tmt/ModelRendererTurbo.java
@@ -1,2256 +1,2256 @@
package co.uk.flansmods.client.tmt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.model.TexturedQuad;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
/**
* An extension to the ModelRenderer class. It basically is a copy to ModelRenderer,
* however, it contains various new methods to make your models.
* <br /><br />
* Since the ModelRendererTurbo class gets loaded during startup, the models made
* can be very complex. This is why I can afford to add, for example, Wavefont OBJ
* support or have the addSprite method, methods that add a lot of vertices and
* polygons.
* @author GaryCXJk
*
*/
public class ModelRendererTurbo extends ModelRenderer
{
public ModelRendererTurbo(ModelBase modelbase, String s)
{
super(modelbase, s);
flip = false;
compiled = false;
displayList = 0;
mirror = false;
showModel = true;
field_1402_i = false;
vertices = new PositionTextureVertex[0];
faces = new TexturedPolygon[0];
forcedRecompile = false;
transformGroup = new HashMap<String, TransformGroup>();
transformGroup.put("0", new TransformGroupBone(new Bone(0, 0, 0, 0), 1D));
textureGroup = new HashMap<String, TextureGroup>();
textureGroup.put("0", new TextureGroup());
currentTextureGroup = textureGroup.get("0");
boxName = s;
defaultTexture = "";
useLegacyCompiler = false;
}
public ModelRendererTurbo(ModelBase modelbase)
{
this(modelbase, null);
}
/**
* Creates a new ModelRenderTurbo object. It requires the coordinates of the
* position of the texture.
* @param modelbase
* @param textureX the x-coordinate on the texture
* @param textureY the y-coordinate on the texture
*/
public ModelRendererTurbo(ModelBase modelbase, int textureX, int textureY)
{
this(modelbase, textureX, textureY, 64, 32);
}
/**
* Creates a new ModelRenderTurbo object. It requires the coordinates of the
* position of the texture, but also allows you to specify the width and height
* of the texture, allowing you to use bigger textures instead.
* @param modelbase
* @param textureX
* @param textureY
* @param textureU
* @param textureV
*/
public ModelRendererTurbo(ModelBase modelbase, int textureX, int textureY, int textureU, int textureV)
{
this(modelbase);
textureOffsetX = textureX;
textureOffsetY = textureY;
textureWidth = textureU;
textureHeight = textureV;
}
/**
* Creates a new polygon.
* @param verts an array of vertices
*/
public void addPolygon(PositionTextureVertex[] verts)
{
copyTo(verts, new TexturedPolygon[] {new TexturedPolygon(verts)});
}
/**
* Creates a new polygon, and adds UV mapping to it.
* @param verts an array of vertices
* @param uv an array of UV coordinates
*/
public void addPolygon(PositionTextureVertex[] verts, int[][] uv)
{
try
{
for(int i = 0; i < verts.length; i++)
{
verts[i] = verts[i].setTexturePosition((float)uv[i][0] / textureWidth, (float)uv[i][1] / textureHeight);
}
}
finally
{
addPolygon(verts);
}
}
/**
* Creates a new polygon with a given UV.
* @param verts an array of vertices
* @param u1
* @param v1
* @param u2
* @param v2
*/
public void addPolygon(PositionTextureVertex[] verts, int u1, int v1, int u2, int v2)
{
copyTo(verts, new TexturedPolygon[] {addPolygonReturn(verts, u1, v1, u2, v2)});
}
private TexturedPolygon addPolygonReturn(PositionTextureVertex[] verts, int u1, int v1, int u2, int v2, float q1, float q2, float q3, float q4)
{
if(verts.length < 3)
return null;
float uOffs = 1.0F / ((float) textureWidth * 10.0F);
float vOffs = 1.0F / ((float) textureHeight * 10.0F);
if(verts.length < 4)
{
float xMin = -1;
float yMin = -1;
float xMax = 0;
float yMax = 0;
for(int i = 0; i < verts.length; i++)
{
float xPos = verts[i].texturePositionX;
float yPos = verts[i].texturePositionY;
xMax = Math.max(xMax, xPos);
xMin = (xMin < -1 ? xPos : Math.min(xMin, xPos));
yMax = Math.max(yMax, yPos);
yMin = (yMin < -1 ? yPos : Math.min(yMin, yPos));
}
float uMin = (float) u1 / (float) textureWidth + uOffs;
float vMin = (float) v1 / (float) textureHeight + vOffs;
float uSize = (float) (u2 - u1) / (float) textureWidth - uOffs * 2;
float vSize = (float) (v2 - v1) / (float) textureHeight - vOffs * 2;
float xSize = xMax - xMin;
float ySize = yMax - yMin;
for(int i = 0; i < verts.length; i++)
{
float xPos = verts[i].texturePositionX;
float yPos = verts[i].texturePositionY;
xPos = (xPos - xMin) / xSize;
yPos = (yPos - yMin) / ySize;
verts[i] = verts[i].setTexturePosition(uMin + (xPos * uSize), vMin + (yPos * vSize));
}
}
else
{
verts[0] = verts[0].setTexturePosition(((float)u2 / (float) textureWidth - uOffs)*q1, ((float)v1 / (float)textureHeight + vOffs)*q1, q1);
verts[1] = verts[1].setTexturePosition(((float)u1 / (float) textureWidth + uOffs)*q2, ((float)v1 / (float)textureHeight + vOffs)*q2, q2);
verts[2] = verts[2].setTexturePosition(((float)u1 / (float) textureWidth + uOffs)*q3, ((float)v2 / (float)textureHeight - vOffs)*q3, q3);
verts[3] = verts[3].setTexturePosition(((float)u2 / (float) textureWidth - uOffs)*q4, ((float)v2 / (float)textureHeight - vOffs)*q4, q4);
}
return new TexturedPolygon(verts);
}
private TexturedPolygon addPolygonReturn(PositionTextureVertex[] verts, int u1, int v1, int u2, int v2)
{
if(verts.length < 3)
return null;
float uOffs = 1.0F / ((float) textureWidth * 10.0F);
float vOffs = 1.0F / ((float) textureHeight * 10.0F);
if(verts.length < 4)
{
float xMin = -1;
float yMin = -1;
float xMax = 0;
float yMax = 0;
for(int i = 0; i < verts.length; i++)
{
float xPos = verts[i].texturePositionX;
float yPos = verts[i].texturePositionY;
xMax = Math.max(xMax, xPos);
xMin = (xMin < -1 ? xPos : Math.min(xMin, xPos));
yMax = Math.max(yMax, yPos);
yMin = (yMin < -1 ? yPos : Math.min(yMin, yPos));
}
float uMin = (float) u1 / (float) textureWidth + uOffs;
float vMin = (float) v1 / (float) textureHeight + vOffs;
float uSize = (float) (u2 - u1) / (float) textureWidth - uOffs * 2;
float vSize = (float) (v2 - v1) / (float) textureHeight - vOffs * 2;
float xSize = xMax - xMin;
float ySize = yMax - yMin;
for(int i = 0; i < verts.length; i++)
{
float xPos = verts[i].texturePositionX;
float yPos = verts[i].texturePositionY;
xPos = (xPos - xMin) / xSize;
yPos = (yPos - yMin) / ySize;
verts[i] = verts[i].setTexturePosition(uMin + (xPos * uSize), vMin + (yPos * vSize));
}
}
else
{
verts[0] = verts[0].setTexturePosition((float)u2 / (float) textureWidth - uOffs, (float)v1 / (float)textureHeight + vOffs);
verts[1] = verts[1].setTexturePosition((float)u1 / (float) textureWidth + uOffs, (float)v1 / (float)textureHeight + vOffs);
verts[2] = verts[2].setTexturePosition((float)u1 / (float) textureWidth + uOffs, (float)v2 / (float)textureHeight - vOffs);
verts[3] = verts[3].setTexturePosition((float)u2 / (float) textureWidth - uOffs, (float)v2 / (float)textureHeight - vOffs);
}
return new TexturedPolygon(verts);
}
/**
* Adds a rectangular shape. Basically, you can make any eight-pointed shape you want,
* as the method requires eight vector coordinates.
* @param v a float array with three values, the x, y and z coordinates of the vertex
* @param v1 a float array with three values, the x, y and z coordinates of the vertex
* @param v2 a float array with three values, the x, y and z coordinates of the vertex
* @param v3 a float array with three values, the x, y and z coordinates of the vertex
* @param v4 a float array with three values, the x, y and z coordinates of the vertex
* @param v5 a float array with three values, the x, y and z coordinates of the vertex
* @param v6 a float array with three values, the x, y and z coordinates of the vertex
* @param v7 a float array with three values, the x, y and z coordinates of the vertex
* @param w the width of the shape, used in determining the texture
* @param h the height of the shape, used in determining the texture
* @param d the depth of the shape, used in determining the texture
*/
public void addRectShape(float[] v, float[] v1, float[] v2, float[] v3, float[] v4, float[] v5, float[] v6, float[] v7, int w, int h, int d)
{
float[] var1 = new float[] {1,1,1,1,1,1,1,1,1,1,1,1};
addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, var1);
}
/**
* Adds a rectangular shape. Basically, you can make any eight-pointed shape you want,
* as the method requires eight vector coordinates. Also does some special texture mapping.
* @param v a float array with three values, the x, y and z coordinates of the vertex
* @param v1 a float array with three values, the x, y and z coordinates of the vertex
* @param v2 a float array with three values, the x, y and z coordinates of the vertex
* @param v3 a float array with three values, the x, y and z coordinates of the vertex
* @param v4 a float array with three values, the x, y and z coordinates of the vertex
* @param v5 a float array with three values, the x, y and z coordinates of the vertex
* @param v6 a float array with three values, the x, y and z coordinates of the vertex
* @param v7 a float array with three values, the x, y and z coordinates of the vertex
* @param w the width of the shape, used in determining the texture
* @param h the height of the shape, used in determining the texture
* @param d the depth of the shape, used in determining the texture
* @param qParam Array containing the q parameters in the order xBack, xBottom, xFront, xTop, yBack, yFront, yLeft, yRight, zBottom, zLeft, zRight, zTop
*/
public void addRectShape(float[] v, float[] v1, float[] v2, float[] v3, float[] v4, float[] v5, float[] v6, float[] v7, int w, int h, int d, float[] qParam)
{
PositionTextureVertex[] verts = new PositionTextureVertex[8];
TexturedPolygon[] poly = new TexturedPolygon[6];
PositionTextureVertex positionTexturevertex = new PositionTextureVertex(v[0], v[1], v[2], 0.0F, 0.0F);
PositionTextureVertex positionTexturevertex1 = new PositionTextureVertex(v1[0], v1[1], v1[2], 0.0F, 8F);
PositionTextureVertex positionTexturevertex2 = new PositionTextureVertex(v2[0], v2[1], v2[2], 8F, 8F);
PositionTextureVertex positionTexturevertex3 = new PositionTextureVertex(v3[0], v3[1], v3[2], 8F, 0.0F);
PositionTextureVertex positionTexturevertex4 = new PositionTextureVertex(v4[0], v4[1], v4[2], 0.0F, 0.0F);
PositionTextureVertex positionTexturevertex5 = new PositionTextureVertex(v5[0], v5[1], v5[2], 0.0F, 8F);
PositionTextureVertex positionTexturevertex6 = new PositionTextureVertex(v6[0], v6[1], v6[2], 8F, 8F);
PositionTextureVertex positionTexturevertex7 = new PositionTextureVertex(v7[0], v7[1], v7[2], 8F, 0.0F);
verts[0] = positionTexturevertex;
verts[1] = positionTexturevertex1;
verts[2] = positionTexturevertex2;
verts[3] = positionTexturevertex3;
verts[4] = positionTexturevertex4;
verts[5] = positionTexturevertex5;
verts[6] = positionTexturevertex6;
verts[7] = positionTexturevertex7;
poly[0] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex5, positionTexturevertex1, positionTexturevertex2, positionTexturevertex6
}, textureOffsetX + d + w, textureOffsetY + d, textureOffsetX + d + w + d, textureOffsetY + d + h,
1F, qParam[7], qParam[10]*qParam[7], qParam[10]);
poly[1] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex, positionTexturevertex4, positionTexturevertex7, positionTexturevertex3
}, textureOffsetX + 0, textureOffsetY + d, textureOffsetX + d, textureOffsetY + d + h,
qParam[9]*qParam[6], qParam[9], 1F, qParam[6]);
poly[2] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex5, positionTexturevertex4, positionTexturevertex, positionTexturevertex1
}, textureOffsetX + d, textureOffsetY + 0, textureOffsetX + d + w, textureOffsetY + d,
1F, qParam[8], qParam[1]*qParam[8], qParam[1]);
poly[3] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex2, positionTexturevertex3, positionTexturevertex7, positionTexturevertex6
}, textureOffsetX + d + w, textureOffsetY + 0, textureOffsetX + d + w + w, textureOffsetY + d,
qParam[3], qParam[3]*qParam[11], qParam[11], 1F);
poly[4] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex1, positionTexturevertex, positionTexturevertex3, positionTexturevertex2
}, textureOffsetX + d, textureOffsetY + d, textureOffsetX + d + w, textureOffsetY + d + h,
qParam[0], qParam[0]*qParam[4], qParam[4], 1F);
poly[5] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex4, positionTexturevertex5, positionTexturevertex6, positionTexturevertex7
}, textureOffsetX + d + w + d, textureOffsetY + d, textureOffsetX + d + w + d + w, textureOffsetY + d + h,
qParam[2]*qParam[5], qParam[2], 1F, qParam[5]);
if(mirror ^ flip)
{
for(int l = 0; l < poly.length; l++)
{
poly[l].flipFace();
}
}
copyTo(verts, poly);
}
/**
* Adds a new box to the model.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width (over the x-direction)
* @param h the height (over the y-direction)
* @param d the depth (over the z-direction)
*/
public ModelRendererTurbo addBox(float x, float y, float z, int w, int h, int d)
{
addBox(x, y, z, w, h, d, 0.0F);
return this;
}
/**
* Adds a new box to the model.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width (over the x-direction)
* @param h the height (over the y-direction)
* @param d the depth (over the z-direction)
* @param expansion the expansion of the box. It increases the size in each direction by that many.
*/
public void addBox(float x, float y, float z, int w, int h, int d, float expansion)
{
addBox(x, y, z, w, h, d, expansion, 1F);
}
/**
* Adds a new box to the model.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width (over the x-direction)
* @param h the height (over the y-direction)
* @param d the depth (over the z-direction)
* @param expansion the expansion of the box. It increases the size in each direction by that many. It's independent from the scale.
* @param scale
*/
public void addBox(float x, float y, float z, int w, int h, int d, float expansion, float scale)
{
float scaleX = (float)w * scale;
float scaleY = (float)h * scale;
float scaleZ = (float)d * scale;
float x1 = x + scaleX;
float y1 = y + scaleY;
float z1 = z + scaleZ;
float expX = expansion + scaleX - (float)w;
float expY = expansion + scaleY - (float)h;
float expZ = expansion + scaleZ - (float)d;
x -= expX;
y -= expY;
z -= expZ;
x1 += expansion;
y1 += expansion;
z1 += expansion;
if(mirror)
{
float xTemp = x1;
x1 = x;
x = xTemp;
}
float[] v = {x, y, z};
float[] v1 = {x1, y, z};
float[] v2 = {x1, y1, z};
float[] v3 = {x, y1, z};
float[] v4 = {x, y, z1};
float[] v5 = {x1, y, z1};
float[] v6 = {x1, y1, z1};
float[] v7 = {x, y1, z1};
addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d);
}
/**
* Adds a trapezoid-like shape. It's achieved by expanding the shape on one side.
* You can use the static variables <code>MR_RIGHT</code>, <code>MR_LEFT</code>,
* <code>MR_FRONT</code>, <code>MR_BACK</code>, <code>MR_TOP</code> and
* <code>MR_BOTTOM</code>.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width (over the x-direction)
* @param h the height (over the y-direction)
* @param d the depth (over the z-direction)
* @param scale the "scale" of the box. It only increases the size in each direction by that many.
* @param bottomScale the "scale" of the bottom
* @param dir the side the scaling is applied to
*/
public void addTrapezoid(float x, float y, float z, int w, int h, int d, float scale, float bottomScale, int dir)
{
float f4 = x + (float)w;
float f5 = y + (float)h;
float f6 = z + (float)d;
x -= scale;
y -= scale;
z -= scale;
f4 += scale;
f5 += scale;
f6 += scale;
int m = (mirror ? -1 : 1);
if(mirror)
{
float f7 = f4;
f4 = x;
x = f7;
}
float[] v = {x, y, z};
float[] v1 = {f4, y, z};
float[] v2 = {f4, f5, z};
float[] v3 = {x, f5, z};
float[] v4 = {x, y, f6};
float[] v5 = {f4, y, f6};
float[] v6 = {f4, f5, f6};
float[] v7 = {x, f5, f6};
switch(dir)
{
case MR_RIGHT:
v[1] -= bottomScale;
v[2] -= bottomScale;
v3[1] += bottomScale;
v3[2] -= bottomScale;
v4[1] -= bottomScale;
v4[2] += bottomScale;
v7[1] += bottomScale;
v7[2] += bottomScale;
break;
case MR_LEFT:
v1[1] -= bottomScale;
v1[2] -= bottomScale;
v2[1] += bottomScale;
v2[2] -= bottomScale;
v5[1] -= bottomScale;
v5[2] += bottomScale;
v6[1] += bottomScale;
v6[2] += bottomScale;
break;
case MR_FRONT:
v[0] -= m * bottomScale;
v[1] -= bottomScale;
v1[0] += m * bottomScale;
v1[1] -= bottomScale;
v2[0] += m * bottomScale;
v2[1] += bottomScale;
v3[0] -= m * bottomScale;
v3[1] += bottomScale;
break;
case MR_BACK:
v4[0] -= m * bottomScale;
v4[1] -= bottomScale;
v5[0] += m * bottomScale;
v5[1] -= bottomScale;
v6[0] += m * bottomScale;
v6[1] += bottomScale;
v7[0] -= m * bottomScale;
v7[1] += bottomScale;
break;
case MR_TOP:
v[0] -= m * bottomScale;
v[2] -= bottomScale;
v1[0] += m * bottomScale;
v1[2] -= bottomScale;
v4[0] -= m * bottomScale;
v4[2] += bottomScale;
v5[0] += m * bottomScale;
v5[2] += bottomScale;
break;
case MR_BOTTOM:
v2[0] += m * bottomScale;
v2[2] -= bottomScale;
v3[0] -= m * bottomScale;
v3[2] -= bottomScale;
v6[0] += m * bottomScale;
v6[2] += bottomScale;
v7[0] -= m * bottomScale;
v7[2] += bottomScale;
break;
}
float[] qValues = new float[] {
Math.abs((v[0] - v1[0])/(v3[0]-v2[0])),
Math.abs((v[0] - v1[0])/(v4[0]-v5[0])),
Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])),
Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])),
Math.abs((v[1] - v3[1])/(v1[1]-v2[1])),
Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])),
Math.abs((v[1] - v3[1])/(v4[1]-v7[1])),
Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])),
Math.abs((v[2] - v4[2])/(v1[2]-v5[2])),
Math.abs((v[2] - v4[2])/(v3[2]-v7[2])),
Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])),
Math.abs((v3[2] - v7[2])/(v2[2]-v6[2]))
};
addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues);
}
/**
* Adds a trapezoid-like shape. It's achieved by expanding the shape on one side.
* You can use the static variables <code>MR_RIGHT</code>, <code>MR_LEFT</code>,
* <code>MR_FRONT</code>, <code>MR_BACK</code>, <code>MR_TOP</code> and
* <code>MR_BOTTOM</code>.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width (over the x-direction)
* @param h the height (over the y-direction)
* @param d the depth (over the z-direction)
* @param scale the "scale" of the box. It only increases the size in each direction by that many.
* @param bScale1 the "scale" of the bottom - Top
* @param bScale2 the "scale" of the bottom - Bottom
* @param bScale3 the "scale" of the bottom - Left
* @param bScale4 the "scale" of the bottom - Right
* @param dir the side the scaling is applied to
*/
public void addFlexBox(float x, float y, float z, int w, int h, int d, float scale, float bScale1, float bScale2, float bScale3, float bScale4, int dir)
{
float f4 = x + (float)w;
float f5 = y + (float)h;
float f6 = z + (float)d;
x -= scale;
y -= scale;
z -= scale;
f4 += scale;
f5 += scale;
f6 += scale;
int m = (mirror ? -1 : 1);
if(mirror)
{
float f7 = f4;
f4 = x;
x = f7;
}
float[] v = {x, y, z};
float[] v1 = {f4, y, z};
float[] v2 = {f4, f5, z};
float[] v3 = {x, f5, z};
float[] v4 = {x, y, f6};
float[] v5 = {f4, y, f6};
float[] v6 = {f4, f5, f6};
float[] v7 = {x, f5, f6};
switch(dir)
{
case MR_RIGHT:
v[1] -= bScale1;
v[2] -= bScale3;
v3[1] += bScale2;
v3[2] -= bScale3;
v4[1] -= bScale1;
v4[2] += bScale4;
v7[1] += bScale2;
v7[2] += bScale4;
break;
case MR_LEFT:
v1[1] -= bScale1;
v1[2] -= bScale3;
v2[1] += bScale2;
v2[2] -= bScale3;
v5[1] -= bScale1;
v5[2] += bScale4;
v6[1] += bScale2;
v6[2] += bScale4;
break;
case MR_FRONT:
v[0] -= m * bScale4;
v[1] -= bScale1;
v1[0] += m * bScale3;
v1[1] -= bScale1;
v2[0] += m * bScale3;
v2[1] += bScale2;
v3[0] -= m * bScale4;
v3[1] += bScale2;
break;
case MR_BACK:
v4[0] -= m * bScale4;
v4[1] -= bScale1;
v5[0] += m * bScale3;
v5[1] -= bScale1;
v6[0] += m * bScale3;
v6[1] += bScale2;
v7[0] -= m * bScale4;
v7[1] += bScale2;
break;
case MR_TOP:
v[0] -= m * bScale1;
v[2] -= bScale3;
v1[0] += m * bScale2;
v1[2] -= bScale3;
v4[0] -= m * bScale1;
v4[2] += bScale4;
v5[0] += m * bScale2;
v5[2] += bScale4;
break;
case MR_BOTTOM:
v2[0] += m * bScale2;
v2[2] -= bScale3;
v3[0] -= m * bScale1;
v3[2] -= bScale3;
v6[0] += m * bScale2;
v6[2] += bScale4;
v7[0] -= m * bScale1;
v7[2] += bScale4;
break;
}
float[] qValues = new float[] {
Math.abs((v[0] - v1[0])/(v3[0]-v2[0])),
Math.abs((v[0] - v1[0])/(v4[0]-v5[0])),
Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])),
Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])),
Math.abs((v[1] - v3[1])/(v1[1]-v2[1])),
Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])),
Math.abs((v[1] - v3[1])/(v4[1]-v7[1])),
Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])),
Math.abs((v[2] - v4[2])/(v1[2]-v5[2])),
Math.abs((v[2] - v4[2])/(v3[2]-v7[2])),
Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])),
Math.abs((v3[2] - v7[2])/(v2[2]-v6[2]))
};
addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues);
}
/**
* Adds a trapezoid-like shape. It's achieved by expanding the shape on one side.
* You can use the static variables <code>MR_RIGHT</code>, <code>MR_LEFT</code>,
* <code>MR_FRONT</code>, <code>MR_BACK</code>, <code>MR_TOP</code> and
* <code>MR_BOTTOM</code>.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width (over the x-direction)
* @param h the height (over the y-direction)
* @param d the depth (over the z-direction)
* @param scale the "scale" of the box. It only increases the size in each direction by that many.
* @param bScale1 the "scale" of the bottom - Top
* @param bScale2 the "scale" of the bottom - Bottom
* @param bScale3 the "scale" of the bottom - Left
* @param bScale4 the "scale" of the bottom - Right
* @param fScale1 the "scale" of the top - Left
* @param fScale2 the "scale" of the top - Right
* @param dir the side the scaling is applied to
*/
public void addFlexTrapezoid(float x, float y, float z, int w, int h, int d, float scale, float bScale1, float bScale2, float bScale3, float bScale4, float fScale1, float fScale2, int dir)
{
float f4 = x + (float)w;
float f5 = y + (float)h;
float f6 = z + (float)d;
x -= scale;
y -= scale;
z -= scale;
f4 += scale;
f5 += scale;
f6 += scale;
int m = (mirror ? -1 : 1);
if(mirror)
{
float f7 = f4;
f4 = x;
x = f7;
}
float[] v = {x, y, z};
float[] v1 = {f4, y, z};
float[] v2 = {f4, f5, z};
float[] v3 = {x, f5, z};
float[] v4 = {x, y, f6};
float[] v5 = {f4, y, f6};
float[] v6 = {f4, f5, f6};
float[] v7 = {x, f5, f6};
switch(dir)
{
case MR_RIGHT:
v[2] -= fScale1;
v1[2] -= fScale1;
v4[2] += fScale2;
v5[2] += fScale2;
v[1] -= bScale1;
v[2] -= bScale3;
v3[1] += bScale2;
v3[2] -= bScale3;
v4[1] -= bScale1;
v4[2] += bScale4;
v7[1] += bScale2;
v7[2] += bScale4;
break;
case MR_LEFT:
v[2] -= fScale1;
v1[2] -= fScale1;
v4[2] += fScale2;
v5[2] += fScale2;
v1[1] -= bScale1;
v1[2] -= bScale3;
v2[1] += bScale2;
v2[2] -= bScale3;
v5[1] -= bScale1;
v5[2] += bScale4;
v6[1] += bScale2;
v6[2] += bScale4;
break;
case MR_FRONT:
- v2[1] += fScale1;
- v3[1] += fScale2;
+ v1[1] -= fScale1;
+ v5[1] -= fScale1;
+ v2[1] += fScale2;
v6[1] += fScale2;
- v7[1] += fScale1;
v[0] -= m * bScale4;
v[1] -= bScale1;
v1[0] += m * bScale3;
v1[1] -= bScale1;
v2[0] += m * bScale3;
v2[1] += bScale2;
v3[0] -= m * bScale4;
v3[1] += bScale2;
break;
case MR_BACK:
- v2[1] += fScale1;
- v3[1] += fScale2;
+ v1[1] -= fScale1;
+ v5[1] -= fScale1;
+ v2[1] += fScale2;
v6[1] += fScale2;
- v7[1] += fScale1;
v4[0] -= m * bScale4;
v4[1] -= bScale1;
v5[0] += m * bScale3;
v5[1] -= bScale1;
v6[0] += m * bScale3;
v6[1] += bScale2;
v7[0] -= m * bScale4;
v7[1] += bScale2;
break;
case MR_TOP:
v1[2] -= fScale1;
v2[2] -= fScale1;
v5[2] += fScale2;
v6[2] += fScale2;
v[0] -= m * bScale1;
v[2] -= bScale3;
v1[0] += m * bScale2;
v1[2] -= bScale3;
v4[0] -= m * bScale1;
v4[2] += bScale4;
v5[0] += m * bScale2;
v5[2] += bScale4;
break;
case MR_BOTTOM:
v1[2] -= fScale1;
v2[2] -= fScale1;
v5[2] += fScale2;
v6[2] += fScale2;
v2[0] += m * bScale2;
v2[2] -= bScale3;
v3[0] -= m * bScale1;
v3[2] -= bScale3;
v6[0] += m * bScale2;
v6[2] += bScale4;
v7[0] -= m * bScale1;
v7[2] += bScale4;
break;
}
float[] qValues = new float[] {
Math.abs((v[0] - v1[0])/(v3[0]-v2[0])),
Math.abs((v[0] - v1[0])/(v4[0]-v5[0])),
Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])),
Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])),
Math.abs((v[1] - v3[1])/(v1[1]-v2[1])),
Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])),
Math.abs((v[1] - v3[1])/(v4[1]-v7[1])),
Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])),
Math.abs((v[2] - v4[2])/(v1[2]-v5[2])),
Math.abs((v[2] - v4[2])/(v3[2]-v7[2])),
Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])),
Math.abs((v3[2] - v7[2])/(v2[2]-v6[2]))
};
addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues);
}
/**
* Adds a trapezoid-like shape. It's achieved by expanding the shape on one side.
* You can use the static variables <code>MR_RIGHT</code>, <code>MR_LEFT</code>,
* <code>MR_FRONT</code>, <code>MR_BACK</code>, <code>MR_TOP</code> and
* <code>MR_BOTTOM</code>.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width (over the x-direction)
* @param h the height (over the y-direction)
* @param d the depth (over the z-direction)
* @param scale the "scale" of the box. It only increases the size in each direction by that many.
* @param x0,y0,z0 - x7,y7,z7 the modifiers of the box corners. each corner can changed seperat by x/y/z values
*/
public void addShapeBox(float x, float y, float z, int w, int h, int d, float scale, float x0, float y0, float z0, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4, float x5, float y5, float z5, float x6, float y6, float z6, float x7, float y7, float z7)
{
float f4 = x + (float)w;
float f5 = y + (float)h;
float f6 = z + (float)d;
x -= scale;
y -= scale;
z -= scale;
f4 += scale;
f5 += scale;
f6 += scale;
int m = (mirror ? -1 : 1);
if(mirror)
{
float f7 = f4;
f4 = x;
x = f7;
}
float[] v = {x - x0, y - y0, z - z0};
float[] v1 = {f4 + x1, y - y1, z - z1};
float[] v2 = {f4 + x5, f5 + y5, z - z5};
float[] v3 = {x - x4, f5 + y4, z - z4};
float[] v4 = {x - x3, y - y3, f6 + z3};
float[] v5 = {f4 + x2, y - y2, f6 + z2};
float[] v6 = {f4 + x6, f5 + y6, f6 + z6};
float[] v7 = {x - x7, f5 + y7, f6 + z7};
float[] qValues = new float[] {
Math.abs((v[0] - v1[0])/(v3[0]-v2[0])),
Math.abs((v[0] - v1[0])/(v4[0]-v5[0])),
Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])),
Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])),
Math.abs((v[1] - v3[1])/(v1[1]-v2[1])),
Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])),
Math.abs((v[1] - v3[1])/(v4[1]-v7[1])),
Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])),
Math.abs((v[2] - v4[2])/(v1[2]-v5[2])),
Math.abs((v[2] - v4[2])/(v3[2]-v7[2])),
Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])),
Math.abs((v3[2] - v7[2])/(v2[2]-v6[2]))
};
addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues);
}
/**
* Creates a shape from a 2D vector shape.
* @param x the starting x position
* @param y the starting y position
* @param z the starting z position
* @param coordinates an array of coordinates that form the shape
* @param depth the depth of the shape
* @param shapeTextureWidth the width of the texture of one side of the shape
* @param shapeTextureHeight the height of the texture the shape
* @param sideTextureWidth the width of the texture of the side of the shape
* @param sideTextureHeight the height of the texture of the side of the shape
* @param direction the direction the starting point of the shape is facing
*/
public void addShape3D(float x, float y, float z, Coord2D[] coordinates, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction)
{
addShape3D(x, y, z, coordinates, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, null);
}
/**
* Creates a shape from a 2D vector shape.
* @param x the starting x position
* @param y the starting y position
* @param z the starting z position
* @param coordinates an array of coordinates that form the shape
* @param depth the depth of the shape
* @param shapeTextureWidth the width of the texture of one side of the shape
* @param shapeTextureHeight the height of the texture the shape
* @param sideTextureWidth the width of the texture of the side of the shape
* @param sideTextureHeight the height of the texture of the side of the shape
* @param direction the direction the starting point of the shape is facing
* @param faceLengths An array with the length of each face. Used to set
* the texture width of each face on the side manually.
*/
public void addShape3D(float x, float y, float z, Coord2D[] coordinates, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction, float[] faceLengths)
{
addShape3D(x, y, z, new Shape2D(coordinates), depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, faceLengths);
}
/**
* Creates a shape from a 2D vector shape.
* @param x the starting x position
* @param y the starting y position
* @param z the starting z position
* @param coordinates an ArrayList of coordinates that form the shape
* @param depth the depth of the shape
* @param shapeTextureWidth the width of the texture of one side of the shape
* @param shapeTextureHeight the height of the texture the shape
* @param sideTextureWidth the width of the texture of the side of the shape
* @param sideTextureHeight the height of the texture of the side of the shape
* @param direction the direction the starting point of the shape is facing
*/
public void addShape3D(float x, float y, float z, ArrayList<Coord2D> coordinates, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction)
{
addShape3D(x, y, z, coordinates, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, null);
}
/**
* Creates a shape from a 2D vector shape.
* @param x the starting x position
* @param y the starting y position
* @param z the starting z position
* @param coordinates an ArrayList of coordinates that form the shape
* @param depth the depth of the shape
* @param shapeTextureWidth the width of the texture of one side of the shape
* @param shapeTextureHeight the height of the texture the shape
* @param sideTextureWidth the width of the texture of the side of the shape
* @param sideTextureHeight the height of the texture of the side of the shape
* @param direction the direction the starting point of the shape is facing
* @param faceLengths An array with the length of each face. Used to set
* the texture width of each face on the side manually.
*/
public void addShape3D(float x, float y, float z, ArrayList<Coord2D> coordinates, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction, float[] faceLengths)
{
addShape3D(x, y, z, new Shape2D(coordinates), depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, faceLengths);
}
/**
* Creates a shape from a 2D vector shape.
* @param x the starting x position
* @param y the starting y position
* @param z the starting z position
* @param shape a Shape2D which contains the coordinates of the shape points
* @param depth the depth of the shape
* @param shapeTextureWidth the width of the texture of one side of the shape
* @param shapeTextureHeight the height of the texture the shape
* @param sideTextureWidth the width of the texture of the side of the shape
* @param sideTextureHeight the height of the texture of the side of the shape
* @param direction the direction the starting point of the shape is facing
*/
public void addShape3D(float x, float y, float z, Shape2D shape, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction)
{
addShape3D(x, y, z, shape, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, direction, null);
}
/**
* Creates a shape from a 2D vector shape.
* @param x the starting x position
* @param y the starting y position
* @param z the starting z position
* @param shape a Shape2D which contains the coordinates of the shape points
* @param depth the depth of the shape
* @param shapeTextureWidth the width of the texture of one side of the shape
* @param shapeTextureHeight the height of the texture the shape
* @param sideTextureWidth the width of the texture of the side of the shape
* @param sideTextureHeight the height of the texture of the side of the shape
* @param direction the direction the starting point of the shape is facing
* @param faceLengths An array with the length of each face. Used to set
* the texture width of each face on the side manually.
*/
public void addShape3D(float x, float y, float z, Shape2D shape, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, int direction, float[] faceLengths)
{
float rotX = 0;
float rotY = 0;
float rotZ = 0;
switch(direction)
{
case MR_LEFT:
rotY = pi / 2;
break;
case MR_RIGHT:
rotY = -pi / 2;
break;
case MR_TOP:
rotX = pi / 2;
break;
case MR_BOTTOM:
rotX = -pi / 2;
break;
case MR_FRONT:
rotY = pi;
break;
case MR_BACK:
break;
}
addShape3D(x, y, z, shape, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, rotX, rotY, rotZ, faceLengths);
}
/**
* Creates a shape from a 2D vector shape.
* @param x the starting x position
* @param y the starting y position
* @param z the starting z position
* @param shape a Shape2D which contains the coordinates of the shape points
* @param depth the depth of the shape
* @param shapeTextureWidth the width of the texture of one side of the shape
* @param shapeTextureHeight the height of the texture the shape
* @param sideTextureWidth the width of the texture of the side of the shape
* @param sideTextureHeight the height of the texture of the side of the shape
* @param rotX the rotation around the x-axis
* @param rotY the rotation around the y-axis
* @param rotZ the rotation around the z-axis
*/
public void addShape3D(float x, float y, float z, Shape2D shape, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, float rotX, float rotY, float rotZ)
{
addShape3D(x, y, z, shape, depth, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, rotX, rotY, rotZ, null);
}
public void addShape3D(float x, float y, float z, Shape2D shape, float depth, int shapeTextureWidth, int shapeTextureHeight, int sideTextureWidth, int sideTextureHeight, float rotX, float rotY, float rotZ, float[] faceLengths)
{
Shape3D shape3D = shape.extrude(x, y, z, rotX, rotY, rotZ, depth, textureOffsetX, textureOffsetY, textureWidth, textureHeight, shapeTextureWidth, shapeTextureHeight, sideTextureWidth, sideTextureHeight, faceLengths);
if(flip)
{
for(int idx = 0; idx < shape3D.faces.length; idx++)
{
shape3D.faces[idx].flipFace();
}
}
copyTo(shape3D.vertices, shape3D.faces);
}
/**
* Adds a cube the size of one pixel. It will take a pixel from the texture and
* uses that as the texture of said cube. The accurate name would actually be
* "addVoxel". This method has been added to make it more compatible with Techne,
* and allows for easy single-colored boxes.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param width the width of the box
* @param height the height of the box
* @param length the length of the box
*/
public void addPixel(float x, float y, float z, float width, float height, float length)
{
addPixel(x, y, z, new float[] {width, height, length}, textureOffsetX, textureOffsetY);
}
/**
* Adds a cube the size of one pixel. It will take a pixel from the texture and
* uses that as the texture of said cube. The accurate name would actually be
* "addVoxel". It will not overwrite the model data, but rather, it will add to
* the model.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param scale the "scale" of the cube, where scale is a float integer consisting of three values
* @param w the x-coordinate on the texture
* @param h the y-coordinate on the texture
*/
public void addPixel(float x, float y, float z, float[] scale, int w, int h)
{
PositionTextureVertex[] verts = new PositionTextureVertex[8];
TexturedPolygon[] poly = new TexturedPolygon[6];
float x1 = x + scale[0];
float y1 = y + scale[1];
float z1 = z + scale[2];
float[] f = {x, y, z};
float[] f1 = {x1, y, z};
float[] f2 = {x1, y1, z};
float[] f3 = {x, y1, z};
float[] f4 = {x, y, z1};
float[] f5 = {x1, y, z1};
float[] f6 = {x1, y1, z1};
float[] f7 = {x, y1, z1};
PositionTextureVertex positionTexturevertex = new PositionTextureVertex(f[0], f[1], f[2], 0.0F, 0.0F);
PositionTextureVertex positionTexturevertex1 = new PositionTextureVertex(f1[0], f1[1], f1[2], 0.0F, 8F);
PositionTextureVertex positionTexturevertex2 = new PositionTextureVertex(f2[0], f2[1], f2[2], 8F, 8F);
PositionTextureVertex positionTexturevertex3 = new PositionTextureVertex(f3[0], f3[1], f3[2], 8F, 0.0F);
PositionTextureVertex positionTexturevertex4 = new PositionTextureVertex(f4[0], f4[1], f4[2], 0.0F, 0.0F);
PositionTextureVertex positionTexturevertex5 = new PositionTextureVertex(f5[0], f5[1], f5[2], 0.0F, 8F);
PositionTextureVertex positionTexturevertex6 = new PositionTextureVertex(f6[0], f6[1], f6[2], 8F, 8F);
PositionTextureVertex positionTexturevertex7 = new PositionTextureVertex(f7[0], f7[1], f7[2], 8F, 0.0F);
verts[0] = positionTexturevertex;
verts[1] = positionTexturevertex1;
verts[2] = positionTexturevertex2;
verts[3] = positionTexturevertex3;
verts[4] = positionTexturevertex4;
verts[5] = positionTexturevertex5;
verts[6] = positionTexturevertex6;
verts[7] = positionTexturevertex7;
poly[0] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex5, positionTexturevertex1, positionTexturevertex2, positionTexturevertex6
}, w, h, w + 1, h + 1);
poly[1] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex, positionTexturevertex4, positionTexturevertex7, positionTexturevertex3
}, w, h, w + 1, h + 1);
poly[2] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex5, positionTexturevertex4, positionTexturevertex, positionTexturevertex1
}, w, h, w + 1, h + 1);
poly[3] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex2, positionTexturevertex3, positionTexturevertex7, positionTexturevertex6
}, w, h, w + 1, h + 1);
poly[4] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex1, positionTexturevertex, positionTexturevertex3, positionTexturevertex2
}, w, h, w + 1, h + 1);
poly[5] = addPolygonReturn(new PositionTextureVertex[] {
positionTexturevertex4, positionTexturevertex5, positionTexturevertex6, positionTexturevertex7
}, w, h, w + 1, h + 1);
copyTo(verts, poly);
}
/**
* Creates a model shaped like the exact image on the texture. Note that this method will
* increase the amount of quads on your model, which could effectively slow down your
* PC, so unless it is really a necessity to use it, I'd suggest you avoid using this
* method to create your model.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width of the sprite
* @param h the height of the sprite
* @param expansion the expansion of the sprite. It only increases the size in each direction by that many.
*/
public void addSprite(float x, float y, float z, int w, int h, float expansion)
{
addSprite(x, y, z, w, h, 1, false, false, false, false, false, expansion);
}
/**
* Creates a model shaped like the exact image on the texture. Note that this method will
* increase the amount of quads on your model, which could effectively slow down your
* PC, so unless it is really a necessity to use it, I'd suggest you avoid using this
* method to create your model.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width of the sprite
* @param h the height of the sprite
* @param rotX a boolean to define if it rotates 90 degrees around its yaw-axis
* @param rotY a boolean to define if it rotates 90 degrees around its pitch-axis
* @param rotZ a boolean to define if it rotates 90 degrees around its roll-axis
* @param mirrorX a boolean to define if the sprite should be mirrored
* @param mirrorY a boolean to define if the sprite should be flipped
* @param expansion the expansion of the sprite. It only increases the size in each direction by that many.
*/
public void addSprite(float x, float y, float z, int w, int h, boolean rotX, boolean rotY, boolean rotZ, boolean mirrorX, boolean mirrorY, float expansion)
{
addSprite(x, y, z, w, h, 1, rotX, rotY, rotZ, mirrorX, mirrorY, expansion);
}
/**
* Creates a model shaped like the exact image on the texture. Note that this method will
* increase the amount of quads on your model, which could effectively slow down your
* PC, so unless it is really a necessity to use it, I'd suggest you avoid using this
* method to create your model.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width of the sprite
* @param h the height of the sprite
* @param d the depth of the shape itself
* @param rotX a boolean to define if it rotates 90 degrees around its yaw-axis
* @param rotY a boolean to define if it rotates 90 degrees around its pitch-axis
* @param rotZ a boolean to define if it rotates 90 degrees around its roll-axis
* @param mirrorX a boolean to define if the sprite should be mirrored
* @param mirrorY a boolean to define if the sprite should be flipped
* @param expansion the expansion of the sprite. It only increases the size in each direction by that many.
*/
public void addSprite(float x, float y, float z, int w, int h, int d, boolean rotX, boolean rotY, boolean rotZ, boolean mirrorX, boolean mirrorY, float expansion)
{
addSprite(x, y, z, w, h, d, 1.0F, rotX, rotY, rotZ, mirrorX, mirrorY, expansion);
}
/**
* Creates a model shaped like the exact image on the texture. Note that this method will
* increase the amount of quads on your model, which could effectively slow down your
* PC, so unless it is really a necessity to use it, I'd suggest you avoid using this
* method to create your model.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param w the width of the sprite
* @param h the height of the sprite
* @param d the depth of the shape itself
* @param pixelScale the scale of each individual pixel
* @param rotX a boolean to define if it rotates 90 degrees around its yaw-axis
* @param rotY a boolean to define if it rotates 90 degrees around its pitch-axis
* @param rotZ a boolean to define if it rotates 90 degrees around its roll-axis
* @param mirrorX a boolean to define if the sprite should be mirrored
* @param mirrorY a boolean to define if the sprite should be flipped
* @param expansion the expansion of the sprite. It only increases the size in each direction by that many.
*/
public void addSprite(float x, float y, float z, int w, int h, int d, float pixelScale, boolean rotX, boolean rotY, boolean rotZ, boolean mirrorX, boolean mirrorY, float expansion)
{
String[] mask = new String[h];
char[] str = new char[w];
Arrays.fill(str, '1');
Arrays.fill(mask, new String(str));
addSprite(x, y, z, mask, d, pixelScale, rotX, rotY, rotZ, mirrorX, mirrorY, expansion);
}
/**
* Creates a model shaped like the exact image on the texture. Note that this method will
* increase the amount of quads on your model, which could effectively slow down your
* PC, so unless it is really a necessity to use it, I'd suggest you avoid using this
* method to create your model.
* <br /><br />
* This method uses a mask string. This way you can reduce the amount of quads used. To
* use this, create a String array, where you use a 1 to signify that the pixel will be
* drawn. Any other character will cause that pixel to not be drawn.
* @param x the starting x-position
* @param y the starting y-position
* @param z the starting z-position
* @param mask an array with the mask string
* @param d the depth of the shape itself
* @param pixelScale the scale of each individual pixel
* @param rotX a boolean to define if it rotates 90 degrees around its yaw-axis
* @param rotY a boolean to define if it rotates 90 degrees around its pitch-axis
* @param rotZ a boolean to define if it rotates 90 degrees around its roll-axis
* @param mirrorX a boolean to define if the sprite should be mirrored
* @param mirrorY a boolean to define if the sprite should be flipped
* @param expansion the expansion of the sprite. It only increases the size in each direction by that many.
*/
public void addSprite(float x, float y, float z, String[] mask, int d, float pixelScale, boolean rotX, boolean rotY, boolean rotZ, boolean mirrorX, boolean mirrorY, float expansion)
{
int w = mask[0].length();
int h = mask.length;
float x1 = x - expansion;
float y1 = y - expansion;
float z1 = z - expansion;
int wDir = 0;
int hDir = 0;
int dDir = 0;
float wScale = 1F + (expansion / ((float) w * pixelScale));
float hScale = 1F + (expansion / ((float) h * pixelScale));
if(!rotX)
{
if(!rotY)
{
if(!rotZ)
{
wDir = 0;
hDir = 1;
dDir = 2;
}
else
{
wDir = 1;
hDir = 0;
dDir = 2;
}
}
else
{
if(!rotZ)
{
wDir = 2;
hDir = 1;
dDir = 0;
}
else
{
wDir = 2;
hDir = 0;
dDir = 1;
}
}
}
else
{
if(!rotY)
{
if(!rotZ)
{
wDir = 0;
hDir = 2;
dDir = 1;
}
else
{
wDir = 1;
hDir = 2;
dDir = 0;
}
}
else
{
if(!rotZ)
{
wDir = 2;
hDir = 0;
dDir = 1;
}
else
{
wDir = 2;
hDir = 1;
dDir = 0;
}
}
}
int texStartX = textureOffsetX + (mirrorX ? w * 1 - 1 : 0);
int texStartY = textureOffsetY + (mirrorY ? h * 1 - 1 : 0);
int texDirX = (mirrorX ? -1 : 1);
int texDirY = (mirrorY ? -1 : 1);
float wVoxSize = getPixelSize(wScale, hScale, d * pixelScale + expansion * 2, 0, 1, wDir, 1, 1);
float hVoxSize = getPixelSize(wScale, hScale, d * pixelScale + expansion * 2, 0, 1, hDir, 1, 1);
float dVoxSize = getPixelSize(wScale, hScale, d * pixelScale + expansion * 2, 0, 1, dDir, 1, 1);
for(int i = 0; i < w; i++)
{
for(int j = 0; j < h; j++)
{
if(mask[j].charAt(i) == '1')
{
addPixel(x1 + getPixelSize(wScale, hScale, 0, wDir, hDir, 0, i, j),
y1 + getPixelSize(wScale, hScale, 0, wDir, hDir, 1, i, j),
z1 + getPixelSize(wScale, hScale, 0, wDir, hDir, 2, i, j),
new float[] {wVoxSize, hVoxSize, dVoxSize}, texStartX + texDirX * i, texStartY + texDirY * j);
}
}
}
}
private float getPixelSize(float wScale, float hScale, float dScale, int wDir, int hDir, int checkDir, int texPosX, int texPosY)
{
return (wDir == checkDir ? wScale * texPosX : (hDir == checkDir ? hScale * texPosY : dScale));
}
/**
* Adds a spherical shape.
* @param x
* @param y
* @param z
* @param r
* @param segs
* @param rings
* @param textureW
* @param textureH
*/
public void addSphere(float x, float y, float z, float r, int segs, int rings, int textureW, int textureH)
{
if(segs < 3)
segs = 3;
rings++;
PositionTextureVertex[] tempVerts = new PositionTextureVertex[segs * (rings - 1) + 2];
TexturedPolygon[] poly = new TexturedPolygon[segs * rings];
tempVerts[0] = new PositionTextureVertex(x, y - r, z, 0, 0);
tempVerts[tempVerts.length - 1] = new PositionTextureVertex(x, y + r, z, 0, 0);
float uOffs = 1.0F / ((float) textureWidth * 10.0F);
float vOffs = 1.0F / ((float) textureHeight * 10.0F);
float texW = (float) textureW / (float)textureWidth - 2F * uOffs;
float texH = (float) textureH / (float)textureHeight - 2F * vOffs;
float segW = texW / (float) segs;
float segH = texH / (float) rings;
float startU = (float) textureOffsetX / (float) textureWidth;
float startV = (float) textureOffsetY / (float) textureHeight;
int currentFace = 0;
for(int j = 1; j < rings; j++)
{
for(int i = 0; i < segs; i++)
{
float yWidth = MathHelper.cos(-pi / 2 + (pi / (float)rings) * (float) j);
float yHeight = MathHelper.sin(-pi / 2 + (pi / (float)rings) * (float) j);
float xSize = MathHelper.sin((pi / (float)segs) * i * 2F + pi) * yWidth;
float zSize = -MathHelper.cos((pi / (float)segs) * i * 2F + pi) * yWidth;
int curVert = 1 + i + segs * (j - 1);
tempVerts[curVert] = new PositionTextureVertex(x + xSize * r, y + yHeight * r, z + zSize * r, 0, 0);
if(i > 0)
{
PositionTextureVertex[] verts;
if(j == 1)
{
verts = new PositionTextureVertex[4];
verts[0] = tempVerts[curVert].setTexturePosition(startU + segW * i, startV + segH * j);
verts[1] = tempVerts[curVert - 1].setTexturePosition(startU + segW * (i - 1), startV + segH * j);
verts[2] = tempVerts[0].setTexturePosition(startU + segW * (i - 1), startV);
verts[3] = tempVerts[0].setTexturePosition(startU + segW + segW * i, startV);
}
else
{
verts = new PositionTextureVertex[4];
verts[0] = tempVerts[curVert].setTexturePosition(startU + segW * i, startV + segH * j);
verts[1] = tempVerts[curVert - 1].setTexturePosition(startU + segW * (i - 1), startV + segH * j);
verts[2] = tempVerts[curVert - 1 - segs].setTexturePosition(startU + segW * (i - 1), startV + segH * (j - 1));
verts[3] = tempVerts[curVert - segs].setTexturePosition(startU + segW * i, startV + segH * (j - 1));
}
poly[currentFace] = new TexturedPolygon(verts);
currentFace++;
}
}
PositionTextureVertex[] verts;
if(j == 1)
{
verts = new PositionTextureVertex[4];
verts[0] = tempVerts[1].setTexturePosition(startU + segW * segs, startV + segH * j);
verts[1] = tempVerts[segs].setTexturePosition(startU + segW * (segs - 1), startV + segH * j);
verts[2] = tempVerts[0].setTexturePosition(startU + segW * (segs - 1), startV);
verts[3] = tempVerts[0].setTexturePosition(startU + segW * segs, startV);
}
else
{
verts = new PositionTextureVertex[4];
verts[0] = tempVerts[1 + segs * (j - 1)].setTexturePosition(startU + texW, startV + segH * j);
verts[1] = tempVerts[segs * (j - 1) + segs].setTexturePosition(startU + texW - segW, startV + segH * j);
verts[2] = tempVerts[segs * (j - 1)].setTexturePosition(startU + texW - segW, startV + segH * (j - 1));
verts[3] = tempVerts[1 + segs * (j - 1) - segs].setTexturePosition(startU + texW, startV + segH * (j - 1));
}
poly[currentFace] = new TexturedPolygon(verts);
currentFace++;
}
for(int i = 0; i < segs; i++)
{
PositionTextureVertex[] verts = new PositionTextureVertex[3];
int curVert = tempVerts.length - (segs + 1);
verts[0] = tempVerts[tempVerts.length - 1].setTexturePosition(startU + segW * (i + 0.5F), startV + texH);
verts[1] = tempVerts[curVert + i].setTexturePosition(startU + segW * i, startV + texH - segH);
verts[2] = tempVerts[curVert + ((i + 1) % segs)].setTexturePosition(startU + segW * (i + 1), startV + texH - segH);
poly[currentFace] = new TexturedPolygon(verts);
currentFace++;
}
copyTo(tempVerts, poly);
}
/**
* Adds a cone.
* @param x the x-position of the base
* @param y the y-position of the base
* @param z the z-position of the base
* @param radius the radius of the cylinder
* @param length the length of the cylinder
* @param segments the amount of segments the cylinder is made of
*/
public void addCone(float x, float y, float z, float radius, float length, int segments)
{
addCone(x, y, z, radius, length, segments, 1F);
}
/**
* Adds a cone.
*
* baseScale cannot be zero. If it is, it will automatically be set to 1F.
*
* @param x the x-position of the base
* @param y the y-position of the base
* @param z the z-position of the base
* @param radius the radius of the cylinder
* @param length the length of the cylinder
* @param segments the amount of segments the cylinder is made of
* @param baseScale the scaling of the base. Can be negative.
*/
public void addCone(float x, float y, float z, float radius, float length, int segments, float baseScale)
{
addCone(x, y, z, radius, length, segments, baseScale, MR_TOP);
}
/**
* Adds a cone.
*
* baseScale cannot be zero. If it is, it will automatically be set to 1F.
*
* Setting the baseDirection to either MR_LEFT, MR_BOTTOM or MR_BACK will result in
* the top being placed at the (x,y,z).
*
* @param x the x-position of the base
* @param y the y-position of the base
* @param z the z-position of the base
* @param radius the radius of the cylinder
* @param length the length of the cylinder
* @param segments the amount of segments the cylinder is made of
* @param baseScale the scaling of the base. Can be negative.
* @param baseDirection the direction it faces
*/
public void addCone(float x, float y, float z, float radius, float length, int segments, float baseScale, int baseDirection)
{
addCone(x, y, z, radius, length, segments, baseScale, baseDirection, (int)Math.floor(radius * 2F), (int)Math.floor(radius * 2F));
}
/**
* Adds a cone.
*
* baseScale cannot be zero. If it is, it will automatically be set to 1F.
*
* Setting the baseDirection to either MR_LEFT, MR_BOTTOM or MR_BACK will result in
* the top being placed at the (x,y,z).
*
* The textures for the sides are placed next to each other.
*
* @param x the x-position of the base
* @param y the y-position of the base
* @param z the z-position of the base
* @param radius the radius of the cylinder
* @param length the length of the cylinder
* @param segments the amount of segments the cylinder is made of
* @param baseScale the scaling of the base. Can be negative.
* @param baseDirection the direction it faces
* @param textureCircleDiameterW the diameter width of the circle on the texture
* @param textureCircleDiameterH the diameter height of the circle on the texture
*/
public void addCone(float x, float y, float z, float radius, float length, int segments, float baseScale, int baseDirection, int textureCircleDiameterW, int textureCircleDiameterH)
{
addCylinder(x, y, z, radius, length, segments, baseScale, 0.0F, baseDirection, textureCircleDiameterW, textureCircleDiameterH, 1);
}
/**
* Adds a cylinder.
* @param x the x-position of the base
* @param y the y-position of the base
* @param z the z-position of the base
* @param radius the radius of the cylinder
* @param length the length of the cylinder
* @param segments the amount of segments the cylinder is made of
*/
public void addCylinder(float x, float y, float z, float radius, float length, int segments)
{
addCylinder(x, y, z, radius, length, segments, 1F, 1F);
}
/**
* Adds a cylinder.
*
* You can make cones by either setting baseScale or topScale to zero. Setting both
* to zero will set the baseScale to 1F.
*
* @param x the x-position of the base
* @param y the y-position of the base
* @param z the z-position of the base
* @param radius the radius of the cylinder
* @param length the length of the cylinder
* @param segments the amount of segments the cylinder is made of
* @param baseScale the scaling of the base. Can be negative.
* @param topScale the scaling of the top. Can be negative.
*/
public void addCylinder(float x, float y, float z, float radius, float length, int segments, float baseScale, float topScale)
{
addCylinder(x, y, z, radius, length, segments, baseScale, topScale, MR_TOP);
}
/**
* Adds a cylinder.
*
* You can make cones by either setting baseScale or topScale to zero. Setting both
* to zero will set the baseScale to 1F.
*
* Setting the baseDirection to either MR_LEFT, MR_BOTTOM or MR_BACK will result in
* the top being placed at the (x,y,z).
*
* @param x the x-position of the base
* @param y the y-position of the base
* @param z the z-position of the base
* @param radius the radius of the cylinder
* @param length the length of the cylinder
* @param segments the amount of segments the cylinder is made of
* @param baseScale the scaling of the base. Can be negative.
* @param topScale the scaling of the top. Can be negative.
* @param baseDirection the direction it faces
*/
public void addCylinder(float x, float y, float z, float radius, float length, int segments, float baseScale, float topScale, int baseDirection)
{
addCylinder(x, y, z, radius, length, segments, baseScale, topScale, baseDirection, (int)Math.floor(radius * 2F), (int)Math.floor(radius * 2F), (int)Math.floor(length));
}
/**
* Adds a cylinder.
*
* You can make cones by either setting baseScale or topScale to zero. Setting both
* to zero will set the baseScale to 1F.
*
* Setting the baseDirection to either MR_LEFT, MR_BOTTOM or MR_BACK will result in
* the top being placed at the (x,y,z).
*
* The textures for the base and top are placed next to each other, while the body
* will be placed below the circles.
*
* @param x the x-position of the base
* @param y the y-position of the base
* @param z the z-position of the base
* @param radius the radius of the cylinder
* @param length the length of the cylinder
* @param segments the amount of segments the cylinder is made of
* @param baseScale the scaling of the base. Can be negative.
* @param topScale the scaling of the top. Can be negative.
* @param baseDirection the direction it faces
* @param textureCircleDiameterW the diameter width of the circle on the texture
* @param textureCircleDiameterH the diameter height of the circle on the texture
* @param textureH the height of the texture of the body
*/
public void addCylinder(float x, float y, float z, float radius, float length, int segments, float baseScale, float topScale, int baseDirection, int textureCircleDiameterW, int textureCircleDiameterH, int textureH)
{
boolean dirTop = (baseDirection == MR_TOP || baseDirection == MR_BOTTOM);
boolean dirSide = (baseDirection == MR_RIGHT || baseDirection == MR_LEFT);
boolean dirFront = (baseDirection == MR_FRONT || baseDirection == MR_BACK);
boolean dirMirror = (baseDirection == MR_LEFT || baseDirection == MR_BOTTOM || baseDirection == MR_BACK);
boolean coneBase = (baseScale == 0);
boolean coneTop = (topScale == 0);
if(coneBase && coneTop)
{
baseScale = 1F;
coneBase = false;
}
PositionTextureVertex[] tempVerts = new PositionTextureVertex[segments * (coneBase || coneTop ? 1 : 2) + 2];
TexturedPolygon[] poly = new TexturedPolygon[segments * (coneBase || coneTop ? 2 : 3)];
float xLength = (dirSide ? length : 0);
float yLength = (dirTop ? length : 0);
float zLength = (dirFront ? length : 0);
float xStart = (dirMirror ? x + xLength : x);
float yStart = (dirMirror ? y + yLength : y);
float zStart = (dirMirror ? z + zLength : z);
float xEnd = (!dirMirror ? x + xLength : x);
float yEnd = (!dirMirror ? y + yLength : y);
float zEnd = (!dirMirror ? z + zLength : z);
tempVerts[0] = new PositionTextureVertex(xStart, yStart, zStart, 0, 0);
tempVerts[tempVerts.length - 1] = new PositionTextureVertex(xEnd, yEnd, zEnd, 0, 0);
float xCur = xStart;
float yCur = yStart;
float zCur = zStart;
float sCur = (coneBase ? topScale : baseScale);
for(int repeat = 0; repeat < (coneBase || coneTop ? 1 : 2); repeat++)
{
for(int index = 0; index < segments; index++)
{
float xSize = (mirror ^ dirMirror ? -1 : 1) * MathHelper.sin((pi / (float)segments) * index * 2F + pi) * radius * sCur;
float zSize = -MathHelper.cos((pi / (float)segments) * index * 2F + pi) * radius * sCur;
float xPlace = xCur + (!dirSide ? xSize : 0);
float yPlace = yCur + (!dirTop ? zSize : 0);
float zPlace = zCur + (dirSide ? xSize : (dirTop ? zSize : 0));
tempVerts[1 + index + repeat * segments] = new PositionTextureVertex(xPlace, yPlace, zPlace, 0, 0 );
}
xCur = xEnd;
yCur = yEnd;
zCur = zEnd;
sCur = topScale;
}
float uScale = 1.0F / (float) textureWidth;
float vScale = 1.0F / (float) textureHeight;
float uOffset = uScale / 20.0F;
float vOffset = vScale / 20.0F;
float uCircle = (float)textureCircleDiameterW * uScale;
float vCircle = (float)textureCircleDiameterH * vScale;
float uWidth = (uCircle * 2F - uOffset * 2F) / (float) segments;
float vHeight = (float)textureH * vScale - uOffset * 2f;
float uStart = (float)textureOffsetX * uScale;
float vStart = (float)textureOffsetY * vScale;
PositionTextureVertex[] vert;
for(int index = 0; index < segments; index++)
{
int index2 = (index + 1) % segments;
float uSize = MathHelper.sin((pi / (float)segments) * index * 2F + (!dirTop ? 0 : pi)) * (0.5F * uCircle - 2F * uOffset);
float vSize = MathHelper.cos((pi / (float)segments) * index * 2F + (!dirTop ? 0 : pi)) * (0.5F * vCircle - 2F * vOffset);
float uSize1 = MathHelper.sin((pi / (float)segments) * index2 * 2F + (!dirTop ? 0 : pi)) * (0.5F * uCircle - 2F * uOffset);
float vSize1 = MathHelper.cos((pi / (float)segments) * index2 * 2F + (!dirTop ? 0 : pi)) * (0.5F * vCircle - 2F * vOffset);
vert = new PositionTextureVertex[3];
vert[0] = tempVerts[0].setTexturePosition(uStart + 0.5F * uCircle, vStart + 0.5F * vCircle);
vert[1] = tempVerts[1 + index2].setTexturePosition(uStart + 0.5F * uCircle + uSize1, vStart + 0.5F * vCircle + vSize1);
vert[2] = tempVerts[1 + index].setTexturePosition(uStart + 0.5F * uCircle + uSize, vStart + 0.5F * vCircle + vSize);
poly[index] = new TexturedPolygon(vert);
if(mirror ^ flip)
poly[index].flipFace();
if(!coneBase && !coneTop)
{
vert = new PositionTextureVertex[4];
vert[0] = tempVerts[1 + index].setTexturePosition(uStart + uOffset + uWidth * (float)index, vStart + vOffset + vCircle);
vert[1] = tempVerts[1 + index2].setTexturePosition(uStart + uOffset + uWidth * (float)(index + 1), vStart + vOffset + vCircle);
vert[2] = tempVerts[1 + segments + index2].setTexturePosition(uStart + uOffset + uWidth * (float)(index + 1), vStart + vOffset + vCircle + vHeight);
vert[3] = tempVerts[1 + segments + index].setTexturePosition(uStart + uOffset + uWidth * (float)index, vStart + vOffset + vCircle + vHeight);
poly[index + segments] = new TexturedPolygon(vert);
if(mirror ^ flip)
poly[index + segments].flipFace();
}
vert = new PositionTextureVertex[3];
vert[0] = tempVerts[tempVerts.length - 1].setTexturePosition(uStart + 1.5F * uCircle, vStart + 0.5F * vCircle);
vert[1] = tempVerts[tempVerts.length - 2 - index].setTexturePosition(uStart + 1.5F * uCircle + uSize1, vStart + 0.5F * vCircle + vSize1);
vert[2] = tempVerts[tempVerts.length - (1 + segments) + ((segments - index) % segments)].setTexturePosition(uStart + 1.5F * uCircle + uSize, vStart + 0.5F * vCircle + vSize);
poly[poly.length - segments + index] = new TexturedPolygon(vert);
if(mirror ^ flip)
poly[poly.length - segments + index].flipFace();
}
copyTo(tempVerts, poly);
}
/**
* Adds a Waveform .obj file as a model. Model files use the entire texture file.
* @param file the location of the .obj file. The location is relative to the base directories,
* which are either resources/models or resources/mods/models.
*/
public void addObj(String file)
{
addModel(file, ModelPool.OBJ);
}
/**
* Adds model format support. Model files use the entire texture file.
* @param file the location of the model file. The location is relative to the base directories,
* which are either resources/models or resources/mods/models.
* @param modelFormat the class of the model format interpreter
*/
public void addModel(String file, Class modelFormat)
{
ModelPoolEntry entry = ModelPool.addFile(file, modelFormat, transformGroup, textureGroup);
if(entry == null)
return;
PositionTextureVertex[] verts = Arrays.copyOf(entry.vertices, entry.vertices.length);
TexturedPolygon[] poly = Arrays.copyOf(entry.faces, entry.faces.length);
if(flip)
{
for(int l = 0; l < faces.length; l++)
{
faces[l].flipFace();
}
}
copyTo(verts, poly, false);
}
/**
* Sets a new position for the texture offset.
* @param x the x-coordinate of the texture start
* @param y the y-coordinate of the texture start
*/
public ModelRendererTurbo setTextureOffset(int x, int y)
{
textureOffsetX = x;
textureOffsetY = y;
return this;
}
/**
* Sets the position of the shape, relative to the model's origins. Note that changing
* the offsets will not change the pivot of the model.
* @param x the x-position of the shape
* @param y the y-position of the shape
* @param z the z-position of the shape
*/
public void setPosition(float x, float y, float z)
{
rotationPointX = x;
rotationPointY = y;
rotationPointZ = z;
}
/**
* Mirrors the model in any direction.
* @param x whether the model should be mirrored in the x-direction
* @param y whether the model should be mirrored in the y-direction
* @param z whether the model should be mirrored in the z-direction
*/
public void doMirror(boolean x, boolean y, boolean z)
{
for(int i = 0; i < faces.length; i++)
{
PositionTextureVertex[] verts = faces[i].vertexPositions;
for(int j = 0; j < verts.length; j++)
{
verts[j].vector3D.xCoord *= (x ? -1 : 1);
verts[j].vector3D.yCoord *= (y ? -1 : 1);
verts[j].vector3D.zCoord *= (z ? -1 : 1);
}
if(x^y^z)
faces[i].flipFace();
}
}
/**
* Sets whether the shape is mirrored or not. This has effect on the way the textures
* get displayed. When working with addSprite, addPixel and addObj, it will be ignored.
* @param isMirrored a boolean to define whether the shape is mirrored
*/
public void setMirrored(boolean isMirrored)
{
mirror = isMirrored;
}
/**
* Sets whether the shape's faces are flipped or not. When GL_CULL_FACE is enabled,
* it won't render the back faces, effectively giving you the possibility to make
* "hollow" shapes. When working with addSprite and addPixel, it will be ignored.
* @param isFlipped a boolean to define whether the shape is flipped
*/
public void setFlipped(boolean isFlipped)
{
flip = isFlipped;
}
/**
* Clears the current shape. Since all shapes are stacked into one shape, you can't
* just replace a shape by overwriting the shape with another one. In this case you
* would need to clear the shape first.
*/
public void clear()
{
vertices = new PositionTextureVertex[0];
faces = new TexturedPolygon[0];
transformGroup.clear();
transformGroup.put("0", new TransformGroupBone(new Bone(0, 0, 0, 0), 1D));
currentGroup = transformGroup.get("0");
}
/**
* Copies an array of vertices and polygons to the current shape. This mainly is
* used to copy each shape to the main class, but you can just use it to copy
* your own shapes, for example from other classes, into the current class.
* @param verts the array of vertices you want to copy
* @param poly the array of polygons you want to copy
*/
public void copyTo(PositionTextureVertex[] verts, TexturedPolygon[] poly)
{
copyTo(verts, poly, true);
}
public void copyTo(PositionTextureVertex[] verts, TexturedPolygon[] poly, boolean copyGroup)
{
vertices = Arrays.copyOf(vertices, vertices.length + verts.length);
faces = Arrays.copyOf(faces, faces.length + poly.length);
for(int idx = 0; idx < verts.length; idx++)
{
vertices[vertices.length - verts.length + idx] = verts[idx];
if(copyGroup && verts[idx] instanceof PositionTransformVertex)
((PositionTransformVertex)verts[idx]).addGroup(currentGroup);
}
for(int idx = 0; idx < poly.length; idx++)
{
faces[faces.length - poly.length + idx] = poly[idx];
if(copyGroup)
currentTextureGroup.addPoly(poly[idx]);
}
}
/**
* Copies an array of vertices and quads to the current shape. This method
* converts quads to polygons and then calls the main copyTo method.
* @param verts the array of vertices you want to copy
* @param quad the array of quads you want to copy
*/
public void copyTo(PositionTextureVertex[] verts, TexturedQuad[] quad)
{
TexturedPolygon[] poly = new TexturedPolygon[quad.length];
for(int idx = 0; idx < quad.length; idx++)
{
poly[idx] = new TexturedPolygon((PositionTextureVertex[])quad[idx].vertexPositions);
}
copyTo(verts, poly);
}
/**
* Sets the current transformation group. The transformation group is used
* to allow for vertex transformation. If a transformation group does not exist,
* a new one will be created.
* @param groupName the name of the transformation group you want to switch to
*/
public void setGroup(String groupName)
{
setGroup(groupName, new Bone(0, 0, 0, 0), 1D);
}
/**
* Sets the current transformation group. The transformation group is used
* to allow for vertex transformation. If a transformation group does not exist,
* a new one will be created.
* @param groupName the name of the transformation group you want to switch to
* @param bone the Bone this transformation group is attached to
* @param weight the weight of the transformation group
*/
public void setGroup(String groupName, Bone bone, double weight)
{
if(!transformGroup.containsKey(groupName))
transformGroup.put(groupName, new TransformGroupBone(bone, weight));
currentGroup = transformGroup.get(groupName);
}
/**
* Gets the current transformation group.
* @return the current PositionTransformGroup.
*/
public TransformGroup getGroup()
{
return currentGroup;
}
/**
* Gets the transformation group with a given group name.
* @return the current PositionTransformGroup.
*/
public TransformGroup getGroup(String groupName)
{
if(!transformGroup.containsKey(groupName))
return null;
return transformGroup.get(groupName);
}
/**
* Sets the current texture group, which is used to switch the
* textures on a per-model base. Do note that any model that is
* rendered afterwards will use the same texture. To counter it,
* set a default texture, either at initialization or before
* rendering.
* @param groupName The name of the texture group. If the texture
* group doesn't exist, it creates a new group automatically.
*/
public void setTextureGroup(String groupName)
{
if(!textureGroup.containsKey(groupName))
{
textureGroup.put(groupName, new TextureGroup());
}
currentTextureGroup = textureGroup.get(groupName);
}
/**
* Gets the current texture group.
* @return a TextureGroup object.
*/
public TextureGroup getTextureGroup()
{
return currentTextureGroup;
}
/**
* Gets the texture group with the given name.
* @param groupName the name of the texture group to return
* @return a TextureGroup object.
*/
public TextureGroup getTextureGroup(String groupName)
{
if(!textureGroup.containsKey(groupName))
return null;
return textureGroup.get(groupName);
}
/**
* Sets the texture of the current texture group.
* @param s the filename
*/
public void setGroupTexture(String s)
{
currentTextureGroup.texture = s;
}
/**
* Sets the default texture. When left as an empty string,
* it will use the texture that has been set previously.
* Note that this will also move on to other rendered models
* of the same entity.
* @param s the filename
*/
public void setDefaultTexture(String s)
{
defaultTexture = s;
}
/**
* Renders the shape.
* @param worldScale the scale of the shape. Usually is 0.0625.
*/
public void render(float worldScale)
{
if(field_1402_i)
{
return;
}
if(!showModel)
{
return;
}
if(!compiled || forcedRecompile)
{
compileDisplayList(worldScale);
}
if(rotateAngleX != 0.0F || rotateAngleY != 0.0F || rotateAngleZ != 0.0F)
{
GL11.glPushMatrix();
GL11.glTranslatef(rotationPointX * worldScale, rotationPointY * worldScale, rotationPointZ * worldScale);
if(rotateAngleY != 0.0F)
{
GL11.glRotatef(rotateAngleY * 57.29578F, 0.0F, 1.0F, 0.0F);
}
if(rotateAngleZ != 0.0F)
{
GL11.glRotatef(rotateAngleZ * 57.29578F, 0.0F, 0.0F, 1.0F);
}
if(rotateAngleX != 0.0F)
{
GL11.glRotatef(rotateAngleX * 57.29578F, 1.0F, 0.0F, 0.0F);
}
callDisplayList();
if(childModels != null)
{
for(int i = 0; i < childModels.size(); i++)
{
((ModelRenderer)childModels.get(i)).render(worldScale);
}
}
GL11.glPopMatrix();
} else
if(rotationPointX != 0.0F || rotationPointY != 0.0F || rotationPointZ != 0.0F)
{
GL11.glTranslatef(rotationPointX * worldScale, rotationPointY * worldScale, rotationPointZ * worldScale);
callDisplayList();
if(childModels != null)
{
for(int i = 0; i < childModels.size(); i++)
{
((ModelRenderer)childModels.get(i)).render(worldScale);
}
}
GL11.glTranslatef(-rotationPointX * worldScale, -rotationPointY * worldScale, -rotationPointZ * worldScale);
} else
{
callDisplayList();
if(childModels != null)
{
for(int i = 0; i < childModels.size(); i++)
{
((ModelRenderer)childModels.get(i)).render(worldScale);
}
}
}
}
public void renderWithRotation(float f)
{
if(field_1402_i)
{
return;
}
if(!showModel)
{
return;
}
if(!compiled)
{
compileDisplayList(f);
}
GL11.glPushMatrix();
GL11.glTranslatef(rotationPointX * f, rotationPointY * f, rotationPointZ * f);
if(rotateAngleY != 0.0F)
{
GL11.glRotatef(rotateAngleY * 57.29578F, 0.0F, 1.0F, 0.0F);
}
if(rotateAngleX != 0.0F)
{
GL11.glRotatef(rotateAngleX * 57.29578F, 1.0F, 0.0F, 0.0F);
}
if(rotateAngleZ != 0.0F)
{
GL11.glRotatef(rotateAngleZ * 57.29578F, 0.0F, 0.0F, 1.0F);
}
callDisplayList();
GL11.glPopMatrix();
}
public void postRender(float f)
{
if(field_1402_i)
{
return;
}
if(!showModel)
{
return;
}
if(!compiled || forcedRecompile)
{
compileDisplayList(f);
}
if(rotateAngleX != 0.0F || rotateAngleY != 0.0F || rotateAngleZ != 0.0F)
{
GL11.glTranslatef(rotationPointX * f, rotationPointY * f, rotationPointZ * f);
if(rotateAngleZ != 0.0F)
{
GL11.glRotatef(rotateAngleZ * 57.29578F, 0.0F, 0.0F, 1.0F);
}
if(rotateAngleY != 0.0F)
{
GL11.glRotatef(rotateAngleY * 57.29578F, 0.0F, 1.0F, 0.0F);
}
if(rotateAngleX != 0.0F)
{
GL11.glRotatef(rotateAngleX * 57.29578F, 1.0F, 0.0F, 0.0F);
}
} else
if(rotationPointX != 0.0F || rotationPointY != 0.0F || rotationPointZ != 0.0F)
{
GL11.glTranslatef(rotationPointX * f, rotationPointY * f, rotationPointZ * f);
}
}
private void callDisplayList()
{
if(useLegacyCompiler)
GL11.glCallList(displayList);
else
{
TextureManager renderEngine = RenderManager.instance.renderEngine;
Collection<TextureGroup> textures = textureGroup.values();
Iterator<TextureGroup> itr = textures.iterator();
for(int i = 0; itr.hasNext(); i++)
{
TextureGroup curTexGroup = (TextureGroup)itr.next();
curTexGroup.loadTexture();
GL11.glCallList(displayListArray[i]);
if(!defaultTexture.equals(""))
renderEngine.bindTexture(new ResourceLocation("", defaultTexture)); //TODO : Check. Not sure about this one
}
}
}
private void compileDisplayList(float worldScale)
{
if(useLegacyCompiler)
compileLegacyDisplayList(worldScale);
else
{
Collection<TextureGroup> textures = textureGroup.values();
Iterator<TextureGroup> itr = textures.iterator();
displayListArray = new int[textureGroup.size()];
for(int i = 0; itr.hasNext(); i++)
{
displayListArray[i] = GLAllocation.generateDisplayLists(1);
GL11.glNewList(displayListArray[i], GL11.GL_COMPILE);
TmtTessellator tessellator = TmtTessellator.instance;
TextureGroup usedGroup = (TextureGroup)itr.next();
for(int j = 0; j < usedGroup.poly.size(); j++)
{
usedGroup.poly.get(j).draw(tessellator, worldScale);
}
GL11.glEndList();
}
}
compiled = true;
}
private void compileLegacyDisplayList(float worldScale)
{
displayList = GLAllocation.generateDisplayLists(1);
GL11.glNewList(displayList, GL11.GL_COMPILE);
TmtTessellator tessellator = TmtTessellator.instance;
for(int i = 0; i < faces.length; i++)
{
faces[i].draw(tessellator, worldScale);
}
GL11.glEndList();
}
private PositionTextureVertex vertices[];
private TexturedPolygon faces[];
private int textureOffsetX;
private int textureOffsetY;
private boolean compiled;
private int displayList;
private int displayListArray[];
private Map<String, TransformGroup> transformGroup;
private Map<String, TextureGroup> textureGroup;
private TransformGroup currentGroup;
private TextureGroup currentTextureGroup;
public boolean mirror;
public boolean flip;
public boolean showModel;
public boolean field_1402_i;
public boolean forcedRecompile;
public boolean useLegacyCompiler;
public List cubeList;
public List childModels;
public final String boxName;
private String defaultTexture;
public static final int MR_FRONT = 0;
public static final int MR_BACK = 1;
public static final int MR_LEFT = 2;
public static final int MR_RIGHT = 3;
public static final int MR_TOP = 4;
public static final int MR_BOTTOM = 5;
private static final float pi = (float) Math.PI;
}
| false | true | public void addFlexTrapezoid(float x, float y, float z, int w, int h, int d, float scale, float bScale1, float bScale2, float bScale3, float bScale4, float fScale1, float fScale2, int dir)
{
float f4 = x + (float)w;
float f5 = y + (float)h;
float f6 = z + (float)d;
x -= scale;
y -= scale;
z -= scale;
f4 += scale;
f5 += scale;
f6 += scale;
int m = (mirror ? -1 : 1);
if(mirror)
{
float f7 = f4;
f4 = x;
x = f7;
}
float[] v = {x, y, z};
float[] v1 = {f4, y, z};
float[] v2 = {f4, f5, z};
float[] v3 = {x, f5, z};
float[] v4 = {x, y, f6};
float[] v5 = {f4, y, f6};
float[] v6 = {f4, f5, f6};
float[] v7 = {x, f5, f6};
switch(dir)
{
case MR_RIGHT:
v[2] -= fScale1;
v1[2] -= fScale1;
v4[2] += fScale2;
v5[2] += fScale2;
v[1] -= bScale1;
v[2] -= bScale3;
v3[1] += bScale2;
v3[2] -= bScale3;
v4[1] -= bScale1;
v4[2] += bScale4;
v7[1] += bScale2;
v7[2] += bScale4;
break;
case MR_LEFT:
v[2] -= fScale1;
v1[2] -= fScale1;
v4[2] += fScale2;
v5[2] += fScale2;
v1[1] -= bScale1;
v1[2] -= bScale3;
v2[1] += bScale2;
v2[2] -= bScale3;
v5[1] -= bScale1;
v5[2] += bScale4;
v6[1] += bScale2;
v6[2] += bScale4;
break;
case MR_FRONT:
v2[1] += fScale1;
v3[1] += fScale2;
v6[1] += fScale2;
v7[1] += fScale1;
v[0] -= m * bScale4;
v[1] -= bScale1;
v1[0] += m * bScale3;
v1[1] -= bScale1;
v2[0] += m * bScale3;
v2[1] += bScale2;
v3[0] -= m * bScale4;
v3[1] += bScale2;
break;
case MR_BACK:
v2[1] += fScale1;
v3[1] += fScale2;
v6[1] += fScale2;
v7[1] += fScale1;
v4[0] -= m * bScale4;
v4[1] -= bScale1;
v5[0] += m * bScale3;
v5[1] -= bScale1;
v6[0] += m * bScale3;
v6[1] += bScale2;
v7[0] -= m * bScale4;
v7[1] += bScale2;
break;
case MR_TOP:
v1[2] -= fScale1;
v2[2] -= fScale1;
v5[2] += fScale2;
v6[2] += fScale2;
v[0] -= m * bScale1;
v[2] -= bScale3;
v1[0] += m * bScale2;
v1[2] -= bScale3;
v4[0] -= m * bScale1;
v4[2] += bScale4;
v5[0] += m * bScale2;
v5[2] += bScale4;
break;
case MR_BOTTOM:
v1[2] -= fScale1;
v2[2] -= fScale1;
v5[2] += fScale2;
v6[2] += fScale2;
v2[0] += m * bScale2;
v2[2] -= bScale3;
v3[0] -= m * bScale1;
v3[2] -= bScale3;
v6[0] += m * bScale2;
v6[2] += bScale4;
v7[0] -= m * bScale1;
v7[2] += bScale4;
break;
}
float[] qValues = new float[] {
Math.abs((v[0] - v1[0])/(v3[0]-v2[0])),
Math.abs((v[0] - v1[0])/(v4[0]-v5[0])),
Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])),
Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])),
Math.abs((v[1] - v3[1])/(v1[1]-v2[1])),
Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])),
Math.abs((v[1] - v3[1])/(v4[1]-v7[1])),
Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])),
Math.abs((v[2] - v4[2])/(v1[2]-v5[2])),
Math.abs((v[2] - v4[2])/(v3[2]-v7[2])),
Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])),
Math.abs((v3[2] - v7[2])/(v2[2]-v6[2]))
};
addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues);
}
| public void addFlexTrapezoid(float x, float y, float z, int w, int h, int d, float scale, float bScale1, float bScale2, float bScale3, float bScale4, float fScale1, float fScale2, int dir)
{
float f4 = x + (float)w;
float f5 = y + (float)h;
float f6 = z + (float)d;
x -= scale;
y -= scale;
z -= scale;
f4 += scale;
f5 += scale;
f6 += scale;
int m = (mirror ? -1 : 1);
if(mirror)
{
float f7 = f4;
f4 = x;
x = f7;
}
float[] v = {x, y, z};
float[] v1 = {f4, y, z};
float[] v2 = {f4, f5, z};
float[] v3 = {x, f5, z};
float[] v4 = {x, y, f6};
float[] v5 = {f4, y, f6};
float[] v6 = {f4, f5, f6};
float[] v7 = {x, f5, f6};
switch(dir)
{
case MR_RIGHT:
v[2] -= fScale1;
v1[2] -= fScale1;
v4[2] += fScale2;
v5[2] += fScale2;
v[1] -= bScale1;
v[2] -= bScale3;
v3[1] += bScale2;
v3[2] -= bScale3;
v4[1] -= bScale1;
v4[2] += bScale4;
v7[1] += bScale2;
v7[2] += bScale4;
break;
case MR_LEFT:
v[2] -= fScale1;
v1[2] -= fScale1;
v4[2] += fScale2;
v5[2] += fScale2;
v1[1] -= bScale1;
v1[2] -= bScale3;
v2[1] += bScale2;
v2[2] -= bScale3;
v5[1] -= bScale1;
v5[2] += bScale4;
v6[1] += bScale2;
v6[2] += bScale4;
break;
case MR_FRONT:
v1[1] -= fScale1;
v5[1] -= fScale1;
v2[1] += fScale2;
v6[1] += fScale2;
v[0] -= m * bScale4;
v[1] -= bScale1;
v1[0] += m * bScale3;
v1[1] -= bScale1;
v2[0] += m * bScale3;
v2[1] += bScale2;
v3[0] -= m * bScale4;
v3[1] += bScale2;
break;
case MR_BACK:
v1[1] -= fScale1;
v5[1] -= fScale1;
v2[1] += fScale2;
v6[1] += fScale2;
v4[0] -= m * bScale4;
v4[1] -= bScale1;
v5[0] += m * bScale3;
v5[1] -= bScale1;
v6[0] += m * bScale3;
v6[1] += bScale2;
v7[0] -= m * bScale4;
v7[1] += bScale2;
break;
case MR_TOP:
v1[2] -= fScale1;
v2[2] -= fScale1;
v5[2] += fScale2;
v6[2] += fScale2;
v[0] -= m * bScale1;
v[2] -= bScale3;
v1[0] += m * bScale2;
v1[2] -= bScale3;
v4[0] -= m * bScale1;
v4[2] += bScale4;
v5[0] += m * bScale2;
v5[2] += bScale4;
break;
case MR_BOTTOM:
v1[2] -= fScale1;
v2[2] -= fScale1;
v5[2] += fScale2;
v6[2] += fScale2;
v2[0] += m * bScale2;
v2[2] -= bScale3;
v3[0] -= m * bScale1;
v3[2] -= bScale3;
v6[0] += m * bScale2;
v6[2] += bScale4;
v7[0] -= m * bScale1;
v7[2] += bScale4;
break;
}
float[] qValues = new float[] {
Math.abs((v[0] - v1[0])/(v3[0]-v2[0])),
Math.abs((v[0] - v1[0])/(v4[0]-v5[0])),
Math.abs((v4[0] - v5[0])/(v7[0]-v6[0])),
Math.abs((v3[0] - v2[0])/(v7[0]-v6[0])),
Math.abs((v[1] - v3[1])/(v1[1]-v2[1])),
Math.abs((v4[1] - v7[1])/(v5[1]-v6[1])),
Math.abs((v[1] - v3[1])/(v4[1]-v7[1])),
Math.abs((v1[1] - v2[1])/(v5[1]-v6[1])),
Math.abs((v[2] - v4[2])/(v1[2]-v5[2])),
Math.abs((v[2] - v4[2])/(v3[2]-v7[2])),
Math.abs((v1[2] - v5[2])/(v2[2]-v6[2])),
Math.abs((v3[2] - v7[2])/(v2[2]-v6[2]))
};
addRectShape(v, v1, v2, v3, v4, v5, v6, v7, w, h, d, qValues);
}
|
diff --git a/e/hu.e.compiler/src/hu/e/compiler/tasks/AssembleHexFileTask.java b/e/hu.e.compiler/src/hu/e/compiler/tasks/AssembleHexFileTask.java
index 6e4cada3..e96a20e6 100644
--- a/e/hu.e.compiler/src/hu/e/compiler/tasks/AssembleHexFileTask.java
+++ b/e/hu.e.compiler/src/hu/e/compiler/tasks/AssembleHexFileTask.java
@@ -1,117 +1,120 @@
/**
*
*/
package hu.e.compiler.tasks;
import hexfile.AddressType;
import hexfile.Entry;
import hexfile.HexFile;
import hexfile.HexfileFactory;
import hu.e.compiler.IModembedTask;
import hu.e.compiler.ITaskContext;
import hu.modembed.hexfile.persistence.HexFileResource;
import hu.modembed.model.architecture.Architecture;
import hu.modembed.model.architecture.MemorySection;
import hu.modembed.model.core.assembler.ConstantSection;
import hu.modembed.model.core.assembler.Instruction;
import hu.modembed.model.core.assembler.InstructionParameter;
import hu.modembed.model.core.assembler.InstructionSection;
import hu.modembed.model.core.assembler.InstructionWord;
import hu.modembed.model.core.assembler.ParameterSection;
import hu.modembed.model.core.assembler.code.AssemblerObject;
import hu.modembed.model.core.assembler.code.InstructionCall;
import hu.modembed.model.core.assembler.code.InstructionCallParameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.resource.Resource;
/**
* @author balazs.grill
*
*/
public class AssembleHexFileTask implements IModembedTask {
public static final String INPUT = "input";
public static final String OUTPUT = "output";
public static final String ARCH = "arch";
/* (non-Javadoc)
* @see hu.e.compiler.IModembedTask#execute(hu.e.compiler.ITaskContext, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public void execute(ITaskContext context, IProgressMonitor monitor) {
String input = context.getParameterValue(INPUT).get(0);
Resource inputmodel = context.getInput(context.getModelURI(input));
AssemblerObject assem = (AssemblerObject) inputmodel.getContents().get(0);
String archmodel = context.getParameterValue(ARCH).get(0);
Resource archres = context.getInput(context.getModelURI(archmodel));
Architecture arch = (Architecture)archres.getContents().get(0);
HexFile hexfile = HexfileFactory.eINSTANCE.createHexFile();
- hexfile.setAddressType(AddressType.EXTENDED_SEGMENT);
+ hexfile.setAddressType(AddressType.EXTENDED_LINEAR);
Resource hexfileRes = context.getOutput(context.getFileURI(context.getParameterValue(OUTPUT).get(0)));
hexfileRes.getContents().add(hexfile);
List<MemorySection> programSections = new LinkedList<MemorySection>();
for(MemorySection ms : arch.getMemory()){
if (ms.isProgram()) programSections.add(ms);
}
List<InstructionCall> calls = assem.getInstructions();
List<Integer> bytes = new ArrayList<Integer>();
for(InstructionCall call : calls){
Map<InstructionParameter, Long> paramvalues = new HashMap<InstructionParameter, Long>();
for(InstructionCallParameter icp : call.getParameters()){
paramvalues.put(icp.getDefinition(), icp.getValue());
}
Instruction i = call.getInstruction();
- for(InstructionWord w : i.getWords()){
+ List<InstructionWord> words = i.getWords();
+ for(InstructionWord w : words){
long wordvalue = 0;
int length = 0;
- for(InstructionSection s : w.getSections()){
+ List<InstructionSection> sections = w.getSections();
+ for(int k=sections.size()-1;k>=0;k--){
+ InstructionSection s = sections.get(k);
long svalue = 0;
if (s instanceof ConstantSection){
svalue = ((ConstantSection) s).getValue();
}
if (s instanceof ParameterSection){
svalue = paramvalues.get(((ParameterSection) s).getParameter());
}
svalue = svalue << length;
svalue = svalue >> s.getShift();
long mask = Disassembler.mask(s.getSize(), length);
length += s.getSize();
wordvalue |= (svalue & mask);
}
int bytenum = ((length-1)/8)+1;
for(int j=0;j<bytenum;j++){
bytes.add((int)(wordvalue & 0xFF));
wordvalue = wordvalue >> 8;
}
}
}
Entry entry = HexfileFactory.eINSTANCE.createEntry();
hexfile.getEntries().add(entry);
entry.setAddress((int)programSections.get(0).getStartAddress());
byte[] data = new byte[bytes.size()];
for(int i=0;i<bytes.size();i++){
data[i] = HexFileResource.intToByte(bytes.get(i));
}
entry.setData(data);
}
}
| false | true | public void execute(ITaskContext context, IProgressMonitor monitor) {
String input = context.getParameterValue(INPUT).get(0);
Resource inputmodel = context.getInput(context.getModelURI(input));
AssemblerObject assem = (AssemblerObject) inputmodel.getContents().get(0);
String archmodel = context.getParameterValue(ARCH).get(0);
Resource archres = context.getInput(context.getModelURI(archmodel));
Architecture arch = (Architecture)archres.getContents().get(0);
HexFile hexfile = HexfileFactory.eINSTANCE.createHexFile();
hexfile.setAddressType(AddressType.EXTENDED_SEGMENT);
Resource hexfileRes = context.getOutput(context.getFileURI(context.getParameterValue(OUTPUT).get(0)));
hexfileRes.getContents().add(hexfile);
List<MemorySection> programSections = new LinkedList<MemorySection>();
for(MemorySection ms : arch.getMemory()){
if (ms.isProgram()) programSections.add(ms);
}
List<InstructionCall> calls = assem.getInstructions();
List<Integer> bytes = new ArrayList<Integer>();
for(InstructionCall call : calls){
Map<InstructionParameter, Long> paramvalues = new HashMap<InstructionParameter, Long>();
for(InstructionCallParameter icp : call.getParameters()){
paramvalues.put(icp.getDefinition(), icp.getValue());
}
Instruction i = call.getInstruction();
for(InstructionWord w : i.getWords()){
long wordvalue = 0;
int length = 0;
for(InstructionSection s : w.getSections()){
long svalue = 0;
if (s instanceof ConstantSection){
svalue = ((ConstantSection) s).getValue();
}
if (s instanceof ParameterSection){
svalue = paramvalues.get(((ParameterSection) s).getParameter());
}
svalue = svalue << length;
svalue = svalue >> s.getShift();
long mask = Disassembler.mask(s.getSize(), length);
length += s.getSize();
wordvalue |= (svalue & mask);
}
int bytenum = ((length-1)/8)+1;
for(int j=0;j<bytenum;j++){
bytes.add((int)(wordvalue & 0xFF));
wordvalue = wordvalue >> 8;
}
}
}
Entry entry = HexfileFactory.eINSTANCE.createEntry();
hexfile.getEntries().add(entry);
entry.setAddress((int)programSections.get(0).getStartAddress());
byte[] data = new byte[bytes.size()];
for(int i=0;i<bytes.size();i++){
data[i] = HexFileResource.intToByte(bytes.get(i));
}
entry.setData(data);
}
| public void execute(ITaskContext context, IProgressMonitor monitor) {
String input = context.getParameterValue(INPUT).get(0);
Resource inputmodel = context.getInput(context.getModelURI(input));
AssemblerObject assem = (AssemblerObject) inputmodel.getContents().get(0);
String archmodel = context.getParameterValue(ARCH).get(0);
Resource archres = context.getInput(context.getModelURI(archmodel));
Architecture arch = (Architecture)archres.getContents().get(0);
HexFile hexfile = HexfileFactory.eINSTANCE.createHexFile();
hexfile.setAddressType(AddressType.EXTENDED_LINEAR);
Resource hexfileRes = context.getOutput(context.getFileURI(context.getParameterValue(OUTPUT).get(0)));
hexfileRes.getContents().add(hexfile);
List<MemorySection> programSections = new LinkedList<MemorySection>();
for(MemorySection ms : arch.getMemory()){
if (ms.isProgram()) programSections.add(ms);
}
List<InstructionCall> calls = assem.getInstructions();
List<Integer> bytes = new ArrayList<Integer>();
for(InstructionCall call : calls){
Map<InstructionParameter, Long> paramvalues = new HashMap<InstructionParameter, Long>();
for(InstructionCallParameter icp : call.getParameters()){
paramvalues.put(icp.getDefinition(), icp.getValue());
}
Instruction i = call.getInstruction();
List<InstructionWord> words = i.getWords();
for(InstructionWord w : words){
long wordvalue = 0;
int length = 0;
List<InstructionSection> sections = w.getSections();
for(int k=sections.size()-1;k>=0;k--){
InstructionSection s = sections.get(k);
long svalue = 0;
if (s instanceof ConstantSection){
svalue = ((ConstantSection) s).getValue();
}
if (s instanceof ParameterSection){
svalue = paramvalues.get(((ParameterSection) s).getParameter());
}
svalue = svalue << length;
svalue = svalue >> s.getShift();
long mask = Disassembler.mask(s.getSize(), length);
length += s.getSize();
wordvalue |= (svalue & mask);
}
int bytenum = ((length-1)/8)+1;
for(int j=0;j<bytenum;j++){
bytes.add((int)(wordvalue & 0xFF));
wordvalue = wordvalue >> 8;
}
}
}
Entry entry = HexfileFactory.eINSTANCE.createEntry();
hexfile.getEntries().add(entry);
entry.setAddress((int)programSections.get(0).getStartAddress());
byte[] data = new byte[bytes.size()];
for(int i=0;i<bytes.size();i++){
data[i] = HexFileResource.intToByte(bytes.get(i));
}
entry.setData(data);
}
|
diff --git a/src/at/ac/tuwien/infosys/aicc11/services/RatingImpl.java b/src/at/ac/tuwien/infosys/aicc11/services/RatingImpl.java
index 67e9aa7..fb1832f 100644
--- a/src/at/ac/tuwien/infosys/aicc11/services/RatingImpl.java
+++ b/src/at/ac/tuwien/infosys/aicc11/services/RatingImpl.java
@@ -1,30 +1,31 @@
package at.ac.tuwien.infosys.aicc11.services;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.apache.cxf.jaxrs.impl.ResponseBuilderImpl;
import at.ac.tuwien.infosys.aicc11.Ratings;
import at.ac.tuwien.infosys.aicc11.legacy.LegacyCustomerRelationsManagement;
import at.ac.tuwien.infosys.aicc11.legacy.LegacyException;
public class RatingImpl implements Rating
{
LegacyCustomerRelationsManagement backend = LegacyCustomerRelationsManagement.instance();
public Ratings getRating(long customerId)
{
try {
return backend.getRating(customerId);
}
catch (LegacyException e) {
System.out.println(e);
ResponseBuilderImpl builder = new ResponseBuilderImpl();
- builder.status(Response.Status.NOT_FOUND);
- builder.entity("The requested customer id does not exist.");
+ builder.status(Response.Status.NOT_FOUND); // == 404
+ builder.type("text/html");
+ builder.entity("<h3>The requested customer id does not exist.</h3>");
Response resp = builder.build();
throw new WebApplicationException(resp);
}
}
}
| true | true | public Ratings getRating(long customerId)
{
try {
return backend.getRating(customerId);
}
catch (LegacyException e) {
System.out.println(e);
ResponseBuilderImpl builder = new ResponseBuilderImpl();
builder.status(Response.Status.NOT_FOUND);
builder.entity("The requested customer id does not exist.");
Response resp = builder.build();
throw new WebApplicationException(resp);
}
}
| public Ratings getRating(long customerId)
{
try {
return backend.getRating(customerId);
}
catch (LegacyException e) {
System.out.println(e);
ResponseBuilderImpl builder = new ResponseBuilderImpl();
builder.status(Response.Status.NOT_FOUND); // == 404
builder.type("text/html");
builder.entity("<h3>The requested customer id does not exist.</h3>");
Response resp = builder.build();
throw new WebApplicationException(resp);
}
}
|
diff --git a/milltown-map-swing/src/main/java/sciuto/corey/milltown/map/swing/components/MultiLineTextField.java b/milltown-map-swing/src/main/java/sciuto/corey/milltown/map/swing/components/MultiLineTextField.java
index c206e4b..5c5d54b 100755
--- a/milltown-map-swing/src/main/java/sciuto/corey/milltown/map/swing/components/MultiLineTextField.java
+++ b/milltown-map-swing/src/main/java/sciuto/corey/milltown/map/swing/components/MultiLineTextField.java
@@ -1,20 +1,21 @@
package sciuto.corey.milltown.map.swing.components;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;
public class MultiLineTextField extends JTextArea {
public MultiLineTextField(String name, int xSize, int ySize){
this.setName(name);
this.setMaximumSize(new Dimension(xSize,ySize));
this.setBorder(BorderFactory.createTitledBorder(null, getName(), TitledBorder.CENTER,TitledBorder.TOP));
this.setEditable(false);
+ this.setFocusable(false);
}
}
| true | true | public MultiLineTextField(String name, int xSize, int ySize){
this.setName(name);
this.setMaximumSize(new Dimension(xSize,ySize));
this.setBorder(BorderFactory.createTitledBorder(null, getName(), TitledBorder.CENTER,TitledBorder.TOP));
this.setEditable(false);
}
| public MultiLineTextField(String name, int xSize, int ySize){
this.setName(name);
this.setMaximumSize(new Dimension(xSize,ySize));
this.setBorder(BorderFactory.createTitledBorder(null, getName(), TitledBorder.CENTER,TitledBorder.TOP));
this.setEditable(false);
this.setFocusable(false);
}
|
diff --git a/spiffyui-app/src/main/java/org/spiffyui/spsample/client/GetStartedPanel.java b/spiffyui-app/src/main/java/org/spiffyui/spsample/client/GetStartedPanel.java
index 79f4145a..d6833a60 100644
--- a/spiffyui-app/src/main/java/org/spiffyui/spsample/client/GetStartedPanel.java
+++ b/spiffyui-app/src/main/java/org/spiffyui/spsample/client/GetStartedPanel.java
@@ -1,61 +1,61 @@
/*******************************************************************************
*
* 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.spiffyui.spsample.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;
/**
* This is the documentation panel
*
*/
public class GetStartedPanel extends HTMLPanel
{
private static final SPSampleStrings STRINGS = (SPSampleStrings) GWT.create(SPSampleStrings.class);
/**
* Creates a new panel
*/
public GetStartedPanel()
{
super("div", STRINGS.GetStartedPanel_html());
getElement().setId("getStartedPanel");
RootPanel.get("mainContent").add(this);
setVisible(false);
/*
* Add the get help anchor
*/
- Anchor getHelp = new Anchor("Get Help page", "GetHelpPanel");
+ Anchor getHelp = new Anchor("Help page", "GetHelpPanel");
getHelp.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
event.preventDefault();
Index.selectItem(Index.HELP_NAV_ITEM_ID);
}
});
add(getHelp, "getStartedGetHelp");
}
}
| true | true | public GetStartedPanel()
{
super("div", STRINGS.GetStartedPanel_html());
getElement().setId("getStartedPanel");
RootPanel.get("mainContent").add(this);
setVisible(false);
/*
* Add the get help anchor
*/
Anchor getHelp = new Anchor("Get Help page", "GetHelpPanel");
getHelp.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
event.preventDefault();
Index.selectItem(Index.HELP_NAV_ITEM_ID);
}
});
add(getHelp, "getStartedGetHelp");
}
| public GetStartedPanel()
{
super("div", STRINGS.GetStartedPanel_html());
getElement().setId("getStartedPanel");
RootPanel.get("mainContent").add(this);
setVisible(false);
/*
* Add the get help anchor
*/
Anchor getHelp = new Anchor("Help page", "GetHelpPanel");
getHelp.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
event.preventDefault();
Index.selectItem(Index.HELP_NAV_ITEM_ID);
}
});
add(getHelp, "getStartedGetHelp");
}
|
diff --git a/src/test/java/org/apache/hadoop/hbase/rest/TestStatusResource.java b/src/test/java/org/apache/hadoop/hbase/rest/TestStatusResource.java
index 2c0e7a673..a6b0e7a40 100644
--- a/src/test/java/org/apache/hadoop/hbase/rest/TestStatusResource.java
+++ b/src/test/java/org/apache/hadoop/hbase/rest/TestStatusResource.java
@@ -1,112 +1,112 @@
/*
* Copyright 2010 The Apache Software Foundation
*
* 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.hadoop.hbase.rest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.rest.client.Client;
import org.apache.hadoop.hbase.rest.client.Cluster;
import org.apache.hadoop.hbase.rest.client.Response;
import org.apache.hadoop.hbase.rest.model.StorageClusterStatusModel;
import org.apache.hadoop.hbase.util.Bytes;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestStatusResource {
private static final byte[] ROOT_REGION_NAME = Bytes.toBytes("-ROOT-,,0");
private static final byte[] META_REGION_NAME = Bytes.toBytes(".META.,,1");
private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static final HBaseRESTTestingUtility REST_TEST_UTIL =
new HBaseRESTTestingUtility(TEST_UTIL.getConfiguration());
private static Client client;
private static JAXBContext context;
private static void validate(StorageClusterStatusModel model) {
assertNotNull(model);
assertTrue(model.getRegions() >= 2);
assertTrue(model.getRequests() >= 0);
- // assumes minicluster with two regionservers
- assertTrue(model.getAverageLoad() >= 1.0);
+ // TODO: testing average load is flaky but not a stargate issue, revisit
+ // assertTrue(model.getAverageLoad() >= 1.0);
assertNotNull(model.getLiveNodes());
assertNotNull(model.getDeadNodes());
assertFalse(model.getLiveNodes().isEmpty());
boolean foundRoot = false, foundMeta = false;
for (StorageClusterStatusModel.Node node: model.getLiveNodes()) {
assertNotNull(node.getName());
assertTrue(node.getStartCode() > 0L);
assertTrue(node.getRequests() >= 0);
assertFalse(node.getRegions().isEmpty());
for (StorageClusterStatusModel.Node.Region region: node.getRegions()) {
if (Bytes.equals(region.getName(), ROOT_REGION_NAME)) {
foundRoot = true;
} else if (Bytes.equals(region.getName(), META_REGION_NAME)) {
foundMeta = true;
}
}
}
assertTrue(foundRoot);
assertTrue(foundMeta);
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
TEST_UTIL.startMiniCluster(2); // some tests depend on having only 2 RS
REST_TEST_UTIL.startServletContainer();
client = new Client(new Cluster().add("localhost",
REST_TEST_UTIL.getServletPort()));
context = JAXBContext.newInstance(StorageClusterStatusModel.class);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
REST_TEST_UTIL.shutdownServletContainer();
TEST_UTIL.shutdownMiniCluster();
}
@Test
public void testGetClusterStatusXML() throws IOException, JAXBException {
Response response = client.get("/status/cluster", Constants.MIMETYPE_XML);
assertEquals(response.getCode(), 200);
StorageClusterStatusModel model = (StorageClusterStatusModel)
context.createUnmarshaller().unmarshal(
new ByteArrayInputStream(response.getBody()));
validate(model);
}
@Test
public void testGetClusterStatusPB() throws IOException {
Response response = client.get("/status/cluster",
Constants.MIMETYPE_PROTOBUF);
assertEquals(response.getCode(), 200);
StorageClusterStatusModel model = new StorageClusterStatusModel();
model.getObjectFromMessage(response.getBody());
validate(model);
}
}
| true | true | private static void validate(StorageClusterStatusModel model) {
assertNotNull(model);
assertTrue(model.getRegions() >= 2);
assertTrue(model.getRequests() >= 0);
// assumes minicluster with two regionservers
assertTrue(model.getAverageLoad() >= 1.0);
assertNotNull(model.getLiveNodes());
assertNotNull(model.getDeadNodes());
assertFalse(model.getLiveNodes().isEmpty());
boolean foundRoot = false, foundMeta = false;
for (StorageClusterStatusModel.Node node: model.getLiveNodes()) {
assertNotNull(node.getName());
assertTrue(node.getStartCode() > 0L);
assertTrue(node.getRequests() >= 0);
assertFalse(node.getRegions().isEmpty());
for (StorageClusterStatusModel.Node.Region region: node.getRegions()) {
if (Bytes.equals(region.getName(), ROOT_REGION_NAME)) {
foundRoot = true;
} else if (Bytes.equals(region.getName(), META_REGION_NAME)) {
foundMeta = true;
}
}
}
assertTrue(foundRoot);
assertTrue(foundMeta);
}
| private static void validate(StorageClusterStatusModel model) {
assertNotNull(model);
assertTrue(model.getRegions() >= 2);
assertTrue(model.getRequests() >= 0);
// TODO: testing average load is flaky but not a stargate issue, revisit
// assertTrue(model.getAverageLoad() >= 1.0);
assertNotNull(model.getLiveNodes());
assertNotNull(model.getDeadNodes());
assertFalse(model.getLiveNodes().isEmpty());
boolean foundRoot = false, foundMeta = false;
for (StorageClusterStatusModel.Node node: model.getLiveNodes()) {
assertNotNull(node.getName());
assertTrue(node.getStartCode() > 0L);
assertTrue(node.getRequests() >= 0);
assertFalse(node.getRegions().isEmpty());
for (StorageClusterStatusModel.Node.Region region: node.getRegions()) {
if (Bytes.equals(region.getName(), ROOT_REGION_NAME)) {
foundRoot = true;
} else if (Bytes.equals(region.getName(), META_REGION_NAME)) {
foundMeta = true;
}
}
}
assertTrue(foundRoot);
assertTrue(foundMeta);
}
|
diff --git a/src/main/java/com/censoredsoftware/demigods/DemigodsPlugin.java b/src/main/java/com/censoredsoftware/demigods/DemigodsPlugin.java
index 08f0b3b0..03a46eb0 100644
--- a/src/main/java/com/censoredsoftware/demigods/DemigodsPlugin.java
+++ b/src/main/java/com/censoredsoftware/demigods/DemigodsPlugin.java
@@ -1,55 +1,55 @@
package com.censoredsoftware.demigods;
import com.censoredsoftware.demigods.data.DataManager;
import com.censoredsoftware.demigods.data.ThreadManager;
import com.censoredsoftware.demigods.exception.DemigodsStartupException;
import com.censoredsoftware.demigods.player.DPlayer;
import com.censoredsoftware.demigods.util.Messages;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Class for all plugins of demigods.
*/
public class DemigodsPlugin extends JavaPlugin
{
/**
* The Bukkit enable method.
*/
@Override
public void onEnable()
{
try
{
// Load the game engine.
new Demigods(this);
// Print success!
Messages.info("Successfully enabled.");
}
catch(DemigodsStartupException ignored)
{}
}
/**
* The Bukkit disable method.
*/
@Override
public void onDisable()
{
// Save all the data.
DataManager.save();
// Toggle all prayer off
for(Player player : Bukkit.getOnlinePlayers())
DPlayer.Util.togglePrayingSilent(player, false, false);;
- // Cancel all threads, callAbilityEvent calls, and connections.
+ // Cancel all threads, Event calls, and connections.
ThreadManager.stopThreads(this);
HandlerList.unregisterAll(this);
Messages.info("Successfully disabled.");
}
}
| true | true | public void onDisable()
{
// Save all the data.
DataManager.save();
// Toggle all prayer off
for(Player player : Bukkit.getOnlinePlayers())
DPlayer.Util.togglePrayingSilent(player, false, false);;
// Cancel all threads, callAbilityEvent calls, and connections.
ThreadManager.stopThreads(this);
HandlerList.unregisterAll(this);
Messages.info("Successfully disabled.");
}
| public void onDisable()
{
// Save all the data.
DataManager.save();
// Toggle all prayer off
for(Player player : Bukkit.getOnlinePlayers())
DPlayer.Util.togglePrayingSilent(player, false, false);;
// Cancel all threads, Event calls, and connections.
ThreadManager.stopThreads(this);
HandlerList.unregisterAll(this);
Messages.info("Successfully disabled.");
}
|
diff --git a/src/jobs/WorkerThread.java b/src/jobs/WorkerThread.java
index 911dbe1..4f69b56 100644
--- a/src/jobs/WorkerThread.java
+++ b/src/jobs/WorkerThread.java
@@ -1,143 +1,146 @@
package jobs;
import loadbalance.Adaptor;
import org.apache.log4j.Logger;
import util.Util;
import java.util.concurrent.atomic.AtomicBoolean;
public class WorkerThread {
private Integer id;
private Thread mainThread;
private Thread monitorThread;
private WorkerThreadManager wtm;
private Adaptor adaptor;
private boolean stopWork;
private AtomicBoolean isSuspended;
private static Long NO_JOB_SLEEP_INTERVAL = 2000L;
private static Long FINISH_SLEEP_INTERVAL = 1000L;
private static Long RUNNING_TIME = 700L;
private static Long SLEEPING_TIME = 1000L - RUNNING_TIME;
private static Logger logger = Logger.getLogger(WorkerThread.class);
private Job curRunJob;
public WorkerThread(Adaptor adaptor, WorkerThreadManager wtm, Integer id) {
stopWork = false;
isSuspended = new AtomicBoolean(false);
curRunJob = null;
this.adaptor = adaptor;
this.wtm = wtm;
this.id = id;
}
public void start() {
mainThread = new Thread(new Runnable() {
@Override
public void run() {
while(!stopWork) {
if(getJobQueue().isEmpty() && getCurRunJob() == null) {
Util.sleep(NO_JOB_SLEEP_INTERVAL);
continue;
}
if(!isSuspended.get()) {
if(getCurRunJob() == null) {
Job job = getJobQueue().pop();
if(job != null)
setCurRunJob(job);
}
if(!getCurRunJob().isFinished())
getCurRunJob().run();
if(getCurRunJob().isFinished()) {
System.out.println(getCurRunJob().getResult());
if(adaptor != null)
adaptor.jobFinished(getCurRunJob());
clearCurJob();
}
}
}
}
});
mainThread.start();
monitorThread = new Thread(new Runnable() {
@Override
public void run() {
while(!stopWork || getCurRunJob()!= null) {
- if(getCurRunJob() == null) continue;
+ if(getCurRunJob() == null) {
+ Util.sleep(NO_JOB_SLEEP_INTERVAL);
+ continue;
+ }
try {
getCurRunJob().resume();
Util.sleep(RUNNING_TIME);
getCurRunJob().stop();
Util.sleep(SLEEPING_TIME);
} catch (NullPointerException ex) {
//do nothing, it's okay when there is a NPE, since the job can be finished during waiting
}
}
}
});
monitorThread.start();
}
public void stop() {
stopWork = true;
}
/**
* This method will suspend the worker mainThread. However, it wont' stop running
* the current job.
*/
public void suspend() {
isSuspended.set(true);
}
public void resume() {
isSuspended.set(false);
}
public boolean setThrottling(Integer percentage) {
if(percentage <=0 || percentage >= 100) {
logger.error("Wrong Throttling Parameter");
return false;
}
RUNNING_TIME = (long) percentage * 10;
SLEEPING_TIME = 1000L - RUNNING_TIME;
return true;
}
private void setCurRunJob(Job job) {
synchronized (this) {
curRunJob = job;
job.setWorkerThreadId(id);
}
}
public Job getCurRunJob() {
synchronized (this) {
return curRunJob;
}
}
public void clearCurJob() {
synchronized (this) {
curRunJob = null;
}
}
private JobQueue getJobQueue() {
return wtm.getJobQueue();
}
private Integer getId() {
return id;
}
}
| true | true | public void start() {
mainThread = new Thread(new Runnable() {
@Override
public void run() {
while(!stopWork) {
if(getJobQueue().isEmpty() && getCurRunJob() == null) {
Util.sleep(NO_JOB_SLEEP_INTERVAL);
continue;
}
if(!isSuspended.get()) {
if(getCurRunJob() == null) {
Job job = getJobQueue().pop();
if(job != null)
setCurRunJob(job);
}
if(!getCurRunJob().isFinished())
getCurRunJob().run();
if(getCurRunJob().isFinished()) {
System.out.println(getCurRunJob().getResult());
if(adaptor != null)
adaptor.jobFinished(getCurRunJob());
clearCurJob();
}
}
}
}
});
mainThread.start();
monitorThread = new Thread(new Runnable() {
@Override
public void run() {
while(!stopWork || getCurRunJob()!= null) {
if(getCurRunJob() == null) continue;
try {
getCurRunJob().resume();
Util.sleep(RUNNING_TIME);
getCurRunJob().stop();
Util.sleep(SLEEPING_TIME);
} catch (NullPointerException ex) {
//do nothing, it's okay when there is a NPE, since the job can be finished during waiting
}
}
}
});
monitorThread.start();
}
| public void start() {
mainThread = new Thread(new Runnable() {
@Override
public void run() {
while(!stopWork) {
if(getJobQueue().isEmpty() && getCurRunJob() == null) {
Util.sleep(NO_JOB_SLEEP_INTERVAL);
continue;
}
if(!isSuspended.get()) {
if(getCurRunJob() == null) {
Job job = getJobQueue().pop();
if(job != null)
setCurRunJob(job);
}
if(!getCurRunJob().isFinished())
getCurRunJob().run();
if(getCurRunJob().isFinished()) {
System.out.println(getCurRunJob().getResult());
if(adaptor != null)
adaptor.jobFinished(getCurRunJob());
clearCurJob();
}
}
}
}
});
mainThread.start();
monitorThread = new Thread(new Runnable() {
@Override
public void run() {
while(!stopWork || getCurRunJob()!= null) {
if(getCurRunJob() == null) {
Util.sleep(NO_JOB_SLEEP_INTERVAL);
continue;
}
try {
getCurRunJob().resume();
Util.sleep(RUNNING_TIME);
getCurRunJob().stop();
Util.sleep(SLEEPING_TIME);
} catch (NullPointerException ex) {
//do nothing, it's okay when there is a NPE, since the job can be finished during waiting
}
}
}
});
monitorThread.start();
}
|
diff --git a/modules/plus/src/test/java/org/mortbay/jetty/plus/jaas/TestJAASUserRealm.java b/modules/plus/src/test/java/org/mortbay/jetty/plus/jaas/TestJAASUserRealm.java
index 70c7d6c7f..6384326c8 100644
--- a/modules/plus/src/test/java/org/mortbay/jetty/plus/jaas/TestJAASUserRealm.java
+++ b/modules/plus/src/test/java/org/mortbay/jetty/plus/jaas/TestJAASUserRealm.java
@@ -1,275 +1,282 @@
// ========================================================================
// $Id$
// Copyright 2003-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.mortbay.jetty.plus.jaas;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Properties;
import java.util.Random;
import javax.naming.Context;
import javax.naming.InitialContext;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.mortbay.jetty.Request;
/* ---------------------------------------------------- */
/** TestJAASUserRealm
* <p> Test JAAS in Jetty - relies on the JDBCUserRealm.
*
* <p><h4>Notes</h4>
* <p>
*
* <p><h4>Usage</h4>
* <pre>
*/
/*
* </pre>
*
* @see
* @version 1.0 Mon Apr 28 2003
* @author Jan Bartel (janb)
*/
public class TestJAASUserRealm extends TestCase
{
private static boolean setupDone = false;
private Random random = new Random();
public TestJAASUserRealm(String name)
throws Exception
{
super (name);
}
public static Test suite()
{
return new TestSuite(TestJAASUserRealm.class);
}
public void setUp ()
throws Exception
{
if (setupDone)
return;
//set up the properties
File propsFile = File.createTempFile("props", null);
propsFile.deleteOnExit();
Properties props = new Properties ();
props.put("user", "user,user,pleb");
FileOutputStream fout=new FileOutputStream(propsFile);
props.store(fout, "");
fout.close();
//set up config
File configFile = File.createTempFile ("loginConf", null);
configFile.deleteOnExit();
PrintWriter writer = new PrintWriter(new FileWriter(configFile));
writer.println ("props {");
writer.println ("org.mortbay.jetty.plus.jaas.spi.PropertyFileLoginModule required");
writer.println ("debug=\"true\"");
writer.println ("file=\""+propsFile.getCanonicalPath().replace('\\','/') +"\";");
writer.println ("};");
writer.println ("ds {");
writer.println ("org.mortbay.jetty.plus.jaas.spi.DataSourceLoginModule required");
writer.println ("debug=\"true\"");
writer.println ("dbJNDIName=\"ds\"");
writer.println ("userTable=\"myusers\"");
writer.println ("userField=\"myuser\"");
writer.println ("credentialField=\"mypassword\"");
writer.println ("userRoleTable=\"myuserroles\"");
writer.println ("userRoleUserField=\"myuser\"");
writer.println ("userRoleRoleField=\"myrole\";");
writer.println ("};");
writer.flush();
writer.close();
BufferedReader reader = new BufferedReader(new FileReader(configFile));
String s = "";
for (s = reader.readLine(); (s != null); s = reader.readLine())
{
System.out.println (s);
}
//create a login module config file
System.setProperty ("java.security.auth.login.config", configFile.toURL().toExternalForm());
setupDone = true;
}
public void testItDataSource ()
throws Exception
{
String tmpDir = System.getProperty("java.io.tmpdir")+System.getProperty("file.separator");
System.setProperty("derby.system.home", tmpDir);
String dbname = "derby-"+(int)(random.nextDouble()*10000);
EmbeddedDataSource eds = new EmbeddedDataSource();
try
{
//make the java:comp/env
InitialContext ic = new InitialContext();
Context comp = (Context)ic.lookup("java:comp");
Context env = comp.createSubcontext ("env");
//make a DataSource
eds.setDatabaseName(dbname);
eds.setCreateDatabase("create");
env.createSubcontext("jdbc");
env.bind("ds", eds);
Connection connection = eds.getConnection();
//create tables
String sql = "create table myusers (myuser varchar(32) PRIMARY KEY, mypassword varchar(32))";
Statement createStatement = connection.createStatement();
createStatement.executeUpdate (sql);
sql = " create table myuserroles (myuser varchar(32), myrole varchar(32))";
createStatement.executeUpdate (sql);
createStatement.close();
//insert test users and roles
sql = "insert into myusers (myuser, mypassword) values (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString (1, "me");
statement.setString (2, "me");
statement.executeUpdate();
sql = "insert into myuserroles (myuser, myrole) values ( ? , ? )";
statement = connection.prepareStatement (sql);
statement.setString (1, "me");
statement.setString (2, "roleA");
statement.executeUpdate();
statement.setString(1, "me");
statement.setString(2, "roleB");
statement.executeUpdate();
statement.close();
connection.close();
//create a JAASUserRealm
JAASUserRealm realm = new JAASUserRealm ("testRealm");
realm.setLoginModuleName ("ds");
JAASUserPrincipal userPrincipal = (JAASUserPrincipal)realm.authenticate ("me", "blah",(Request)null);
assertNull (userPrincipal);
userPrincipal = (JAASUserPrincipal)realm.authenticate ("me", "me", (Request)null);
assertNotNull (userPrincipal);
assertNotNull (userPrincipal.getName());
assertTrue (userPrincipal.getName().equals("me"));
assertTrue (userPrincipal.isUserInRole("roleA"));
assertTrue (userPrincipal.isUserInRole("roleB"));
assertTrue (!userPrincipal.isUserInRole("roleC"));
realm.pushRole (userPrincipal, "roleC");
assertTrue (userPrincipal.isUserInRole("roleC"));
assertTrue (!userPrincipal.isUserInRole("roleA"));
assertTrue (!userPrincipal.isUserInRole("roleB"));
realm.pushRole (userPrincipal, "roleD");
assertTrue (userPrincipal.isUserInRole("roleD"));
assertTrue (!userPrincipal.isUserInRole("roleC"));
assertTrue (!userPrincipal.isUserInRole("roleA"));
assertTrue (!userPrincipal.isUserInRole("roleB"));
realm.popRole(userPrincipal);
assertTrue (userPrincipal.isUserInRole("roleC"));
assertTrue (!userPrincipal.isUserInRole("roleA"));
assertTrue (!userPrincipal.isUserInRole("roleB"));
realm.popRole(userPrincipal);
assertTrue (!userPrincipal.isUserInRole("roleC"));
assertTrue (userPrincipal.isUserInRole("roleA"));
realm.disassociate(userPrincipal);
}
finally
{
- Connection c = eds.getConnection();
- Statement s = c.createStatement();
- s.executeUpdate("drop table myusers");
- s.executeUpdate("drop table myuserroles");
- s.close();
- c.close();
+ try
+ {
+ Connection c = eds.getConnection();
+ Statement s = c.createStatement();
+ s.executeUpdate("drop table myusers");
+ s.executeUpdate("drop table myuserroles");
+ s.close();
+ c.close();
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ }
}
}
public void testItPropertyFile ()
throws Exception
{
//create a JAASUserRealm
JAASUserRealm realm = new JAASUserRealm ("props");
realm.setLoginModuleName ("props");
JAASUserPrincipal userPrincipal = (JAASUserPrincipal)realm.authenticate ("user", "wrong",(Request)null);
assertNull (userPrincipal);
userPrincipal = (JAASUserPrincipal)realm.authenticate ("user", "user", (Request)null);
assertNotNull (userPrincipal);
assertTrue (userPrincipal.getName().equals("user"));
assertTrue (userPrincipal.isUserInRole("pleb"));
assertTrue (userPrincipal.isUserInRole("user"));
assertTrue (!userPrincipal.isUserInRole("other"));
realm.disassociate (userPrincipal);
}
public void tearDown ()
throws Exception
{
}
}
| true | true | public void testItDataSource ()
throws Exception
{
String tmpDir = System.getProperty("java.io.tmpdir")+System.getProperty("file.separator");
System.setProperty("derby.system.home", tmpDir);
String dbname = "derby-"+(int)(random.nextDouble()*10000);
EmbeddedDataSource eds = new EmbeddedDataSource();
try
{
//make the java:comp/env
InitialContext ic = new InitialContext();
Context comp = (Context)ic.lookup("java:comp");
Context env = comp.createSubcontext ("env");
//make a DataSource
eds.setDatabaseName(dbname);
eds.setCreateDatabase("create");
env.createSubcontext("jdbc");
env.bind("ds", eds);
Connection connection = eds.getConnection();
//create tables
String sql = "create table myusers (myuser varchar(32) PRIMARY KEY, mypassword varchar(32))";
Statement createStatement = connection.createStatement();
createStatement.executeUpdate (sql);
sql = " create table myuserroles (myuser varchar(32), myrole varchar(32))";
createStatement.executeUpdate (sql);
createStatement.close();
//insert test users and roles
sql = "insert into myusers (myuser, mypassword) values (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString (1, "me");
statement.setString (2, "me");
statement.executeUpdate();
sql = "insert into myuserroles (myuser, myrole) values ( ? , ? )";
statement = connection.prepareStatement (sql);
statement.setString (1, "me");
statement.setString (2, "roleA");
statement.executeUpdate();
statement.setString(1, "me");
statement.setString(2, "roleB");
statement.executeUpdate();
statement.close();
connection.close();
//create a JAASUserRealm
JAASUserRealm realm = new JAASUserRealm ("testRealm");
realm.setLoginModuleName ("ds");
JAASUserPrincipal userPrincipal = (JAASUserPrincipal)realm.authenticate ("me", "blah",(Request)null);
assertNull (userPrincipal);
userPrincipal = (JAASUserPrincipal)realm.authenticate ("me", "me", (Request)null);
assertNotNull (userPrincipal);
assertNotNull (userPrincipal.getName());
assertTrue (userPrincipal.getName().equals("me"));
assertTrue (userPrincipal.isUserInRole("roleA"));
assertTrue (userPrincipal.isUserInRole("roleB"));
assertTrue (!userPrincipal.isUserInRole("roleC"));
realm.pushRole (userPrincipal, "roleC");
assertTrue (userPrincipal.isUserInRole("roleC"));
assertTrue (!userPrincipal.isUserInRole("roleA"));
assertTrue (!userPrincipal.isUserInRole("roleB"));
realm.pushRole (userPrincipal, "roleD");
assertTrue (userPrincipal.isUserInRole("roleD"));
assertTrue (!userPrincipal.isUserInRole("roleC"));
assertTrue (!userPrincipal.isUserInRole("roleA"));
assertTrue (!userPrincipal.isUserInRole("roleB"));
realm.popRole(userPrincipal);
assertTrue (userPrincipal.isUserInRole("roleC"));
assertTrue (!userPrincipal.isUserInRole("roleA"));
assertTrue (!userPrincipal.isUserInRole("roleB"));
realm.popRole(userPrincipal);
assertTrue (!userPrincipal.isUserInRole("roleC"));
assertTrue (userPrincipal.isUserInRole("roleA"));
realm.disassociate(userPrincipal);
}
finally
{
Connection c = eds.getConnection();
Statement s = c.createStatement();
s.executeUpdate("drop table myusers");
s.executeUpdate("drop table myuserroles");
s.close();
c.close();
}
}
| public void testItDataSource ()
throws Exception
{
String tmpDir = System.getProperty("java.io.tmpdir")+System.getProperty("file.separator");
System.setProperty("derby.system.home", tmpDir);
String dbname = "derby-"+(int)(random.nextDouble()*10000);
EmbeddedDataSource eds = new EmbeddedDataSource();
try
{
//make the java:comp/env
InitialContext ic = new InitialContext();
Context comp = (Context)ic.lookup("java:comp");
Context env = comp.createSubcontext ("env");
//make a DataSource
eds.setDatabaseName(dbname);
eds.setCreateDatabase("create");
env.createSubcontext("jdbc");
env.bind("ds", eds);
Connection connection = eds.getConnection();
//create tables
String sql = "create table myusers (myuser varchar(32) PRIMARY KEY, mypassword varchar(32))";
Statement createStatement = connection.createStatement();
createStatement.executeUpdate (sql);
sql = " create table myuserroles (myuser varchar(32), myrole varchar(32))";
createStatement.executeUpdate (sql);
createStatement.close();
//insert test users and roles
sql = "insert into myusers (myuser, mypassword) values (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString (1, "me");
statement.setString (2, "me");
statement.executeUpdate();
sql = "insert into myuserroles (myuser, myrole) values ( ? , ? )";
statement = connection.prepareStatement (sql);
statement.setString (1, "me");
statement.setString (2, "roleA");
statement.executeUpdate();
statement.setString(1, "me");
statement.setString(2, "roleB");
statement.executeUpdate();
statement.close();
connection.close();
//create a JAASUserRealm
JAASUserRealm realm = new JAASUserRealm ("testRealm");
realm.setLoginModuleName ("ds");
JAASUserPrincipal userPrincipal = (JAASUserPrincipal)realm.authenticate ("me", "blah",(Request)null);
assertNull (userPrincipal);
userPrincipal = (JAASUserPrincipal)realm.authenticate ("me", "me", (Request)null);
assertNotNull (userPrincipal);
assertNotNull (userPrincipal.getName());
assertTrue (userPrincipal.getName().equals("me"));
assertTrue (userPrincipal.isUserInRole("roleA"));
assertTrue (userPrincipal.isUserInRole("roleB"));
assertTrue (!userPrincipal.isUserInRole("roleC"));
realm.pushRole (userPrincipal, "roleC");
assertTrue (userPrincipal.isUserInRole("roleC"));
assertTrue (!userPrincipal.isUserInRole("roleA"));
assertTrue (!userPrincipal.isUserInRole("roleB"));
realm.pushRole (userPrincipal, "roleD");
assertTrue (userPrincipal.isUserInRole("roleD"));
assertTrue (!userPrincipal.isUserInRole("roleC"));
assertTrue (!userPrincipal.isUserInRole("roleA"));
assertTrue (!userPrincipal.isUserInRole("roleB"));
realm.popRole(userPrincipal);
assertTrue (userPrincipal.isUserInRole("roleC"));
assertTrue (!userPrincipal.isUserInRole("roleA"));
assertTrue (!userPrincipal.isUserInRole("roleB"));
realm.popRole(userPrincipal);
assertTrue (!userPrincipal.isUserInRole("roleC"));
assertTrue (userPrincipal.isUserInRole("roleA"));
realm.disassociate(userPrincipal);
}
finally
{
try
{
Connection c = eds.getConnection();
Statement s = c.createStatement();
s.executeUpdate("drop table myusers");
s.executeUpdate("drop table myuserroles");
s.close();
c.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
diff --git a/annis-gui/src/main/java/annis/gui/controlpanel/ControlPanel.java b/annis-gui/src/main/java/annis/gui/controlpanel/ControlPanel.java
index 8f9ce58b9..700ef86b2 100644
--- a/annis-gui/src/main/java/annis/gui/controlpanel/ControlPanel.java
+++ b/annis-gui/src/main/java/annis/gui/controlpanel/ControlPanel.java
@@ -1,241 +1,244 @@
/*
* Copyright 2011 Corpuslinguistic working group Humboldt University Berlin.
*
* 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 annis.gui.controlpanel;
import annis.gui.Helper;
import annis.gui.SearchWindow;
import annis.gui.beans.HistoryEntry;
import annis.service.objects.Count;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.ChameleonTheme;
import java.util.Set;
import org.apache.commons.collections15.set.ListOrderedSet;
import org.apache.commons.lang3.StringUtils;
/**
*
* @author thomas
*/
public class ControlPanel extends Panel
{
private static final long serialVersionUID = -2220211539424865671L;
private QueryPanel queryPanel;
private CorpusListPanel corpusList;
private SearchWindow searchWindow;
private Window window;
private String lastQuery;
private Set<String> lastCorpusSelection;
private SearchOptionsPanel searchOptions;
private ListOrderedSet<HistoryEntry> history;
public ControlPanel(SearchWindow searchWindow)
{
super("Search Form");
this.searchWindow = searchWindow;
this.history = new ListOrderedSet<HistoryEntry>();
setStyleName(ChameleonTheme.PANEL_BORDERLESS);
addStyleName("control");
VerticalLayout layout = (VerticalLayout) getContent();
layout.setHeight(100f, UNITS_PERCENTAGE);
Accordion accordion = new Accordion();
accordion.setHeight(100f, Layout.UNITS_PERCENTAGE);
corpusList = new CorpusListPanel(this);
searchOptions = new SearchOptionsPanel();
queryPanel = new QueryPanel(this);
queryPanel.setHeight(18f, Layout.UNITS_EM);
accordion.addTab(corpusList, "Corpus List", null);
accordion.addTab(searchOptions, "Search Options", null);
accordion.addTab(new ExportPanel(queryPanel, corpusList), "Export", null);
addComponent(queryPanel);
addComponent(accordion);
layout.setExpandRatio(accordion, 1.0f);
}
@Override
public void attach()
{
super.attach();
this.window = getWindow();
}
public void setQuery(String query, Set<String> corpora)
{
if (queryPanel != null && corpusList != null)
{
queryPanel.setQuery(query);
if (corpora != null)
{
corpusList.selectCorpora(corpora);
}
}
}
public void setQuery(String query, Set<String> corpora,
int contextLeft, int contextRight)
{
setQuery(query, corpora);
searchOptions.setLeftContext(contextLeft);
searchOptions.setRightContext(contextRight);
}
public Set<String> getSelectedCorpora()
{
return corpusList.getSelectedCorpora();
}
@Override
public void paintContent(PaintTarget target) throws PaintException
{
super.paintContent(target);
}
public void executeQuery()
{
if (getApplication() != null && corpusList != null && queryPanel
!= null)
{
lastQuery = queryPanel.getQuery();
lastCorpusSelection = corpusList.getSelectedCorpora();
if (lastCorpusSelection == null || lastCorpusSelection.isEmpty())
{
getWindow().showNotification("Please select a corpus",
Window.Notification.TYPE_WARNING_MESSAGE);
return;
}
if ("".equals(lastQuery))
{
getWindow().showNotification("Empty query",
Window.Notification.TYPE_WARNING_MESSAGE);
return;
}
HistoryEntry e = new HistoryEntry();
e.setQuery(lastQuery);
e.setCorpora(lastCorpusSelection);
// remove it first in order to let it appear on the beginning of the list
history.remove(e);
history.add(0, e);
queryPanel.updateShortHistory(history.asList());
queryPanel.setCountIndicatorEnabled(true);
CountThread countThread = new CountThread();
countThread.start();
searchWindow.showQueryResult(lastQuery, lastCorpusSelection,
searchOptions.getLeftContext(), searchOptions.getRightContext(),
searchOptions.getSegmentationLayer(),
searchOptions.getResultsPerPage());
}
}
public Set<HistoryEntry> getHistory()
{
return history;
}
public void corpusSelectionChanged()
{
searchOptions.updateSegmentationList(corpusList.getSelectedCorpora());
}
private class CountThread extends Thread
{
private Count count = null;
@Override
public void run()
{
WebResource res = null;
synchronized(getApplication())
{
res = Helper.getAnnisWebResource(getApplication());
}
//AnnisService service = Helper.getService(getApplication(), window);
if (res != null)
{
try
{
count = res.path("query").path("search").path("count").queryParam(
"q", lastQuery).queryParam("corpora",
StringUtils.join(lastCorpusSelection, ",")).get(Count.class);
}
catch (UniformInterfaceException ex)
{
synchronized(getApplication())
{
if (ex.getResponse().getStatus() == 400)
{
window.showNotification(
"parsing error",
ex.getResponse().getEntity(String.class),
Window.Notification.TYPE_WARNING_MESSAGE);
}
else if(ex.getResponse().getStatus() == 504) // gateway timeout
{
window.showNotification(
"Timeout: query execution took too long.",
"Try to simplyfiy your query e.g. by replacing \"node\" with an annotation name or adding more constraints between the nodes.",
Window.Notification.TYPE_WARNING_MESSAGE);
}
else
{
window.showNotification(
"unknown error " + ex.
getResponse().getStatus(),
ex.getResponse().getEntity(String.class),
Window.Notification.TYPE_WARNING_MESSAGE);
}
}
}
}
synchronized(getApplication())
{
- queryPanel.setStatus("" + count.getTupelMatched() + " matches <br/>in " + count.getDocumentsMatched() + " documents" );
- searchWindow.updateQueryCount(count.getTupelMatched());
+ queryPanel.setCountIndicatorEnabled(false);
+ if(count != null)
+ {
+ queryPanel.setStatus("" + count.getTupelMatched() + " matches <br/>in " + count.getDocumentsMatched() + " documents" );
+ searchWindow.updateQueryCount(count.getTupelMatched());
+ }
}
- queryPanel.setCountIndicatorEnabled(false);
}
public int getCount()
{
return count.getTupelMatched();
}
}
}
| false | true | public void run()
{
WebResource res = null;
synchronized(getApplication())
{
res = Helper.getAnnisWebResource(getApplication());
}
//AnnisService service = Helper.getService(getApplication(), window);
if (res != null)
{
try
{
count = res.path("query").path("search").path("count").queryParam(
"q", lastQuery).queryParam("corpora",
StringUtils.join(lastCorpusSelection, ",")).get(Count.class);
}
catch (UniformInterfaceException ex)
{
synchronized(getApplication())
{
if (ex.getResponse().getStatus() == 400)
{
window.showNotification(
"parsing error",
ex.getResponse().getEntity(String.class),
Window.Notification.TYPE_WARNING_MESSAGE);
}
else if(ex.getResponse().getStatus() == 504) // gateway timeout
{
window.showNotification(
"Timeout: query execution took too long.",
"Try to simplyfiy your query e.g. by replacing \"node\" with an annotation name or adding more constraints between the nodes.",
Window.Notification.TYPE_WARNING_MESSAGE);
}
else
{
window.showNotification(
"unknown error " + ex.
getResponse().getStatus(),
ex.getResponse().getEntity(String.class),
Window.Notification.TYPE_WARNING_MESSAGE);
}
}
}
}
synchronized(getApplication())
{
queryPanel.setStatus("" + count.getTupelMatched() + " matches <br/>in " + count.getDocumentsMatched() + " documents" );
searchWindow.updateQueryCount(count.getTupelMatched());
}
queryPanel.setCountIndicatorEnabled(false);
}
| public void run()
{
WebResource res = null;
synchronized(getApplication())
{
res = Helper.getAnnisWebResource(getApplication());
}
//AnnisService service = Helper.getService(getApplication(), window);
if (res != null)
{
try
{
count = res.path("query").path("search").path("count").queryParam(
"q", lastQuery).queryParam("corpora",
StringUtils.join(lastCorpusSelection, ",")).get(Count.class);
}
catch (UniformInterfaceException ex)
{
synchronized(getApplication())
{
if (ex.getResponse().getStatus() == 400)
{
window.showNotification(
"parsing error",
ex.getResponse().getEntity(String.class),
Window.Notification.TYPE_WARNING_MESSAGE);
}
else if(ex.getResponse().getStatus() == 504) // gateway timeout
{
window.showNotification(
"Timeout: query execution took too long.",
"Try to simplyfiy your query e.g. by replacing \"node\" with an annotation name or adding more constraints between the nodes.",
Window.Notification.TYPE_WARNING_MESSAGE);
}
else
{
window.showNotification(
"unknown error " + ex.
getResponse().getStatus(),
ex.getResponse().getEntity(String.class),
Window.Notification.TYPE_WARNING_MESSAGE);
}
}
}
}
synchronized(getApplication())
{
queryPanel.setCountIndicatorEnabled(false);
if(count != null)
{
queryPanel.setStatus("" + count.getTupelMatched() + " matches <br/>in " + count.getDocumentsMatched() + " documents" );
searchWindow.updateQueryCount(count.getTupelMatched());
}
}
}
|
diff --git a/web/src/main/java/de/betterform/agent/web/resources/ResourceServlet.java b/web/src/main/java/de/betterform/agent/web/resources/ResourceServlet.java
index 497b5ea6..1759b2ab 100644
--- a/web/src/main/java/de/betterform/agent/web/resources/ResourceServlet.java
+++ b/web/src/main/java/de/betterform/agent/web/resources/ResourceServlet.java
@@ -1,275 +1,275 @@
/*
* Copyright (c) 2012. betterFORM Project - http://www.betterform.de
* Licensed under the terms of BSD License
*/
package de.betterform.agent.web.resources;
import de.betterform.agent.web.resources.stream.DefaultResourceStreamer;
import de.betterform.agent.web.resources.stream.ResourceStreamer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* ResourceServlet is responsible for streaming resources like css, script, images and etc to the client.
* Streaming is done via ResourceStreamers and resources are forced to be cached indefinitely using convenient response headers.
*/
public class ResourceServlet extends HttpServlet {
private static final Log LOG = LogFactory.getLog(ResourceServlet.class);
private static Map<String, String> mimeTypes;
private List<ResourceStreamer> resourceStreamers;
private boolean caching;
private boolean exploded = false;
private long oneYear = 31363200000L;
/**
* RESOURCE_FOLDER refers to the location in the classpath where resources are found.
*/
public final static String RESOURCE_FOLDER = "/META-INF/resources";
/**
* RESOURCE_PATTERN is the string used in URLs requesting resources. This value is hardcoded for now - meaning
* that all requests to internal betterFORM resources like CSS, images, scripts and XSLTs have to use
* 'bfResources'.
*
* Example:
* http://somehost.com/betterform/bfResources/images/image.gif"
* will try to load an image 'image.gif' from /META-INF/resources/images/image.gif
*
*/
public final static String RESOURCE_PATTERN = "bfResources";
private long lastModified = 0;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
if("false".equals(config.getInitParameter("caching"))){
caching=false;
if(LOG.isTraceEnabled()){
LOG.trace("Caching of Resources is disabled");
}
}else {
caching=true;
if(LOG.isTraceEnabled()){
LOG.trace("Caching of Resources is enabled - resources are loaded from classpath");
}
}
this.lastModified = getLastModifiedValue();
final String path = config.getServletContext().getRealPath("WEB-INF/classes/META-INF/resources");
if (path != null && new File(path).exists()) {
exploded = true;
}
initMimeTypes();
initResourceStreamers();
}
// todo: shouldn't we move these definitions to web.xml and use servletContext.getMimeType?
private void initMimeTypes() {
mimeTypes = new HashMap<String, String>();
mimeTypes.put("css", "text/css");
mimeTypes.put("js", "text/javascript");
mimeTypes.put("jpg", "image/jpeg");
mimeTypes.put("jpeg", "image/jpeg");
mimeTypes.put("png", "image/png");
mimeTypes.put("gif", "image/gif");
mimeTypes.put("gif", "image/gif");
mimeTypes.put("html", "text/html");
mimeTypes.put("swf", "application/x-shockwave-flash");
mimeTypes.put("xsl","application/xml+xslt");
}
private void initResourceStreamers() {
resourceStreamers = new ArrayList<ResourceStreamer>();
resourceStreamers.add(new DefaultResourceStreamer());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestUri = req.getRequestURI();
String resourcePath = RESOURCE_FOLDER + getResourcePath(requestUri);
URL url = ResourceServlet.class.getResource(resourcePath);
if (LOG.isTraceEnabled()) {
LOG.trace("Request URI: " + requestUri);
LOG.trace("resource fpath: " + resourcePath);
}
if (url == null) {
boolean error = true;
if (requestUri.endsWith(".js")) {
//try optimized version first
if (requestUri.contains("scripts/betterform/betterform-")) {
if (ResourceServlet.class.getResource(resourcePath) == null) {
resourcePath = resourcePath.replace("betterform-", "BfRequired");
if (ResourceServlet.class.getResource(resourcePath) != null) {
error = false;
}
}
}
}
if (error) {
if (LOG.isWarnEnabled()) {
- LOG.warn("Resource \"{0}\" not found - " + resourcePath);
+ LOG.warn("Resource "+ resourcePath + " not found");
}
resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource " + resourcePath + " not found" );
return;
}
}
if (LOG.isTraceEnabled()){
- LOG.trace("Streaming resource \"{0}\" - " + resourcePath);
+ LOG.trace("Streaming resource " + resourcePath);
}
InputStream inputStream = null;
try {
if(exploded){
String path = ResourceServlet.class.getResource(resourcePath).getPath();
inputStream = new FileInputStream(new File(path));
if(LOG.isTraceEnabled()){
LOG.trace("loading reources form file: " + path);
}
}else{
inputStream = ResourceServlet.class.getResourceAsStream(resourcePath);
}
String mimeType = getResourceContentType(resourcePath);
if(mimeType == null){
mimeType = getServletContext().getMimeType(resourcePath);
}
if (mimeType == null) {
if(LOG.isTraceEnabled()){
- LOG.trace("MimeType for \"{0}\" not found. Sending 'not found' response - " + resourcePath);
+ LOG.trace("MimeType for "+ resourcePath + " not found. Sending 'not found' response" );
}
resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "MimeType for " + resourcePath + " not found. Sending 'not found' response");
return;
}
resp.setContentType(mimeType);
resp.setStatus(HttpServletResponse.SC_OK);
setCaching(req, resp);
streamResource(req, resp, mimeType, inputStream);
if(LOG.isTraceEnabled()){
- LOG.trace( "Resource \"{0}\" streamed succesfully - " + resourcePath);
+ LOG.trace( "Resource "+ resourcePath + " streamed succesfully");
}
} catch (Exception exception) {
- LOG.error("Error in streaming resource \"{0}\". Exception is \"{1}\" - " + new Object[]{resourcePath, exception.getMessage()});
+ LOG.error("Error in streaming resource "+ resourcePath + ". Exception is " + exception.getMessage());
} finally {
if (inputStream != null) {
inputStream.close();
}
resp.getOutputStream().flush();
resp.getOutputStream().close();
}
}
private void streamResource(HttpServletRequest req, HttpServletResponse resp, String mimeType, InputStream inputStream) throws IOException {
for (ResourceStreamer streamer : resourceStreamers) {
if (streamer.isAppropriateStreamer(mimeType))
streamer.stream(req, resp, inputStream);
}
}
/**
* set the caching headers for the resource response. Caching can be disabled by adding and init-param
* of 'caching' with value 'false' to web.xml
*
* @param request the http servlet request
* @param response the http servlet response
*/
protected void setCaching(HttpServletRequest request, HttpServletResponse response) {
long now = System.currentTimeMillis();
if (caching) {
response.setHeader("Cache-Control", "max-age=3600, public");
response.setDateHeader("Date", now);
response.setDateHeader("Expires", now + this.oneYear);
response.setDateHeader("Last-Modified", this.getLastModifiedValue());
} else {
// Set to expire far in the past.
response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
}
}
protected String getResourcePath(String requestURI) {
int jsessionidIndex = requestURI.toLowerCase().indexOf(";jsessionid");
if (jsessionidIndex != -1) {
requestURI = requestURI.substring(0, jsessionidIndex);
}
int patternIndex = requestURI.indexOf(RESOURCE_PATTERN);
return requestURI.substring(patternIndex + RESOURCE_PATTERN.length(), requestURI.length());
}
protected String getResourceContentType(String resourcePath) {
String resourceFileExtension = getResourceFileExtension(resourcePath);
return mimeTypes.get(resourceFileExtension);
}
protected String getResourceFileExtension(String resourcePath) {
String parsed[] = resourcePath.split("\\.");
return parsed[parsed.length - 1];
}
private long getLastModifiedValue() {
if(this.lastModified == 0){
long bfTimestamp;
try {
String path = this.getServletContext().getRealPath("/WEB-INF/betterform-version.info");
StringBuilder versionInfo = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new FileInputStream(path), "UTF-8");
try {
while (scanner.hasNextLine()){
versionInfo.append(scanner.nextLine() + NL);
}
}
finally{
scanner.close();
}
if(LOG.isDebugEnabled()){
LOG.debug("VersionInfo: " + versionInfo);
}
// String APP_NAME = APP_INFO.substring(0, APP_INFO.indexOf(" "));
// String APP_VERSION = APP_INFO.substring(APP_INFO.indexOf(" ") + 1, APP_INFO.indexOf("-") - 1);
String timestamp = versionInfo.substring(versionInfo.indexOf("Timestamp:")+10,versionInfo.length());
String df = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(df);
Date date = sdf.parse(timestamp);
bfTimestamp = date.getTime();
} catch (Exception e) {
LOG.error("Error setting HTTP Header 'Last Modified', could not parse the given date.");
bfTimestamp = 0;
}
this.lastModified = bfTimestamp;
}
return lastModified;
}
protected long getLastModified(HttpServletRequest req) {
return this.getLastModifiedValue();
}
}
| false | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestUri = req.getRequestURI();
String resourcePath = RESOURCE_FOLDER + getResourcePath(requestUri);
URL url = ResourceServlet.class.getResource(resourcePath);
if (LOG.isTraceEnabled()) {
LOG.trace("Request URI: " + requestUri);
LOG.trace("resource fpath: " + resourcePath);
}
if (url == null) {
boolean error = true;
if (requestUri.endsWith(".js")) {
//try optimized version first
if (requestUri.contains("scripts/betterform/betterform-")) {
if (ResourceServlet.class.getResource(resourcePath) == null) {
resourcePath = resourcePath.replace("betterform-", "BfRequired");
if (ResourceServlet.class.getResource(resourcePath) != null) {
error = false;
}
}
}
}
if (error) {
if (LOG.isWarnEnabled()) {
LOG.warn("Resource \"{0}\" not found - " + resourcePath);
}
resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource " + resourcePath + " not found" );
return;
}
}
if (LOG.isTraceEnabled()){
LOG.trace("Streaming resource \"{0}\" - " + resourcePath);
}
InputStream inputStream = null;
try {
if(exploded){
String path = ResourceServlet.class.getResource(resourcePath).getPath();
inputStream = new FileInputStream(new File(path));
if(LOG.isTraceEnabled()){
LOG.trace("loading reources form file: " + path);
}
}else{
inputStream = ResourceServlet.class.getResourceAsStream(resourcePath);
}
String mimeType = getResourceContentType(resourcePath);
if(mimeType == null){
mimeType = getServletContext().getMimeType(resourcePath);
}
if (mimeType == null) {
if(LOG.isTraceEnabled()){
LOG.trace("MimeType for \"{0}\" not found. Sending 'not found' response - " + resourcePath);
}
resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "MimeType for " + resourcePath + " not found. Sending 'not found' response");
return;
}
resp.setContentType(mimeType);
resp.setStatus(HttpServletResponse.SC_OK);
setCaching(req, resp);
streamResource(req, resp, mimeType, inputStream);
if(LOG.isTraceEnabled()){
LOG.trace( "Resource \"{0}\" streamed succesfully - " + resourcePath);
}
} catch (Exception exception) {
LOG.error("Error in streaming resource \"{0}\". Exception is \"{1}\" - " + new Object[]{resourcePath, exception.getMessage()});
} finally {
if (inputStream != null) {
inputStream.close();
}
resp.getOutputStream().flush();
resp.getOutputStream().close();
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestUri = req.getRequestURI();
String resourcePath = RESOURCE_FOLDER + getResourcePath(requestUri);
URL url = ResourceServlet.class.getResource(resourcePath);
if (LOG.isTraceEnabled()) {
LOG.trace("Request URI: " + requestUri);
LOG.trace("resource fpath: " + resourcePath);
}
if (url == null) {
boolean error = true;
if (requestUri.endsWith(".js")) {
//try optimized version first
if (requestUri.contains("scripts/betterform/betterform-")) {
if (ResourceServlet.class.getResource(resourcePath) == null) {
resourcePath = resourcePath.replace("betterform-", "BfRequired");
if (ResourceServlet.class.getResource(resourcePath) != null) {
error = false;
}
}
}
}
if (error) {
if (LOG.isWarnEnabled()) {
LOG.warn("Resource "+ resourcePath + " not found");
}
resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource " + resourcePath + " not found" );
return;
}
}
if (LOG.isTraceEnabled()){
LOG.trace("Streaming resource " + resourcePath);
}
InputStream inputStream = null;
try {
if(exploded){
String path = ResourceServlet.class.getResource(resourcePath).getPath();
inputStream = new FileInputStream(new File(path));
if(LOG.isTraceEnabled()){
LOG.trace("loading reources form file: " + path);
}
}else{
inputStream = ResourceServlet.class.getResourceAsStream(resourcePath);
}
String mimeType = getResourceContentType(resourcePath);
if(mimeType == null){
mimeType = getServletContext().getMimeType(resourcePath);
}
if (mimeType == null) {
if(LOG.isTraceEnabled()){
LOG.trace("MimeType for "+ resourcePath + " not found. Sending 'not found' response" );
}
resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "MimeType for " + resourcePath + " not found. Sending 'not found' response");
return;
}
resp.setContentType(mimeType);
resp.setStatus(HttpServletResponse.SC_OK);
setCaching(req, resp);
streamResource(req, resp, mimeType, inputStream);
if(LOG.isTraceEnabled()){
LOG.trace( "Resource "+ resourcePath + " streamed succesfully");
}
} catch (Exception exception) {
LOG.error("Error in streaming resource "+ resourcePath + ". Exception is " + exception.getMessage());
} finally {
if (inputStream != null) {
inputStream.close();
}
resp.getOutputStream().flush();
resp.getOutputStream().close();
}
}
|
diff --git a/test/org/bodytrack/client/GraphAxisTest.java b/test/org/bodytrack/client/GraphAxisTest.java
index efe2097..8e751da 100644
--- a/test/org/bodytrack/client/GraphAxisTest.java
+++ b/test/org/bodytrack/client/GraphAxisTest.java
@@ -1,35 +1,36 @@
package org.bodytrack.client;
import org.junit.Test;
import junit.framework.TestCase;
public class GraphAxisTest extends TestCase {
@Test
public void test_ticks() {
- GraphAxis g=new GraphAxis(0, 1, // min, max
+ GraphAxis g = new GraphAxis(GraphAxis.NO_CHANNEL_NAME,
+ 0, 1, // min, max
Basis.xDownYRight,
5 // width
);
int height = 100;
int tick_pixels = 10;
double epsilon = 1e-10;
assertEquals(0.1, g.computeTickSize( 9), epsilon);
assertEquals(0.1, g.computeTickSize( 10), epsilon);
assertEquals(0.2, g.computeTickSize( 11), epsilon);
assertEquals(0.2, g.computeTickSize( 19), epsilon);
assertEquals(0.2, g.computeTickSize( 20), epsilon);
assertEquals(0.5, g.computeTickSize( 21), epsilon);
assertEquals(0.5, g.computeTickSize( 49), epsilon);
assertEquals(0.5, g.computeTickSize( 50), epsilon);
assertEquals(1.0, g.computeTickSize( 51), epsilon);
assertEquals(1.0, g.computeTickSize( 99), epsilon);
assertEquals(1.0, g.computeTickSize(100), epsilon);
}
}
| true | true | public void test_ticks() {
GraphAxis g=new GraphAxis(0, 1, // min, max
Basis.xDownYRight,
5 // width
);
int height = 100;
int tick_pixels = 10;
double epsilon = 1e-10;
assertEquals(0.1, g.computeTickSize( 9), epsilon);
assertEquals(0.1, g.computeTickSize( 10), epsilon);
assertEquals(0.2, g.computeTickSize( 11), epsilon);
assertEquals(0.2, g.computeTickSize( 19), epsilon);
assertEquals(0.2, g.computeTickSize( 20), epsilon);
assertEquals(0.5, g.computeTickSize( 21), epsilon);
assertEquals(0.5, g.computeTickSize( 49), epsilon);
assertEquals(0.5, g.computeTickSize( 50), epsilon);
assertEquals(1.0, g.computeTickSize( 51), epsilon);
assertEquals(1.0, g.computeTickSize( 99), epsilon);
assertEquals(1.0, g.computeTickSize(100), epsilon);
}
| public void test_ticks() {
GraphAxis g = new GraphAxis(GraphAxis.NO_CHANNEL_NAME,
0, 1, // min, max
Basis.xDownYRight,
5 // width
);
int height = 100;
int tick_pixels = 10;
double epsilon = 1e-10;
assertEquals(0.1, g.computeTickSize( 9), epsilon);
assertEquals(0.1, g.computeTickSize( 10), epsilon);
assertEquals(0.2, g.computeTickSize( 11), epsilon);
assertEquals(0.2, g.computeTickSize( 19), epsilon);
assertEquals(0.2, g.computeTickSize( 20), epsilon);
assertEquals(0.5, g.computeTickSize( 21), epsilon);
assertEquals(0.5, g.computeTickSize( 49), epsilon);
assertEquals(0.5, g.computeTickSize( 50), epsilon);
assertEquals(1.0, g.computeTickSize( 51), epsilon);
assertEquals(1.0, g.computeTickSize( 99), epsilon);
assertEquals(1.0, g.computeTickSize(100), epsilon);
}
|
diff --git a/Server/Portal/trustednet-login/src/main/java/com/digt/web/ReminderController.java b/Server/Portal/trustednet-login/src/main/java/com/digt/web/ReminderController.java
index 16ae104..8a28119 100644
--- a/Server/Portal/trustednet-login/src/main/java/com/digt/web/ReminderController.java
+++ b/Server/Portal/trustednet-login/src/main/java/com/digt/web/ReminderController.java
@@ -1,120 +1,120 @@
package com.digt.web;
import com.digt.service.UserAccountService;
import com.digt.util.MailUtils;
import com.digt.util.PwdUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.digt.web.beans.ReminderBean;
import com.digt.web.beans.json.Message;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.rave.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.FieldError;
import org.springframework.context.MessageSource;
@Controller
public class ReminderController {
private final UserAccountService userService;
private final Session mailSession;
private final ServletContext ctx;
private final MessageSource messages;
private static final Logger LOG = Logger.getLogger(
ReminderController.class.getName());
public static final String ATTR_REMINDER_SENT = LOG.getName() + ".sent";
@Autowired
public ReminderController(UserAccountService uacSvc, Session mailSess,
ServletContext ctx, MessageSource messages) {
this.userService = uacSvc;
this.mailSession = mailSess;
this.ctx = ctx;
this.messages = messages;
}
@RequestMapping(value = "/reminder", method = RequestMethod.GET)
public String showReminder(HttpServletRequest request, HttpSession session,
@ModelAttribute("formBean") ReminderBean form)
{
//model.addAttribute("recaptcha", reCaptcha);
session.removeAttribute(ATTR_REMINDER_SENT);
return "reminder";
}
@RequestMapping(value = "/reminder", method = RequestMethod.POST)
public String sendReminder(HttpServletRequest request, Model model,
@ModelAttribute("formBean") ReminderBean form,
HttpSession session,
BindingResult result) throws MessagingException, UnsupportedEncodingException, IOException
{
if (session.getAttribute(ATTR_REMINDER_SENT) != null)
return "remindDone";
String email = form.getEmail();
User user = userService.getUserByEmail(email);
if (user == null) {
FieldError fieldError = new FieldError(
"formBean",
"email",
messages.getMessage("reminder.email.notexist", null, null));
result.addError(fieldError);
}
else
{
MimeMessage msg = new MimeMessage(mailSession);
msg.setRecipient(RecipientType.TO, new InternetAddress(email));
BufferedReader in = new BufferedReader(
new InputStreamReader(ctx.getResourceAsStream("/WEB-INF/tpl/send_reminder.tpl"), MailUtils.MAIL_CHARSET));
msg.setSubject(in.readLine(), MailUtils.MAIL_CHARSET);
String password = RandomStringUtils.randomAlphanumeric(8);
try {
user.setPassword(new String(PwdUtils.cryptPassword(password.toCharArray())));
} catch (NoSuchAlgorithmException ex) {
LOG.log(Level.SEVERE, null, ex);
}
userService.updatePassword(user);
msg.setContent(MailUtils.readTemplate(in)
.replaceAll("\\{\\$firstname\\}", user.getGivenName())
.replaceAll("\\{\\$lastname\\}", user.getFamilyName())
.replaceAll("\\{\\$password\\}", password)
.replaceAll("\\{\\$login\\}", user.getUsername()),
"text/html;charset="+MailUtils.MAIL_CHARSET);
Transport.send(msg);
model.addAttribute("message",
new Message(true, user.getEmail()));
- session.setAttribute(ATTR_REMINDER_SENT, null);
+ session.setAttribute(ATTR_REMINDER_SENT, true);
return "remindDone";
}
return "reminder";
}
}
| true | true | public String sendReminder(HttpServletRequest request, Model model,
@ModelAttribute("formBean") ReminderBean form,
HttpSession session,
BindingResult result) throws MessagingException, UnsupportedEncodingException, IOException
{
if (session.getAttribute(ATTR_REMINDER_SENT) != null)
return "remindDone";
String email = form.getEmail();
User user = userService.getUserByEmail(email);
if (user == null) {
FieldError fieldError = new FieldError(
"formBean",
"email",
messages.getMessage("reminder.email.notexist", null, null));
result.addError(fieldError);
}
else
{
MimeMessage msg = new MimeMessage(mailSession);
msg.setRecipient(RecipientType.TO, new InternetAddress(email));
BufferedReader in = new BufferedReader(
new InputStreamReader(ctx.getResourceAsStream("/WEB-INF/tpl/send_reminder.tpl"), MailUtils.MAIL_CHARSET));
msg.setSubject(in.readLine(), MailUtils.MAIL_CHARSET);
String password = RandomStringUtils.randomAlphanumeric(8);
try {
user.setPassword(new String(PwdUtils.cryptPassword(password.toCharArray())));
} catch (NoSuchAlgorithmException ex) {
LOG.log(Level.SEVERE, null, ex);
}
userService.updatePassword(user);
msg.setContent(MailUtils.readTemplate(in)
.replaceAll("\\{\\$firstname\\}", user.getGivenName())
.replaceAll("\\{\\$lastname\\}", user.getFamilyName())
.replaceAll("\\{\\$password\\}", password)
.replaceAll("\\{\\$login\\}", user.getUsername()),
"text/html;charset="+MailUtils.MAIL_CHARSET);
Transport.send(msg);
model.addAttribute("message",
new Message(true, user.getEmail()));
session.setAttribute(ATTR_REMINDER_SENT, null);
return "remindDone";
}
return "reminder";
}
| public String sendReminder(HttpServletRequest request, Model model,
@ModelAttribute("formBean") ReminderBean form,
HttpSession session,
BindingResult result) throws MessagingException, UnsupportedEncodingException, IOException
{
if (session.getAttribute(ATTR_REMINDER_SENT) != null)
return "remindDone";
String email = form.getEmail();
User user = userService.getUserByEmail(email);
if (user == null) {
FieldError fieldError = new FieldError(
"formBean",
"email",
messages.getMessage("reminder.email.notexist", null, null));
result.addError(fieldError);
}
else
{
MimeMessage msg = new MimeMessage(mailSession);
msg.setRecipient(RecipientType.TO, new InternetAddress(email));
BufferedReader in = new BufferedReader(
new InputStreamReader(ctx.getResourceAsStream("/WEB-INF/tpl/send_reminder.tpl"), MailUtils.MAIL_CHARSET));
msg.setSubject(in.readLine(), MailUtils.MAIL_CHARSET);
String password = RandomStringUtils.randomAlphanumeric(8);
try {
user.setPassword(new String(PwdUtils.cryptPassword(password.toCharArray())));
} catch (NoSuchAlgorithmException ex) {
LOG.log(Level.SEVERE, null, ex);
}
userService.updatePassword(user);
msg.setContent(MailUtils.readTemplate(in)
.replaceAll("\\{\\$firstname\\}", user.getGivenName())
.replaceAll("\\{\\$lastname\\}", user.getFamilyName())
.replaceAll("\\{\\$password\\}", password)
.replaceAll("\\{\\$login\\}", user.getUsername()),
"text/html;charset="+MailUtils.MAIL_CHARSET);
Transport.send(msg);
model.addAttribute("message",
new Message(true, user.getEmail()));
session.setAttribute(ATTR_REMINDER_SENT, true);
return "remindDone";
}
return "reminder";
}
|
diff --git a/plugins/org.eclipse.tcf.cdt.ui/src/org/eclipse/tcf/internal/cdt/ui/breakpoints/BreakpointScopeOrganizer.java b/plugins/org.eclipse.tcf.cdt.ui/src/org/eclipse/tcf/internal/cdt/ui/breakpoints/BreakpointScopeOrganizer.java
index b3b9e8a6a..544bbefac 100644
--- a/plugins/org.eclipse.tcf.cdt.ui/src/org/eclipse/tcf/internal/cdt/ui/breakpoints/BreakpointScopeOrganizer.java
+++ b/plugins/org.eclipse.tcf.cdt.ui/src/org/eclipse/tcf/internal/cdt/ui/breakpoints/BreakpointScopeOrganizer.java
@@ -1,144 +1,144 @@
/*******************************************************************************
* Copyright (c) 2012 Wind River Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.internal.cdt.ui.breakpoints;
import org.eclipse.cdt.debug.core.model.ICBreakpoint;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IBreakpointsListener;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.debug.internal.ui.breakpoints.provisional.IBreakpointContainer;
import org.eclipse.debug.ui.AbstractBreakpointOrganizerDelegate;
import org.eclipse.debug.ui.IBreakpointOrganizerDelegate;
import org.eclipse.tcf.internal.cdt.ui.Activator;
import org.eclipse.tcf.internal.debug.model.ITCFConstants;
import org.eclipse.tcf.internal.debug.model.TCFBreakpointsModel;
/**
* Breakpoint organizer which groups breakpoints according to their
* breakpoint scope attributes.
*
* @see IBreakpointOrganizerDelegate
*/
@SuppressWarnings("restriction")
public class BreakpointScopeOrganizer extends AbstractBreakpointOrganizerDelegate implements IBreakpointsListener {
private static IAdaptable[] DEFAULT_CATEGORY_ARRAY = new IAdaptable[] { new BreakpointScopeCategory(null, null) };
static
{
Platform.getAdapterManager().registerAdapters(new BreakpointScopeContainerAdapterFactory(), IBreakpointContainer.class);
}
public BreakpointScopeOrganizer() {
DebugPlugin.getDefault().getBreakpointManager().addBreakpointListener(this);
}
public IAdaptable[] getCategories(IBreakpoint breakpoint) {
IMarker marker = breakpoint.getMarker();
if (marker != null) {
String filter = marker.getAttribute(TCFBreakpointsModel.ATTR_CONTEXT_QUERY, null);
String contextIds = marker.getAttribute(TCFBreakpointsModel.ATTR_CONTEXTIDS, null);
return new IAdaptable[] { new BreakpointScopeCategory(filter, contextIds) };
}
return DEFAULT_CATEGORY_ARRAY;
}
@Override
public void dispose() {
DebugPlugin.getDefault().getBreakpointManager().removeBreakpointListener(this);
super.dispose();
}
public void breakpointsAdded(IBreakpoint[] breakpoints) {
}
public void breakpointsChanged(IBreakpoint[] breakpoints, IMarkerDelta[] deltas) {
// Using delta's to see which attributes have changed is not reliable.
// Therefore we need to force a full refresh of scope categories whenever
// we get a breakpoints changed notiifcation.
fireCategoryChanged(null);
}
public void breakpointsRemoved(IBreakpoint[] breakpoints, IMarkerDelta[] deltas) {
}
@Override
public void addBreakpoint(IBreakpoint breakpoint, IAdaptable category) {
if (category instanceof BreakpointScopeCategory && breakpoint instanceof ICBreakpoint) {
String filter = ((BreakpointScopeCategory)category).getFilter();
String contextIds = ((BreakpointScopeCategory)category).getContextIds();
ICBreakpoint cBreakpoint = (ICBreakpoint) breakpoint;
TCFBreakpointScopeExtension scopeExtension;
try {
- scopeExtension = cBreakpoint.getExtension(
+ scopeExtension = (TCFBreakpointScopeExtension)cBreakpoint.getExtension(
ITCFConstants.ID_TCF_DEBUG_MODEL, TCFBreakpointScopeExtension.class);
if (scopeExtension != null) {
scopeExtension.setPropertiesFilter(filter);
scopeExtension.setRawContextIds(contextIds);
}
}
catch (CoreException e) {
Activator.log(e);
}
}
}
@Override
public boolean canAdd(IBreakpoint breakpoint, IAdaptable category) {
return category instanceof BreakpointScopeCategory && breakpoint instanceof ICBreakpoint;
}
@Override
public boolean canRemove(IBreakpoint breakpoint, IAdaptable category) {
return breakpoint instanceof ICBreakpoint;
}
@Override
public void removeBreakpoint(IBreakpoint breakpoint, IAdaptable category) {
// Nothing to do, changes handled by add.
}
}
/**
* Adapter factory which returns the breakpoint category for a given breakpoint
* container element that is shown in Breakpoints view.
*/
@SuppressWarnings("restriction")
class BreakpointScopeContainerAdapterFactory implements IAdapterFactory {
private static final Class<?>[] fgAdapterList = new Class[] {
BreakpointScopeCategory.class
};
public Object getAdapter(Object obj, @SuppressWarnings("rawtypes") Class adapterType) {
if ( !(obj instanceof IBreakpointContainer) ) return null;
if ( BreakpointScopeCategory.class.equals(adapterType) ) {
IAdaptable category = ((IBreakpointContainer)obj).getCategory();
if (category instanceof BreakpointScopeCategory) {
return category;
}
}
return null;
}
@SuppressWarnings("rawtypes")
public Class[] getAdapterList() {
return fgAdapterList;
}
}
| true | true | public void addBreakpoint(IBreakpoint breakpoint, IAdaptable category) {
if (category instanceof BreakpointScopeCategory && breakpoint instanceof ICBreakpoint) {
String filter = ((BreakpointScopeCategory)category).getFilter();
String contextIds = ((BreakpointScopeCategory)category).getContextIds();
ICBreakpoint cBreakpoint = (ICBreakpoint) breakpoint;
TCFBreakpointScopeExtension scopeExtension;
try {
scopeExtension = cBreakpoint.getExtension(
ITCFConstants.ID_TCF_DEBUG_MODEL, TCFBreakpointScopeExtension.class);
if (scopeExtension != null) {
scopeExtension.setPropertiesFilter(filter);
scopeExtension.setRawContextIds(contextIds);
}
}
catch (CoreException e) {
Activator.log(e);
}
}
}
| public void addBreakpoint(IBreakpoint breakpoint, IAdaptable category) {
if (category instanceof BreakpointScopeCategory && breakpoint instanceof ICBreakpoint) {
String filter = ((BreakpointScopeCategory)category).getFilter();
String contextIds = ((BreakpointScopeCategory)category).getContextIds();
ICBreakpoint cBreakpoint = (ICBreakpoint) breakpoint;
TCFBreakpointScopeExtension scopeExtension;
try {
scopeExtension = (TCFBreakpointScopeExtension)cBreakpoint.getExtension(
ITCFConstants.ID_TCF_DEBUG_MODEL, TCFBreakpointScopeExtension.class);
if (scopeExtension != null) {
scopeExtension.setPropertiesFilter(filter);
scopeExtension.setRawContextIds(contextIds);
}
}
catch (CoreException e) {
Activator.log(e);
}
}
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/map/MapStoreWriteProcessor.java b/hazelcast/src/main/java/com/hazelcast/map/MapStoreWriteProcessor.java
index 28c50f7698..ed1d676da1 100644
--- a/hazelcast/src/main/java/com/hazelcast/map/MapStoreWriteProcessor.java
+++ b/hazelcast/src/main/java/com/hazelcast/map/MapStoreWriteProcessor.java
@@ -1,115 +1,115 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.map;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.util.scheduler.EntryTaskScheduler;
import com.hazelcast.util.scheduler.ScheduledEntry;
import com.hazelcast.util.scheduler.ScheduledEntryProcessor;
import java.util.*;
public class MapStoreWriteProcessor implements ScheduledEntryProcessor<Data, Object> {
private final MapContainer mapContainer;
private final MapService mapService;
private final ILogger logger;
public MapStoreWriteProcessor(MapContainer mapContainer, MapService mapService) {
this.mapContainer = mapContainer;
this.mapService = mapService;
this.logger = mapService.getNodeEngine().getLogger(getClass());
}
private Exception tryStore(EntryTaskScheduler<Data, Object> scheduler, Map.Entry<Data, Object> entry) {
Exception exception = null;
try {
mapContainer.getStore().store(mapService.toObject(entry.getKey()), mapService.toObject(entry.getValue()));
} catch (Exception e) {
logger.warning(mapContainer.getStore().getMapStore().getClass() + " --> store failed, " +
"now Hazelcast reschedules this operation ", e);
exception = e;
scheduler.schedule(mapContainer.getWriteDelayMillis(), mapService.toData(entry.getKey()), mapService.toData(entry.getValue()));
}
return exception;
}
public void process(EntryTaskScheduler<Data, Object> scheduler, Collection<ScheduledEntry<Data, Object>> entries) {
if (entries.isEmpty())
return;
final ILogger logger = mapService.getNodeEngine().getLogger(getClass());
if (entries.size() == 1) {
ScheduledEntry<Data, Object> entry = entries.iterator().next();
Exception exception = tryStore(scheduler, entry);
if (exception != null) {
logger.severe(exception);
}
} else { // if entries size > 0, we will call storeAll
final Queue<ScheduledEntry> duplicateKeys = new LinkedList<ScheduledEntry>();
final Map<Object,Object> map = new HashMap<Object,Object>(entries.size());
for (ScheduledEntry<Data, Object> entry : entries) {
final Object key = mapService.toObject(entry.getKey());
if (map.get(key) != null) {
duplicateKeys.offer(entry);
continue;
}
map.put(key, mapService.toObject(entry.getValue()));
}
// we will traverse duplicate keys to filter first duplicates from storeAll's map
for (ScheduledEntry duplicateKey : duplicateKeys) {
Object key = duplicateKey.getKey();
- if(map.containsKey(key)) {
- final Exception ex = tryStore(scheduler, new AbstractMap.SimpleEntry(key, map.get(key)));
+ Object removed = map.remove(key);
+ if(removed != null) {
+ final Exception ex = tryStore(scheduler, new AbstractMap.SimpleEntry(key, removed));
if (ex != null) {
logger.severe(ex);
}
}
- map.remove(key);
}
Exception exception = null;
try {
mapContainer.getStore().storeAll(map);
} catch (Exception e) {
logger.warning(mapContainer.getStore().getMapStore().getClass() + " --> storeAll was failed, " +
"now Hazelcast is trying to store one by one: ", e);
// if store all throws exception we will try to put insert them one by one.
for (ScheduledEntry<Data, Object> entry : entries) {
Exception temp = tryStore(scheduler, entry);
if (temp != null) {
exception = temp;
}
}
}
ScheduledEntry entry;
while ((entry = duplicateKeys.poll()) != null) {
final Exception temp = tryStore(scheduler, entry);
if (temp != null) {
exception = temp;
}
}
if (exception != null) {
logger.severe(exception);
}
}
}
}
| false | true | public void process(EntryTaskScheduler<Data, Object> scheduler, Collection<ScheduledEntry<Data, Object>> entries) {
if (entries.isEmpty())
return;
final ILogger logger = mapService.getNodeEngine().getLogger(getClass());
if (entries.size() == 1) {
ScheduledEntry<Data, Object> entry = entries.iterator().next();
Exception exception = tryStore(scheduler, entry);
if (exception != null) {
logger.severe(exception);
}
} else { // if entries size > 0, we will call storeAll
final Queue<ScheduledEntry> duplicateKeys = new LinkedList<ScheduledEntry>();
final Map<Object,Object> map = new HashMap<Object,Object>(entries.size());
for (ScheduledEntry<Data, Object> entry : entries) {
final Object key = mapService.toObject(entry.getKey());
if (map.get(key) != null) {
duplicateKeys.offer(entry);
continue;
}
map.put(key, mapService.toObject(entry.getValue()));
}
// we will traverse duplicate keys to filter first duplicates from storeAll's map
for (ScheduledEntry duplicateKey : duplicateKeys) {
Object key = duplicateKey.getKey();
if(map.containsKey(key)) {
final Exception ex = tryStore(scheduler, new AbstractMap.SimpleEntry(key, map.get(key)));
if (ex != null) {
logger.severe(ex);
}
}
map.remove(key);
}
Exception exception = null;
try {
mapContainer.getStore().storeAll(map);
} catch (Exception e) {
logger.warning(mapContainer.getStore().getMapStore().getClass() + " --> storeAll was failed, " +
"now Hazelcast is trying to store one by one: ", e);
// if store all throws exception we will try to put insert them one by one.
for (ScheduledEntry<Data, Object> entry : entries) {
Exception temp = tryStore(scheduler, entry);
if (temp != null) {
exception = temp;
}
}
}
ScheduledEntry entry;
while ((entry = duplicateKeys.poll()) != null) {
final Exception temp = tryStore(scheduler, entry);
if (temp != null) {
exception = temp;
}
}
if (exception != null) {
logger.severe(exception);
}
}
}
| public void process(EntryTaskScheduler<Data, Object> scheduler, Collection<ScheduledEntry<Data, Object>> entries) {
if (entries.isEmpty())
return;
final ILogger logger = mapService.getNodeEngine().getLogger(getClass());
if (entries.size() == 1) {
ScheduledEntry<Data, Object> entry = entries.iterator().next();
Exception exception = tryStore(scheduler, entry);
if (exception != null) {
logger.severe(exception);
}
} else { // if entries size > 0, we will call storeAll
final Queue<ScheduledEntry> duplicateKeys = new LinkedList<ScheduledEntry>();
final Map<Object,Object> map = new HashMap<Object,Object>(entries.size());
for (ScheduledEntry<Data, Object> entry : entries) {
final Object key = mapService.toObject(entry.getKey());
if (map.get(key) != null) {
duplicateKeys.offer(entry);
continue;
}
map.put(key, mapService.toObject(entry.getValue()));
}
// we will traverse duplicate keys to filter first duplicates from storeAll's map
for (ScheduledEntry duplicateKey : duplicateKeys) {
Object key = duplicateKey.getKey();
Object removed = map.remove(key);
if(removed != null) {
final Exception ex = tryStore(scheduler, new AbstractMap.SimpleEntry(key, removed));
if (ex != null) {
logger.severe(ex);
}
}
}
Exception exception = null;
try {
mapContainer.getStore().storeAll(map);
} catch (Exception e) {
logger.warning(mapContainer.getStore().getMapStore().getClass() + " --> storeAll was failed, " +
"now Hazelcast is trying to store one by one: ", e);
// if store all throws exception we will try to put insert them one by one.
for (ScheduledEntry<Data, Object> entry : entries) {
Exception temp = tryStore(scheduler, entry);
if (temp != null) {
exception = temp;
}
}
}
ScheduledEntry entry;
while ((entry = duplicateKeys.poll()) != null) {
final Exception temp = tryStore(scheduler, entry);
if (temp != null) {
exception = temp;
}
}
if (exception != null) {
logger.severe(exception);
}
}
}
|
diff --git a/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java b/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java
index 1e275c8..fd2aed4 100644
--- a/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java
+++ b/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java
@@ -1,104 +1,105 @@
package net.appositedesigns.fileexplorer.quickactions;
import java.io.File;
import net.appositedesigns.fileexplorer.FileExplorerMain;
import net.appositedesigns.fileexplorer.FileListEntry;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.util.FileActionsHelper;
import android.view.View;
import android.view.View.OnClickListener;
public final class QuickActionHelper {
private FileExplorerMain mContext;
public QuickActionHelper(FileExplorerMain mContext) {
super();
this.mContext = mContext;
}
public void showQuickActions(final View view, final FileListEntry entry) {
final File file = entry.getPath();
final QuickAction actions = new QuickAction(view);
int[] availableActions = FileActionsHelper.getContextMenuOptions(file, mContext);
ActionItem action = null;
for(int i=availableActions.length-1;i>=0;i--)
{
int a = availableActions[i];
action = null;
switch (a) {
case R.string.action_cut:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_cut));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.cutFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_copy:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_copy));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.copyFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_delete:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_delete));
action.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
actions.dismiss();
FileActionsHelper.deleteFile(file, mContext);
}
});
+ break;
case R.string.action_share:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_share));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.share(file, mContext);
}
});
break;
default:
break;
}
if(action!=null)
{
actions.addActionItem(action);
}
}
actions.setAnimStyle(QuickAction.ANIM_AUTO);
actions.show();
}
}
| true | true | public void showQuickActions(final View view, final FileListEntry entry) {
final File file = entry.getPath();
final QuickAction actions = new QuickAction(view);
int[] availableActions = FileActionsHelper.getContextMenuOptions(file, mContext);
ActionItem action = null;
for(int i=availableActions.length-1;i>=0;i--)
{
int a = availableActions[i];
action = null;
switch (a) {
case R.string.action_cut:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_cut));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.cutFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_copy:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_copy));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.copyFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_delete:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_delete));
action.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
actions.dismiss();
FileActionsHelper.deleteFile(file, mContext);
}
});
case R.string.action_share:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_share));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.share(file, mContext);
}
});
break;
default:
break;
}
if(action!=null)
{
actions.addActionItem(action);
}
}
actions.setAnimStyle(QuickAction.ANIM_AUTO);
actions.show();
}
| public void showQuickActions(final View view, final FileListEntry entry) {
final File file = entry.getPath();
final QuickAction actions = new QuickAction(view);
int[] availableActions = FileActionsHelper.getContextMenuOptions(file, mContext);
ActionItem action = null;
for(int i=availableActions.length-1;i>=0;i--)
{
int a = availableActions[i];
action = null;
switch (a) {
case R.string.action_cut:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_cut));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.cutFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_copy:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_copy));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.copyFile(file, mContext);
actions.dismiss();
}
});
break;
case R.string.action_delete:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_delete));
action.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
actions.dismiss();
FileActionsHelper.deleteFile(file, mContext);
}
});
break;
case R.string.action_share:
action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_share));
action.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
FileActionsHelper.share(file, mContext);
}
});
break;
default:
break;
}
if(action!=null)
{
actions.addActionItem(action);
}
}
actions.setAnimStyle(QuickAction.ANIM_AUTO);
actions.show();
}
|
diff --git a/cpf-pentaho/src/pt/webdetails/cpk/CpkContentGenerator.java b/cpf-pentaho/src/pt/webdetails/cpk/CpkContentGenerator.java
index ef78ccd..24392f3 100644
--- a/cpf-pentaho/src/pt/webdetails/cpk/CpkContentGenerator.java
+++ b/cpf-pentaho/src/pt/webdetails/cpk/CpkContentGenerator.java
@@ -1,236 +1,239 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
package pt.webdetails.cpk;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.dom4j.DocumentException;
import org.pentaho.platform.api.engine.IParameterProvider;
import pt.webdetails.cpf.RestContentGenerator;
import pt.webdetails.cpf.RestRequestHandler;
import pt.webdetails.cpf.Router;
import pt.webdetails.cpf.WrapperUtils;
import pt.webdetails.cpf.annotations.AccessLevel;
import pt.webdetails.cpf.annotations.Exposed;
import pt.webdetails.cpf.http.ICommonParameterProvider;
import pt.webdetails.cpf.plugins.IPluginFilter;
import pt.webdetails.cpf.plugins.Plugin;
import pt.webdetails.cpf.plugins.PluginsAnalyzer;
import pt.webdetails.cpf.repository.PentahoRepositoryAccess;
import pt.webdetails.cpf.utils.PluginUtils;
import pt.webdetails.cpk.datasources.CpkDataSourceMetadata;
import pt.webdetails.cpk.datasources.DataSource;
import pt.webdetails.cpk.datasources.DataSourceDefinition;
import pt.webdetails.cpk.datasources.DataSourceMetadata;
import pt.webdetails.cpk.elements.IElement;
import pt.webdetails.cpk.elements.impl.KettleElementType;
import pt.webdetails.cpk.sitemap.LinkGenerator;
public class CpkContentGenerator extends RestContentGenerator {
private static final long serialVersionUID = 1L;
public static final String PLUGIN_NAME = "cpk";
protected CpkCoreService coreService;
protected ICpkEnvironment cpkEnv;
public CpkContentGenerator() {
this.pluginUtils = new PluginUtils();
this.cpkEnv = new CpkPentahoEnvironment(pluginUtils, new PentahoRepositoryAccess());
this.coreService = new CpkCoreService(cpkEnv);
}
@Override
public void createContent() throws Exception {
wrapParams();
try {
coreService.createContent(map);
} catch (NoElementException e) {
super.createContent();
}
}
@Exposed(accessLevel = AccessLevel.PUBLIC)
public void reload(OutputStream out) throws DocumentException, IOException {
coreService.reload(out, map);
}
@Exposed(accessLevel = AccessLevel.PUBLIC)
public void refresh(OutputStream out) throws DocumentException, IOException {
coreService.refresh(out, map);
}
@Exposed(accessLevel = AccessLevel.PUBLIC)
public void version(OutputStream out) {
PluginsAnalyzer pluginsAnalyzer = new PluginsAnalyzer();
pluginsAnalyzer.refresh();
String version = null;
IPluginFilter thisPlugin = new IPluginFilter() {
@Override
public boolean include(Plugin plugin) {
return plugin.getId().equalsIgnoreCase(pluginUtils.getPluginName());
}
};
List<Plugin> plugins = pluginsAnalyzer.getPlugins(thisPlugin);
version = plugins.get(0).getVersion().toString();
writeMessage(out, version);
}
@Exposed(accessLevel = AccessLevel.PUBLIC)
public void status(OutputStream out) throws DocumentException, IOException {
if(map.get("request").hasParameter("json")){
coreService.statusJson(out,map);
}else{
coreService.status(out, map);
}
}
@Exposed(accessLevel = AccessLevel.PUBLIC)
public void getPluginMetadata(OutputStream out){
ObjectMapper mapper = new ObjectMapper();
String json = null;
IPluginFilter pluginFilter = new IPluginFilter() {
@Override
public boolean include(Plugin plugin) {
return plugin.getId().equals(pluginUtils.getPluginName());
}
};
PluginsAnalyzer pluginsAnalyzer = new PluginsAnalyzer();
pluginsAnalyzer.refresh();
List<Plugin> plugins = pluginsAnalyzer.getPlugins(pluginFilter);
Plugin plugin = null;
if(!plugins.isEmpty()){
plugin = plugins.get(0);
try {
json = mapper.writeValueAsString(plugin);
} catch (IOException ex) {
Logger.getLogger(CpkContentGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(json == null){
json = "{\"error\":\"There was a problem getting the plugin metadata into JSON. The result was 'null'\"}";
}
writeMessage(out, json);
}
@Exposed(accessLevel = AccessLevel.PUBLIC)
public void getSitemapJson(OutputStream out) throws IOException {
TreeMap<String, IElement> elementsMap = CpkEngine.getInstance().getElementsMap();
JsonNode sitemap = null;
if (elementsMap != null) {
LinkGenerator linkGen = new LinkGenerator(elementsMap, pluginUtils);
sitemap = linkGen.getLinksJson();
}
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, sitemap);
}
@Exposed(accessLevel = AccessLevel.PUBLIC)
public void elementsList(OutputStream out) {
coreService.getElementsList(out,map);
}
@Override
public String getPluginName() {
return pluginUtils.getPluginName();
}
private void writeMessage(OutputStream out, String message) {
try {
out.write(message.getBytes(ENCODING));
} catch (IOException ex) {
Logger.getLogger(CpkContentGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public RestRequestHandler getRequestHandler() {
return Router.getBaseRouter();
}
private void wrapParams() {
if (parameterProviders != null) {
Iterator it = parameterProviders.entrySet().iterator();
map = new HashMap<String, ICommonParameterProvider>();
while (it.hasNext()) {
@SuppressWarnings("unchecked")
Map.Entry<String, IParameterProvider> e = (Map.Entry<String, IParameterProvider>) it.next();
map.put(e.getKey(), WrapperUtils.wrapParamProvider(e.getValue()));
}
}
}
// New Jackson API (version 2.x)
static final com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
static {
mapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY);
}
@Exposed(accessLevel = AccessLevel.PUBLIC, outputType = MimeType.JSON)
public void listDataAccessTypes(final OutputStream out) throws Exception {
//boolean refreshCache = Boolean.parseBoolean(getRequestParameters().getStringParameter("refreshCache", "false"));
Set<DataSource> dataSources = new LinkedHashSet<DataSource>();
StringBuilder dsDeclarations = new StringBuilder("{");
IElement[] endpoints = coreService.getElements();
if (endpoints != null) {
for (IElement endpoint : endpoints) {
// filter endpoints that aren't of kettle type
if (!(endpoint instanceof KettleElementType || endpoint.getElementType().equalsIgnoreCase("kettle"))) {
continue;
}
logger.info(String.format("CPK Kettle Endpoint found: %s)", endpoint));
String pluginId = coreService.getPluginName();
String endpointName = endpoint.getName();
DataSourceMetadata metadata = new CpkDataSourceMetadata(pluginId, endpointName);
DataSourceDefinition definition = new DataSourceDefinition();
DataSource dataSource = new DataSource().setMetadata(metadata).setDefinition(definition);
dataSources.add(dataSource);
dsDeclarations.append(String.format("\"%s_%s_CPKENDPOINT\": ", pluginId, endpointName));
dsDeclarations.append(mapper.writeValueAsString(dataSource));
dsDeclarations.append(",");
}
}
- dsDeclarations.deleteCharAt(dsDeclarations.lastIndexOf(","));
+ int index = dsDeclarations.lastIndexOf(",");
+ if (index > 0) {
+ dsDeclarations.deleteCharAt(index);
+ }
dsDeclarations.append("}");
out.write(dsDeclarations.toString().getBytes());
}
}
| true | true | public void listDataAccessTypes(final OutputStream out) throws Exception {
//boolean refreshCache = Boolean.parseBoolean(getRequestParameters().getStringParameter("refreshCache", "false"));
Set<DataSource> dataSources = new LinkedHashSet<DataSource>();
StringBuilder dsDeclarations = new StringBuilder("{");
IElement[] endpoints = coreService.getElements();
if (endpoints != null) {
for (IElement endpoint : endpoints) {
// filter endpoints that aren't of kettle type
if (!(endpoint instanceof KettleElementType || endpoint.getElementType().equalsIgnoreCase("kettle"))) {
continue;
}
logger.info(String.format("CPK Kettle Endpoint found: %s)", endpoint));
String pluginId = coreService.getPluginName();
String endpointName = endpoint.getName();
DataSourceMetadata metadata = new CpkDataSourceMetadata(pluginId, endpointName);
DataSourceDefinition definition = new DataSourceDefinition();
DataSource dataSource = new DataSource().setMetadata(metadata).setDefinition(definition);
dataSources.add(dataSource);
dsDeclarations.append(String.format("\"%s_%s_CPKENDPOINT\": ", pluginId, endpointName));
dsDeclarations.append(mapper.writeValueAsString(dataSource));
dsDeclarations.append(",");
}
}
dsDeclarations.deleteCharAt(dsDeclarations.lastIndexOf(","));
dsDeclarations.append("}");
out.write(dsDeclarations.toString().getBytes());
}
| public void listDataAccessTypes(final OutputStream out) throws Exception {
//boolean refreshCache = Boolean.parseBoolean(getRequestParameters().getStringParameter("refreshCache", "false"));
Set<DataSource> dataSources = new LinkedHashSet<DataSource>();
StringBuilder dsDeclarations = new StringBuilder("{");
IElement[] endpoints = coreService.getElements();
if (endpoints != null) {
for (IElement endpoint : endpoints) {
// filter endpoints that aren't of kettle type
if (!(endpoint instanceof KettleElementType || endpoint.getElementType().equalsIgnoreCase("kettle"))) {
continue;
}
logger.info(String.format("CPK Kettle Endpoint found: %s)", endpoint));
String pluginId = coreService.getPluginName();
String endpointName = endpoint.getName();
DataSourceMetadata metadata = new CpkDataSourceMetadata(pluginId, endpointName);
DataSourceDefinition definition = new DataSourceDefinition();
DataSource dataSource = new DataSource().setMetadata(metadata).setDefinition(definition);
dataSources.add(dataSource);
dsDeclarations.append(String.format("\"%s_%s_CPKENDPOINT\": ", pluginId, endpointName));
dsDeclarations.append(mapper.writeValueAsString(dataSource));
dsDeclarations.append(",");
}
}
int index = dsDeclarations.lastIndexOf(",");
if (index > 0) {
dsDeclarations.deleteCharAt(index);
}
dsDeclarations.append("}");
out.write(dsDeclarations.toString().getBytes());
}
|
diff --git a/org.rubypeople.rdt.launching.tests/src/org/rubypeople/rdt/internal/launching/TC_RubyRuntime.java b/org.rubypeople.rdt.launching.tests/src/org/rubypeople/rdt/internal/launching/TC_RubyRuntime.java
index 1e846cce..bf7a290e 100644
--- a/org.rubypeople.rdt.launching.tests/src/org/rubypeople/rdt/internal/launching/TC_RubyRuntime.java
+++ b/org.rubypeople.rdt.launching.tests/src/org/rubypeople/rdt/internal/launching/TC_RubyRuntime.java
@@ -1,378 +1,378 @@
package org.rubypeople.rdt.internal.launching;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileState;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourceAttributes;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.rubypeople.rdt.launching.IInterpreter;
public class TC_RubyRuntime extends TestCase {
protected StringWriter runtimeConfigurationWriter = new StringWriter();
public TC_RubyRuntime(String name) {
super(name);
}
public void testGetInstalledInterpreters() {
ShamRubyRuntime runtime = new ShamRubyRuntime();
IInterpreter interpreterOne = new RubyInterpreter("InterpreterOne", new File("C:/RubyInstallRootOne"));
IInterpreter interpreterTwo = new RubyInterpreter("InterpreterTwo", new File("C:/RubyInstallRootTwo"));
assertTrue("Runtime should contain all interpreters.", runtime.getInstalledInterpreters().containsAll(Arrays.asList(new Object[] { interpreterOne, interpreterTwo })));
assertTrue("interpreterTwo should be selected interpreter.", runtime.getSelectedInterpreter().equals(interpreterTwo));
}
public void testSetInstalledInterpreters() {
ShamRubyRuntime runtime = new ShamRubyRuntime();
IInterpreter interpreterOne = new RubyInterpreter("InterpreterOne", new File("C:/RubyInstallRootOne"));
runtime.setInstalledInterpreters(Arrays.asList(new IInterpreter[] { interpreterOne }));
- assertEquals("XML should indicate only one interpreter with it being the selected.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:/RubyInstallRootOne\" selected=\"true\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
+ assertEquals("XML should indicate only one interpreter with it being the selected.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:\\RubyInstallRootOne\" selected=\"true\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
RubyInterpreter interpreterTwo = new RubyInterpreter("InterpreterTwo", new File("C:/RubyInstallRootTwo"));
runtime.setInstalledInterpreters(Arrays.asList(new IInterpreter[] { interpreterOne, interpreterTwo }));
- assertEquals("XML should indicate both interpreters with the first one being selected.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:/RubyInstallRootOne\" selected=\"true\"/><interpreter name=\"InterpreterTwo\" path=\"C:/RubyInstallRootTwo\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
+ assertEquals("XML should indicate both interpreters with the first one being selected.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:\\RubyInstallRootOne\" selected=\"true\"/><interpreter name=\"InterpreterTwo\" path=\"C:\\RubyInstallRootTwo\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
runtime.setSelectedInterpreter(interpreterTwo);
- assertEquals("XML should indicate selected interpreter change.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:/RubyInstallRootOne\"/><interpreter name=\"InterpreterTwo\" path=\"C:/RubyInstallRootTwo\" selected=\"true\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
+ assertEquals("XML should indicate selected interpreter change.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:\\RubyInstallRootOne\"/><interpreter name=\"InterpreterTwo\" path=\"C:\\RubyInstallRootTwo\" selected=\"true\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
}
protected class ShamRubyRuntime extends RubyRuntime {
protected ShamRubyRuntime() {
super();
}
protected Reader getRuntimeConfigurationReader() {
return new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:/RubyInstallRootOne\"/><interpreter name=\"InterpreterTwo\" path=\"C:/RubyInstallRootTwo\" selected=\"true\"/></runtimeconfig>");
}
protected Writer getRuntimeConfigurationWriter() {
return runtimeConfigurationWriter;
}
public void setInstalledInterpreters(List<IInterpreter> newInstalledInterpreters) {
super.setInstalledInterpreters(newInstalledInterpreters);
}
public void saveRuntimeConfiguration() {
runtimeConfigurationWriter = new StringWriter();
super.saveRuntimeConfiguration() ;
}
}
protected class RuntimeConfigurationFile implements IFile {
protected RuntimeConfigurationFile() {}
public void setCharset(String newCharset, IProgressMonitor monitor) throws CoreException {
}
public void appendContents(InputStream source, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {}
public void appendContents(InputStream source, int updateFlags, IProgressMonitor monitor) throws CoreException {}
public void create(InputStream source, boolean force, IProgressMonitor monitor) throws CoreException {}
public void create(InputStream source, int updateFlags, IProgressMonitor monitor) throws CoreException {}
public void delete(boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {}
public InputStream getContents() throws CoreException {
return new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:/RubyInstallRootOne\"/><interpreter name=\"InterpreterTwo\" path=\"C:/RubyInstallRootTwo\" selected=\"true\"/></runtimeconfig>".getBytes());
}
public InputStream getContents(boolean force) throws CoreException {
return getContents();
}
public IPath getFullPath() {
return null;
}
public IFileState[] getHistory(IProgressMonitor monitor) throws CoreException {
return null;
}
public String getName() {
return null;
}
public boolean isReadOnly() {
return false;
}
public String getCharset() throws CoreException {
return null;
}
public void move(IPath destination, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {}
public void setContents(IFileState source, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {}
public void setContents(IFileState source, int updateFlags, IProgressMonitor monitor) throws CoreException {}
public void setContents(InputStream source, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {}
public void setContents(InputStream source, int updateFlags, IProgressMonitor monitor) throws CoreException {}
public void accept(IResourceVisitor visitor, int depth, boolean includePhantoms) throws CoreException {}
public void accept(IResourceVisitor visitor, int depth, int memberFlags) throws CoreException {}
public void accept(IResourceVisitor visitor) throws CoreException {}
public void clearHistory(IProgressMonitor monitor) throws CoreException {}
public void copy(IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {}
public void copy(IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {}
public void copy(IProjectDescription description, boolean force, IProgressMonitor monitor) throws CoreException {}
public void copy(IProjectDescription description, int updateFlags, IProgressMonitor monitor) throws CoreException {}
public IMarker createMarker(String type) throws CoreException {
return null;
}
public void delete(boolean force, IProgressMonitor monitor) throws CoreException {}
public void delete(int updateFlags, IProgressMonitor monitor) throws CoreException {}
public void deleteMarkers(String type, boolean includeSubtypes, int depth) throws CoreException {}
public boolean exists() {
return false;
}
public IMarker findMarker(long id) throws CoreException {
return null;
}
public IMarker[] findMarkers(String type, boolean includeSubtypes, int depth) throws CoreException {
return null;
}
public String getFileExtension() {
return null;
}
public IPath getLocation() {
return null;
}
public IMarker getMarker(long id) {
return null;
}
public long getModificationStamp() {
return 0;
}
public IContainer getParent() {
return null;
}
public String getPersistentProperty(QualifiedName key) throws CoreException {
return null;
}
public IProject getProject() {
return null;
}
public IPath getProjectRelativePath() {
return null;
}
public Object getSessionProperty(QualifiedName key) throws CoreException {
return null;
}
public int getType() {
return 0;
}
public IWorkspace getWorkspace() {
return null;
}
public boolean isAccessible() {
return false;
}
public boolean isDerived() {
return false;
}
public boolean isLocal(int depth) {
return false;
}
public boolean isPhantom() {
return false;
}
public boolean isTeamPrivateMember() {
return false;
}
public void move(IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {}
public void move(IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {}
public void move(IProjectDescription description, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {}
public void move(IProjectDescription description, int updateFlags, IProgressMonitor monitor) throws CoreException {}
public void refreshLocal(int depth, IProgressMonitor monitor) throws CoreException {}
public void setDerived(boolean isDerived) throws CoreException {}
public void setLocal(boolean flag, int depth, IProgressMonitor monitor) throws CoreException {}
public void setPersistentProperty(QualifiedName key, String value) throws CoreException {}
public void setReadOnly(boolean readOnly) {}
public void setSessionProperty(QualifiedName key, Object value) throws CoreException {}
public void setTeamPrivateMember(boolean isTeamPrivate) throws CoreException {}
public void touch(IProgressMonitor monitor) throws CoreException {}
public Object getAdapter(Class adapter) {
return null;
}
public boolean isSynchronized(int depth) {
return false;
}
public int getEncoding() throws CoreException {
return 0;
}
public void createLink(
IPath localLocation,
int updateFlags,
IProgressMonitor monitor)
throws CoreException {
}
public IPath getRawLocation() {
return null;
}
public boolean isLinked() {
return false;
}
public void accept(IResourceProxyVisitor arg0, int arg1) throws CoreException {
}
public long getLocalTimeStamp() {
return 0;
}
public long setLocalTimeStamp(long value) throws CoreException {
return 0;
}
public boolean contains(ISchedulingRule rule) {
return false;
}
public boolean isConflicting(ISchedulingRule rule) {
return false;
}
public void setCharset(String newCharset) throws CoreException {
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.IFile#getCharset(boolean)
*/
public String getCharset(boolean checkImplicit) throws CoreException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.IFile#getContentDescription()
*/
public IContentDescription getContentDescription() throws CoreException {
// TODO Auto-generated method stub
return null;
}
public String getCharsetFor(Reader reader) throws CoreException {
// TODO Auto-generated method stub
return null;
}
public ResourceAttributes getResourceAttributes() {
// TODO Auto-generated method stub
return null;
}
public void revertModificationStamp(long value) throws CoreException {
// TODO Auto-generated method stub
}
public void setResourceAttributes(ResourceAttributes attributes) throws CoreException {
// TODO Auto-generated method stub
}
public URI getLocationURI() {
// TODO Auto-generated method stub
return null;
}
public void createLink(URI location, int updateFlags, IProgressMonitor monitor) throws CoreException {
// TODO Auto-generated method stub
}
public URI getRawLocationURI() {
// TODO Auto-generated method stub
return null;
}
public boolean isLinked(int options) {
// TODO Auto-generated method stub
return false;
}
public IResourceProxy createProxy() {
// TODO Auto-generated method stub
return null;
}
}
}
| false | true | public void testSetInstalledInterpreters() {
ShamRubyRuntime runtime = new ShamRubyRuntime();
IInterpreter interpreterOne = new RubyInterpreter("InterpreterOne", new File("C:/RubyInstallRootOne"));
runtime.setInstalledInterpreters(Arrays.asList(new IInterpreter[] { interpreterOne }));
assertEquals("XML should indicate only one interpreter with it being the selected.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:/RubyInstallRootOne\" selected=\"true\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
RubyInterpreter interpreterTwo = new RubyInterpreter("InterpreterTwo", new File("C:/RubyInstallRootTwo"));
runtime.setInstalledInterpreters(Arrays.asList(new IInterpreter[] { interpreterOne, interpreterTwo }));
assertEquals("XML should indicate both interpreters with the first one being selected.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:/RubyInstallRootOne\" selected=\"true\"/><interpreter name=\"InterpreterTwo\" path=\"C:/RubyInstallRootTwo\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
runtime.setSelectedInterpreter(interpreterTwo);
assertEquals("XML should indicate selected interpreter change.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:/RubyInstallRootOne\"/><interpreter name=\"InterpreterTwo\" path=\"C:/RubyInstallRootTwo\" selected=\"true\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
}
| public void testSetInstalledInterpreters() {
ShamRubyRuntime runtime = new ShamRubyRuntime();
IInterpreter interpreterOne = new RubyInterpreter("InterpreterOne", new File("C:/RubyInstallRootOne"));
runtime.setInstalledInterpreters(Arrays.asList(new IInterpreter[] { interpreterOne }));
assertEquals("XML should indicate only one interpreter with it being the selected.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:\\RubyInstallRootOne\" selected=\"true\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
RubyInterpreter interpreterTwo = new RubyInterpreter("InterpreterTwo", new File("C:/RubyInstallRootTwo"));
runtime.setInstalledInterpreters(Arrays.asList(new IInterpreter[] { interpreterOne, interpreterTwo }));
assertEquals("XML should indicate both interpreters with the first one being selected.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:\\RubyInstallRootOne\" selected=\"true\"/><interpreter name=\"InterpreterTwo\" path=\"C:\\RubyInstallRootTwo\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
runtime.setSelectedInterpreter(interpreterTwo);
assertEquals("XML should indicate selected interpreter change.", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><runtimeconfig><interpreter name=\"InterpreterOne\" path=\"C:\\RubyInstallRootOne\"/><interpreter name=\"InterpreterTwo\" path=\"C:\\RubyInstallRootTwo\" selected=\"true\"/></runtimeconfig>", runtimeConfigurationWriter.toString());
}
|
diff --git a/SongSelectionScreen.java b/SongSelectionScreen.java
index 3d56f78..fbbc5de 100644
--- a/SongSelectionScreen.java
+++ b/SongSelectionScreen.java
@@ -1,150 +1,153 @@
package crescendo.sheetmusic;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import crescendo.base.ErrorHandler;
import crescendo.base.ErrorHandler.Response;
import crescendo.base.profile.ProfileManager;
import crescendo.base.profile.SongPreference;
import crescendo.base.song.SongFactory;
import crescendo.base.song.SongModel;
public class SongSelectionScreen extends JPanel {
private JLabel Song1 = new JLabel("Song1");
private JButton LoadFile = new JButton("Load Song File");
private EventListener l = new EventListener();
private SheetMusic module;
private List<SongPreference> s;
private List<SongLabel> songsLabelsList = new ArrayList<SongLabel>();
private int width, height;
public SongSelectionScreen(SheetMusic module,int width, int height){
this.module = module;
this.setSize(width, height);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Song1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
Song1.setSize(width, height/10);
parseSongList();
LoadFile.addActionListener(l);
this.add(LoadFile);
}
private void makeLabels(int i){
for(int j = 0; j<i; j++){
songsLabelsList.add(new SongLabel());
}
}
private JPanel getPane(){
return this;
}
private void parseSongList() {
s = ProfileManager.getInstance().getActiveProfile().getSongPreferences();
makeLabels(s.size());
for(int i = 0; i<s.size();i++){
songsLabelsList.get(i).setSongPath(s.get(i).getFilePath());
songsLabelsList.get(i).setText(s.get(i).getSongName()+"\n"+s.get(i).getCreator());
songsLabelsList.get(i).addActionListener(l);
add(songsLabelsList.get(i));
}
}
private void loadSong(String filename){
File file = new File(filename);
SongModel loadedSong = null;
boolean loading = true;
try {
while(loading){
loadedSong = SongFactory.generateSongFromFile(file.getAbsolutePath());
loading = false;
}
} catch (IOException e1) {
Response response = ErrorHandler.showRetryFail("Failed to load song", "Application failed to load song: "+file.getAbsolutePath()+" would you like to try again?");
if(response == Response.RETRY){
loading = true;
}else{
loading = false;
}
}
if(loadedSong!=null){
SongPreference newSong = new SongPreference(filename, loadedSong.getTracks().size(), 0);
newSong.setSongName(loadedSong.getTitle());
- newSong.setCreator(loadedSong.getCreators().get(0).getName());
+ if(loadedSong.getCreators().size()>0)
+ newSong.setCreator(loadedSong.getCreators().get(0).getName());
+ else
+ newSong.setCreator("");
boolean doAdd = true;
for(SongPreference p : ProfileManager.getInstance().getActiveProfile().getSongPreferences()){
if(p.getFilePath().equals(filename)){
doAdd=false;
}
}
if(doAdd){
ProfileManager.getInstance().getActiveProfile().getSongPreferences().add(newSong);
}
module.loadSong(loadedSong,0);
}
}
private class EventListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof SongLabel){
String songPath = ((SongLabel)(e.getSource())).getSongPath();
loadSong(songPath);
}
if(e.getSource() == LoadFile){
JFileChooser jfc = new JFileChooser();
int returnVal = jfc.showOpenDialog(SongSelectionScreen.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = jfc.getSelectedFile();
loadSong(file.getAbsolutePath());
}
}
}
}
@SuppressWarnings("serial")
private class SongLabel extends JButton{
private String songPath;
public String getSongPath(){
return songPath;
}
public void setSongPath(String p){
songPath = p;
}
}
}
| true | true | private void loadSong(String filename){
File file = new File(filename);
SongModel loadedSong = null;
boolean loading = true;
try {
while(loading){
loadedSong = SongFactory.generateSongFromFile(file.getAbsolutePath());
loading = false;
}
} catch (IOException e1) {
Response response = ErrorHandler.showRetryFail("Failed to load song", "Application failed to load song: "+file.getAbsolutePath()+" would you like to try again?");
if(response == Response.RETRY){
loading = true;
}else{
loading = false;
}
}
if(loadedSong!=null){
SongPreference newSong = new SongPreference(filename, loadedSong.getTracks().size(), 0);
newSong.setSongName(loadedSong.getTitle());
newSong.setCreator(loadedSong.getCreators().get(0).getName());
boolean doAdd = true;
for(SongPreference p : ProfileManager.getInstance().getActiveProfile().getSongPreferences()){
if(p.getFilePath().equals(filename)){
doAdd=false;
}
}
if(doAdd){
ProfileManager.getInstance().getActiveProfile().getSongPreferences().add(newSong);
}
module.loadSong(loadedSong,0);
}
}
| private void loadSong(String filename){
File file = new File(filename);
SongModel loadedSong = null;
boolean loading = true;
try {
while(loading){
loadedSong = SongFactory.generateSongFromFile(file.getAbsolutePath());
loading = false;
}
} catch (IOException e1) {
Response response = ErrorHandler.showRetryFail("Failed to load song", "Application failed to load song: "+file.getAbsolutePath()+" would you like to try again?");
if(response == Response.RETRY){
loading = true;
}else{
loading = false;
}
}
if(loadedSong!=null){
SongPreference newSong = new SongPreference(filename, loadedSong.getTracks().size(), 0);
newSong.setSongName(loadedSong.getTitle());
if(loadedSong.getCreators().size()>0)
newSong.setCreator(loadedSong.getCreators().get(0).getName());
else
newSong.setCreator("");
boolean doAdd = true;
for(SongPreference p : ProfileManager.getInstance().getActiveProfile().getSongPreferences()){
if(p.getFilePath().equals(filename)){
doAdd=false;
}
}
if(doAdd){
ProfileManager.getInstance().getActiveProfile().getSongPreferences().add(newSong);
}
module.loadSong(loadedSong,0);
}
}
|
diff --git a/src/main/java/org/mapdb/HTreeMap.java b/src/main/java/org/mapdb/HTreeMap.java
index bd408e7c..640a247a 100644
--- a/src/main/java/org/mapdb/HTreeMap.java
+++ b/src/main/java/org/mapdb/HTreeMap.java
@@ -1,1366 +1,1366 @@
/*
* Copyright (c) 2012 Jan Kotek
*
* 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.mapdb;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Thread safe concurrent HashMap
* <p/>
* This map uses full 32bit hash from beginning, There is no initial load factor and rehash.
* Technically it is not hash table, but hash tree with nodes expanding when they become full.
* <p/>
* This map is suitable for number of records 1e9 and over.
* Larger number of records will increase hash collisions and performance
* will degrade linearly with number of records (separate chaining).
* <p/>
* Concurrent scalability is achieved by splitting HashMap into 16 segments, each with separate lock.
* Very similar to ConcurrentHashMap
*
* @author Jan Kotek
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class HTreeMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K, V>, Bind.MapWithModificationListener<K,V> {
protected static final int BUCKET_OVERFLOW = 4;
/** is this a Map or Set? if false, entries do not have values, only keys are allowed*/
protected final boolean hasValues;
/**
* Salt added to hash before rehashing, so it is harder to trigger hash collision attack.
*/
protected final int hashSalt;
protected final Atomic.Long counter;
protected final Serializer<K> keySerializer;
protected final Serializer<V> valueSerializer;
protected final Engine engine;
protected final boolean expireFlag;
protected final long expireTimeStart;
protected final long expire;
protected final boolean expireAccessFlag;
protected final long expireAccess;
protected final long[] expireHeads;
protected final long[] expireTails;
/** node which holds key-value pair */
protected static final class LinkedNode<K,V>{
public final long next;
public final long expireLinkNodeRecid;
public final K key;
public final V value;
public LinkedNode(final long next, long expireLinkNodeRecid, final K key, final V value ){
this.key = key;
this.expireLinkNodeRecid = expireLinkNodeRecid;
this.value = value;
this.next = next;
}
}
protected final Serializer<LinkedNode<K,V>> LN_SERIALIZER = new Serializer<LinkedNode<K,V>>() {
@Override
public void serialize(DataOutput out, LinkedNode<K,V> value) throws IOException {
Utils.packLong(out, value.next);
Utils.packLong(out, value.expireLinkNodeRecid); //TODO save one byte if `expire` is not on
keySerializer.serialize(out,value.key);
if(hasValues)
valueSerializer.serialize(out,value.value);
}
@Override
public LinkedNode<K,V> deserialize(DataInput in, int available) throws IOException {
return new LinkedNode<K, V>(
Utils.unpackLong(in),
Utils.unpackLong(in),
(K) keySerializer.deserialize(in,-1),
hasValues? (V) valueSerializer.deserialize(in,-1) : (V) Utils.EMPTY_STRING
);
}
};
protected static final Serializer<long[][]>DIR_SERIALIZER = new Serializer<long[][]>() {
@Override
public void serialize(DataOutput out, long[][] value) throws IOException {
if(value.length!=16) throw new InternalError();
//first write mask which indicate subarray nullability
int nulls = 0;
for(int i = 0;i<16;i++){
if(value[i]!=null){
for(long l:value[i]){
if(l!=0){
nulls |= 1<<i;
break;
}
}
}
}
out.writeShort(nulls);
//write non null subarrays
for(int i = 0;i<16;i++){
if(value[i]!=null){
if(value[i].length!=8) throw new InternalError();
for(long l:value[i]){
Utils.packLong(out, l);
}
}
}
}
@Override
public long[][] deserialize(DataInput in, int available) throws IOException {
final long[][] ret = new long[16][];
//there are 16 subarrays, each bite indicates if subarray is null
int nulls = in.readUnsignedShort();
for(int i=0;i<16;i++){
if((nulls & 1)!=0){
final long[] subarray = new long[8];
for(int j=0;j<8;j++){
subarray[j] = Utils.unpackLong(in);
}
ret[i] = subarray;
}
nulls = nulls>>>1;
}
return ret;
}
};
protected static final class ExpireLinkNode{
public static final Serializer<ExpireLinkNode> SERIALIZER = new Serializer<ExpireLinkNode>() {
@Override
public void serialize(DataOutput out, ExpireLinkNode value) throws IOException {
if(value == null) return;
Utils.packLong(out,value.prev);
Utils.packLong(out,value.next);
Utils.packLong(out,value.keyRecid);
Utils.packLong(out,value.time);
out.writeInt(value.hash);
}
@Override
public ExpireLinkNode deserialize(DataInput in, int available) throws IOException {
if(available==0) return null;
return new ExpireLinkNode(
Utils.unpackLong(in),Utils.unpackLong(in),Utils.unpackLong(in),Utils.unpackLong(in),
in.readInt()
);
}
};
public final long prev;
public final long next;
public final long keyRecid;
public final long time;
public final int hash;
public ExpireLinkNode(long prev, long next, long keyRecid, long time, int hash) {
this.prev = prev;
this.next = next;
this.keyRecid = keyRecid;
this.time = time;
this.hash = hash;
}
public ExpireLinkNode copyNext(long next2) {
return new ExpireLinkNode(prev,next2, keyRecid,time,hash);
}
public ExpireLinkNode copyPrev(long prev2) {
return new ExpireLinkNode(prev2,next, keyRecid,time,hash);
}
public ExpireLinkNode copyTime(long time2) {
return new ExpireLinkNode(prev,next,keyRecid,time2,hash);
}
}
/** list of segments, this is immutable*/
protected final long[] segmentRecids;
protected final ReentrantReadWriteLock[] segmentLocks = new ReentrantReadWriteLock[16];
{
for(int i=0;i< 16;i++) segmentLocks[i]=new ReentrantReadWriteLock();
}
/**
* Opens HTreeMap
*/
public HTreeMap(Engine engine,long counterRecid, int hashSalt, long[] segmentRecids,
Serializer<K> keySerializer, Serializer<V> valueSerializer,
long expireTimeStart, long expire, long expireAccess, long expiryMaxSize,
long[] expireHeads, long[] expireTails) {
if(engine==null) throw new NullPointerException();
if(segmentRecids==null) throw new NullPointerException();
if(keySerializer==null) throw new NullPointerException();
SerializerBase.assertSerializable(keySerializer);
this.hasValues = valueSerializer!=null;
if(hasValues) {
SerializerBase.assertSerializable(valueSerializer);
}
if(segmentRecids.length!=16) throw new IllegalArgumentException();
this.engine = engine;
this.hashSalt = hashSalt;
this.segmentRecids = Arrays.copyOf(segmentRecids,16);
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
this.expireFlag = expire !=0L;
this.expire = expire;
this.expireTimeStart = expireTimeStart;
this.expireAccessFlag = expireAccess !=0L;
this.expireAccess = expireAccess;
this.expireHeads = expireHeads==null? null : Arrays.copyOf(expireHeads,16);
this.expireTails = expireTails==null? null : Arrays.copyOf(expireTails,16);
if(counterRecid!=0){
this.counter = new Atomic.Long(engine,counterRecid);
Bind.size(this,counter);
}else{
this.counter = null;
}
}
protected static long[] preallocateSegments(Engine engine){
//prealocate segmentRecids, so we dont have to lock on those latter
long[] ret = new long[16];
for(int i=0;i<16;i++)
ret[i] = engine.put(new long[16][], DIR_SERIALIZER);
return ret;
}
@Override
public boolean containsKey(final Object o){
return get(o)!=null;
}
@Override
public int size() {
if(counter!=null)
return (int) counter.get(); //TODO larger then MAX_INT
long counter = 0;
//search tree, until we find first non null
for(int i=0;i<16;i++){
try{
segmentLocks[i].readLock().lock();
final long dirRecid = segmentRecids[i];
counter+=recursiveDirCount(dirRecid);
}finally {
segmentLocks[i].readLock().unlock();
}
}
if(counter>Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return (int) counter;
}
private long recursiveDirCount(final long dirRecid) {
long[][] dir = engine.get(dirRecid, DIR_SERIALIZER);
long counter = 0;
for(long[] subdir:dir){
if(subdir == null) continue;
for(long recid:subdir){
if(recid == 0) continue;
if((recid&1)==0){
//reference to another subdir
recid = recid>>>1;
counter += recursiveDirCount(recid);
}else{
//reference to linked list, count it
recid = recid>>>1;
while(recid!=0){
LinkedNode n = engine.get(recid, LN_SERIALIZER);
if(n!=null){
counter++;
recid = n.next;
}else{
recid = 0;
}
}
}
}
}
return counter;
}
@Override
public boolean isEmpty() {
//search tree, until we find first non null
for(int i=0;i<16;i++){
try{
segmentLocks[i].readLock().lock();
long dirRecid = segmentRecids[i];
long[][] dir = engine.get(dirRecid, DIR_SERIALIZER);
for(long[] d:dir){
if(d!=null) return false;
}
}finally {
segmentLocks[i].readLock().unlock();
}
}
return true;
}
@Override
public V get(final Object o){
if(o==null) return null;
final int h = hash(o);
final int segment = h >>>28;
segmentLocks[segment].readLock().lock();
LinkedNode<K,V> ln;
try{
ln = getInner(o, h, segment);
}finally {
segmentLocks[segment].readLock().unlock();
}
if(ln==null) return null;
if(expireAccessFlag) expireLinkBump(segment,ln.expireLinkNodeRecid,expireAccess);
return ln.value;
}
protected LinkedNode<K,V> getInner(Object o, int h, int segment) {
long recid = segmentRecids[segment];
for(int level=3;level>=0;level--){
long[][] dir = engine.get(recid, DIR_SERIALIZER);
if(dir == null) return null;
int slot = (h>>>(level*7 )) & 0x7F;
if(slot>=128) throw new InternalError();
if(dir[slot/8]==null) return null;
recid = dir[slot/8][slot%8];
if(recid == 0) return null;
if((recid&1)!=0){ //last bite indicates if referenced record is LinkedNode
recid = recid>>>1;
while(true){
LinkedNode<K,V> ln = engine.get(recid, LN_SERIALIZER);
if(ln == null) return null;
if(ln.key.equals(o)){
return ln;
}
if(ln.next==0) return null;
recid = ln.next;
}
}
recid = recid>>>1;
}
return null;
}
@Override
public V put(final K key, final V value){
if (key == null)
throw new IllegalArgumentException("null key");
if (value == null)
throw new IllegalArgumentException("null value");
Utils.checkMapValueIsNotCollecion(value);
final int h = hash(key);
final int segment = h >>>28;
try{
segmentLocks[segment].writeLock().lock();
long dirRecid = segmentRecids[segment];
int level = 3;
while(true){
long[][] dir = engine.get(dirRecid, DIR_SERIALIZER);
final int slot = (h>>>(7*level )) & 0x7F;
if(slot>127) throw new InternalError();
if(dir == null ){
//create new dir
dir = new long[16][];
}
if(dir[slot/8] == null){
dir = Arrays.copyOf(dir,16);
dir[slot/8] = new long[8];
}
int counter = 0;
long recid = dir[slot/8][slot%8];
if(recid!=0){
if((recid&1) == 0){
dirRecid = recid>>>1;
level--;
continue;
}
recid = recid>>>1;
//traverse linked list, try to replace previous value
LinkedNode<K,V> ln = engine.get(recid, LN_SERIALIZER);
while(ln!=null){
if(ln.key.equals(key)){
//found, replace value at this node
V oldVal = ln.value;
ln = new LinkedNode<K, V>(ln.next, ln.expireLinkNodeRecid, ln.key, value);
engine.update(recid, ln, LN_SERIALIZER);
if(expireFlag) expireLinkBump(segment,ln.expireLinkNodeRecid,expire);
notify(key, oldVal, value);
return oldVal;
}
recid = ln.next;
ln = recid==0? null : engine.get(recid, LN_SERIALIZER);
counter++;
}
//key was not found at linked list, so just append it to beginning
}
//check if linked list has overflow and needs to be expanded to new dir level
if(counter>=BUCKET_OVERFLOW && level>=1){
long[][] nextDir = new long[16][];
{
final long expireNodeRecid = expireFlag? engine.put(null, ExpireLinkNode.SERIALIZER):0L;
- final LinkedNode node = new LinkedNode<K, V>(0, expireNodeRecid, key, value);
+ final LinkedNode<K,V> node = new LinkedNode<K, V>(0, expireNodeRecid, key, value);
final long newRecid = engine.put(node, LN_SERIALIZER);
//add newly inserted record
int pos =(h >>>(7*(level-1) )) & 0x7F;
nextDir[pos/8] = new long[8];
nextDir[pos/8][pos%8] = ( newRecid<<1) | 1;
if(expireFlag) expireLinkAdd(segment,expireNodeRecid,newRecid,h);
}
//redistribute linked bucket into new dir
long nodeRecid = dir[slot/8][slot%8]>>>1;
while(nodeRecid!=0){
LinkedNode<K,V> n = engine.get(nodeRecid, LN_SERIALIZER);
final long nextRecid = n.next;
int pos = (hash(n.key) >>>(7*(level -1) )) & 0x7F;
if(nextDir[pos/8]==null) nextDir[pos/8] = new long[8];
n = new LinkedNode<K, V>(nextDir[pos/8][pos%8]>>>1, n.expireLinkNodeRecid, n.key, n.value);
nextDir[pos/8][pos%8] = (nodeRecid<<1) | 1;
engine.update(nodeRecid, n, LN_SERIALIZER);
nodeRecid = nextRecid;
}
//insert nextDir and update parent dir
long nextDirRecid = engine.put(nextDir, DIR_SERIALIZER);
int parentPos = (h>>>(7*level )) & 0x7F;
dir = Arrays.copyOf(dir,16);
dir[parentPos/8] = Arrays.copyOf(dir[parentPos/8],8);
dir[parentPos/8][parentPos%8] = (nextDirRecid<<1) | 0;
engine.update(dirRecid, dir, DIR_SERIALIZER);
notify(key, null, value);
return null;
}else{
// record does not exist in linked list, so create new one
recid = dir[slot/8][slot%8]>>>1;
final long expireNodeRecid = expireFlag? engine.put(null, ExpireLinkNode.SERIALIZER):0L;
final long newRecid = engine.put(new LinkedNode<K, V>(recid, expireNodeRecid, key, value), LN_SERIALIZER);
dir = Arrays.copyOf(dir,16);
dir[slot/8] = Arrays.copyOf(dir[slot/8],8);
dir[slot/8][slot%8] = (newRecid<<1) | 1;
engine.update(dirRecid, dir, DIR_SERIALIZER);
if(expireFlag) expireLinkAdd(segment,expireNodeRecid, newRecid,h);
notify(key, null, value);
return null;
}
}
}finally {
segmentLocks[segment].writeLock().unlock();
}
}
@Override
public V remove(Object key){
final int h = hash(key);
final int segment = h >>>28;
try{
segmentLocks[segment].writeLock().lock();
final long[] dirRecids = new long[4];
int level = 3;
dirRecids[level] = segmentRecids[segment];
while(true){
long[][] dir = engine.get(dirRecids[level], DIR_SERIALIZER);
final int slot = (h>>>(7*level )) & 0x7F;
if(slot>127) throw new InternalError();
if(dir == null ){
//create new dir
dir = new long[16][];
}
if(dir[slot/8] == null){
dir = Arrays.copyOf(dir,16);
dir[slot/8] = new long[8];
}
// int counter = 0;
long recid = dir[slot/8][slot%8];
if(recid!=0){
if((recid&1) == 0){
level--;
dirRecids[level] = recid>>>1;
continue;
}
recid = recid>>>1;
//traverse linked list, try to remove node
LinkedNode<K,V> ln = engine.get(recid, LN_SERIALIZER);
LinkedNode<K,V> prevLn = null;
long prevRecid = 0;
while(ln!=null){
if(ln.key.equals(key)){
//remove from linkedList
if(prevLn == null ){
//referenced directly from dir
if(ln.next==0){
recursiveDirDelete(h, level, dirRecids, dir, slot);
}else{
dir=Arrays.copyOf(dir,16);
dir[slot/8] = Arrays.copyOf(dir[slot/8],8);
dir[slot/8][slot%8] = (ln.next<<1)|1;
engine.update(dirRecids[level], dir, DIR_SERIALIZER);
}
}else{
//referenced from LinkedNode
prevLn = new LinkedNode<K, V>(ln.next, prevLn.expireLinkNodeRecid,prevLn.key, prevLn.value);
engine.update(prevRecid, prevLn, LN_SERIALIZER);
}
//found, remove this node
engine.delete(recid, LN_SERIALIZER);
if(expireFlag) expireLinkRemove(segment, ln.expireLinkNodeRecid);
notify((K) key, ln.value, null);
return ln.value;
}
prevRecid = recid;
prevLn = ln;
recid = ln.next;
ln = recid==0? null : engine.get(recid, LN_SERIALIZER);
// counter++;
}
//key was not found at linked list, so it does not exist
return null;
}
//recid is 0, so entry does not exist
return null;
}
}finally {
segmentLocks[segment].writeLock().unlock();
}
}
private void recursiveDirDelete(int h, int level, long[] dirRecids, long[][] dir, int slot) {
//TODO keep dir immutable while recursive delete
//was only item in linked list, so try to collapse the dir
dir=Arrays.copyOf(dir,16);
dir[slot/8] = Arrays.copyOf(dir[slot/8],8);
dir[slot/8][slot%8] = 0;
//one record was zeroed out, check if subarray can be collapsed to null
boolean allZero = true;
for(long l:dir[slot/8]){
if(l!=0){
allZero = false;
break;
}
}
if(allZero){
dir[slot/8] = null;
}
allZero = true;
for(long[] l:dir){
if(l!=null){
allZero = false;
break;
}
}
if(allZero){
//delete from parent dir
if(level==3){
//parent is segment, recid of this dir can not be modified, so just update to null
engine.update(dirRecids[level], new long[16][], DIR_SERIALIZER);
}else{
engine.delete(dirRecids[level], DIR_SERIALIZER);
final long[][] parentDir = engine.get(dirRecids[level + 1], DIR_SERIALIZER);
final int parentPos = (h >>> (7 * (level + 1))) & 0x7F;
recursiveDirDelete(h,level+1,dirRecids, parentDir, parentPos);
//parentDir[parentPos/8][parentPos%8] = 0;
//engine.update(dirRecids[level + 1],parentDir,DIR_SERIALIZER);
}
}else{
engine.update(dirRecids[level], dir, DIR_SERIALIZER);
}
}
@Override
public void clear() {
for(int i = 0; i<16;i++) try{
segmentLocks[i].writeLock().lock();
final long dirRecid = segmentRecids[i];
recursiveDirClear(dirRecid);
//set dir to null, as segment recid is immutable
engine.update(dirRecid, new long[16][], DIR_SERIALIZER);
if(expireFlag)
while(expireLinkRemoveLast(i)!=null){} //TODO speedup remove all
}finally {
segmentLocks[i].writeLock().unlock();
}
}
private void recursiveDirClear(final long dirRecid) {
final long[][] dir = engine.get(dirRecid, DIR_SERIALIZER);
if(dir == null) return;
for(long[] subdir:dir){
if(subdir==null) continue;
for(long recid:subdir){
if(recid == 0) continue;
if((recid&1)==0){
//another dir
recid = recid>>>1;
//recursively remove dir
recursiveDirClear(recid);
engine.delete(recid, DIR_SERIALIZER);
}else{
//linked list to delete
recid = recid>>>1;
while(recid!=0){
LinkedNode n = engine.get(recid, LN_SERIALIZER);
engine.delete(recid,LN_SERIALIZER);
notify((K)n.key, (V)n.value , null);
recid = n.next;
}
}
}
}
}
@Override
public boolean containsValue(Object value) {
for (V v : values()) {
if (v.equals(value)) return true;
}
return false;
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for(Entry<? extends K, ? extends V> e:m.entrySet()){
put(e.getKey(),e.getValue());
}
}
protected class KeySet extends AbstractSet<K> {
@Override
public int size() {
return HTreeMap.this.size();
}
@Override
public boolean isEmpty() {
return HTreeMap.this.isEmpty();
}
@Override
public boolean contains(Object o) {
return HTreeMap.this.containsKey(o);
}
@Override
public Iterator<K> iterator() {
return new KeyIterator();
}
@Override
public boolean add(K k) {
if(HTreeMap.this.hasValues)
throw new UnsupportedOperationException();
else
return HTreeMap.this.put(k, (V) Utils.EMPTY_STRING) == null;
}
@Override
public boolean remove(Object o) {
// if(o instanceof Entry){
// Entry e = (Entry) o;
// return HTreeMap.this.remove(((Entry) o).getKey(),((Entry) o).getValue());
// }
return HTreeMap.this.remove(o)!=null;
}
@Override
public void clear() {
HTreeMap.this.clear();
}
public HTreeMap<K,V> parent(){
return HTreeMap.this;
}
}
private final Set<K> _keySet = new KeySet();
@Override
public Set<K> keySet() {
return _keySet;
}
private final Collection<V> _values = new AbstractCollection<V>(){
@Override
public int size() {
return HTreeMap.this.size();
}
@Override
public boolean isEmpty() {
return HTreeMap.this.isEmpty();
}
@Override
public boolean contains(Object o) {
return HTreeMap.this.containsValue(o);
}
@Override
public Iterator<V> iterator() {
return new ValueIterator();
}
};
@Override
public Collection<V> values() {
return _values;
}
private Set<Entry<K,V>> _entrySet = new AbstractSet<Entry<K,V>>(){
@Override
public int size() {
return HTreeMap.this.size();
}
@Override
public boolean isEmpty() {
return HTreeMap.this.isEmpty();
}
@Override
public boolean contains(Object o) {
if(o instanceof Entry){
Entry e = (Entry) o;
Object val = HTreeMap.this.get(e.getKey());
return val!=null && val.equals(e.getValue());
}else
return false;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public boolean add(Entry<K, V> kvEntry) {
K key = kvEntry.getKey();
V value = kvEntry.getValue();
if(key==null || value == null) throw new NullPointerException();
HTreeMap.this.put(key, value);
return true;
}
@Override
public boolean remove(Object o) {
if(o instanceof Entry){
Entry e = (Entry) o;
Object key = e.getKey();
if(key == null) return false;
return HTreeMap.this.remove(key, e.getValue());
}
return false;
}
@Override
public void clear() {
HTreeMap.this.clear();
}
};
@Override
public Set<Entry<K, V>> entrySet() {
return _entrySet;
}
protected int hash(final Object key) {
int h = key.hashCode() ^ hashSalt;
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
abstract class HashIterator{
protected LinkedNode[] currentLinkedList;
protected int currentLinkedListPos = 0;
private K lastReturnedKey = null;
private int lastSegment = 0;
HashIterator(){
currentLinkedList = findNextLinkedNode(0);
}
public void remove() {
final K keyToRemove = lastReturnedKey;
if (lastReturnedKey == null)
throw new IllegalStateException();
lastReturnedKey = null;
HTreeMap.this.remove(keyToRemove);
}
public boolean hasNext(){
return currentLinkedList!=null && currentLinkedListPos<currentLinkedList.length;
}
protected void moveToNext(){
lastReturnedKey = (K) currentLinkedList[currentLinkedListPos].key;
if(expireAccessFlag){
int segment = hash(lastReturnedKey)>>>28;
expireLinkBump(segment, currentLinkedList[currentLinkedListPos].expireLinkNodeRecid,expireAccess);
}
currentLinkedListPos+=1;
if(currentLinkedListPos==currentLinkedList.length){
final int lastHash = hash(lastReturnedKey);
currentLinkedList = advance(lastHash);
currentLinkedListPos = 0;
}
}
private LinkedNode[] advance(int lastHash){
int segment = lastHash >>>28;
//two phases, first find old item and increase hash
try{
segmentLocks[segment].readLock().lock();
long dirRecid = segmentRecids[segment];
int level = 3;
//dive into tree, finding last hash position
while(true){
long[][] dir = engine.get(dirRecid, DIR_SERIALIZER);
int pos = (lastHash>>>(7 * level)) & 0x7F;
//check if we need to expand deeper
if(dir[pos/8]==null || dir[pos/8][pos%8]==0 || (dir[pos/8][pos%8]&1)==1) {
//increase hash by 1
if(level!=0){
lastHash = ((lastHash>>>(7 * level)) + 1) << (7*level); //should use mask and XOR
}else
lastHash +=1;
if(lastHash==0){
return null;
}
break;
}
//reference is dir, move to next level
dirRecid = dir[pos/8][pos%8]>>>1;
level--;
}
}finally {
segmentLocks[segment].readLock().unlock();
}
return findNextLinkedNode(lastHash);
}
private LinkedNode[] findNextLinkedNode(int hash) {
//second phase, start search from increased hash to find next items
for(int segment = Math.max(hash >>>28, lastSegment); segment<16;segment++)try{
lastSegment = Math.max(segment,lastSegment);
segmentLocks[segment].readLock().lock();
long dirRecid = segmentRecids[segment];
LinkedNode ret[] = findNextLinkedNodeRecur(dirRecid, hash, 3);
//System.out.println(Arrays.asList(ret));
if(ret !=null) return ret;
hash = 0;
}finally {
segmentLocks[segment].readLock().unlock();
}
return null;
}
private LinkedNode[] findNextLinkedNodeRecur(long dirRecid, int newHash, int level){
long[][] dir = engine.get(dirRecid, DIR_SERIALIZER);
if(dir == null) return null;
int pos = (newHash>>>(level*7)) & 0x7F;
boolean first = true;
while(pos<128){
if(dir[pos/8]!=null){
long recid = dir[pos/8][pos%8];
if(recid!=0){
if((recid&1) == 1){
recid = recid>>1;
//found linked list, load it into array and return
LinkedNode[] array = new LinkedNode[1];
int arrayPos = 0;
while(recid!=0){
LinkedNode ln = engine.get(recid, LN_SERIALIZER);
if(ln==null){
recid = 0;
continue;
}
//increase array size if needed
if(arrayPos == array.length)
array = Arrays.copyOf(array, array.length+1);
array[arrayPos++] = ln;
recid = ln.next;
}
return array;
}else{
//found another dir, continue dive
recid = recid>>1;
LinkedNode[] ret = findNextLinkedNodeRecur(recid, first ? newHash : 0, level - 1);
if(ret != null) return ret;
}
}
}
first = false;
pos++;
}
return null;
}
}
class KeyIterator extends HashIterator implements Iterator<K>{
@Override
public K next() {
if(currentLinkedList == null)
throw new NoSuchElementException();
K key = (K) currentLinkedList[currentLinkedListPos].key;
moveToNext();
return key;
}
}
class ValueIterator extends HashIterator implements Iterator<V>{
@Override
public V next() {
if(currentLinkedList == null)
throw new NoSuchElementException();
V value = (V) currentLinkedList[currentLinkedListPos].value;
moveToNext();
return value;
}
}
class EntryIterator extends HashIterator implements Iterator<Entry<K,V>>{
@Override
public Entry<K, V> next() {
if(currentLinkedList == null)
throw new NoSuchElementException();
K key = (K) currentLinkedList[currentLinkedListPos].key;
moveToNext();
return new Entry2(key);
}
}
class Entry2 implements Entry<K,V>{
private final K key;
Entry2(K key) {
this.key = key;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return HTreeMap.this.get(key);
}
@Override
public V setValue(V value) {
return HTreeMap.this.put(key,value);
}
@Override
public boolean equals(Object o) {
return (o instanceof Entry) && key.equals(((Entry) o).getKey());
}
@Override
public int hashCode() {
final V value = HTreeMap.this.get(key);
return (key == null ? 0 : key.hashCode()) ^
(value == null ? 0 : value.hashCode());
}
}
@Override
public V putIfAbsent(K key, V value) {
if(key==null||value==null) throw new NullPointerException();
Utils.checkMapValueIsNotCollecion(value);
final int segment = HTreeMap.this.hash(key) >>>28;
try{
segmentLocks[segment].writeLock().lock();
if (!containsKey(key))
return put(key, value);
else
return get(key);
}finally {
segmentLocks[segment].writeLock().unlock();
}
}
@Override
public boolean remove(Object key, Object value) {
if(key==null||value==null) throw new NullPointerException();
final int segment = HTreeMap.this.hash(key) >>>28;
try{
segmentLocks[segment].writeLock().lock();
if (containsKey(key) && get(key).equals(value)) {
remove(key);
return true;
}else
return false;
}finally {
segmentLocks[segment].writeLock().unlock();
}
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
if(key==null||oldValue==null||newValue==null) throw new NullPointerException();
final int segment = HTreeMap.this.hash(key) >>>28;
try{
segmentLocks[segment].writeLock().lock();
if (containsKey(key) && get(key).equals(oldValue)) {
put(key, newValue);
return true;
} else
return false;
}finally {
segmentLocks[segment].writeLock().unlock();
}
}
@Override
public V replace(K key, V value) {
if(key==null||value==null) throw new NullPointerException();
final int segment = HTreeMap.this.hash(key) >>>28;
try{
segmentLocks[segment].writeLock().lock();
if (containsKey(key))
return put(key, value);
else
return null;
}finally {
segmentLocks[segment].writeLock().unlock();
}
}
protected void expireLinkAdd(int segment, long expireNodeRecid, long keyRecid, int hash){
assert(segmentLocks[segment].writeLock().isHeldByCurrentThread());
long time = expire+System.currentTimeMillis()-expireTimeStart;
long head = engine.get(expireHeads[segment],Serializer.LONG_SERIALIZER);
if(head == 0){
//insert new
ExpireLinkNode n = new ExpireLinkNode(0,0,keyRecid,time,hash);
engine.update(expireNodeRecid, n, ExpireLinkNode.SERIALIZER);
engine.update(expireHeads[segment],expireNodeRecid,Serializer.LONG_SERIALIZER);
engine.update(expireTails[segment],expireNodeRecid,Serializer.LONG_SERIALIZER);
}else{
//insert new head
ExpireLinkNode n = new ExpireLinkNode(head,0,keyRecid,time,hash);
engine.update(expireNodeRecid, n, ExpireLinkNode.SERIALIZER);
//update old head to have new head as next
ExpireLinkNode oldHead = engine.get(head,ExpireLinkNode.SERIALIZER);
oldHead=oldHead.copyNext(expireNodeRecid);
engine.update(head,oldHead,ExpireLinkNode.SERIALIZER);
//and update head
engine.update(expireHeads[segment],expireNodeRecid,Serializer.LONG_SERIALIZER);
}
}
protected void expireLinkBump(int segment, long nodeRecid, long timeIncrement){
segmentLocks[segment].writeLock().lock();
try{
ExpireLinkNode n = engine.get(nodeRecid,ExpireLinkNode.SERIALIZER);
long newTime = timeIncrement+System.currentTimeMillis()-expireTimeStart;
//TODO optimize bellow, but what if there is only size limit?
//if(n.time>newTime) return; // older time greater than new one, do not update
if(n.next==0){
//already head, so just update time
n = n.copyTime(newTime);
engine.update(nodeRecid,n,ExpireLinkNode.SERIALIZER);
}else{
//update prev so it points to next
if(n.prev!=0){
//not a tail
ExpireLinkNode prev = engine.get(n.prev,ExpireLinkNode.SERIALIZER);
prev=prev.copyNext(n.next);
engine.update(n.prev, prev, ExpireLinkNode.SERIALIZER);
}else{
//yes tail, so just update it to point to next
engine.update(expireTails[segment],n.next,Serializer.LONG_SERIALIZER);
}
//update next so it points to prev
ExpireLinkNode next = engine.get(n.next, ExpireLinkNode.SERIALIZER);
next=next.copyPrev(n.prev);
engine.update(n.next,next,ExpireLinkNode.SERIALIZER);
//TODO optimize if oldHead==next
//now insert node as new head
long oldHeadRecid = engine.get(expireHeads[segment],Serializer.LONG_SERIALIZER);
ExpireLinkNode oldHead = engine.get(oldHeadRecid, ExpireLinkNode.SERIALIZER);
oldHead = oldHead.copyNext(nodeRecid);
engine.update(oldHeadRecid,oldHead,ExpireLinkNode.SERIALIZER);
engine.update(expireHeads[segment],nodeRecid,Serializer.LONG_SERIALIZER);
n = new ExpireLinkNode(oldHeadRecid,0, n.keyRecid, newTime, n.hash);
engine.update(nodeRecid,n,ExpireLinkNode.SERIALIZER);
}
}finally{
segmentLocks[segment].writeLock().unlock();
}
}
protected ExpireLinkNode expireLinkRemoveLast(int segment){
assert(segmentLocks[segment].writeLock().isHeldByCurrentThread());
long tail = engine.get(expireTails[segment],Serializer.LONG_SERIALIZER);
if(tail==0) return null;
ExpireLinkNode n = engine.get(tail,ExpireLinkNode.SERIALIZER);
if(n.next==0){
//update tail and head
engine.update(expireHeads[segment],0L,Serializer.LONG_SERIALIZER);
engine.update(expireTails[segment],0L,Serializer.LONG_SERIALIZER);
}else{
//point tail to next record
engine.update(expireTails[segment],n.next,Serializer.LONG_SERIALIZER);
//update next record to have zero prev
ExpireLinkNode next = engine.get(n.next,ExpireLinkNode.SERIALIZER);
next=next.copyPrev(0L);
engine.update(n.next, next, ExpireLinkNode.SERIALIZER);
}
engine.delete(tail,ExpireLinkNode.SERIALIZER);
return n;
}
protected ExpireLinkNode expireLinkRemove(int segment, long nodeRecid){
assert(segmentLocks[segment].writeLock().isHeldByCurrentThread());
ExpireLinkNode n = engine.get(nodeRecid,ExpireLinkNode.SERIALIZER);
engine.delete(nodeRecid,ExpireLinkNode.SERIALIZER);
if(n.next == 0 && n.prev==0){
engine.update(expireHeads[segment],0L,Serializer.LONG_SERIALIZER);
engine.update(expireTails[segment],0L,Serializer.LONG_SERIALIZER);
}else if (n.next == 0) {
ExpireLinkNode prev = engine.get(n.prev,ExpireLinkNode.SERIALIZER);
prev=prev.copyNext(0);
engine.update(n.prev,prev,ExpireLinkNode.SERIALIZER);
engine.update(expireHeads[segment],n.prev,Serializer.LONG_SERIALIZER);
}else if (n.prev == 0) {
ExpireLinkNode next = engine.get(n.next,ExpireLinkNode.SERIALIZER);
next=next.copyPrev(0);
engine.update(n.next,next,ExpireLinkNode.SERIALIZER);
engine.update(expireTails[segment],n.next,Serializer.LONG_SERIALIZER);
}else{
ExpireLinkNode next = engine.get(n.next,ExpireLinkNode.SERIALIZER);
next=next.copyPrev(n.prev);
engine.update(n.next,next,ExpireLinkNode.SERIALIZER);
ExpireLinkNode prev = engine.get(n.prev,ExpireLinkNode.SERIALIZER);
prev=prev.copyNext(n.next);
engine.update(n.prev,prev,ExpireLinkNode.SERIALIZER);
}
return n;
}
/**
* Make readonly snapshot view of current Map. Snapshot is immutable and not affected by modifications made by other threads.
* Useful if you need consistent view on Map.
* <p>
* Maintaining snapshot have some overhead, underlying Engine is closed after Map view is GCed.
* Please make sure to release reference to this Map view, so snapshot view can be garbage collected.
*
* @return snapshot
*/
public Map<K,V> snapshot(){
Engine snapshot = SnapshotEngine.createSnapshotFor(engine);
return new HTreeMap<K, V>(snapshot, counter==null?0:counter.recid,
hashSalt, segmentRecids, keySerializer, valueSerializer,0L,0L,0L,0L,null,null);
}
protected final Object modListenersLock = new Object();
protected Bind.MapListener<K,V>[] modListeners = new Bind.MapListener[0];
@Override
public void addModificationListener(Bind.MapListener<K,V> listener) {
synchronized (modListenersLock){
Bind.MapListener<K,V>[] modListeners2 =
Arrays.copyOf(modListeners,modListeners.length+1);
modListeners2[modListeners2.length-1] = listener;
modListeners = modListeners2;
}
}
@Override
public void removeModificationListener(Bind.MapListener<K,V> listener) {
synchronized (modListenersLock){
for(int i=0;i<modListeners.length;i++){
if(modListeners[i]==listener) modListeners[i]=null;
}
}
}
protected void notify(K key, V oldValue, V newValue) {
Bind.MapListener<K,V>[] modListeners2 = modListeners;
for(Bind.MapListener<K,V> listener:modListeners2){
if(listener!=null)
listener.update(key, oldValue, newValue);
}
}
/**
* Closes underlying storage and releases all resources.
* Used mostly with temporary collections where engine is not accessible.
*/
public void close(){
engine.close();
}
}
| true | true | public V put(final K key, final V value){
if (key == null)
throw new IllegalArgumentException("null key");
if (value == null)
throw new IllegalArgumentException("null value");
Utils.checkMapValueIsNotCollecion(value);
final int h = hash(key);
final int segment = h >>>28;
try{
segmentLocks[segment].writeLock().lock();
long dirRecid = segmentRecids[segment];
int level = 3;
while(true){
long[][] dir = engine.get(dirRecid, DIR_SERIALIZER);
final int slot = (h>>>(7*level )) & 0x7F;
if(slot>127) throw new InternalError();
if(dir == null ){
//create new dir
dir = new long[16][];
}
if(dir[slot/8] == null){
dir = Arrays.copyOf(dir,16);
dir[slot/8] = new long[8];
}
int counter = 0;
long recid = dir[slot/8][slot%8];
if(recid!=0){
if((recid&1) == 0){
dirRecid = recid>>>1;
level--;
continue;
}
recid = recid>>>1;
//traverse linked list, try to replace previous value
LinkedNode<K,V> ln = engine.get(recid, LN_SERIALIZER);
while(ln!=null){
if(ln.key.equals(key)){
//found, replace value at this node
V oldVal = ln.value;
ln = new LinkedNode<K, V>(ln.next, ln.expireLinkNodeRecid, ln.key, value);
engine.update(recid, ln, LN_SERIALIZER);
if(expireFlag) expireLinkBump(segment,ln.expireLinkNodeRecid,expire);
notify(key, oldVal, value);
return oldVal;
}
recid = ln.next;
ln = recid==0? null : engine.get(recid, LN_SERIALIZER);
counter++;
}
//key was not found at linked list, so just append it to beginning
}
//check if linked list has overflow and needs to be expanded to new dir level
if(counter>=BUCKET_OVERFLOW && level>=1){
long[][] nextDir = new long[16][];
{
final long expireNodeRecid = expireFlag? engine.put(null, ExpireLinkNode.SERIALIZER):0L;
final LinkedNode node = new LinkedNode<K, V>(0, expireNodeRecid, key, value);
final long newRecid = engine.put(node, LN_SERIALIZER);
//add newly inserted record
int pos =(h >>>(7*(level-1) )) & 0x7F;
nextDir[pos/8] = new long[8];
nextDir[pos/8][pos%8] = ( newRecid<<1) | 1;
if(expireFlag) expireLinkAdd(segment,expireNodeRecid,newRecid,h);
}
//redistribute linked bucket into new dir
long nodeRecid = dir[slot/8][slot%8]>>>1;
while(nodeRecid!=0){
LinkedNode<K,V> n = engine.get(nodeRecid, LN_SERIALIZER);
final long nextRecid = n.next;
int pos = (hash(n.key) >>>(7*(level -1) )) & 0x7F;
if(nextDir[pos/8]==null) nextDir[pos/8] = new long[8];
n = new LinkedNode<K, V>(nextDir[pos/8][pos%8]>>>1, n.expireLinkNodeRecid, n.key, n.value);
nextDir[pos/8][pos%8] = (nodeRecid<<1) | 1;
engine.update(nodeRecid, n, LN_SERIALIZER);
nodeRecid = nextRecid;
}
//insert nextDir and update parent dir
long nextDirRecid = engine.put(nextDir, DIR_SERIALIZER);
int parentPos = (h>>>(7*level )) & 0x7F;
dir = Arrays.copyOf(dir,16);
dir[parentPos/8] = Arrays.copyOf(dir[parentPos/8],8);
dir[parentPos/8][parentPos%8] = (nextDirRecid<<1) | 0;
engine.update(dirRecid, dir, DIR_SERIALIZER);
notify(key, null, value);
return null;
}else{
// record does not exist in linked list, so create new one
recid = dir[slot/8][slot%8]>>>1;
final long expireNodeRecid = expireFlag? engine.put(null, ExpireLinkNode.SERIALIZER):0L;
final long newRecid = engine.put(new LinkedNode<K, V>(recid, expireNodeRecid, key, value), LN_SERIALIZER);
dir = Arrays.copyOf(dir,16);
dir[slot/8] = Arrays.copyOf(dir[slot/8],8);
dir[slot/8][slot%8] = (newRecid<<1) | 1;
engine.update(dirRecid, dir, DIR_SERIALIZER);
if(expireFlag) expireLinkAdd(segment,expireNodeRecid, newRecid,h);
notify(key, null, value);
return null;
}
}
}finally {
segmentLocks[segment].writeLock().unlock();
}
}
| public V put(final K key, final V value){
if (key == null)
throw new IllegalArgumentException("null key");
if (value == null)
throw new IllegalArgumentException("null value");
Utils.checkMapValueIsNotCollecion(value);
final int h = hash(key);
final int segment = h >>>28;
try{
segmentLocks[segment].writeLock().lock();
long dirRecid = segmentRecids[segment];
int level = 3;
while(true){
long[][] dir = engine.get(dirRecid, DIR_SERIALIZER);
final int slot = (h>>>(7*level )) & 0x7F;
if(slot>127) throw new InternalError();
if(dir == null ){
//create new dir
dir = new long[16][];
}
if(dir[slot/8] == null){
dir = Arrays.copyOf(dir,16);
dir[slot/8] = new long[8];
}
int counter = 0;
long recid = dir[slot/8][slot%8];
if(recid!=0){
if((recid&1) == 0){
dirRecid = recid>>>1;
level--;
continue;
}
recid = recid>>>1;
//traverse linked list, try to replace previous value
LinkedNode<K,V> ln = engine.get(recid, LN_SERIALIZER);
while(ln!=null){
if(ln.key.equals(key)){
//found, replace value at this node
V oldVal = ln.value;
ln = new LinkedNode<K, V>(ln.next, ln.expireLinkNodeRecid, ln.key, value);
engine.update(recid, ln, LN_SERIALIZER);
if(expireFlag) expireLinkBump(segment,ln.expireLinkNodeRecid,expire);
notify(key, oldVal, value);
return oldVal;
}
recid = ln.next;
ln = recid==0? null : engine.get(recid, LN_SERIALIZER);
counter++;
}
//key was not found at linked list, so just append it to beginning
}
//check if linked list has overflow and needs to be expanded to new dir level
if(counter>=BUCKET_OVERFLOW && level>=1){
long[][] nextDir = new long[16][];
{
final long expireNodeRecid = expireFlag? engine.put(null, ExpireLinkNode.SERIALIZER):0L;
final LinkedNode<K,V> node = new LinkedNode<K, V>(0, expireNodeRecid, key, value);
final long newRecid = engine.put(node, LN_SERIALIZER);
//add newly inserted record
int pos =(h >>>(7*(level-1) )) & 0x7F;
nextDir[pos/8] = new long[8];
nextDir[pos/8][pos%8] = ( newRecid<<1) | 1;
if(expireFlag) expireLinkAdd(segment,expireNodeRecid,newRecid,h);
}
//redistribute linked bucket into new dir
long nodeRecid = dir[slot/8][slot%8]>>>1;
while(nodeRecid!=0){
LinkedNode<K,V> n = engine.get(nodeRecid, LN_SERIALIZER);
final long nextRecid = n.next;
int pos = (hash(n.key) >>>(7*(level -1) )) & 0x7F;
if(nextDir[pos/8]==null) nextDir[pos/8] = new long[8];
n = new LinkedNode<K, V>(nextDir[pos/8][pos%8]>>>1, n.expireLinkNodeRecid, n.key, n.value);
nextDir[pos/8][pos%8] = (nodeRecid<<1) | 1;
engine.update(nodeRecid, n, LN_SERIALIZER);
nodeRecid = nextRecid;
}
//insert nextDir and update parent dir
long nextDirRecid = engine.put(nextDir, DIR_SERIALIZER);
int parentPos = (h>>>(7*level )) & 0x7F;
dir = Arrays.copyOf(dir,16);
dir[parentPos/8] = Arrays.copyOf(dir[parentPos/8],8);
dir[parentPos/8][parentPos%8] = (nextDirRecid<<1) | 0;
engine.update(dirRecid, dir, DIR_SERIALIZER);
notify(key, null, value);
return null;
}else{
// record does not exist in linked list, so create new one
recid = dir[slot/8][slot%8]>>>1;
final long expireNodeRecid = expireFlag? engine.put(null, ExpireLinkNode.SERIALIZER):0L;
final long newRecid = engine.put(new LinkedNode<K, V>(recid, expireNodeRecid, key, value), LN_SERIALIZER);
dir = Arrays.copyOf(dir,16);
dir[slot/8] = Arrays.copyOf(dir[slot/8],8);
dir[slot/8][slot%8] = (newRecid<<1) | 1;
engine.update(dirRecid, dir, DIR_SERIALIZER);
if(expireFlag) expireLinkAdd(segment,expireNodeRecid, newRecid,h);
notify(key, null, value);
return null;
}
}
}finally {
segmentLocks[segment].writeLock().unlock();
}
}
|
diff --git a/src/powercrystals/minefactoryreloaded/decorative/BlockFactoryRoad.java b/src/powercrystals/minefactoryreloaded/decorative/BlockFactoryRoad.java
index 417595dc..6bdb988f 100644
--- a/src/powercrystals/minefactoryreloaded/decorative/BlockFactoryRoad.java
+++ b/src/powercrystals/minefactoryreloaded/decorative/BlockFactoryRoad.java
@@ -1,72 +1,80 @@
package powercrystals.minefactoryreloaded.decorative;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import powercrystals.core.util.Util;
import powercrystals.minefactoryreloaded.MineFactoryReloadedCore;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockFactoryRoad extends Block
{
public BlockFactoryRoad(int id)
{
super(id, Material.rock);
blockIndexInTexture = 12;
slipperiness = 0.98F;
setHardness(2.0F);
setBlockName("factoryRoadBlock");
setResistance(25.0F);
setStepSound(soundStoneFootstep);
}
@Override
public int getBlockTextureFromSideAndMetadata(int side, int meta)
{
if(meta == 0) return 12;
if(meta == 1 || meta == 3) return 13;
if(meta == 2 || meta == 4) return 14;
return 12;
}
public void onNeighborBlockChange(World world, int x, int y, int z, int neighborId)
{
if(!world.isRemote)
{
int meta = world.getBlockMetadata(x, y, z);
boolean isPowered = Util.isRedstonePowered(world, x, y, z);
- if((meta == 1 || meta == 3) && isPowered)
+ if(meta == 1 && isPowered)
{
- world.setBlockMetadataWithNotify(x, y, z, meta + 1);
+ world.setBlockMetadataWithNotify(x, y, z, 2);
}
- else if((meta == 2 || meta == 4) && !isPowered)
+ else if(meta == 2 && !isPowered)
{
- world.setBlockMetadataWithNotify(x, y, z, meta - 1);
+ world.setBlockMetadataWithNotify(x, y, z, 1);
+ }
+ else if(meta == 3 && !isPowered)
+ {
+ world.setBlockMetadataWithNotify(x, y, z, 4);
+ }
+ else if(meta == 4 && isPowered)
+ {
+ world.setBlockMetadataWithNotify(x, y, z, 3);
}
}
}
@Override
public int damageDropped(int meta)
{
if(meta == 1 || meta == 2) return 1;
if(meta == 3 || meta == 4) return 4;
return 0;
}
@Override
@SideOnly(Side.CLIENT)
public float getBlockBrightness(IBlockAccess world, int x, int y, int z)
{
int meta = world.getBlockMetadata(x, y, z);
return meta == 2 || meta == 4 ? 1 : 0;
}
@Override
public String getTextureFile()
{
return MineFactoryReloadedCore.terrainTexture;
}
}
| false | true | public void onNeighborBlockChange(World world, int x, int y, int z, int neighborId)
{
if(!world.isRemote)
{
int meta = world.getBlockMetadata(x, y, z);
boolean isPowered = Util.isRedstonePowered(world, x, y, z);
if((meta == 1 || meta == 3) && isPowered)
{
world.setBlockMetadataWithNotify(x, y, z, meta + 1);
}
else if((meta == 2 || meta == 4) && !isPowered)
{
world.setBlockMetadataWithNotify(x, y, z, meta - 1);
}
}
}
| public void onNeighborBlockChange(World world, int x, int y, int z, int neighborId)
{
if(!world.isRemote)
{
int meta = world.getBlockMetadata(x, y, z);
boolean isPowered = Util.isRedstonePowered(world, x, y, z);
if(meta == 1 && isPowered)
{
world.setBlockMetadataWithNotify(x, y, z, 2);
}
else if(meta == 2 && !isPowered)
{
world.setBlockMetadataWithNotify(x, y, z, 1);
}
else if(meta == 3 && !isPowered)
{
world.setBlockMetadataWithNotify(x, y, z, 4);
}
else if(meta == 4 && isPowered)
{
world.setBlockMetadataWithNotify(x, y, z, 3);
}
}
}
|
diff --git a/core/src/main/java/hudson/lifecycle/WindowsSlaveInstaller.java b/core/src/main/java/hudson/lifecycle/WindowsSlaveInstaller.java
index d05ab8469..480a92700 100644
--- a/core/src/main/java/hudson/lifecycle/WindowsSlaveInstaller.java
+++ b/core/src/main/java/hudson/lifecycle/WindowsSlaveInstaller.java
@@ -1,177 +1,183 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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 hudson.lifecycle;
import hudson.FilePath;
import hudson.Launcher.LocalLauncher;
import hudson.remoting.Callable;
import hudson.remoting.Engine;
import hudson.remoting.jnlp.MainDialog;
import hudson.remoting.jnlp.MainMenu;
import hudson.util.StreamTaskListener;
import hudson.util.jna.DotNet;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
/**
* @author Kohsuke Kawaguchi
*/
public class WindowsSlaveInstaller implements Callable<Void,RuntimeException>, ActionListener {
/**
* Root directory of this slave.
* String, not File because the platform can be different.
*/
private final String rootDir;
private transient Engine engine;
private transient MainDialog dialog;
public WindowsSlaveInstaller(String rootDir) {
this.rootDir = rootDir;
}
public Void call() {
if(File.separatorChar=='/') return null; // not Windows
if(System.getProperty("hudson.showWindowsServiceInstallLink")==null)
return null; // only show this when it makes sense, which is when we run from JNLP
dialog = MainDialog.get();
if(dialog==null) return null; // can't find the main window. Maybe not running with GUI
// capture the engine
engine = Engine.current();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainMenu mainMenu = dialog.getMainMenu();
JMenu m = mainMenu.getFileMenu();
JMenuItem menu = new JMenuItem(Messages.WindowsInstallerLink_DisplayName(), KeyEvent.VK_W);
menu.addActionListener(WindowsSlaveInstaller.this);
m.add(menu);
mainMenu.commit();
}
});
return null;
}
/**
* Called when the install menu is selected
*/
public void actionPerformed(ActionEvent e) {
int r = JOptionPane.showConfirmDialog(dialog,
"This will install a slave agent as a Windows service,\n" +
"so that this slave will connect to Hudson as soon as the machine boots.\n" +
"Do you want to proceed with installation?",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.OK_CANCEL_OPTION);
if(r!=JOptionPane.OK_OPTION) return;
if(!DotNet.isInstalled(2,0)) {
JOptionPane.showMessageDialog(dialog,".NET Framework 2.0 or later is required for this feature",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.ERROR_MESSAGE);
return;
}
final File dir = new File(rootDir);
+ if (!dir.exists()) {
+ JOptionPane.showMessageDialog(dialog,"Slave root directory '"+rootDir+"' doesn't exist",
+ Messages.WindowsInstallerLink_DisplayName(),
+ JOptionPane.ERROR_MESSAGE);
+ return;
+ }
try {
final File slaveExe = new File(dir, "hudson-slave.exe");
FileUtils.copyURLToFile(getClass().getResource("/windows-service/hudson.exe"), slaveExe);
// write out the descriptor
URL jnlp = new URL(engine.getHudsonUrl(),"computer/"+engine.slaveName+"/slave-agent.jnlp");
String xml = generateSlaveXml(System.getProperty("java.home")+"\\bin\\java.exe", "-jnlpUrl "+jnlp.toExternalForm());
FileUtils.writeStringToFile(new File(dir, "hudson-slave.xml"),xml,"UTF-8");
// copy slave.jar
URL slaveJar = new URL(engine.getHudsonUrl(),"jnlpJars/remoting.jar");
File dstSlaveJar = new File(dir,"slave.jar").getCanonicalFile();
if(!dstSlaveJar.exists()) // perhaps slave.jar is already there?
FileUtils.copyURLToFile(slaveJar,dstSlaveJar);
// install as a service
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamTaskListener task = new StreamTaskListener(baos);
r = new LocalLauncher(task).launch().cmds(slaveExe, "install").stdout(task).pwd(dir).join();
if(r!=0) {
JOptionPane.showMessageDialog(
dialog,baos.toString(),"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
r = JOptionPane.showConfirmDialog(dialog,
"Installation was successful. Would you like to\n" +
"Stop this slave agent and start the newly installed service?",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.OK_CANCEL_OPTION);
if(r!=JOptionPane.OK_OPTION) return;
// let the service start after we close our connection, to avoid conflicts
Runtime.getRuntime().addShutdownHook(new Thread("service starter") {
public void run() {
try {
StreamTaskListener task = new StreamTaskListener(System.out);
int r = new LocalLauncher(task).launch().cmds(slaveExe, "start").stdout(task).pwd(dir).join();
task.getLogger().println(r==0?"Successfully started":"start service failed. Exit code="+r);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.exit(0);
} catch (Exception t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
JOptionPane.showMessageDialog(
dialog,sw.toString(),"Error",
JOptionPane.ERROR_MESSAGE);
}
}
public static String generateSlaveXml(String java, String args) throws IOException {
String xml = IOUtils.toString(WindowsSlaveInstaller.class.getResourceAsStream("/windows-service/hudson-slave.xml"), "UTF-8");
xml = xml.replace("@JAVA@", java);
xml = xml.replace("@ARGS@", args);
return xml;
}
private static final long serialVersionUID = 1L;
}
| true | true | public void actionPerformed(ActionEvent e) {
int r = JOptionPane.showConfirmDialog(dialog,
"This will install a slave agent as a Windows service,\n" +
"so that this slave will connect to Hudson as soon as the machine boots.\n" +
"Do you want to proceed with installation?",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.OK_CANCEL_OPTION);
if(r!=JOptionPane.OK_OPTION) return;
if(!DotNet.isInstalled(2,0)) {
JOptionPane.showMessageDialog(dialog,".NET Framework 2.0 or later is required for this feature",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.ERROR_MESSAGE);
return;
}
final File dir = new File(rootDir);
try {
final File slaveExe = new File(dir, "hudson-slave.exe");
FileUtils.copyURLToFile(getClass().getResource("/windows-service/hudson.exe"), slaveExe);
// write out the descriptor
URL jnlp = new URL(engine.getHudsonUrl(),"computer/"+engine.slaveName+"/slave-agent.jnlp");
String xml = generateSlaveXml(System.getProperty("java.home")+"\\bin\\java.exe", "-jnlpUrl "+jnlp.toExternalForm());
FileUtils.writeStringToFile(new File(dir, "hudson-slave.xml"),xml,"UTF-8");
// copy slave.jar
URL slaveJar = new URL(engine.getHudsonUrl(),"jnlpJars/remoting.jar");
File dstSlaveJar = new File(dir,"slave.jar").getCanonicalFile();
if(!dstSlaveJar.exists()) // perhaps slave.jar is already there?
FileUtils.copyURLToFile(slaveJar,dstSlaveJar);
// install as a service
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamTaskListener task = new StreamTaskListener(baos);
r = new LocalLauncher(task).launch().cmds(slaveExe, "install").stdout(task).pwd(dir).join();
if(r!=0) {
JOptionPane.showMessageDialog(
dialog,baos.toString(),"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
r = JOptionPane.showConfirmDialog(dialog,
"Installation was successful. Would you like to\n" +
"Stop this slave agent and start the newly installed service?",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.OK_CANCEL_OPTION);
if(r!=JOptionPane.OK_OPTION) return;
// let the service start after we close our connection, to avoid conflicts
Runtime.getRuntime().addShutdownHook(new Thread("service starter") {
public void run() {
try {
StreamTaskListener task = new StreamTaskListener(System.out);
int r = new LocalLauncher(task).launch().cmds(slaveExe, "start").stdout(task).pwd(dir).join();
task.getLogger().println(r==0?"Successfully started":"start service failed. Exit code="+r);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.exit(0);
} catch (Exception t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
JOptionPane.showMessageDialog(
dialog,sw.toString(),"Error",
JOptionPane.ERROR_MESSAGE);
}
}
| public void actionPerformed(ActionEvent e) {
int r = JOptionPane.showConfirmDialog(dialog,
"This will install a slave agent as a Windows service,\n" +
"so that this slave will connect to Hudson as soon as the machine boots.\n" +
"Do you want to proceed with installation?",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.OK_CANCEL_OPTION);
if(r!=JOptionPane.OK_OPTION) return;
if(!DotNet.isInstalled(2,0)) {
JOptionPane.showMessageDialog(dialog,".NET Framework 2.0 or later is required for this feature",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.ERROR_MESSAGE);
return;
}
final File dir = new File(rootDir);
if (!dir.exists()) {
JOptionPane.showMessageDialog(dialog,"Slave root directory '"+rootDir+"' doesn't exist",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.ERROR_MESSAGE);
return;
}
try {
final File slaveExe = new File(dir, "hudson-slave.exe");
FileUtils.copyURLToFile(getClass().getResource("/windows-service/hudson.exe"), slaveExe);
// write out the descriptor
URL jnlp = new URL(engine.getHudsonUrl(),"computer/"+engine.slaveName+"/slave-agent.jnlp");
String xml = generateSlaveXml(System.getProperty("java.home")+"\\bin\\java.exe", "-jnlpUrl "+jnlp.toExternalForm());
FileUtils.writeStringToFile(new File(dir, "hudson-slave.xml"),xml,"UTF-8");
// copy slave.jar
URL slaveJar = new URL(engine.getHudsonUrl(),"jnlpJars/remoting.jar");
File dstSlaveJar = new File(dir,"slave.jar").getCanonicalFile();
if(!dstSlaveJar.exists()) // perhaps slave.jar is already there?
FileUtils.copyURLToFile(slaveJar,dstSlaveJar);
// install as a service
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamTaskListener task = new StreamTaskListener(baos);
r = new LocalLauncher(task).launch().cmds(slaveExe, "install").stdout(task).pwd(dir).join();
if(r!=0) {
JOptionPane.showMessageDialog(
dialog,baos.toString(),"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
r = JOptionPane.showConfirmDialog(dialog,
"Installation was successful. Would you like to\n" +
"Stop this slave agent and start the newly installed service?",
Messages.WindowsInstallerLink_DisplayName(),
JOptionPane.OK_CANCEL_OPTION);
if(r!=JOptionPane.OK_OPTION) return;
// let the service start after we close our connection, to avoid conflicts
Runtime.getRuntime().addShutdownHook(new Thread("service starter") {
public void run() {
try {
StreamTaskListener task = new StreamTaskListener(System.out);
int r = new LocalLauncher(task).launch().cmds(slaveExe, "start").stdout(task).pwd(dir).join();
task.getLogger().println(r==0?"Successfully started":"start service failed. Exit code="+r);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.exit(0);
} catch (Exception t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
JOptionPane.showMessageDialog(
dialog,sw.toString(),"Error",
JOptionPane.ERROR_MESSAGE);
}
}
|
diff --git a/src/lorian/graph/GraphMain.java b/src/lorian/graph/GraphMain.java
index 6c097c9..01e02a3 100644
--- a/src/lorian/graph/GraphMain.java
+++ b/src/lorian/graph/GraphMain.java
@@ -1,158 +1,158 @@
package lorian.graph;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import lorian.graph.fileio.GraphFileWriter;
import lorian.graph.function.Function;
import lorian.graph.function.Function2Var;
import lorian.graph.function.ParameterFunction;
import org.eclipse.jdt.internal.jarinjarloader.*;
import org.eclipse.swt.widgets.Display;
public class GraphMain {
private static String sSwtVersion = "4.3";
public static void main(String[] args) throws Throwable {
System.out.println("Graph v" + GraphFunctionsFrame.version);
boolean use_swing = false;
boolean load_libs = true;
- String foreLangName = null;
+ String forceLangName = null;
for(int i = 0; i < args.length; i++)
{
String arg = args[i];
if(arg.equalsIgnoreCase("-swt"))
{
use_swing = false;
}
else if(arg.equalsIgnoreCase("-swing"))
{
use_swing = true;
}
else if(arg.equalsIgnoreCase("-language"))
{
if(i+1 < args.length)
{
- foreLangName = args[++i];
+ forceLangName = args[++i];
}
}
else if(arg.equalsIgnoreCase("-no-libs"))
{
load_libs = false;
}
}
if(load_libs)
{
try {
ClassLoader cl = getClassloader();
Thread.currentThread().setContextClassLoader(cl);
} catch (JarinJarLoadFailed ex) {
String reason = ex.getMessage();
System.err.println("Launch failed: " + reason);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JOptionPane.showMessageDialog(null, "Launch failed: " + reason, "Launching UI Failed", JOptionPane.ERROR_MESSAGE);
return;
}
}
else
{
System.out.println("Warning: Not loading any libraries.");
}
if(use_swing)
GraphFunctionsFrame.funcframe = new GraphFunctionsFrame(false, false, false);
else
{
- new GraphSwtFrame(new Display(), foreLangName);
+ new GraphSwtFrame(new Display(), forceLangName);
}
}
private static ClassLoader getClassloader() throws GraphMain.JarinJarLoadFailed {
String swtFileName = getSwtJarName();
String gluegenFileName = getGluegenJarName();
String joglFileName = getJoglJarName();
try {
//URL[] allNativeJarsUrl = new URL[] { new URL("rsrc:" + swtFileName), new URL("rsrc:" + gluegenFileName), new URL("rsrc:" + joglFileName) };
URLClassLoader cl = (URLClassLoader) GraphMain.class.getClassLoader();
URL.setURLStreamHandlerFactory(new RsrcURLStreamHandlerFactory(cl));
Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
addUrlMethod.setAccessible(true);
URL swtFileUrl = new URL("rsrc:" + swtFileName);
URL gluegenFileUrl = new URL("rsrc:" + gluegenFileName);
URL joglFileUrl = new URL("rsrc:" + joglFileName);
URL gluegenRtFileUrl = new URL("rsrc:gluegen-rt.jar");
URL joglAllFileUrl = new URL("rsrc:jogl-all.jar");
addUrlMethod.invoke(cl, new Object[] { swtFileUrl });
addUrlMethod.invoke(cl, new Object[] { gluegenRtFileUrl });
addUrlMethod.invoke(cl, new Object[] { joglAllFileUrl });
addUrlMethod.invoke(cl, new Object[] { gluegenFileUrl });
addUrlMethod.invoke(cl, new Object[] { joglFileUrl });
return cl;
} catch (Exception exx) {
throw new JarinJarLoadFailed(exx.getClass().getSimpleName() + ": " + exx.getMessage());
}
}
private static String getSwtJarName() throws GraphMain.JarinJarLoadFailed {
String osName = System.getProperty("os.name").toLowerCase();
String swtFileNameOsPart = (osName.contains("linux")) || (osName.contains("nix")) ? "linux" : osName.contains("mac") ? "osx" : osName.contains("win") ? "win" : "";
if ("".equals(swtFileNameOsPart)) {
throw new JarinJarLoadFailed("Unknown OS name: " + osName);
}
String swtFileNameArchPart = System.getProperty("os.arch").toLowerCase().contains("64") ? "64" : "32";
String swtFileName = "swt-" + swtFileNameOsPart + swtFileNameArchPart + "-" + sSwtVersion + ".jar";
System.out.printf("Loading %s...\n", swtFileName);
return swtFileName;
}
private static String getGluegenJarName() throws GraphMain.JarinJarLoadFailed {
String osName = System.getProperty("os.name").toLowerCase();
String gluegenFileNameOsPart = (osName.contains("linux")) || (osName.contains("nix")) ? "linux" : osName.contains("mac") ? "macosx" : osName.contains("win") ? "windows" : "";
if ("".equals(gluegenFileNameOsPart)) {
throw new JarinJarLoadFailed("Unknown OS name: " + osName);
}
String gluegenFileNameArchPart = System.getProperty("os.arch").toLowerCase().contains("64") ? "amd64" : "i586";
String gluegenFileName = "gluegen-rt-natives-" + gluegenFileNameOsPart + "-" + gluegenFileNameArchPart + ".jar";
System.out.printf("Loading %s...\n", gluegenFileName);
return gluegenFileName;
}
private static String getJoglJarName() throws GraphMain.JarinJarLoadFailed {
String osName = System.getProperty("os.name").toLowerCase();
String joglFileNameOsPart = (osName.contains("linux")) || (osName.contains("nix")) ? "linux" : osName.contains("mac") ? "macosx" : osName.contains("win") ? "windows" : "";
if ("".equals(joglFileNameOsPart)) {
throw new JarinJarLoadFailed("Unknown OS name: " + osName);
}
String joglFileNameArchPart = System.getProperty("os.arch").toLowerCase().contains("64") ? "amd64" : "i586";
String joglFileName = "jogl-all-natives-" + joglFileNameOsPart + "-" + joglFileNameArchPart + ".jar";
System.out.printf("Loading %s...\n", joglFileName);
return joglFileName;
}
private static class JarinJarLoadFailed extends Exception {
private static final long serialVersionUID = 1L;
private JarinJarLoadFailed(String message) {
super(message);
}
}
}
| false | true | public static void main(String[] args) throws Throwable {
System.out.println("Graph v" + GraphFunctionsFrame.version);
boolean use_swing = false;
boolean load_libs = true;
String foreLangName = null;
for(int i = 0; i < args.length; i++)
{
String arg = args[i];
if(arg.equalsIgnoreCase("-swt"))
{
use_swing = false;
}
else if(arg.equalsIgnoreCase("-swing"))
{
use_swing = true;
}
else if(arg.equalsIgnoreCase("-language"))
{
if(i+1 < args.length)
{
foreLangName = args[++i];
}
}
else if(arg.equalsIgnoreCase("-no-libs"))
{
load_libs = false;
}
}
if(load_libs)
{
try {
ClassLoader cl = getClassloader();
Thread.currentThread().setContextClassLoader(cl);
} catch (JarinJarLoadFailed ex) {
String reason = ex.getMessage();
System.err.println("Launch failed: " + reason);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JOptionPane.showMessageDialog(null, "Launch failed: " + reason, "Launching UI Failed", JOptionPane.ERROR_MESSAGE);
return;
}
}
else
{
System.out.println("Warning: Not loading any libraries.");
}
if(use_swing)
GraphFunctionsFrame.funcframe = new GraphFunctionsFrame(false, false, false);
else
{
new GraphSwtFrame(new Display(), foreLangName);
}
}
| public static void main(String[] args) throws Throwable {
System.out.println("Graph v" + GraphFunctionsFrame.version);
boolean use_swing = false;
boolean load_libs = true;
String forceLangName = null;
for(int i = 0; i < args.length; i++)
{
String arg = args[i];
if(arg.equalsIgnoreCase("-swt"))
{
use_swing = false;
}
else if(arg.equalsIgnoreCase("-swing"))
{
use_swing = true;
}
else if(arg.equalsIgnoreCase("-language"))
{
if(i+1 < args.length)
{
forceLangName = args[++i];
}
}
else if(arg.equalsIgnoreCase("-no-libs"))
{
load_libs = false;
}
}
if(load_libs)
{
try {
ClassLoader cl = getClassloader();
Thread.currentThread().setContextClassLoader(cl);
} catch (JarinJarLoadFailed ex) {
String reason = ex.getMessage();
System.err.println("Launch failed: " + reason);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JOptionPane.showMessageDialog(null, "Launch failed: " + reason, "Launching UI Failed", JOptionPane.ERROR_MESSAGE);
return;
}
}
else
{
System.out.println("Warning: Not loading any libraries.");
}
if(use_swing)
GraphFunctionsFrame.funcframe = new GraphFunctionsFrame(false, false, false);
else
{
new GraphSwtFrame(new Display(), forceLangName);
}
}
|
diff --git a/src/org/antlr/codegen/RubyTarget.java b/src/org/antlr/codegen/RubyTarget.java
index d40a74b..bc08e11 100644
--- a/src/org/antlr/codegen/RubyTarget.java
+++ b/src/org/antlr/codegen/RubyTarget.java
@@ -1,73 +1,73 @@
/*
[The "BSD licence"]
Copyright (c) 2005 Martin Traverso
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.codegen;
public class RubyTarget
extends Target
{
public String getTargetCharLiteralFromANTLRCharLiteral(
CodeGenerator generator,
String literal)
{
literal = literal.substring(1, literal.length() - 1);
- String result = "?";
+ String result = "";
if (literal.equals("\\")) {
result += "\\\\";
}
else if (literal.equals(" ")) {
result += "\\s";
}
else if (literal.startsWith("\\u")) {
result = "0x" + literal.substring(2);
}
else {
result += literal;
}
return result;
}
public int getMaxCharValue(CodeGenerator generator)
{
// we don't support unicode, yet.
return 0xFF;
}
public String getTokenTypeAsTargetLabel(CodeGenerator generator, int ttype)
{
String name = generator.grammar.getTokenDisplayName(ttype);
// If name is a literal, return the token type instead
if ( name.charAt(0)=='\'' ) {
return generator.grammar.computeTokenNameFromLiteral(ttype, name);
}
return name;
}
}
| true | true | public String getTargetCharLiteralFromANTLRCharLiteral(
CodeGenerator generator,
String literal)
{
literal = literal.substring(1, literal.length() - 1);
String result = "?";
if (literal.equals("\\")) {
result += "\\\\";
}
else if (literal.equals(" ")) {
result += "\\s";
}
else if (literal.startsWith("\\u")) {
result = "0x" + literal.substring(2);
}
else {
result += literal;
}
return result;
}
| public String getTargetCharLiteralFromANTLRCharLiteral(
CodeGenerator generator,
String literal)
{
literal = literal.substring(1, literal.length() - 1);
String result = "";
if (literal.equals("\\")) {
result += "\\\\";
}
else if (literal.equals(" ")) {
result += "\\s";
}
else if (literal.startsWith("\\u")) {
result = "0x" + literal.substring(2);
}
else {
result += literal;
}
return result;
}
|
diff --git a/src/main/java/de/markiewb/netbeans/plugin/git/openinexternalviewer/OpenAction.java b/src/main/java/de/markiewb/netbeans/plugin/git/openinexternalviewer/OpenAction.java
index c5b151c..1c0a80e 100644
--- a/src/main/java/de/markiewb/netbeans/plugin/git/openinexternalviewer/OpenAction.java
+++ b/src/main/java/de/markiewb/netbeans/plugin/git/openinexternalviewer/OpenAction.java
@@ -1,130 +1,137 @@
/**
* Copyright 2013 markiewb
*
* 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 de.markiewb.netbeans.plugin.git.openinexternalviewer;
import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Collection;
import javax.swing.AbstractAction;
import javax.swing.Action;
import static javax.swing.Action.NAME;
import org.netbeans.api.project.Project;
import org.netbeans.libs.git.GitBranch;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.awt.DynamicMenuContent;
import org.openide.awt.HtmlBrowser;
import org.openide.filesystems.FileObject;
import org.openide.util.ContextAwareAction;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
@ActionID(category = "Git", id = "de.markiewb.netbeans.plugin.git.openinexternalviewer.OpenAction")
@ActionRegistration(lazy = false, displayName = "openinexternalviewer.OpenAction")
@ActionReferences({
@ActionReference(path = "Projects/Actions", position = 500)
})
public final class OpenAction extends AbstractAction implements ContextAwareAction {
@Override
public void actionPerformed(ActionEvent e) {
}
@Override
public Action createContextAwareInstance(Lookup lkp) {
return new ContextAction(lkp);
}
static class ContextAction extends AbstractAction {
private String url = null;
private ContextAction(Lookup lkp) {
putValue(NAME, null);
putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true);
init(lkp);
}
private RepoStrategy getStrategy(String remote) {
Collection<? extends RepoStrategy> strategies = Lookup.getDefault().lookupAll(RepoStrategy.class);
RepoStrategy usedStrategy = null;
for (RepoStrategy strategy : strategies) {
boolean supported = strategy.supports(remote);
if (supported) {
usedStrategy = strategy;
break;
}
}
return usedStrategy;
}
@Override
public void actionPerformed(ActionEvent e) {
if (null != url) {
try {
HtmlBrowser.URLDisplayer.getDefault().showURLExternal(new URL(url));
} catch (MalformedURLException ex) {
Exceptions.printStackTrace(ex);
}
}
}
private void init(Lookup lkp) {
setEnabled(false);
//only support one project selected project
Collection<? extends Project> lookupAll = lkp.lookupAll(Project.class);
if (lookupAll != null && lookupAll.size() >= 2) {
return;
}
Project project = lkp.lookup(Project.class);
FileObject gitRepoDirectory = GitUtils.getGitRepoDirectory(project.getProjectDirectory());
if (gitRepoDirectory == null) {
return;
}
GitBranch activeBranch = GitUtils.getActiveBranch(gitRepoDirectory);
if (activeBranch == null) {
return;
}
if (activeBranch.getTrackedBranch() == null) {
//TODO support detached heads
//TODO support tags
return;
} else {
final String remoteBranchName = activeBranch.getTrackedBranch().getName();
//split "origin/master" to "origin" "master"
- String[] split = remoteBranchName.split("/");
- if (2 == split.length) {
- final String origin = split[0];
- final String remoteName = split[1];
+ //split "orgin/feature/myfeature" to "origin" "feature/myfeature"
+ int indexOf = remoteBranchName.indexOf("/");
+ if (indexOf<=0 || remoteBranchName.startsWith("/") || remoteBranchName.endsWith("/")){
+ // no slash found OR
+ // slash is the first char? NOGO
+ //slash at the end? NOGO
+ return;
+ }
+ {
+ final String origin = remoteBranchName.substring(0, indexOf);
+ final String remoteName = remoteBranchName.substring(indexOf + 1);
final String remote = GitUtils.getRemote(gitRepoDirectory, origin);
final RepoStrategy strategy = getStrategy(remote);
if (strategy != null) {
putValue(NAME, MessageFormat.format("Open ''{0}'' at ''{1}''", remoteBranchName, strategy.getLabel()));
url = strategy.getUrl(remote, remoteName, activeBranch.getId());
setEnabled(null != url);
}
}
}
}
}
}
| true | true | private void init(Lookup lkp) {
setEnabled(false);
//only support one project selected project
Collection<? extends Project> lookupAll = lkp.lookupAll(Project.class);
if (lookupAll != null && lookupAll.size() >= 2) {
return;
}
Project project = lkp.lookup(Project.class);
FileObject gitRepoDirectory = GitUtils.getGitRepoDirectory(project.getProjectDirectory());
if (gitRepoDirectory == null) {
return;
}
GitBranch activeBranch = GitUtils.getActiveBranch(gitRepoDirectory);
if (activeBranch == null) {
return;
}
if (activeBranch.getTrackedBranch() == null) {
//TODO support detached heads
//TODO support tags
return;
} else {
final String remoteBranchName = activeBranch.getTrackedBranch().getName();
//split "origin/master" to "origin" "master"
String[] split = remoteBranchName.split("/");
if (2 == split.length) {
final String origin = split[0];
final String remoteName = split[1];
final String remote = GitUtils.getRemote(gitRepoDirectory, origin);
final RepoStrategy strategy = getStrategy(remote);
if (strategy != null) {
putValue(NAME, MessageFormat.format("Open ''{0}'' at ''{1}''", remoteBranchName, strategy.getLabel()));
url = strategy.getUrl(remote, remoteName, activeBranch.getId());
setEnabled(null != url);
}
}
}
}
| private void init(Lookup lkp) {
setEnabled(false);
//only support one project selected project
Collection<? extends Project> lookupAll = lkp.lookupAll(Project.class);
if (lookupAll != null && lookupAll.size() >= 2) {
return;
}
Project project = lkp.lookup(Project.class);
FileObject gitRepoDirectory = GitUtils.getGitRepoDirectory(project.getProjectDirectory());
if (gitRepoDirectory == null) {
return;
}
GitBranch activeBranch = GitUtils.getActiveBranch(gitRepoDirectory);
if (activeBranch == null) {
return;
}
if (activeBranch.getTrackedBranch() == null) {
//TODO support detached heads
//TODO support tags
return;
} else {
final String remoteBranchName = activeBranch.getTrackedBranch().getName();
//split "origin/master" to "origin" "master"
//split "orgin/feature/myfeature" to "origin" "feature/myfeature"
int indexOf = remoteBranchName.indexOf("/");
if (indexOf<=0 || remoteBranchName.startsWith("/") || remoteBranchName.endsWith("/")){
// no slash found OR
// slash is the first char? NOGO
//slash at the end? NOGO
return;
}
{
final String origin = remoteBranchName.substring(0, indexOf);
final String remoteName = remoteBranchName.substring(indexOf + 1);
final String remote = GitUtils.getRemote(gitRepoDirectory, origin);
final RepoStrategy strategy = getStrategy(remote);
if (strategy != null) {
putValue(NAME, MessageFormat.format("Open ''{0}'' at ''{1}''", remoteBranchName, strategy.getLabel()));
url = strategy.getUrl(remote, remoteName, activeBranch.getId());
setEnabled(null != url);
}
}
}
}
|
diff --git a/src/com/android/launcher2/AppsCustomizePagedView.java b/src/com/android/launcher2/AppsCustomizePagedView.java
index 3f8360f1..55e66896 100644
--- a/src/com/android/launcher2/AppsCustomizePagedView.java
+++ b/src/com/android/launcher2/AppsCustomizePagedView.java
@@ -1,1706 +1,1707 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.launcher.R;
import com.android.launcher2.DropTarget.DragObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* A simple callback interface which also provides the results of the task.
*/
interface AsyncTaskCallback {
void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
}
/**
* The data needed to perform either of the custom AsyncTasks.
*/
class AsyncTaskPageData {
enum Type {
LoadWidgetPreviewData
}
AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, AsyncTaskCallback bgR,
AsyncTaskCallback postR, WidgetPreviewLoader w) {
page = p;
items = l;
generatedImages = new ArrayList<Bitmap>();
maxImageWidth = cw;
maxImageHeight = ch;
doInBackgroundCallback = bgR;
postExecuteCallback = postR;
widgetPreviewLoader = w;
}
void cleanup(boolean cancelled) {
// Clean up any references to source/generated bitmaps
if (generatedImages != null) {
if (cancelled) {
for (int i = 0; i < generatedImages.size(); i++) {
widgetPreviewLoader.releaseBitmap(items.get(i), generatedImages.get(i));
}
}
generatedImages.clear();
}
}
int page;
ArrayList<Object> items;
ArrayList<Bitmap> sourceImages;
ArrayList<Bitmap> generatedImages;
int maxImageWidth;
int maxImageHeight;
AsyncTaskCallback doInBackgroundCallback;
AsyncTaskCallback postExecuteCallback;
WidgetPreviewLoader widgetPreviewLoader;
}
/**
* A generic template for an async task used in AppsCustomize.
*/
class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) {
page = p;
threadPriority = Process.THREAD_PRIORITY_DEFAULT;
dataType = ty;
}
@Override
protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
if (params.length != 1) return null;
// Load each of the widget previews in the background
params[0].doInBackgroundCallback.run(this, params[0]);
return params[0];
}
@Override
protected void onPostExecute(AsyncTaskPageData result) {
// All the widget previews are loaded, so we can just callback to inflate the page
result.postExecuteCallback.run(this, result);
}
void setThreadPriority(int p) {
threadPriority = p;
}
void syncThreadPriority() {
Process.setThreadPriority(threadPriority);
}
// The page that this async task is associated with
AsyncTaskPageData.Type dataType;
int page;
int threadPriority;
}
/**
* The Apps/Customize page that displays all the applications, widgets, and shortcuts.
*/
public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
View.OnClickListener, View.OnKeyListener, DragSource,
PagedViewIcon.PressedCallback, PagedViewWidget.ShortPressListener,
LauncherTransitionable {
static final String TAG = "AppsCustomizePagedView";
/**
* The different content types that this paged view can show.
*/
public enum ContentType {
Applications,
Widgets
}
// Refs
private Launcher mLauncher;
private DragController mDragController;
private final LayoutInflater mLayoutInflater;
private final PackageManager mPackageManager;
// Save and Restore
private int mSaveInstanceStateItemIndex = -1;
private PagedViewIcon mPressedIcon;
// Content
private ArrayList<ApplicationInfo> mApps;
private ArrayList<Object> mWidgets;
// Cling
private boolean mHasShownAllAppsCling;
private int mClingFocusedX;
private int mClingFocusedY;
// Caching
private Canvas mCanvas;
private IconCache mIconCache;
// Dimens
private int mContentWidth;
private int mMaxAppCellCountX, mMaxAppCellCountY;
private int mWidgetCountX, mWidgetCountY;
private int mWidgetWidthGap, mWidgetHeightGap;
private PagedViewCellLayout mWidgetSpacingLayout;
private int mNumAppsPages;
private int mNumWidgetPages;
// Relating to the scroll and overscroll effects
Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f);
private static float CAMERA_DISTANCE = 6500;
private static float TRANSITION_SCALE_FACTOR = 0.74f;
private static float TRANSITION_PIVOT = 0.65f;
private static float TRANSITION_MAX_ROTATION = 22;
private static final boolean PERFORM_OVERSCROLL_ROTATION = true;
private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f);
private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4);
// Previews & outlines
ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
private static final int sPageSleepDelay = 200;
private Runnable mInflateWidgetRunnable = null;
private Runnable mBindWidgetRunnable = null;
static final int WIDGET_NO_CLEANUP_REQUIRED = -1;
static final int WIDGET_PRELOAD_PENDING = 0;
static final int WIDGET_BOUND = 1;
static final int WIDGET_INFLATED = 2;
int mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
int mWidgetLoadingId = -1;
PendingAddWidgetInfo mCreateWidgetInfo = null;
private boolean mDraggingWidget = false;
private Toast mWidgetInstructionToast;
// Deferral of loading widget previews during launcher transitions
private boolean mInTransition;
private ArrayList<AsyncTaskPageData> mDeferredSyncWidgetPageItems =
new ArrayList<AsyncTaskPageData>();
private ArrayList<Runnable> mDeferredPrepareLoadWidgetPreviewsTasks =
new ArrayList<Runnable>();
private Rect mTmpRect = new Rect();
// Used for drawing shortcut previews
BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
PaintCache mCachedShortcutPreviewPaint = new PaintCache();
CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
// Used for drawing widget previews
CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
WidgetPreviewLoader mWidgetPreviewLoader;
public AppsCustomizePagedView(Context context, AttributeSet attrs) {
super(context, attrs);
mLayoutInflater = LayoutInflater.from(context);
mPackageManager = context.getPackageManager();
mApps = new ArrayList<ApplicationInfo>();
mWidgets = new ArrayList<Object>();
mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
mCanvas = new Canvas();
mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>();
// Save the default widget preview background
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0);
mMaxAppCellCountX = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountX, -1);
mMaxAppCellCountY = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountY, -1);
mWidgetWidthGap =
a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0);
mWidgetHeightGap =
a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0);
mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2);
mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0);
mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0);
a.recycle();
mWidgetSpacingLayout = new PagedViewCellLayout(getContext());
// The padding on the non-matched dimension for the default widget preview icons
// (top + bottom)
mFadeInAdjacentScreens = false;
// Unless otherwise specified this view is important for accessibility.
if (getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
}
@Override
protected void init() {
super.init();
mCenterPagesVertically = false;
Context context = getContext();
Resources r = context.getResources();
setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f);
}
/** Returns the item index of the center item on this page so that we can restore to this
* item index when we rotate. */
private int getMiddleComponentIndexOnCurrentPage() {
int i = -1;
if (getPageCount() > 0) {
int currentPage = getCurrentPage();
if (currentPage < mNumAppsPages) {
PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage);
PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout();
int numItemsPerPage = mCellCountX * mCellCountY;
int childCount = childrenLayout.getChildCount();
if (childCount > 0) {
i = (currentPage * numItemsPerPage) + (childCount / 2);
}
} else {
int numApps = mApps.size();
PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage);
int numItemsPerPage = mWidgetCountX * mWidgetCountY;
int childCount = layout.getChildCount();
if (childCount > 0) {
i = numApps +
((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2);
}
}
}
return i;
}
/** Get the index of the item to restore to if we need to restore the current page. */
int getSaveInstanceStateIndex() {
if (mSaveInstanceStateItemIndex == -1) {
mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage();
}
return mSaveInstanceStateItemIndex;
}
/** Returns the page in the current orientation which is expected to contain the specified
* item index. */
int getPageForComponent(int index) {
if (index < 0) return 0;
if (index < mApps.size()) {
int numItemsPerPage = mCellCountX * mCellCountY;
return (index / numItemsPerPage);
} else {
int numItemsPerPage = mWidgetCountX * mWidgetCountY;
return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage);
}
}
/** Restores the page for an item at the specified index */
void restorePageForIndex(int index) {
if (index < 0) return;
mSaveInstanceStateItemIndex = index;
}
private void updatePageCounts() {
mNumWidgetPages = (int) Math.ceil(mWidgets.size() /
(float) (mWidgetCountX * mWidgetCountY));
mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
}
protected void onDataReady(int width, int height) {
if (mWidgetPreviewLoader == null) {
mWidgetPreviewLoader = new WidgetPreviewLoader(mLauncher);
}
// Note that we transpose the counts in portrait so that we get a similar layout
boolean isLandscape = getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE;
int maxCellCountX = Integer.MAX_VALUE;
int maxCellCountY = Integer.MAX_VALUE;
if (LauncherApplication.isScreenLarge()) {
maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() :
LauncherModel.getCellCountY());
maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() :
LauncherModel.getCellCountX());
}
if (mMaxAppCellCountX > -1) {
maxCellCountX = Math.min(maxCellCountX, mMaxAppCellCountX);
}
// Temp hack for now: only use the max cell count Y for widget layout
int maxWidgetCellCountY = maxCellCountY;
if (mMaxAppCellCountY > -1) {
maxWidgetCellCountY = Math.min(maxWidgetCellCountY, mMaxAppCellCountY);
}
// Now that the data is ready, we can calculate the content width, the number of cells to
// use for each page
mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY);
mCellCountX = mWidgetSpacingLayout.getCellCountX();
mCellCountY = mWidgetSpacingLayout.getCellCountY();
updatePageCounts();
// Force a measure to update recalculate the gaps
int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxWidgetCellCountY);
mWidgetSpacingLayout.measure(widthSpec, heightSpec);
mContentWidth = mWidgetSpacingLayout.getContentWidth();
AppsCustomizeTabHost host = (AppsCustomizeTabHost) getTabHost();
final boolean hostIsTransitioning = host.isTransitioning();
// Restore the page
int page = getPageForComponent(mSaveInstanceStateItemIndex);
invalidatePageData(Math.max(0, page), hostIsTransitioning);
// Show All Apps cling if we are finished transitioning, otherwise, we will try again when
// the transition completes in AppsCustomizeTabHost (otherwise the wrong offsets will be
// returned while animating)
if (!hostIsTransitioning) {
post(new Runnable() {
@Override
public void run() {
showAllAppsCling();
}
});
}
}
void showAllAppsCling() {
if (!mHasShownAllAppsCling && isDataReady()) {
mHasShownAllAppsCling = true;
// Calculate the position for the cling punch through
int[] offset = new int[2];
int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY);
mLauncher.getDragLayer().getLocationInDragLayer(this, offset);
// PagedViews are centered horizontally but top aligned
// Note we have to shift the items up now that Launcher sits under the status bar
pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 +
offset[0];
pos[1] += offset[1] - mLauncher.getDragLayer().getPaddingTop();
mLauncher.showFirstRunAllAppsCling(pos);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (!isDataReady()) {
if (!mApps.isEmpty() && !mWidgets.isEmpty()) {
setDataIsReady();
setMeasuredDimension(width, height);
onDataReady(width, height);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void onPackagesUpdated() {
// Get the list of widgets and shortcuts
mWidgets.clear();
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
for (AppWidgetProviderInfo widget : widgets) {
if (widget.minWidth > 0 && widget.minHeight > 0) {
// Ensure that all widgets we show can be added on a workspace of this size
int[] spanXY = Launcher.getSpanForWidget(mLauncher, widget);
int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, widget);
int minSpanX = Math.min(spanXY[0], minSpanXY[0]);
int minSpanY = Math.min(spanXY[1], minSpanXY[1]);
if (minSpanX <= LauncherModel.getCellCountX() &&
minSpanY <= LauncherModel.getCellCountY()) {
mWidgets.add(widget);
} else {
Log.e(TAG, "Widget " + widget.provider + " can not fit on this device (" +
widget.minWidth + ", " + widget.minHeight + ")");
}
} else {
Log.e(TAG, "Widget " + widget.provider + " has invalid dimensions (" +
widget.minWidth + ", " + widget.minHeight + ")");
}
}
mWidgets.addAll(shortcuts);
Collections.sort(mWidgets,
new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
updatePageCounts();
invalidateOnDataChange();
}
@Override
public void onClick(View v) {
// When we have exited all apps or are in transition, disregard clicks
if (!mLauncher.isAllAppsVisible() ||
mLauncher.getWorkspace().isSwitchingState()) return;
if (v instanceof PagedViewIcon) {
// Animate some feedback to the click
final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
// Lock the drawable state to pressed until we return to Launcher
if (mPressedIcon != null) {
mPressedIcon.lockDrawableState();
}
// NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
// to be consistent. So re-enable the flag here, and we will re-disable it as necessary
// when Launcher resumes and we are still in AllApps.
mLauncher.updateWallpaperVisibility(true);
mLauncher.startActivitySafely(v, appInfo.intent, appInfo);
} else if (v instanceof PagedViewWidget) {
// Let the user know that they have to long press to add a widget
if (mWidgetInstructionToast != null) {
mWidgetInstructionToast.cancel();
}
mWidgetInstructionToast = Toast.makeText(getContext(),R.string.long_press_widget_to_add,
Toast.LENGTH_SHORT);
mWidgetInstructionToast.show();
// Create a little animation to show that the widget can move
float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
AnimatorSet bounce = LauncherAnimUtils.createAnimatorSet();
ValueAnimator tyuAnim = LauncherAnimUtils.ofFloat(p, "translationY", offsetY);
tyuAnim.setDuration(125);
ValueAnimator tydAnim = LauncherAnimUtils.ofFloat(p, "translationY", 0f);
tydAnim.setDuration(100);
bounce.play(tyuAnim).before(tydAnim);
bounce.setInterpolator(new AccelerateInterpolator());
bounce.start();
}
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
return FocusHelper.handleAppsCustomizeKeyEvent(v, keyCode, event);
}
/*
* PagedViewWithDraggableItems implementation
*/
@Override
protected void determineDraggingStart(android.view.MotionEvent ev) {
// Disable dragging by pulling an app down for now.
}
private void beginDraggingApplication(View v) {
mLauncher.getWorkspace().onDragStartedWithItem(v);
mLauncher.getWorkspace().beginDragShared(v, this);
}
Bundle getDefaultOptionsForWidget(Launcher launcher, PendingAddWidgetInfo info) {
Bundle options = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
AppWidgetResizeFrame.getWidgetSizeRanges(mLauncher, info.spanX, info.spanY, mTmpRect);
Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(mLauncher,
info.componentName, null);
float density = getResources().getDisplayMetrics().density;
int xPaddingDips = (int) ((padding.left + padding.right) / density);
int yPaddingDips = (int) ((padding.top + padding.bottom) / density);
options = new Bundle();
options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH,
mTmpRect.left - xPaddingDips);
options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT,
mTmpRect.top - yPaddingDips);
options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH,
mTmpRect.right - xPaddingDips);
options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT,
mTmpRect.bottom - yPaddingDips);
}
return options;
}
private void preloadWidget(final PendingAddWidgetInfo info) {
final AppWidgetProviderInfo pInfo = info.info;
final Bundle options = getDefaultOptionsForWidget(mLauncher, info);
if (pInfo.configure != null) {
info.bindOptions = options;
return;
}
mWidgetCleanupState = WIDGET_PRELOAD_PENDING;
mBindWidgetRunnable = new Runnable() {
@Override
public void run() {
mWidgetLoadingId = mLauncher.getAppWidgetHost().allocateAppWidgetId();
// Options will be null for platforms with JB or lower, so this serves as an
// SDK level check.
if (options == null) {
if (AppWidgetManager.getInstance(mLauncher).bindAppWidgetIdIfAllowed(
mWidgetLoadingId, info.componentName)) {
mWidgetCleanupState = WIDGET_BOUND;
}
} else {
if (AppWidgetManager.getInstance(mLauncher).bindAppWidgetIdIfAllowed(
mWidgetLoadingId, info.componentName, options)) {
mWidgetCleanupState = WIDGET_BOUND;
}
}
}
};
post(mBindWidgetRunnable);
mInflateWidgetRunnable = new Runnable() {
@Override
public void run() {
if (mWidgetCleanupState != WIDGET_BOUND) {
return;
}
AppWidgetHostView hostView = mLauncher.
getAppWidgetHost().createView(getContext(), mWidgetLoadingId, pInfo);
info.boundWidget = hostView;
mWidgetCleanupState = WIDGET_INFLATED;
hostView.setVisibility(INVISIBLE);
int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(info.spanX,
info.spanY, info, false);
// We want the first widget layout to be the correct size. This will be important
// for width size reporting to the AppWidgetManager.
DragLayer.LayoutParams lp = new DragLayer.LayoutParams(unScaledSize[0],
unScaledSize[1]);
lp.x = lp.y = 0;
lp.customPosition = true;
hostView.setLayoutParams(lp);
mLauncher.getDragLayer().addView(hostView);
}
};
post(mInflateWidgetRunnable);
}
@Override
public void onShortPress(View v) {
// We are anticipating a long press, and we use this time to load bind and instantiate
// the widget. This will need to be cleaned up if it turns out no long press occurs.
if (mCreateWidgetInfo != null) {
// Just in case the cleanup process wasn't properly executed. This shouldn't happen.
cleanupWidgetPreloading(false);
}
mCreateWidgetInfo = new PendingAddWidgetInfo((PendingAddWidgetInfo) v.getTag());
preloadWidget(mCreateWidgetInfo);
}
private void cleanupWidgetPreloading(boolean widgetWasAdded) {
if (!widgetWasAdded) {
// If the widget was not added, we may need to do further cleanup.
PendingAddWidgetInfo info = mCreateWidgetInfo;
mCreateWidgetInfo = null;
if (mWidgetCleanupState == WIDGET_PRELOAD_PENDING) {
// We never did any preloading, so just remove pending callbacks to do so
removeCallbacks(mBindWidgetRunnable);
removeCallbacks(mInflateWidgetRunnable);
} else if (mWidgetCleanupState == WIDGET_BOUND) {
// Delete the widget id which was allocated
if (mWidgetLoadingId != -1) {
mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
}
// We never got around to inflating the widget, so remove the callback to do so.
removeCallbacks(mInflateWidgetRunnable);
} else if (mWidgetCleanupState == WIDGET_INFLATED) {
// Delete the widget id which was allocated
if (mWidgetLoadingId != -1) {
mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
}
// The widget was inflated and added to the DragLayer -- remove it.
AppWidgetHostView widget = info.boundWidget;
mLauncher.getDragLayer().removeView(widget);
}
}
mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
mWidgetLoadingId = -1;
mCreateWidgetInfo = null;
PagedViewWidget.resetShortPressTarget();
}
@Override
public void cleanUpShortPress(View v) {
if (!mDraggingWidget) {
cleanupWidgetPreloading(false);
}
}
private boolean beginDraggingWidget(View v) {
mDraggingWidget = true;
// Get the widget preview as the drag representation
ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
// If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
// we abort the drag.
if (image.getDrawable() == null) {
mDraggingWidget = false;
return false;
}
// Compose the drag image
Bitmap preview;
Bitmap outline;
float scale = 1f;
Point previewPadding = null;
if (createItemInfo instanceof PendingAddWidgetInfo) {
// This can happen in some weird cases involving multi-touch. We can't start dragging
// the widget if this is null, so we break out.
if (mCreateWidgetInfo == null) {
return false;
}
PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
createItemInfo = createWidgetInfo;
int spanX = createItemInfo.spanX;
int spanY = createItemInfo.spanY;
int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY,
createWidgetInfo, true);
FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable();
float minScale = 1.25f;
int maxWidth, maxHeight;
maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]);
maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]);
int[] previewSizeBeforeScale = new int[1];
preview = mWidgetPreviewLoader.generateWidgetPreview(createWidgetInfo.componentName,
createWidgetInfo.previewImage, createWidgetInfo.icon, spanX, spanY,
maxWidth, maxHeight, null, previewSizeBeforeScale);
// Compare the size of the drag preview to the preview in the AppsCustomize tray
int previewWidthInAppsCustomize = Math.min(previewSizeBeforeScale[0],
mWidgetPreviewLoader.maxWidthForWidgetPreview(spanX));
scale = previewWidthInAppsCustomize / (float) preview.getWidth();
// The bitmap in the AppsCustomize tray is always the the same size, so there
// might be extra pixels around the preview itself - this accounts for that
if (previewWidthInAppsCustomize < previewDrawable.getIntrinsicWidth()) {
int padding =
(previewDrawable.getIntrinsicWidth() - previewWidthInAppsCustomize) / 2;
previewPadding = new Point(padding, 0);
}
} else {
PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag();
Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo);
preview = Bitmap.createBitmap(icon.getIntrinsicWidth(),
icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
mCanvas.setBitmap(preview);
mCanvas.save();
WidgetPreviewLoader.renderDrawableToBitmap(icon, preview, 0, 0,
icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
mCanvas.restore();
mCanvas.setBitmap(null);
createItemInfo.spanX = createItemInfo.spanY = 1;
}
// Don't clip alpha values for the drag outline if we're using the default widget preview
boolean clipAlpha = !(createItemInfo instanceof PendingAddWidgetInfo &&
(((PendingAddWidgetInfo) createItemInfo).previewImage == 0));
// Save the preview for the outline generation, then dim the preview
outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(),
false);
// Start the drag
mLauncher.lockScreenOrientation();
mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, clipAlpha);
mDragController.startDrag(image, preview, this, createItemInfo,
DragController.DRAG_ACTION_COPY, previewPadding, scale);
outline.recycle();
preview.recycle();
return true;
}
@Override
protected boolean beginDragging(final View v) {
if (!super.beginDragging(v)) return false;
if (v instanceof PagedViewIcon) {
beginDraggingApplication(v);
} else if (v instanceof PagedViewWidget) {
if (!beginDraggingWidget(v)) {
return false;
}
}
// We delay entering spring-loaded mode slightly to make sure the UI
// thready is free of any work.
postDelayed(new Runnable() {
@Override
public void run() {
// We don't enter spring-loaded mode if the drag has been cancelled
if (mLauncher.getDragController().isDragging()) {
// Dismiss the cling
mLauncher.dismissAllAppsCling(null);
// Reset the alpha on the dragged icon before we drag
resetDrawableState();
// Go into spring loaded mode (must happen before we startDrag())
mLauncher.enterSpringLoadedDragMode();
}
}
}, 150);
return true;
}
/**
* Clean up after dragging.
*
* @param target where the item was dragged to (can be null if the item was flung)
*/
private void endDragging(View target, boolean isFlingToDelete, boolean success) {
if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() &&
!(target instanceof DeleteDropTarget))) {
// Exit spring loaded mode if we have not successfully dropped or have not handled the
// drop in Workspace
mLauncher.exitSpringLoadedDragMode();
}
mLauncher.unlockScreenOrientation(false);
}
@Override
public View getContent() {
return null;
}
@Override
public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
mInTransition = true;
if (toWorkspace) {
cancelAllTasks();
}
}
@Override
public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
}
@Override
public void onLauncherTransitionStep(Launcher l, float t) {
}
@Override
public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
mInTransition = false;
for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) {
onSyncWidgetPageItems(d);
}
mDeferredSyncWidgetPageItems.clear();
for (Runnable r : mDeferredPrepareLoadWidgetPreviewsTasks) {
r.run();
}
mDeferredPrepareLoadWidgetPreviewsTasks.clear();
mForceDrawAllChildrenNextFrame = !toWorkspace;
}
@Override
public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
boolean success) {
// Return early and wait for onFlingToDeleteCompleted if this was the result of a fling
if (isFlingToDelete) return;
endDragging(target, false, success);
// Display an error message if the drag failed due to there not being enough space on the
// target layout we were dropping on.
if (!success) {
boolean showOutOfSpaceMessage = false;
if (target instanceof Workspace) {
int currentScreen = mLauncher.getCurrentWorkspaceScreen();
Workspace workspace = (Workspace) target;
CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
ItemInfo itemInfo = (ItemInfo) d.dragInfo;
if (layout != null) {
layout.calculateSpans(itemInfo);
showOutOfSpaceMessage =
!layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
}
}
if (showOutOfSpaceMessage) {
mLauncher.showOutOfSpaceMessage(false);
}
d.deferDragViewCleanupPostAnimation = false;
}
cleanupWidgetPreloading(success);
mDraggingWidget = false;
}
@Override
public void onFlingToDeleteCompleted() {
// We just dismiss the drag when we fling, so cleanup here
endDragging(null, true, true);
cleanupWidgetPreloading(false);
mDraggingWidget = false;
}
@Override
public boolean supportsFlingToDelete() {
return true;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
cancelAllTasks();
}
public void clearAllWidgetPages() {
cancelAllTasks();
int count = getChildCount();
for (int i = 0; i < count; i++) {
View v = getPageAt(i);
if (v instanceof PagedViewGridLayout) {
((PagedViewGridLayout) v).removeAllViewsOnPage();
mDirtyPageContent.set(i, true);
}
}
}
private void cancelAllTasks() {
// Clean up all the async tasks
Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
while (iter.hasNext()) {
AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
task.cancel(false);
iter.remove();
mDirtyPageContent.set(task.page, true);
// We've already preallocated the views for the data to load into, so clear them as well
View v = getPageAt(task.page);
if (v instanceof PagedViewGridLayout) {
((PagedViewGridLayout) v).removeAllViewsOnPage();
}
}
mDeferredSyncWidgetPageItems.clear();
mDeferredPrepareLoadWidgetPreviewsTasks.clear();
}
public void setContentType(ContentType type) {
if (type == ContentType.Widgets) {
invalidatePageData(mNumAppsPages, true);
} else if (type == ContentType.Applications) {
invalidatePageData(0, true);
}
}
protected void snapToPage(int whichPage, int delta, int duration) {
super.snapToPage(whichPage, delta, duration);
updateCurrentTab(whichPage);
// Update the thread priorities given the direction lookahead
Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
while (iter.hasNext()) {
AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
int pageIndex = task.page;
if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) ||
(mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) {
task.setThreadPriority(getThreadPriorityForPage(pageIndex));
} else {
task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
}
}
}
private void updateCurrentTab(int currentPage) {
AppsCustomizeTabHost tabHost = getTabHost();
if (tabHost != null) {
String tag = tabHost.getCurrentTabTag();
if (tag != null) {
if (currentPage >= mNumAppsPages &&
!tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) {
tabHost.setCurrentTabFromContent(ContentType.Widgets);
} else if (currentPage < mNumAppsPages &&
!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
tabHost.setCurrentTabFromContent(ContentType.Applications);
}
}
}
}
/*
* Apps PagedView implementation
*/
private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
int childCount = layout.getChildCount();
for (int i = 0; i < childCount; ++i) {
layout.getChildAt(i).setVisibility(visibility);
}
}
private void setupPage(PagedViewCellLayout layout) {
layout.setCellCount(mCellCountX, mCellCountY);
layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
// Note: We force a measure here to get around the fact that when we do layout calculations
// immediately after syncing, we don't have a proper width. That said, we already know the
// expected page width, so we can actually optimize by hiding all the TextView-based
// children that are expensive to measure, and let that happen naturally later.
setVisibilityOnChildren(layout, View.GONE);
int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
layout.setMinimumWidth(getPageContentWidth());
layout.measure(widthSpec, heightSpec);
setVisibilityOnChildren(layout, View.VISIBLE);
}
public void syncAppsPageItems(int page, boolean immediate) {
// ensure that we have the right number of items on the pages
int numCells = mCellCountX * mCellCountY;
int startIndex = page * numCells;
int endIndex = Math.min(startIndex + numCells, mApps.size());
PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page);
layout.removeAllViewsOnPage();
ArrayList<Object> items = new ArrayList<Object>();
ArrayList<Bitmap> images = new ArrayList<Bitmap>();
for (int i = startIndex; i < endIndex; ++i) {
ApplicationInfo info = mApps.get(i);
PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
R.layout.apps_customize_application, layout, false);
icon.applyFromApplicationInfo(info, true, this);
icon.setOnClickListener(this);
icon.setOnLongClickListener(this);
icon.setOnTouchListener(this);
icon.setOnKeyListener(this);
int index = i - startIndex;
int x = index % mCellCountX;
int y = index / mCellCountX;
layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
items.add(info);
images.add(info.iconBitmap);
}
enableHwLayersOnVisiblePages();
}
/**
* A helper to return the priority for loading of the specified widget page.
*/
private int getWidgetPageLoadPriority(int page) {
// If we are snapping to another page, use that index as the target page index
int toPage = mCurrentPage;
if (mNextPage > -1) {
toPage = mNextPage;
}
// We use the distance from the target page as an initial guess of priority, but if there
// are no pages of higher priority than the page specified, then bump up the priority of
// the specified page.
Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
int minPageDiff = Integer.MAX_VALUE;
while (iter.hasNext()) {
AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
minPageDiff = Math.abs(task.page - toPage);
}
int rawPageDiff = Math.abs(page - toPage);
return rawPageDiff - Math.min(rawPageDiff, minPageDiff);
}
/**
* Return the appropriate thread priority for loading for a given page (we give the current
* page much higher priority)
*/
private int getThreadPriorityForPage(int page) {
// TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
int pageDiff = getWidgetPageLoadPriority(page);
if (pageDiff <= 0) {
return Process.THREAD_PRIORITY_LESS_FAVORABLE;
} else if (pageDiff <= 1) {
return Process.THREAD_PRIORITY_LOWEST;
} else {
return Process.THREAD_PRIORITY_LOWEST;
}
}
private int getSleepForPage(int page) {
int pageDiff = getWidgetPageLoadPriority(page);
return Math.max(0, pageDiff * sPageSleepDelay);
}
/**
* Creates and executes a new AsyncTask to load a page of widget previews.
*/
private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
int cellWidth, int cellHeight, int cellCountX) {
// Prune all tasks that are no longer needed
Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
while (iter.hasNext()) {
AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
int taskPage = task.page;
if (taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
task.cancel(false);
iter.remove();
} else {
task.setThreadPriority(getThreadPriorityForPage(taskPage));
}
}
// We introduce a slight delay to order the loading of side pages so that we don't thrash
final int sleepMs = getSleepForPage(page);
AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
new AsyncTaskCallback() {
@Override
public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
try {
try {
Thread.sleep(sleepMs);
} catch (Exception e) {}
loadWidgetPreviewsInBackground(task, data);
} finally {
if (task.isCancelled()) {
data.cleanup(true);
}
}
}
},
new AsyncTaskCallback() {
@Override
public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
mRunningTasks.remove(task);
if (task.isCancelled()) return;
// do cleanup inside onSyncWidgetPageItems
onSyncWidgetPageItems(data);
}
}, mWidgetPreviewLoader);
// Ensure that the task is appropriately prioritized and runs in parallel
AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page,
AsyncTaskPageData.Type.LoadWidgetPreviewData);
t.setThreadPriority(getThreadPriorityForPage(page));
t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
mRunningTasks.add(t);
}
/*
* Widgets PagedView implementation
*/
private void setupPage(PagedViewGridLayout layout) {
layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
// Note: We force a measure here to get around the fact that when we do layout calculations
// immediately after syncing, we don't have a proper width.
int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
layout.setMinimumWidth(getPageContentWidth());
layout.measure(widthSpec, heightSpec);
}
public void syncWidgetPageItems(final int page, final boolean immediate) {
int numItemsPerPage = mWidgetCountX * mWidgetCountY;
// Calculate the dimensions of each cell we are giving to each widget
final ArrayList<Object> items = new ArrayList<Object>();
int contentWidth = mWidgetSpacingLayout.getContentWidth();
final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
- ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
int contentHeight = mWidgetSpacingLayout.getContentHeight();
final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
- ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
// Prepare the set of widgets to load previews for in the background
int offset = (page - mNumAppsPages) * numItemsPerPage;
for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
items.add(mWidgets.get(i));
}
// Prepopulate the pages with the other widget info, and fill in the previews later
final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
layout.setColumnCount(layout.getCellCountX());
for (int i = 0; i < items.size(); ++i) {
Object rawInfo = items.get(i);
PendingAddItemInfo createItemInfo = null;
PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
R.layout.apps_customize_widget, layout, false);
if (rawInfo instanceof AppWidgetProviderInfo) {
// Fill in the widget information
AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
createItemInfo = new PendingAddWidgetInfo(info, null, null);
// Determine the widget spans and min resize spans.
int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
createItemInfo.spanX = spanXY[0];
createItemInfo.spanY = spanXY[1];
int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
createItemInfo.minSpanX = minSpanXY[0];
createItemInfo.minSpanY = minSpanXY[1];
widget.applyFromAppWidgetProviderInfo(info, -1, spanXY, mWidgetPreviewLoader);
widget.setTag(createItemInfo);
widget.setShortPressListener(this);
} else if (rawInfo instanceof ResolveInfo) {
// Fill in the shortcuts information
ResolveInfo info = (ResolveInfo) rawInfo;
createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
info.activityInfo.name);
widget.applyFromResolveInfo(mPackageManager, info, mWidgetPreviewLoader);
widget.setTag(createItemInfo);
}
widget.setOnClickListener(this);
widget.setOnLongClickListener(this);
widget.setOnTouchListener(this);
widget.setOnKeyListener(this);
// Layout each widget
int ix = i % mWidgetCountX;
int iy = i / mWidgetCountX;
GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
GridLayout.spec(iy, GridLayout.START),
GridLayout.spec(ix, GridLayout.TOP));
lp.width = cellWidth;
lp.height = cellHeight;
lp.setGravity(Gravity.TOP | Gravity.START);
if (ix > 0) lp.leftMargin = mWidgetWidthGap;
if (iy > 0) lp.topMargin = mWidgetHeightGap;
layout.addView(widget, lp);
}
// wait until a call on onLayout to start loading, because
// PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
// TODO: can we do a measure/layout immediately?
layout.setOnLayoutListener(new Runnable() {
public void run() {
// Load the widget previews
int maxPreviewWidth = cellWidth;
int maxPreviewHeight = cellHeight;
if (layout.getChildCount() > 0) {
PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
int[] maxSize = w.getPreviewSize();
maxPreviewWidth = maxSize[0];
maxPreviewHeight = maxSize[1];
}
mWidgetPreviewLoader.setPreviewSize(
maxPreviewWidth, maxPreviewHeight, mWidgetSpacingLayout);
if (immediate) {
AsyncTaskPageData data = new AsyncTaskPageData(page, items,
maxPreviewWidth, maxPreviewHeight, null, null, mWidgetPreviewLoader);
loadWidgetPreviewsInBackground(null, data);
onSyncWidgetPageItems(data);
} else {
if (mInTransition) {
mDeferredPrepareLoadWidgetPreviewsTasks.add(this);
} else {
prepareLoadWidgetPreviewsTask(page, items,
maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
}
}
+ layout.setOnLayoutListener(null);
}
});
}
private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
AsyncTaskPageData data) {
// loadWidgetPreviewsInBackground can be called without a task to load a set of widget
// previews synchronously
if (task != null) {
// Ensure that this task starts running at the correct priority
task.syncThreadPriority();
}
// Load each of the widget/shortcut previews
ArrayList<Object> items = data.items;
ArrayList<Bitmap> images = data.generatedImages;
int count = items.size();
for (int i = 0; i < count; ++i) {
if (task != null) {
// Ensure we haven't been cancelled yet
if (task.isCancelled()) break;
// Before work on each item, ensure that this task is running at the correct
// priority
task.syncThreadPriority();
}
images.add(mWidgetPreviewLoader.getPreview(items.get(i)));
}
}
private void onSyncWidgetPageItems(AsyncTaskPageData data) {
if (mInTransition) {
mDeferredSyncWidgetPageItems.add(data);
return;
}
try {
int page = data.page;
PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
ArrayList<Object> items = data.items;
int count = items.size();
for (int i = 0; i < count; ++i) {
PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i);
if (widget != null) {
Bitmap preview = data.generatedImages.get(i);
widget.applyPreview(new FastBitmapDrawable(preview), i);
}
}
enableHwLayersOnVisiblePages();
// Update all thread priorities
Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
while (iter.hasNext()) {
AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
int pageIndex = task.page;
task.setThreadPriority(getThreadPriorityForPage(pageIndex));
}
} finally {
data.cleanup(false);
}
}
@Override
public void syncPages() {
removeAllViews();
cancelAllTasks();
Context context = getContext();
for (int j = 0; j < mNumWidgetPages; ++j) {
PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
mWidgetCountY);
setupPage(layout);
addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
}
for (int i = 0; i < mNumAppsPages; ++i) {
PagedViewCellLayout layout = new PagedViewCellLayout(context);
setupPage(layout);
addView(layout);
}
}
@Override
public void syncPageItems(int page, boolean immediate) {
if (page < mNumAppsPages) {
syncAppsPageItems(page, immediate);
} else {
syncWidgetPageItems(page, immediate);
}
}
// We want our pages to be z-ordered such that the further a page is to the left, the higher
// it is in the z-order. This is important to insure touch events are handled correctly.
View getPageAt(int index) {
return getChildAt(indexToPage(index));
}
@Override
protected int indexToPage(int index) {
return getChildCount() - index - 1;
}
// In apps customize, we have a scrolling effect which emulates pulling cards off of a stack.
@Override
protected void screenScrolled(int screenCenter) {
final boolean isRtl = isLayoutRtl();
super.screenScrolled(screenCenter);
for (int i = 0; i < getChildCount(); i++) {
View v = getPageAt(i);
if (v != null) {
float scrollProgress = getScrollProgress(screenCenter, v, i);
float interpolatedProgress;
float translationX;
float maxScrollProgress = Math.max(0, scrollProgress);
float minScrollProgress = Math.min(0, scrollProgress);
if (isRtl) {
translationX = maxScrollProgress * v.getMeasuredWidth();
interpolatedProgress = mZInterpolator.getInterpolation(Math.abs(maxScrollProgress));
} else {
translationX = minScrollProgress * v.getMeasuredWidth();
interpolatedProgress = mZInterpolator.getInterpolation(Math.abs(minScrollProgress));
}
float scale = (1 - interpolatedProgress) +
interpolatedProgress * TRANSITION_SCALE_FACTOR;
float alpha;
if (isRtl && (scrollProgress > 0)) {
alpha = mAlphaInterpolator.getInterpolation(1 - Math.abs(maxScrollProgress));
} else if (!isRtl && (scrollProgress < 0)) {
alpha = mAlphaInterpolator.getInterpolation(1 - Math.abs(scrollProgress));
} else {
// On large screens we need to fade the page as it nears its leftmost position
alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress);
}
v.setCameraDistance(mDensity * CAMERA_DISTANCE);
int pageWidth = v.getMeasuredWidth();
int pageHeight = v.getMeasuredHeight();
if (PERFORM_OVERSCROLL_ROTATION) {
float xPivot = isRtl ? 1f - TRANSITION_PIVOT : TRANSITION_PIVOT;
boolean isOverscrollingFirstPage = isRtl ? scrollProgress > 0 : scrollProgress < 0;
boolean isOverscrollingLastPage = isRtl ? scrollProgress < 0 : scrollProgress > 0;
if (i == 0 && isOverscrollingFirstPage) {
// Overscroll to the left
v.setPivotX(xPivot * pageWidth);
v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
scale = 1.0f;
alpha = 1.0f;
// On the first page, we don't want the page to have any lateral motion
translationX = 0;
} else if (i == getChildCount() - 1 && isOverscrollingLastPage) {
// Overscroll to the right
v.setPivotX((1 - xPivot) * pageWidth);
v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
scale = 1.0f;
alpha = 1.0f;
// On the last page, we don't want the page to have any lateral motion.
translationX = 0;
} else {
v.setPivotY(pageHeight / 2.0f);
v.setPivotX(pageWidth / 2.0f);
v.setRotationY(0f);
}
}
v.setTranslationX(translationX);
v.setScaleX(scale);
v.setScaleY(scale);
v.setAlpha(alpha);
// If the view has 0 alpha, we set it to be invisible so as to prevent
// it from accepting touches
if (alpha == 0) {
v.setVisibility(INVISIBLE);
} else if (v.getVisibility() != VISIBLE) {
v.setVisibility(VISIBLE);
}
}
}
enableHwLayersOnVisiblePages();
}
private void enableHwLayersOnVisiblePages() {
final int screenCount = getChildCount();
getVisiblePages(mTempVisiblePagesRange);
int leftScreen = mTempVisiblePagesRange[0];
int rightScreen = mTempVisiblePagesRange[1];
int forceDrawScreen = -1;
if (leftScreen == rightScreen) {
// make sure we're caching at least two pages always
if (rightScreen < screenCount - 1) {
rightScreen++;
forceDrawScreen = rightScreen;
} else if (leftScreen > 0) {
leftScreen--;
forceDrawScreen = leftScreen;
}
} else {
forceDrawScreen = leftScreen + 1;
}
for (int i = 0; i < screenCount; i++) {
final View layout = (View) getPageAt(i);
if (!(leftScreen <= i && i <= rightScreen &&
(i == forceDrawScreen || shouldDrawChild(layout)))) {
layout.setLayerType(LAYER_TYPE_NONE, null);
}
}
for (int i = 0; i < screenCount; i++) {
final View layout = (View) getPageAt(i);
if (leftScreen <= i && i <= rightScreen &&
(i == forceDrawScreen || shouldDrawChild(layout))) {
if (layout.getLayerType() != LAYER_TYPE_HARDWARE) {
layout.setLayerType(LAYER_TYPE_HARDWARE, null);
}
}
}
}
protected void overScroll(float amount) {
acceleratedOverScroll(amount);
}
/**
* Used by the parent to get the content width to set the tab bar to
* @return
*/
public int getPageContentWidth() {
return mContentWidth;
}
@Override
protected void onPageEndMoving() {
super.onPageEndMoving();
mForceDrawAllChildrenNextFrame = true;
// We reset the save index when we change pages so that it will be recalculated on next
// rotation
mSaveInstanceStateItemIndex = -1;
}
/*
* AllAppsView implementation
*/
public void setup(Launcher launcher, DragController dragController) {
mLauncher = launcher;
mDragController = dragController;
}
/**
* We should call thise method whenever the core data changes (mApps, mWidgets) so that we can
* appropriately determine when to invalidate the PagedView page data. In cases where the data
* has yet to be set, we can requestLayout() and wait for onDataReady() to be called in the
* next onMeasure() pass, which will trigger an invalidatePageData() itself.
*/
private void invalidateOnDataChange() {
if (!isDataReady()) {
// The next layout pass will trigger data-ready if both widgets and apps are set, so
// request a layout to trigger the page data when ready.
requestLayout();
} else {
cancelAllTasks();
invalidatePageData();
}
}
public void setApps(ArrayList<ApplicationInfo> list) {
mApps = list;
Collections.sort(mApps, LauncherModel.getAppNameComparator());
updatePageCounts();
invalidateOnDataChange();
}
private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
// We add it in place, in alphabetical order
int count = list.size();
for (int i = 0; i < count; ++i) {
ApplicationInfo info = list.get(i);
int index = Collections.binarySearch(mApps, info, LauncherModel.getAppNameComparator());
if (index < 0) {
mApps.add(-(index + 1), info);
}
}
}
public void addApps(ArrayList<ApplicationInfo> list) {
addAppsWithoutInvalidate(list);
updatePageCounts();
invalidateOnDataChange();
}
private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
ComponentName removeComponent = item.intent.getComponent();
int length = list.size();
for (int i = 0; i < length; ++i) {
ApplicationInfo info = list.get(i);
if (info.intent.getComponent().equals(removeComponent)) {
return i;
}
}
return -1;
}
private int findAppByPackage(List<ApplicationInfo> list, String packageName) {
int length = list.size();
for (int i = 0; i < length; ++i) {
ApplicationInfo info = list.get(i);
if (ItemInfo.getPackageName(info.intent).equals(packageName)) {
return i;
}
}
return -1;
}
private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
// loop through all the apps and remove apps that have the same component
int length = list.size();
for (int i = 0; i < length; ++i) {
ApplicationInfo info = list.get(i);
int removeIndex = findAppByComponent(mApps, info);
if (removeIndex > -1) {
mApps.remove(removeIndex);
}
}
}
private void removeAppsWithPackageNameWithoutInvalidate(ArrayList<String> packageNames) {
// loop through all the package names and remove apps that have the same package name
for (String pn : packageNames) {
int removeIndex = findAppByPackage(mApps, pn);
while (removeIndex > -1) {
mApps.remove(removeIndex);
removeIndex = findAppByPackage(mApps, pn);
}
}
}
public void removeApps(ArrayList<String> packageNames) {
removeAppsWithPackageNameWithoutInvalidate(packageNames);
updatePageCounts();
invalidateOnDataChange();
}
public void updateApps(ArrayList<ApplicationInfo> list) {
// We remove and re-add the updated applications list because it's properties may have
// changed (ie. the title), and this will ensure that the items will be in their proper
// place in the list.
removeAppsWithoutInvalidate(list);
addAppsWithoutInvalidate(list);
updatePageCounts();
invalidateOnDataChange();
}
public void reset() {
// If we have reset, then we should not continue to restore the previous state
mSaveInstanceStateItemIndex = -1;
AppsCustomizeTabHost tabHost = getTabHost();
String tag = tabHost.getCurrentTabTag();
if (tag != null) {
if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
tabHost.setCurrentTabFromContent(ContentType.Applications);
}
}
if (mCurrentPage != 0) {
invalidatePageData(0);
}
}
private AppsCustomizeTabHost getTabHost() {
return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane);
}
public void dumpState() {
// TODO: Dump information related to current list of Applications, Widgets, etc.
ApplicationInfo.dumpApplicationInfoList(TAG, "mApps", mApps);
dumpAppWidgetProviderInfoList(TAG, "mWidgets", mWidgets);
}
private void dumpAppWidgetProviderInfoList(String tag, String label,
ArrayList<Object> list) {
Log.d(tag, label + " size=" + list.size());
for (Object i: list) {
if (i instanceof AppWidgetProviderInfo) {
AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage
+ " resizeMode=" + info.resizeMode + " configure=" + info.configure
+ " initialLayout=" + info.initialLayout
+ " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
} else if (i instanceof ResolveInfo) {
ResolveInfo info = (ResolveInfo) i;
Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon="
+ info.icon);
}
}
}
public void surrender() {
// TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
// should stop this now.
// Stop all background tasks
cancelAllTasks();
}
@Override
public void iconPressed(PagedViewIcon icon) {
// Reset the previously pressed icon and store a reference to the pressed icon so that
// we can reset it on return to Launcher (in Launcher.onResume())
if (mPressedIcon != null) {
mPressedIcon.resetDrawableState();
}
mPressedIcon = icon;
}
public void resetDrawableState() {
if (mPressedIcon != null) {
mPressedIcon.resetDrawableState();
mPressedIcon = null;
}
}
/*
* We load an extra page on each side to prevent flashes from scrolling and loading of the
* widget previews in the background with the AsyncTasks.
*/
final static int sLookBehindPageCount = 2;
final static int sLookAheadPageCount = 2;
protected int getAssociatedLowerPageBound(int page) {
final int count = getChildCount();
int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
int windowMinIndex = Math.max(Math.min(page - sLookBehindPageCount, count - windowSize), 0);
return windowMinIndex;
}
protected int getAssociatedUpperPageBound(int page) {
final int count = getChildCount();
int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
int windowMaxIndex = Math.min(Math.max(page + sLookAheadPageCount, windowSize - 1),
count - 1);
return windowMaxIndex;
}
@Override
protected String getCurrentPageDescription() {
int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
int stringId = R.string.default_scroll_format;
int count = 0;
if (page < mNumAppsPages) {
stringId = R.string.apps_customize_apps_scroll_format;
count = mNumAppsPages;
} else {
page -= mNumAppsPages;
stringId = R.string.apps_customize_widgets_scroll_format;
count = mNumWidgetPages;
}
return String.format(getContext().getString(stringId), page + 1, count);
}
}
| true | true | public void syncWidgetPageItems(final int page, final boolean immediate) {
int numItemsPerPage = mWidgetCountX * mWidgetCountY;
// Calculate the dimensions of each cell we are giving to each widget
final ArrayList<Object> items = new ArrayList<Object>();
int contentWidth = mWidgetSpacingLayout.getContentWidth();
final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
- ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
int contentHeight = mWidgetSpacingLayout.getContentHeight();
final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
- ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
// Prepare the set of widgets to load previews for in the background
int offset = (page - mNumAppsPages) * numItemsPerPage;
for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
items.add(mWidgets.get(i));
}
// Prepopulate the pages with the other widget info, and fill in the previews later
final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
layout.setColumnCount(layout.getCellCountX());
for (int i = 0; i < items.size(); ++i) {
Object rawInfo = items.get(i);
PendingAddItemInfo createItemInfo = null;
PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
R.layout.apps_customize_widget, layout, false);
if (rawInfo instanceof AppWidgetProviderInfo) {
// Fill in the widget information
AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
createItemInfo = new PendingAddWidgetInfo(info, null, null);
// Determine the widget spans and min resize spans.
int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
createItemInfo.spanX = spanXY[0];
createItemInfo.spanY = spanXY[1];
int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
createItemInfo.minSpanX = minSpanXY[0];
createItemInfo.minSpanY = minSpanXY[1];
widget.applyFromAppWidgetProviderInfo(info, -1, spanXY, mWidgetPreviewLoader);
widget.setTag(createItemInfo);
widget.setShortPressListener(this);
} else if (rawInfo instanceof ResolveInfo) {
// Fill in the shortcuts information
ResolveInfo info = (ResolveInfo) rawInfo;
createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
info.activityInfo.name);
widget.applyFromResolveInfo(mPackageManager, info, mWidgetPreviewLoader);
widget.setTag(createItemInfo);
}
widget.setOnClickListener(this);
widget.setOnLongClickListener(this);
widget.setOnTouchListener(this);
widget.setOnKeyListener(this);
// Layout each widget
int ix = i % mWidgetCountX;
int iy = i / mWidgetCountX;
GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
GridLayout.spec(iy, GridLayout.START),
GridLayout.spec(ix, GridLayout.TOP));
lp.width = cellWidth;
lp.height = cellHeight;
lp.setGravity(Gravity.TOP | Gravity.START);
if (ix > 0) lp.leftMargin = mWidgetWidthGap;
if (iy > 0) lp.topMargin = mWidgetHeightGap;
layout.addView(widget, lp);
}
// wait until a call on onLayout to start loading, because
// PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
// TODO: can we do a measure/layout immediately?
layout.setOnLayoutListener(new Runnable() {
public void run() {
// Load the widget previews
int maxPreviewWidth = cellWidth;
int maxPreviewHeight = cellHeight;
if (layout.getChildCount() > 0) {
PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
int[] maxSize = w.getPreviewSize();
maxPreviewWidth = maxSize[0];
maxPreviewHeight = maxSize[1];
}
mWidgetPreviewLoader.setPreviewSize(
maxPreviewWidth, maxPreviewHeight, mWidgetSpacingLayout);
if (immediate) {
AsyncTaskPageData data = new AsyncTaskPageData(page, items,
maxPreviewWidth, maxPreviewHeight, null, null, mWidgetPreviewLoader);
loadWidgetPreviewsInBackground(null, data);
onSyncWidgetPageItems(data);
} else {
if (mInTransition) {
mDeferredPrepareLoadWidgetPreviewsTasks.add(this);
} else {
prepareLoadWidgetPreviewsTask(page, items,
maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
}
}
}
});
}
| public void syncWidgetPageItems(final int page, final boolean immediate) {
int numItemsPerPage = mWidgetCountX * mWidgetCountY;
// Calculate the dimensions of each cell we are giving to each widget
final ArrayList<Object> items = new ArrayList<Object>();
int contentWidth = mWidgetSpacingLayout.getContentWidth();
final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
- ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
int contentHeight = mWidgetSpacingLayout.getContentHeight();
final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
- ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
// Prepare the set of widgets to load previews for in the background
int offset = (page - mNumAppsPages) * numItemsPerPage;
for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
items.add(mWidgets.get(i));
}
// Prepopulate the pages with the other widget info, and fill in the previews later
final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
layout.setColumnCount(layout.getCellCountX());
for (int i = 0; i < items.size(); ++i) {
Object rawInfo = items.get(i);
PendingAddItemInfo createItemInfo = null;
PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
R.layout.apps_customize_widget, layout, false);
if (rawInfo instanceof AppWidgetProviderInfo) {
// Fill in the widget information
AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
createItemInfo = new PendingAddWidgetInfo(info, null, null);
// Determine the widget spans and min resize spans.
int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
createItemInfo.spanX = spanXY[0];
createItemInfo.spanY = spanXY[1];
int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
createItemInfo.minSpanX = minSpanXY[0];
createItemInfo.minSpanY = minSpanXY[1];
widget.applyFromAppWidgetProviderInfo(info, -1, spanXY, mWidgetPreviewLoader);
widget.setTag(createItemInfo);
widget.setShortPressListener(this);
} else if (rawInfo instanceof ResolveInfo) {
// Fill in the shortcuts information
ResolveInfo info = (ResolveInfo) rawInfo;
createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
info.activityInfo.name);
widget.applyFromResolveInfo(mPackageManager, info, mWidgetPreviewLoader);
widget.setTag(createItemInfo);
}
widget.setOnClickListener(this);
widget.setOnLongClickListener(this);
widget.setOnTouchListener(this);
widget.setOnKeyListener(this);
// Layout each widget
int ix = i % mWidgetCountX;
int iy = i / mWidgetCountX;
GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
GridLayout.spec(iy, GridLayout.START),
GridLayout.spec(ix, GridLayout.TOP));
lp.width = cellWidth;
lp.height = cellHeight;
lp.setGravity(Gravity.TOP | Gravity.START);
if (ix > 0) lp.leftMargin = mWidgetWidthGap;
if (iy > 0) lp.topMargin = mWidgetHeightGap;
layout.addView(widget, lp);
}
// wait until a call on onLayout to start loading, because
// PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
// TODO: can we do a measure/layout immediately?
layout.setOnLayoutListener(new Runnable() {
public void run() {
// Load the widget previews
int maxPreviewWidth = cellWidth;
int maxPreviewHeight = cellHeight;
if (layout.getChildCount() > 0) {
PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
int[] maxSize = w.getPreviewSize();
maxPreviewWidth = maxSize[0];
maxPreviewHeight = maxSize[1];
}
mWidgetPreviewLoader.setPreviewSize(
maxPreviewWidth, maxPreviewHeight, mWidgetSpacingLayout);
if (immediate) {
AsyncTaskPageData data = new AsyncTaskPageData(page, items,
maxPreviewWidth, maxPreviewHeight, null, null, mWidgetPreviewLoader);
loadWidgetPreviewsInBackground(null, data);
onSyncWidgetPageItems(data);
} else {
if (mInTransition) {
mDeferredPrepareLoadWidgetPreviewsTasks.add(this);
} else {
prepareLoadWidgetPreviewsTask(page, items,
maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
}
}
layout.setOnLayoutListener(null);
}
});
}
|
diff --git a/okapi/filters/table/src/main/java/net/sf/okapi/filters/table/csv/CSVSkeletonWriter.java b/okapi/filters/table/src/main/java/net/sf/okapi/filters/table/csv/CSVSkeletonWriter.java
index 5f7749d3d..69e6c552e 100644
--- a/okapi/filters/table/src/main/java/net/sf/okapi/filters/table/csv/CSVSkeletonWriter.java
+++ b/okapi/filters/table/src/main/java/net/sf/okapi/filters/table/csv/CSVSkeletonWriter.java
@@ -1,58 +1,57 @@
package net.sf.okapi.filters.table.csv;
import net.sf.okapi.common.LocaleId;
import net.sf.okapi.common.encoder.EncoderManager;
import net.sf.okapi.common.filterwriter.ILayerProvider;
import net.sf.okapi.common.resource.ITextUnit;
import net.sf.okapi.common.resource.StartDocument;
import net.sf.okapi.common.resource.TextContainer;
import net.sf.okapi.common.resource.TextUnitUtil;
import net.sf.okapi.common.skeleton.GenericSkeletonWriter;
public class CSVSkeletonWriter extends GenericSkeletonWriter {
private LocaleId outputLocale;
@Override
public String processStartDocument(LocaleId outputLocale,
String outputEncoding, ILayerProvider layer,
EncoderManager encoderManager, StartDocument resource) {
this.outputLocale = outputLocale;
return super.processStartDocument(outputLocale, outputEncoding, layer,
encoderManager, resource);
}
@Override
public String processTextUnit(ITextUnit tu) {
- System.out.println(tu.getSource().getUnSegmentedContentCopy().toString());
if (tu.isReferent()) {
return super.processTextUnit(tu);
}
if (tu.hasProperty(CommaSeparatedValuesFilter.PROP_QUALIFIED) &&
"yes".equals(tu.getProperty(CommaSeparatedValuesFilter.PROP_QUALIFIED).getValue())) {
return super.processTextUnit(tu);
}
TextContainer tc;
String text;
boolean isTarget = tu.hasTarget(outputLocale);
if (isTarget) {
tc = tu.getTarget(outputLocale);
}
else {
tc = tu.getSource();
}
if (tc == null)
return super.processTextUnit(tu);
text = tc.getUnSegmentedContentCopy().toText(); // Just to detect "bad" characters
if (text.contains(",") || text.contains("\n")) {
TextUnitUtil.addQualifiers(tu, "\"");
}
return super.processTextUnit(tu);
}
}
| true | true | public String processTextUnit(ITextUnit tu) {
System.out.println(tu.getSource().getUnSegmentedContentCopy().toString());
if (tu.isReferent()) {
return super.processTextUnit(tu);
}
if (tu.hasProperty(CommaSeparatedValuesFilter.PROP_QUALIFIED) &&
"yes".equals(tu.getProperty(CommaSeparatedValuesFilter.PROP_QUALIFIED).getValue())) {
return super.processTextUnit(tu);
}
TextContainer tc;
String text;
boolean isTarget = tu.hasTarget(outputLocale);
if (isTarget) {
tc = tu.getTarget(outputLocale);
}
else {
tc = tu.getSource();
}
if (tc == null)
return super.processTextUnit(tu);
text = tc.getUnSegmentedContentCopy().toText(); // Just to detect "bad" characters
if (text.contains(",") || text.contains("\n")) {
TextUnitUtil.addQualifiers(tu, "\"");
}
return super.processTextUnit(tu);
}
| public String processTextUnit(ITextUnit tu) {
if (tu.isReferent()) {
return super.processTextUnit(tu);
}
if (tu.hasProperty(CommaSeparatedValuesFilter.PROP_QUALIFIED) &&
"yes".equals(tu.getProperty(CommaSeparatedValuesFilter.PROP_QUALIFIED).getValue())) {
return super.processTextUnit(tu);
}
TextContainer tc;
String text;
boolean isTarget = tu.hasTarget(outputLocale);
if (isTarget) {
tc = tu.getTarget(outputLocale);
}
else {
tc = tu.getSource();
}
if (tc == null)
return super.processTextUnit(tu);
text = tc.getUnSegmentedContentCopy().toText(); // Just to detect "bad" characters
if (text.contains(",") || text.contains("\n")) {
TextUnitUtil.addQualifiers(tu, "\"");
}
return super.processTextUnit(tu);
}
|
diff --git a/src/Main.java b/src/Main.java
index d5bae6e..3508009 100644
--- a/src/Main.java
+++ b/src/Main.java
@@ -1,128 +1,127 @@
import java.util.Iterator;
import java.util.List;
public class Main {
/**
* Entry point for program
* @param args
*/
public static void main(String[] args) {
//Read instructions from program file
List<Long> instructions = ProgramReader.getInstructions(args[0]);
//load instructions into instruction memory
Long numInstr = (long) instructions.size();
Long firstInstrAddr = Long.parseLong("1000", 16);
Memory instrMemory = new Memory(firstInstrAddr,firstInstrAddr+(numInstr*4-1));
for(int i = 0; i < numInstr ; i++){
- System.out.println(firstInstrAddr+i*4);
instrMemory.storeWord(firstInstrAddr+i*4, instructions.get(i));
}
//initialize data memory
Memory dataMemory = new Memory(Long.parseLong("0", 16),Long.parseLong("ffc", 16));
//initialize everything
Mux aluSrcMux = new Mux();
Mux memToRegMux = new Mux();
Mux regDstMux = new Mux();
Mux jumpMux = new Mux();
Mux branchMux = new Mux();
ShiftLeftTwo slt1 = new ShiftLeftTwo();
ShiftLeftTwo slt2 = new ShiftLeftTwo();
ALUControl aluControl = new ALUControl();
ALU alu = new ALU();
ALU aluAdd = new ALU();
aluAdd.control.setValue((long)2);
ALU aluP4 = new ALU();
aluP4.control.setValue((long)2);
aluP4.input2.setValue((long) 4);
MemoryIO memoryIo = new MemoryIO(dataMemory);
Control control = new Control();
RegisterFile regFile = new RegisterFile();
Fetch fetch = new Fetch(instrMemory);
And branchMuxAnd = new And();
ProgramCounter pc = new ProgramCounter();
Decode decode = new Decode();
// Connect output of PC
pc.pcOut.connectTo(fetch.pc);
// Connect output of fetch
fetch.instr.connectTo(decode.instruction);
// Connect the outputs of the decode
decode.opcode.connectTo(control.opcode);
decode.rs.connectTo(regFile.readReg1);
decode.rt.connectTo(regFile.readReg2);
decode.rt.connectTo(regDstMux.input0);
decode.rd.connectTo(regDstMux.input1);
decode.target.connectTo(slt1.in);
decode.offset.connectTo(slt2.in);
decode.funct.connectTo(aluControl.func);
// Connect outputs of regFile
regFile.readData1.connectTo(alu.input1);
regFile.readData2.connectTo(aluSrcMux.input0);
regFile.readData2.connectTo(memoryIo.writeData);
// Connect outputs of ALU and related
aluSrcMux.output.connectTo(alu.input2);
alu.result.connectTo(memoryIo.address);
alu.result.connectTo(memToRegMux.input0);
alu.zero.connectTo(branchMuxAnd.input1);
// Connect output of memoryIo
memoryIo.readData.connectTo(memToRegMux.input1);
memToRegMux.output.connectTo(regFile.writeData);
regDstMux.output.connectTo(regFile.writeReg);
slt1.out.connectTo(jumpMux.input1);
slt2.out.connectTo(aluAdd.input2);
branchMuxAnd.output.connectTo(branchMux.switcher);
jumpMux.output.connectTo(pc.pcIn);
// connect the control signals
control.regDst.connectTo(regDstMux.switcher);
control.jump.connectTo(jumpMux.switcher);
control.branch.connectTo(branchMuxAnd.input0);
control.memRead.connectTo(memoryIo.memRead);
control.memToReg.connectTo(memToRegMux.input1);
control.aluOp.connectTo(aluControl.aluOp);
control.memWrite.connectTo(memoryIo.memWrite);
control.aluSrc.connectTo(aluSrcMux.switcher);
control.regWrite.connectTo(regFile.regWrite);
aluControl.aluControl.connectTo(alu.control);
pc.pcIn.setValue(firstInstrAddr);
for(Long instruction : instructions){
pc.clockEdge();
// fetch the instruction
fetch.clockEdge();
// decode the instruction
decode.clockEdge();
if(decode.isHalt()){
break;
}
// set the output control signals
control.setSignals();
// clock the mux that takes regDST as switcher
regDstMux.clockEdge();
// clock the regfile
regFile.clockEdge();
}
System.out.println("Final register values:");
- for(int x = 0 ; x < 32 ; x++){
- System.out.println(" $r" + x + ": 0x" + Long.toHexString(regFile.getVal(x)));
+ for(int i = 0 ; i < 32 ; i++){
+ System.out.println(" $r" + i + ": 0x" + Long.toHexString(regFile.getVal(i)));
}
}
}
| false | true | public static void main(String[] args) {
//Read instructions from program file
List<Long> instructions = ProgramReader.getInstructions(args[0]);
//load instructions into instruction memory
Long numInstr = (long) instructions.size();
Long firstInstrAddr = Long.parseLong("1000", 16);
Memory instrMemory = new Memory(firstInstrAddr,firstInstrAddr+(numInstr*4-1));
for(int i = 0; i < numInstr ; i++){
System.out.println(firstInstrAddr+i*4);
instrMemory.storeWord(firstInstrAddr+i*4, instructions.get(i));
}
//initialize data memory
Memory dataMemory = new Memory(Long.parseLong("0", 16),Long.parseLong("ffc", 16));
//initialize everything
Mux aluSrcMux = new Mux();
Mux memToRegMux = new Mux();
Mux regDstMux = new Mux();
Mux jumpMux = new Mux();
Mux branchMux = new Mux();
ShiftLeftTwo slt1 = new ShiftLeftTwo();
ShiftLeftTwo slt2 = new ShiftLeftTwo();
ALUControl aluControl = new ALUControl();
ALU alu = new ALU();
ALU aluAdd = new ALU();
aluAdd.control.setValue((long)2);
ALU aluP4 = new ALU();
aluP4.control.setValue((long)2);
aluP4.input2.setValue((long) 4);
MemoryIO memoryIo = new MemoryIO(dataMemory);
Control control = new Control();
RegisterFile regFile = new RegisterFile();
Fetch fetch = new Fetch(instrMemory);
And branchMuxAnd = new And();
ProgramCounter pc = new ProgramCounter();
Decode decode = new Decode();
// Connect output of PC
pc.pcOut.connectTo(fetch.pc);
// Connect output of fetch
fetch.instr.connectTo(decode.instruction);
// Connect the outputs of the decode
decode.opcode.connectTo(control.opcode);
decode.rs.connectTo(regFile.readReg1);
decode.rt.connectTo(regFile.readReg2);
decode.rt.connectTo(regDstMux.input0);
decode.rd.connectTo(regDstMux.input1);
decode.target.connectTo(slt1.in);
decode.offset.connectTo(slt2.in);
decode.funct.connectTo(aluControl.func);
// Connect outputs of regFile
regFile.readData1.connectTo(alu.input1);
regFile.readData2.connectTo(aluSrcMux.input0);
regFile.readData2.connectTo(memoryIo.writeData);
// Connect outputs of ALU and related
aluSrcMux.output.connectTo(alu.input2);
alu.result.connectTo(memoryIo.address);
alu.result.connectTo(memToRegMux.input0);
alu.zero.connectTo(branchMuxAnd.input1);
// Connect output of memoryIo
memoryIo.readData.connectTo(memToRegMux.input1);
memToRegMux.output.connectTo(regFile.writeData);
regDstMux.output.connectTo(regFile.writeReg);
slt1.out.connectTo(jumpMux.input1);
slt2.out.connectTo(aluAdd.input2);
branchMuxAnd.output.connectTo(branchMux.switcher);
jumpMux.output.connectTo(pc.pcIn);
// connect the control signals
control.regDst.connectTo(regDstMux.switcher);
control.jump.connectTo(jumpMux.switcher);
control.branch.connectTo(branchMuxAnd.input0);
control.memRead.connectTo(memoryIo.memRead);
control.memToReg.connectTo(memToRegMux.input1);
control.aluOp.connectTo(aluControl.aluOp);
control.memWrite.connectTo(memoryIo.memWrite);
control.aluSrc.connectTo(aluSrcMux.switcher);
control.regWrite.connectTo(regFile.regWrite);
aluControl.aluControl.connectTo(alu.control);
pc.pcIn.setValue(firstInstrAddr);
for(Long instruction : instructions){
pc.clockEdge();
// fetch the instruction
fetch.clockEdge();
// decode the instruction
decode.clockEdge();
if(decode.isHalt()){
break;
}
// set the output control signals
control.setSignals();
// clock the mux that takes regDST as switcher
regDstMux.clockEdge();
// clock the regfile
regFile.clockEdge();
}
System.out.println("Final register values:");
for(int x = 0 ; x < 32 ; x++){
System.out.println(" $r" + x + ": 0x" + Long.toHexString(regFile.getVal(x)));
}
}
| public static void main(String[] args) {
//Read instructions from program file
List<Long> instructions = ProgramReader.getInstructions(args[0]);
//load instructions into instruction memory
Long numInstr = (long) instructions.size();
Long firstInstrAddr = Long.parseLong("1000", 16);
Memory instrMemory = new Memory(firstInstrAddr,firstInstrAddr+(numInstr*4-1));
for(int i = 0; i < numInstr ; i++){
instrMemory.storeWord(firstInstrAddr+i*4, instructions.get(i));
}
//initialize data memory
Memory dataMemory = new Memory(Long.parseLong("0", 16),Long.parseLong("ffc", 16));
//initialize everything
Mux aluSrcMux = new Mux();
Mux memToRegMux = new Mux();
Mux regDstMux = new Mux();
Mux jumpMux = new Mux();
Mux branchMux = new Mux();
ShiftLeftTwo slt1 = new ShiftLeftTwo();
ShiftLeftTwo slt2 = new ShiftLeftTwo();
ALUControl aluControl = new ALUControl();
ALU alu = new ALU();
ALU aluAdd = new ALU();
aluAdd.control.setValue((long)2);
ALU aluP4 = new ALU();
aluP4.control.setValue((long)2);
aluP4.input2.setValue((long) 4);
MemoryIO memoryIo = new MemoryIO(dataMemory);
Control control = new Control();
RegisterFile regFile = new RegisterFile();
Fetch fetch = new Fetch(instrMemory);
And branchMuxAnd = new And();
ProgramCounter pc = new ProgramCounter();
Decode decode = new Decode();
// Connect output of PC
pc.pcOut.connectTo(fetch.pc);
// Connect output of fetch
fetch.instr.connectTo(decode.instruction);
// Connect the outputs of the decode
decode.opcode.connectTo(control.opcode);
decode.rs.connectTo(regFile.readReg1);
decode.rt.connectTo(regFile.readReg2);
decode.rt.connectTo(regDstMux.input0);
decode.rd.connectTo(regDstMux.input1);
decode.target.connectTo(slt1.in);
decode.offset.connectTo(slt2.in);
decode.funct.connectTo(aluControl.func);
// Connect outputs of regFile
regFile.readData1.connectTo(alu.input1);
regFile.readData2.connectTo(aluSrcMux.input0);
regFile.readData2.connectTo(memoryIo.writeData);
// Connect outputs of ALU and related
aluSrcMux.output.connectTo(alu.input2);
alu.result.connectTo(memoryIo.address);
alu.result.connectTo(memToRegMux.input0);
alu.zero.connectTo(branchMuxAnd.input1);
// Connect output of memoryIo
memoryIo.readData.connectTo(memToRegMux.input1);
memToRegMux.output.connectTo(regFile.writeData);
regDstMux.output.connectTo(regFile.writeReg);
slt1.out.connectTo(jumpMux.input1);
slt2.out.connectTo(aluAdd.input2);
branchMuxAnd.output.connectTo(branchMux.switcher);
jumpMux.output.connectTo(pc.pcIn);
// connect the control signals
control.regDst.connectTo(regDstMux.switcher);
control.jump.connectTo(jumpMux.switcher);
control.branch.connectTo(branchMuxAnd.input0);
control.memRead.connectTo(memoryIo.memRead);
control.memToReg.connectTo(memToRegMux.input1);
control.aluOp.connectTo(aluControl.aluOp);
control.memWrite.connectTo(memoryIo.memWrite);
control.aluSrc.connectTo(aluSrcMux.switcher);
control.regWrite.connectTo(regFile.regWrite);
aluControl.aluControl.connectTo(alu.control);
pc.pcIn.setValue(firstInstrAddr);
for(Long instruction : instructions){
pc.clockEdge();
// fetch the instruction
fetch.clockEdge();
// decode the instruction
decode.clockEdge();
if(decode.isHalt()){
break;
}
// set the output control signals
control.setSignals();
// clock the mux that takes regDST as switcher
regDstMux.clockEdge();
// clock the regfile
regFile.clockEdge();
}
System.out.println("Final register values:");
for(int i = 0 ; i < 32 ; i++){
System.out.println(" $r" + i + ": 0x" + Long.toHexString(regFile.getVal(i)));
}
}
|
diff --git a/src/com/nadmm/airports/wx/WxCursorAdapter.java b/src/com/nadmm/airports/wx/WxCursorAdapter.java
index 8f1394ea..751d3c13 100644
--- a/src/com/nadmm/airports/wx/WxCursorAdapter.java
+++ b/src/com/nadmm/airports/wx/WxCursorAdapter.java
@@ -1,247 +1,251 @@
/*
* FlightIntel for Pilots
*
* Copyright 2012 Nadeem Hasan <[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.nadmm.airports.wx;
import java.util.HashMap;
import java.util.Locale;
import android.content.Context;
import android.database.Cursor;
import android.location.Location;
import android.support.v4.widget.ResourceCursorAdapter;
import android.view.View;
import android.widget.TextView;
import com.nadmm.airports.DatabaseManager.Airports;
import com.nadmm.airports.DatabaseManager.Awos1;
import com.nadmm.airports.DatabaseManager.LocationColumns;
import com.nadmm.airports.DatabaseManager.Wxs;
import com.nadmm.airports.R;
import com.nadmm.airports.utils.DataUtils;
import com.nadmm.airports.utils.FormatUtils;
import com.nadmm.airports.utils.GeoUtils;
import com.nadmm.airports.utils.TimeUtils;
import com.nadmm.airports.utils.UiUtils;
public final class WxCursorAdapter extends ResourceCursorAdapter {
private HashMap<String, Metar> mStationWx;
public WxCursorAdapter( Context context, Cursor c ) {
super( context, R.layout.wx_list_item, c, 0 );
}
public void setMetars( HashMap<String, Metar> wx ) {
mStationWx = wx;
}
@Override
public void bindView( View view, Context context, Cursor c ) {
String name = c.getString( c.getColumnIndex( Wxs.STATION_NAME ) );
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
if ( name != null && name.length() > 0 ) {
tv.setText( name );
}
String stationId = c.getString( c.getColumnIndex( Wxs.STATION_ID ) );
tv = (TextView) view.findViewById( R.id.wx_station_id );
tv.setText( stationId );
view.setTag( stationId );
StringBuilder info = new StringBuilder();
String city = c.getString( c.getColumnIndex( Airports.ASSOC_CITY ) );
if ( city != null && city.length() > 0 ) {
if ( info.length() > 0 ) {
info.append( ", " );
}
info.append( city );
}
String state = c.getString( c.getColumnIndex( Airports.ASSOC_STATE ) );
if ( state != null && state.length() > 0 ) {
if ( info.length() > 0 ) {
info.append( ", " );
}
info.append( state );
}
tv = (TextView) view.findViewById( R.id.wx_station_info );
if ( info.length() > 0 ) {
tv.setText( info.toString() );
} else {
tv.setText( "Location not available" );
}
String freq = c.getString( c.getColumnIndex( Awos1.STATION_FREQUENCY ) );
if ( freq == null || freq.length() == 0 ) {
freq = c.getString( c.getColumnIndex( Awos1.SECOND_STATION_FREQUENCY ) );
}
tv = (TextView) view.findViewById( R.id.wx_station_freq );
if ( freq != null && freq.length() > 0 ) {
try {
tv.setText( FormatUtils.formatFreq( Float.valueOf( freq ) ) );
} catch ( NumberFormatException e ) {
}
} else {
tv.setText( "" );
}
info.setLength( 0 );
String type = c.getString( c.getColumnIndex( Awos1.WX_SENSOR_TYPE ) );
if ( type == null || type.length() == 0 ) {
type = "ASOS/AWOS";
}
info.append( type );
info.append( ", " );
int elevation = c.getInt( c.getColumnIndex( Wxs.STATION_ELEVATOIN_METER ) );
info.append( FormatUtils.formatFeetMsl( DataUtils.metersToFeet( elevation ) ) );
info.append( " elev." );
tv = (TextView) view.findViewById( R.id.wx_station_info2 );
tv.setText( info.toString() );
tv = (TextView) view.findViewById( R.id.wx_station_phone );
String phone = c.getString( c.getColumnIndex( Awos1.STATION_PHONE_NUMBER ) );
if ( phone != null && phone.length() > 0 ) {
tv.setText( phone );
} else {
tv.setText( "" );
}
tv = (TextView) view.findViewById( R.id.wx_station_distance );
if ( c.getColumnIndex( LocationColumns.DISTANCE ) >= 0
&& c.getColumnIndex( LocationColumns.BEARING ) >= 0 ) {
float distance = c.getFloat( c.getColumnIndex( LocationColumns.DISTANCE ) );
float bearing = c.getFloat( c.getColumnIndex( LocationColumns.BEARING ) );
tv.setText( String.format( "%.1f NM %s",
distance, GeoUtils.getCardinalDirection( bearing ) ) );
tv.setVisibility( View.VISIBLE );
} else {
tv.setVisibility( View.GONE );
}
if ( mStationWx != null ) {
Metar metar = mStationWx.get( stationId );
showMetarInfo( view, c, metar );
}
}
protected void showMetarInfo( View view, Cursor c, Metar metar ) {
if ( metar != null ) {
if ( metar.isValid ) {
// We have METAR for this station
double lat = c.getDouble(
c.getColumnIndex( Wxs.STATION_LATITUDE_DEGREES ) );
double lon = c.getDouble(
c.getColumnIndex( Wxs.STATION_LONGITUDE_DEGREES ) );
Location location = new Location( "" );
location.setLatitude( lat );
location.setLongitude( lon );
float declination = GeoUtils.getMagneticDeclination( location );
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
WxUtils.setColorizedWxDrawable( tv, metar, declination );
StringBuilder info = new StringBuilder();
info.append( metar.flightCategory );
if ( metar.wxList.size() > 0 ) {
for ( WxSymbol wx : metar.wxList ) {
if ( !wx.getSymbol().equals( "NSW" ) ) {
info.append( ", " );
info.append( wx.toString().toLowerCase( Locale.US ) );
}
}
}
info.append( ", winds " );
if ( metar.windSpeedKnots == 0 ) {
info.append( "calm" );
} else if ( metar.windGustKnots < Integer.MAX_VALUE ) {
info.append( String.format( "%dG%dKT",
metar.windSpeedKnots, metar.windGustKnots ) );
} else {
info.append( String.format( "%dKT", metar.windSpeedKnots ) );
}
- if ( metar.windSpeedKnots > 0 && metar.windDirDegrees == 0 ) {
- info.append( " variable" );
- } else {
- info.append( " from "+FormatUtils.formatDegrees( metar.windDirDegrees ) );
+ if ( metar.windSpeedKnots > 0 ) {
+ if ( metar.windDirDegrees == 0 ) {
+ info.append( " variable" );
+ } else {
+ info.append( " from "+FormatUtils.formatDegrees( metar.windDirDegrees ) );
+ }
}
tv = (TextView) view.findViewById( R.id.wx_station_wx );
tv.setVisibility( View.VISIBLE );
tv.setText( info.toString() );
info.setLength( 0 );
SkyCondition sky = WxUtils.getCeiling( metar.skyConditions );
int ceiling = sky.getCloudBaseAGL();
String skyCover = sky.getSkyCover();
if ( !skyCover.equals( "NSC" ) ) {
info.append( "Ceiling "+skyCover+" "+FormatUtils.formatFeet( ceiling ) );
} else {
if ( !metar.skyConditions.isEmpty() ) {
sky = metar.skyConditions.get( 0 );
skyCover = sky.getSkyCover();
if ( skyCover.equals( "CLR" ) || skyCover.equals( "SKC" ) ) {
info.append( "Sky clear" );
- } else {
+ } else if ( !skyCover.equals( "SKM" ) ) {
info.append( skyCover );
info.append( " "+FormatUtils.formatFeet( ceiling ) );
+ } else {
+ info.append( "No sky" );
}
} else {
info.append( "No sky" );
}
}
info.append( ", " );
info.append( FormatUtils.formatTemperatureF( metar.tempCelsius ) );
info.append( "/" );
info.append( FormatUtils.formatTemperatureF( metar.dewpointCelsius ) );
info.append( ", " );
info.append( FormatUtils.formatAltimeterHg( metar.altimeterHg ) );
tv = (TextView) view.findViewById( R.id.wx_station_wx2 );
tv.setVisibility( View.VISIBLE );
tv.setText( info.toString() );
tv = (TextView) view.findViewById( R.id.wx_report_age );
tv.setVisibility( View.VISIBLE );
tv.setText( TimeUtils.formatElapsedTime( metar.observationTime ) );
} else {
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
WxUtils.setColorizedWxDrawable( tv, metar, 0 );
tv = (TextView) view.findViewById( R.id.wx_station_wx );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_station_wx2 );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_report_age );
tv.setVisibility( View.GONE );
}
} else {
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
UiUtils.setTextViewDrawable( tv, null );
tv = (TextView) view.findViewById( R.id.wx_station_wx );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_station_wx2 );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_report_age );
tv.setVisibility( View.GONE );
}
}
}
| false | true | protected void showMetarInfo( View view, Cursor c, Metar metar ) {
if ( metar != null ) {
if ( metar.isValid ) {
// We have METAR for this station
double lat = c.getDouble(
c.getColumnIndex( Wxs.STATION_LATITUDE_DEGREES ) );
double lon = c.getDouble(
c.getColumnIndex( Wxs.STATION_LONGITUDE_DEGREES ) );
Location location = new Location( "" );
location.setLatitude( lat );
location.setLongitude( lon );
float declination = GeoUtils.getMagneticDeclination( location );
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
WxUtils.setColorizedWxDrawable( tv, metar, declination );
StringBuilder info = new StringBuilder();
info.append( metar.flightCategory );
if ( metar.wxList.size() > 0 ) {
for ( WxSymbol wx : metar.wxList ) {
if ( !wx.getSymbol().equals( "NSW" ) ) {
info.append( ", " );
info.append( wx.toString().toLowerCase( Locale.US ) );
}
}
}
info.append( ", winds " );
if ( metar.windSpeedKnots == 0 ) {
info.append( "calm" );
} else if ( metar.windGustKnots < Integer.MAX_VALUE ) {
info.append( String.format( "%dG%dKT",
metar.windSpeedKnots, metar.windGustKnots ) );
} else {
info.append( String.format( "%dKT", metar.windSpeedKnots ) );
}
if ( metar.windSpeedKnots > 0 && metar.windDirDegrees == 0 ) {
info.append( " variable" );
} else {
info.append( " from "+FormatUtils.formatDegrees( metar.windDirDegrees ) );
}
tv = (TextView) view.findViewById( R.id.wx_station_wx );
tv.setVisibility( View.VISIBLE );
tv.setText( info.toString() );
info.setLength( 0 );
SkyCondition sky = WxUtils.getCeiling( metar.skyConditions );
int ceiling = sky.getCloudBaseAGL();
String skyCover = sky.getSkyCover();
if ( !skyCover.equals( "NSC" ) ) {
info.append( "Ceiling "+skyCover+" "+FormatUtils.formatFeet( ceiling ) );
} else {
if ( !metar.skyConditions.isEmpty() ) {
sky = metar.skyConditions.get( 0 );
skyCover = sky.getSkyCover();
if ( skyCover.equals( "CLR" ) || skyCover.equals( "SKC" ) ) {
info.append( "Sky clear" );
} else {
info.append( skyCover );
info.append( " "+FormatUtils.formatFeet( ceiling ) );
}
} else {
info.append( "No sky" );
}
}
info.append( ", " );
info.append( FormatUtils.formatTemperatureF( metar.tempCelsius ) );
info.append( "/" );
info.append( FormatUtils.formatTemperatureF( metar.dewpointCelsius ) );
info.append( ", " );
info.append( FormatUtils.formatAltimeterHg( metar.altimeterHg ) );
tv = (TextView) view.findViewById( R.id.wx_station_wx2 );
tv.setVisibility( View.VISIBLE );
tv.setText( info.toString() );
tv = (TextView) view.findViewById( R.id.wx_report_age );
tv.setVisibility( View.VISIBLE );
tv.setText( TimeUtils.formatElapsedTime( metar.observationTime ) );
} else {
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
WxUtils.setColorizedWxDrawable( tv, metar, 0 );
tv = (TextView) view.findViewById( R.id.wx_station_wx );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_station_wx2 );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_report_age );
tv.setVisibility( View.GONE );
}
} else {
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
UiUtils.setTextViewDrawable( tv, null );
tv = (TextView) view.findViewById( R.id.wx_station_wx );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_station_wx2 );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_report_age );
tv.setVisibility( View.GONE );
}
}
| protected void showMetarInfo( View view, Cursor c, Metar metar ) {
if ( metar != null ) {
if ( metar.isValid ) {
// We have METAR for this station
double lat = c.getDouble(
c.getColumnIndex( Wxs.STATION_LATITUDE_DEGREES ) );
double lon = c.getDouble(
c.getColumnIndex( Wxs.STATION_LONGITUDE_DEGREES ) );
Location location = new Location( "" );
location.setLatitude( lat );
location.setLongitude( lon );
float declination = GeoUtils.getMagneticDeclination( location );
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
WxUtils.setColorizedWxDrawable( tv, metar, declination );
StringBuilder info = new StringBuilder();
info.append( metar.flightCategory );
if ( metar.wxList.size() > 0 ) {
for ( WxSymbol wx : metar.wxList ) {
if ( !wx.getSymbol().equals( "NSW" ) ) {
info.append( ", " );
info.append( wx.toString().toLowerCase( Locale.US ) );
}
}
}
info.append( ", winds " );
if ( metar.windSpeedKnots == 0 ) {
info.append( "calm" );
} else if ( metar.windGustKnots < Integer.MAX_VALUE ) {
info.append( String.format( "%dG%dKT",
metar.windSpeedKnots, metar.windGustKnots ) );
} else {
info.append( String.format( "%dKT", metar.windSpeedKnots ) );
}
if ( metar.windSpeedKnots > 0 ) {
if ( metar.windDirDegrees == 0 ) {
info.append( " variable" );
} else {
info.append( " from "+FormatUtils.formatDegrees( metar.windDirDegrees ) );
}
}
tv = (TextView) view.findViewById( R.id.wx_station_wx );
tv.setVisibility( View.VISIBLE );
tv.setText( info.toString() );
info.setLength( 0 );
SkyCondition sky = WxUtils.getCeiling( metar.skyConditions );
int ceiling = sky.getCloudBaseAGL();
String skyCover = sky.getSkyCover();
if ( !skyCover.equals( "NSC" ) ) {
info.append( "Ceiling "+skyCover+" "+FormatUtils.formatFeet( ceiling ) );
} else {
if ( !metar.skyConditions.isEmpty() ) {
sky = metar.skyConditions.get( 0 );
skyCover = sky.getSkyCover();
if ( skyCover.equals( "CLR" ) || skyCover.equals( "SKC" ) ) {
info.append( "Sky clear" );
} else if ( !skyCover.equals( "SKM" ) ) {
info.append( skyCover );
info.append( " "+FormatUtils.formatFeet( ceiling ) );
} else {
info.append( "No sky" );
}
} else {
info.append( "No sky" );
}
}
info.append( ", " );
info.append( FormatUtils.formatTemperatureF( metar.tempCelsius ) );
info.append( "/" );
info.append( FormatUtils.formatTemperatureF( metar.dewpointCelsius ) );
info.append( ", " );
info.append( FormatUtils.formatAltimeterHg( metar.altimeterHg ) );
tv = (TextView) view.findViewById( R.id.wx_station_wx2 );
tv.setVisibility( View.VISIBLE );
tv.setText( info.toString() );
tv = (TextView) view.findViewById( R.id.wx_report_age );
tv.setVisibility( View.VISIBLE );
tv.setText( TimeUtils.formatElapsedTime( metar.observationTime ) );
} else {
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
WxUtils.setColorizedWxDrawable( tv, metar, 0 );
tv = (TextView) view.findViewById( R.id.wx_station_wx );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_station_wx2 );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_report_age );
tv.setVisibility( View.GONE );
}
} else {
TextView tv = (TextView) view.findViewById( R.id.wx_station_name );
UiUtils.setTextViewDrawable( tv, null );
tv = (TextView) view.findViewById( R.id.wx_station_wx );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_station_wx2 );
tv.setVisibility( View.GONE );
tv = (TextView) view.findViewById( R.id.wx_report_age );
tv.setVisibility( View.GONE );
}
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java
index 97aa2ea3..fd959472 100644
--- a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java
+++ b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java
@@ -1,72 +1,72 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Console;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandtempban extends EssentialsCommand
{
public Commandtempban()
{
super("tempban");
}
@Override
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
final User user = getPlayer(server, args, 0, true);
if (!user.isOnline())
{
if (sender instanceof Player
&& !ess.getUser(sender).isAuthorized("essentials.tempban.offline"))
{
sender.sendMessage(_("tempbanExempt"));
return;
}
}
else
{
if (user.isAuthorized("essentials.tempban.exempt") && sender instanceof Player)
{
sender.sendMessage(_("tempbanExempt"));
return;
}
}
final String time = getFinalArg(args, 1);
final long banTimestamp = Util.parseDateDiff(time, true);
final long maxBanLength = ess.getSettings().getMaxTempban() * 1000;
- if(maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && ess.getUser(sender).isAuthorized("essentials.tempban.unlimited"))
+ if(maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && !(ess.getUser(sender).isAuthorized("essentials.tempban.unlimited")))
{
sender.sendMessage(_("oversizedTempban"));
throw new NoChargeException();
}
final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
final String banReason = _("tempBanned", Util.formatDateDiff(banTimestamp), senderName);
user.setBanReason(banReason);
user.setBanTimeout(banTimestamp);
user.setBanned(true);
user.kickPlayer(banReason);
for (Player onlinePlayer : server.getOnlinePlayers())
{
final User player = ess.getUser(onlinePlayer);
if (player.isAuthorized("essentials.ban.notify"))
{
onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason));
}
}
}
}
| true | true | public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
final User user = getPlayer(server, args, 0, true);
if (!user.isOnline())
{
if (sender instanceof Player
&& !ess.getUser(sender).isAuthorized("essentials.tempban.offline"))
{
sender.sendMessage(_("tempbanExempt"));
return;
}
}
else
{
if (user.isAuthorized("essentials.tempban.exempt") && sender instanceof Player)
{
sender.sendMessage(_("tempbanExempt"));
return;
}
}
final String time = getFinalArg(args, 1);
final long banTimestamp = Util.parseDateDiff(time, true);
final long maxBanLength = ess.getSettings().getMaxTempban() * 1000;
if(maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && ess.getUser(sender).isAuthorized("essentials.tempban.unlimited"))
{
sender.sendMessage(_("oversizedTempban"));
throw new NoChargeException();
}
final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
final String banReason = _("tempBanned", Util.formatDateDiff(banTimestamp), senderName);
user.setBanReason(banReason);
user.setBanTimeout(banTimestamp);
user.setBanned(true);
user.kickPlayer(banReason);
for (Player onlinePlayer : server.getOnlinePlayers())
{
final User player = ess.getUser(onlinePlayer);
if (player.isAuthorized("essentials.ban.notify"))
{
onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason));
}
}
}
| public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
final User user = getPlayer(server, args, 0, true);
if (!user.isOnline())
{
if (sender instanceof Player
&& !ess.getUser(sender).isAuthorized("essentials.tempban.offline"))
{
sender.sendMessage(_("tempbanExempt"));
return;
}
}
else
{
if (user.isAuthorized("essentials.tempban.exempt") && sender instanceof Player)
{
sender.sendMessage(_("tempbanExempt"));
return;
}
}
final String time = getFinalArg(args, 1);
final long banTimestamp = Util.parseDateDiff(time, true);
final long maxBanLength = ess.getSettings().getMaxTempban() * 1000;
if(maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && !(ess.getUser(sender).isAuthorized("essentials.tempban.unlimited")))
{
sender.sendMessage(_("oversizedTempban"));
throw new NoChargeException();
}
final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
final String banReason = _("tempBanned", Util.formatDateDiff(banTimestamp), senderName);
user.setBanReason(banReason);
user.setBanTimeout(banTimestamp);
user.setBanned(true);
user.kickPlayer(banReason);
for (Player onlinePlayer : server.getOnlinePlayers())
{
final User player = ess.getUser(onlinePlayer);
if (player.isAuthorized("essentials.ban.notify"))
{
onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason));
}
}
}
|
diff --git a/src/org/eclipse/core/internal/resources/ProjectPreferences.java b/src/org/eclipse/core/internal/resources/ProjectPreferences.java
index 6c1f6be3..59f1a9ba 100644
--- a/src/org/eclipse/core/internal/resources/ProjectPreferences.java
+++ b/src/org/eclipse/core/internal/resources/ProjectPreferences.java
@@ -1,577 +1,577 @@
/*******************************************************************************
* Copyright (c) 2004, 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.core.internal.resources;
import java.io.*;
import java.util.*;
import org.eclipse.core.internal.preferences.EclipsePreferences;
import org.eclipse.core.internal.preferences.ExportedPreferences;
import org.eclipse.core.internal.utils.*;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.MultiRule;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IExportedPreferences;
import org.eclipse.osgi.util.NLS;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;
/**
* Represents a node in the Eclipse preference hierarchy which stores preference
* values for projects.
*
* @since 3.0
*/
public class ProjectPreferences extends EclipsePreferences {
class SortedProperties extends Properties {
class IteratorWrapper implements Enumeration {
Iterator iterator;
public IteratorWrapper(Iterator iterator) {
this.iterator = iterator;
}
public boolean hasMoreElements() {
return iterator.hasNext();
}
public Object nextElement() {
return iterator.next();
}
}
private static final long serialVersionUID = 1L;
/* (non-Javadoc)
* @see java.util.Hashtable#keys()
*/
public synchronized Enumeration keys() {
TreeSet set = new TreeSet();
for (Enumeration e = super.keys(); e.hasMoreElements();)
set.add(e.nextElement());
return new IteratorWrapper(set.iterator());
}
}
/**
* Cache which nodes have been loaded from disk
*/
protected static Set loadedNodes = new HashSet();
private IFile file;
private boolean initialized = false;
/**
* Flag indicating that this node is currently reading values from disk,
* to avoid flushing during a read.
*/
private boolean isReading;
/**
* Flag indicating that this node is currently writing values to disk,
* to avoid re-reading after the write completes.
*/
private boolean isWriting;
private IEclipsePreferences loadLevel;
private IProject project;
private String qualifier;
// cache
private int segmentCount;
static void deleted(IFile file) throws CoreException {
IPath path = file.getFullPath();
int count = path.segmentCount();
if (count != 3)
return;
// check if we are in the .settings directory
if (!EclipsePreferences.DEFAULT_PREFERENCES_DIRNAME.equals(path.segment(1)))
return;
Preferences root = Platform.getPreferencesService().getRootNode();
String project = path.segment(0);
String qualifier = path.removeFileExtension().lastSegment();
ProjectPreferences projectNode = (ProjectPreferences) root.node(ProjectScope.SCOPE).node(project);
// if the node isn't known then just return
try {
if (!projectNode.nodeExists(qualifier))
return;
} catch (BackingStoreException e) {
// ignore
}
// if the node was loaded we need to clear the values and remove
// its reference from the parent (don't save it though)
// otherwise just remove the reference from the parent
String childPath = projectNode.absolutePath() + IPath.SEPARATOR + qualifier;
if (projectNode.isAlreadyLoaded(childPath))
removeNode(projectNode.node(qualifier));
else
projectNode.removeNode(qualifier);
// notifies the CharsetManager if needed
if (qualifier.equals(ResourcesPlugin.PI_RESOURCES))
preferencesChanged(file.getProject());
}
static void deleted(IFolder folder) throws CoreException {
IPath path = folder.getFullPath();
int count = path.segmentCount();
if (count != 2)
return;
// check if we are the .settings directory
if (!EclipsePreferences.DEFAULT_PREFERENCES_DIRNAME.equals(path.segment(1)))
return;
Preferences root = Platform.getPreferencesService().getRootNode();
// The settings dir has been removed/moved so remove all project prefs
// for the resource.
String project = path.segment(0);
Preferences projectNode = root.node(ProjectScope.SCOPE).node(project);
// check if we need to notify the charset manager
boolean hasResourcesSettings = getFile(folder, ResourcesPlugin.PI_RESOURCES).exists();
// remove the preferences
removeNode(projectNode);
// notifies the CharsetManager
if (hasResourcesSettings)
preferencesChanged(folder.getProject());
}
/*
* The whole project has been removed so delete all of the project settings
*/
static void deleted(IProject project) throws CoreException {
// The settings dir has been removed/moved so remove all project prefs
// for the resource. We have to do this now because (since we aren't
// synchronizing) there is short-circuit code that doesn't visit the
// children.
Preferences root = Platform.getPreferencesService().getRootNode();
Preferences projectNode = root.node(ProjectScope.SCOPE).node(project.getName());
// check if we need to notify the charset manager
boolean hasResourcesSettings = getFile(project, ResourcesPlugin.PI_RESOURCES).exists();
// remove the preferences
removeNode(projectNode);
// notifies the CharsetManager
if (hasResourcesSettings)
preferencesChanged(project);
}
static void deleted(IResource resource) throws CoreException {
switch (resource.getType()) {
case IResource.FILE :
deleted((IFile) resource);
return;
case IResource.FOLDER :
deleted((IFolder) resource);
return;
case IResource.PROJECT :
deleted((IProject) resource);
return;
}
}
/*
* Return the preferences file for the given folder and qualifier.
*/
static IFile getFile(IFolder folder, String qualifier) {
Assert.isLegal(folder.getName().equals(DEFAULT_PREFERENCES_DIRNAME));
return folder.getFile(new Path(qualifier).addFileExtension(PREFS_FILE_EXTENSION));
}
/*
* Return the preferences file for the given project and qualifier.
*/
static IFile getFile(IProject project, String qualifier) {
return project.getFile(new Path(DEFAULT_PREFERENCES_DIRNAME).append(qualifier).addFileExtension(PREFS_FILE_EXTENSION));
}
private static Properties loadProperties(IFile file) throws BackingStoreException {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Loading preferences from file: " + file.getFullPath()); //$NON-NLS-1$
Properties result = new Properties();
InputStream input = null;
try {
input = new BufferedInputStream(file.getContents(true));
result.load(input);
} catch (CoreException e) {
String message = NLS.bind(Messages.preferences_loadException, file.getFullPath());
log(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
} catch (IOException e) {
String message = NLS.bind(Messages.preferences_loadException, file.getFullPath());
log(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
} finally {
FileUtil.safeClose(input);
}
return result;
}
private static void preferencesChanged(IProject project) {
Workspace workspace = ((Workspace) ResourcesPlugin.getWorkspace());
workspace.getCharsetManager().projectPreferencesChanged(project);
workspace.getContentDescriptionManager().projectPreferencesChanged(project);
}
private static void read(ProjectPreferences node, IFile file) throws BackingStoreException, CoreException {
if (file == null || !file.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Unable to determine preference file or file does not exist for node: " + node.absolutePath()); //$NON-NLS-1$
return;
}
Properties fromDisk = loadProperties(file);
// no work to do
if (fromDisk.isEmpty())
return;
// create a new node to store the preferences in.
IExportedPreferences myNode = (IExportedPreferences) ExportedPreferences.newRoot().node(node.absolutePath());
convertFromProperties((EclipsePreferences) myNode, fromDisk, false);
//flag that we are currently reading, to avoid unnecessary writing
boolean oldIsReading = node.isReading;
node.isReading = true;
try {
Platform.getPreferencesService().applyPreferences(myNode);
} finally {
node.isReading = oldIsReading;
}
}
static void removeNode(Preferences node) throws CoreException {
String message = NLS.bind(Messages.preferences_removeNodeException, node.absolutePath());
try {
node.removeNode();
} catch (BackingStoreException e) {
IStatus status = new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e);
throw new CoreException(status);
}
String path = node.absolutePath();
for (Iterator i = loadedNodes.iterator(); i.hasNext();) {
String key = (String) i.next();
if (key.startsWith(path))
i.remove();
}
}
public static void updatePreferences(IFile file) throws CoreException {
IPath path = file.getFullPath();
// if we made it this far we are inside /project/.settings and might
// have a change to a preference file
if (!PREFS_FILE_EXTENSION.equals(path.getFileExtension()))
return;
String project = path.segment(0);
String qualifier = path.removeFileExtension().lastSegment();
Preferences root = Platform.getPreferencesService().getRootNode();
Preferences node = root.node(ProjectScope.SCOPE).node(project).node(qualifier);
String message = null;
try {
message = NLS.bind(Messages.preferences_syncException, node.absolutePath());
if (!(node instanceof ProjectPreferences))
return;
ProjectPreferences projectPrefs = (ProjectPreferences) node;
if (projectPrefs.isWriting)
return;
read(projectPrefs, file);
// make sure that we generate the appropriate resource change events
// if encoding settings have changed
if (ResourcesPlugin.PI_RESOURCES.equals(qualifier))
preferencesChanged(file.getProject());
} catch (BackingStoreException e) {
IStatus status = new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e);
throw new CoreException(status);
}
}
/**
* Default constructor. Should only be called by #createExecutableExtension.
*/
public ProjectPreferences() {
super(null, null);
}
private ProjectPreferences(EclipsePreferences parent, String name) {
super(parent, name);
// cache the segment count
String path = absolutePath();
segmentCount = getSegmentCount(path);
if (segmentCount == 1)
return;
// cache the project name
String projectName = getSegment(path, 1);
if (projectName != null)
project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
// cache the qualifier
if (segmentCount > 2)
qualifier = getSegment(path, 2);
if (segmentCount != 2)
return;
// else segmentCount == 2 so we initialize the children
if (initialized)
return;
try {
synchronized (this) {
String[] names = computeChildren();
for (int i = 0; i < names.length; i++)
addChild(names[i], null);
}
} finally {
initialized = true;
}
}
/*
* Figure out what the children of this node are based on the resources
* that are in the workspace.
*/
private String[] computeChildren() {
if (project == null)
return EMPTY_STRING_ARRAY;
IFolder folder = project.getFolder(DEFAULT_PREFERENCES_DIRNAME);
if (!folder.exists())
return EMPTY_STRING_ARRAY;
IResource[] members = null;
try {
members = folder.members();
} catch (CoreException e) {
return EMPTY_STRING_ARRAY;
}
ArrayList result = new ArrayList();
for (int i = 0; i < members.length; i++) {
IResource resource = members[i];
if (resource.getType() == IResource.FILE && PREFS_FILE_EXTENSION.equals(resource.getFullPath().getFileExtension()))
result.add(resource.getFullPath().removeFileExtension().lastSegment());
}
return (String[]) result.toArray(EMPTY_STRING_ARRAY);
}
public void flush() throws BackingStoreException {
if (isReading)
return;
isWriting = true;
try {
super.flush();
} finally {
isWriting = false;
}
}
private IFile getFile() {
if (file == null) {
if (project == null || qualifier == null)
return null;
file = getFile(project, qualifier);
}
return file;
}
/*
* Return the node at which these preferences are loaded/saved.
*/
protected IEclipsePreferences getLoadLevel() {
if (loadLevel == null) {
if (project == null || qualifier == null)
return null;
// Make it relative to this node rather than navigating to it from the root.
// Walk backwards up the tree starting at this node.
// This is important to avoid a chicken/egg thing on startup.
EclipsePreferences node = this;
for (int i = 3; i < segmentCount; i++)
node = (EclipsePreferences) node.parent();
loadLevel = node;
}
return loadLevel;
}
/*
* Calculate and return the file system location for this preference node.
* Use the absolute path of the node to find out the project name so
* we can get its location on disk.
*
* NOTE: we cannot cache the location since it may change over the course
* of the project life-cycle.
*/
protected IPath getLocation() {
if (project == null || qualifier == null)
return null;
IPath path = project.getLocation();
return computeLocation(path, qualifier);
}
protected EclipsePreferences internalCreate(EclipsePreferences nodeParent, String nodeName, Object context) {
return new ProjectPreferences(nodeParent, nodeName);
}
protected boolean isAlreadyLoaded(IEclipsePreferences node) {
return loadedNodes.contains(node.absolutePath());
}
protected boolean isAlreadyLoaded(String path) {
return loadedNodes.contains(path);
}
protected void load() throws BackingStoreException {
IFile localFile = getFile();
if (localFile == null || !localFile.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Unable to determine preference file or file does not exist for node: " + absolutePath()); //$NON-NLS-1$
return;
}
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Loading preferences from file: " + localFile.getFullPath()); //$NON-NLS-1$
Properties fromDisk = new Properties();
InputStream input = null;
try {
input = new BufferedInputStream(localFile.getContents(true));
fromDisk.load(input);
} catch (CoreException e) {
String message = NLS.bind(Messages.preferences_loadException, localFile.getFullPath());
log(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
} catch (IOException e) {
String message = NLS.bind(Messages.preferences_loadException, localFile.getFullPath());
log(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
} finally {
FileUtil.safeClose(input);
}
convertFromProperties(this, fromDisk, true);
}
protected void loaded() {
loadedNodes.add(absolutePath());
}
/* (non-Javadoc)
* @see org.eclipse.core.internal.preferences.EclipsePreferences#nodeExists(java.lang.String)
*
* If we are at the /project node and we are checking for the existance of a child, we
* want special behaviour. If the child is a single segment name, then we want to
* return true if the node exists OR if a project with that name exists in the workspace.
*/
public boolean nodeExists(String path) throws BackingStoreException {
if (segmentCount != 1)
return super.nodeExists(path);
if (path.length() == 0)
return super.nodeExists(path);
if (path.charAt(0) == IPath.SEPARATOR)
return super.nodeExists(path);
if (path.indexOf(IPath.SEPARATOR) != -1)
return super.nodeExists(path);
// if we are checking existance of a single segment child of /project, base the answer on
// whether or not it exists in the workspace.
return ResourcesPlugin.getWorkspace().getRoot().getProject(path).exists() || super.nodeExists(path);
}
protected void save() throws BackingStoreException {
final IFile fileInWorkspace = getFile();
if (fileInWorkspace == null) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Not saving preferences since there is no file for node: " + absolutePath()); //$NON-NLS-1$
return;
}
Properties table = convertToProperties(new SortedProperties(), ""); //$NON-NLS-1$
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResourceRuleFactory factory = workspace.getRuleFactory();
try {
if (table.isEmpty()) {
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
// nothing to save. delete existing file if one exists.
if (fileInWorkspace.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Deleting preference file: " + fileInWorkspace.getFullPath()); //$NON-NLS-1$
if (fileInWorkspace.isReadOnly()) {
- IStatus status = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, null);
+ IStatus status = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, IWorkspace.VALIDATE_PROMPT);
if (!status.isOK())
throw new CoreException(status);
}
try {
fileInWorkspace.delete(true, null);
} catch (CoreException e) {
String message = NLS.bind(Messages.preferences_deleteException, fileInWorkspace.getFullPath());
log(new Status(IStatus.WARNING, ResourcesPlugin.PI_RESOURCES, IStatus.WARNING, message, null));
}
}
}
};
ISchedulingRule rule = factory.deleteRule(fileInWorkspace);
try {
ResourcesPlugin.getWorkspace().run(operation, rule, IResource.NONE, null);
} catch (OperationCanceledException e) {
throw new BackingStoreException(Messages.preferences_operationCanceled);
}
return;
}
table.put(VERSION_KEY, VERSION_VALUE);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
table.store(output, null);
} catch (IOException e) {
String message = NLS.bind(Messages.preferences_saveProblems, absolutePath());
log(new Status(IStatus.ERROR, Platform.PI_RUNTIME, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
} finally {
try {
output.close();
} catch (IOException e) {
// ignore
}
}
final InputStream input = new BufferedInputStream(new ByteArrayInputStream(output.toByteArray()));
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
if (fileInWorkspace.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Setting preference file contents for: " + fileInWorkspace.getFullPath()); //$NON-NLS-1$
if (fileInWorkspace.isReadOnly()) {
- IStatus status = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, null);
+ IStatus status = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, IWorkspace.VALIDATE_PROMPT);
if (!status.isOK())
throw new CoreException(status);
}
// set the contents
fileInWorkspace.setContents(input, IResource.KEEP_HISTORY, null);
} else {
// create the file
IFolder folder = (IFolder) fileInWorkspace.getParent();
if (!folder.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Creating parent preference directory: " + folder.getFullPath()); //$NON-NLS-1$
folder.create(IResource.NONE, true, null);
}
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Creating preference file: " + fileInWorkspace.getLocation()); //$NON-NLS-1$
fileInWorkspace.create(input, IResource.NONE, null);
}
}
};
//don't bother with scheduling rules if we are already inside an operation
try {
if (((Workspace) workspace).getWorkManager().isLockAlreadyAcquired()) {
operation.run(null);
} else {
// we might: create the .settings folder, create the file, or modify the file.
ISchedulingRule rule = MultiRule.combine(factory.createRule(fileInWorkspace.getParent()), factory.modifyRule(fileInWorkspace));
workspace.run(operation, rule, IResource.NONE, null);
}
} catch (OperationCanceledException e) {
throw new BackingStoreException(Messages.preferences_operationCanceled);
}
} catch (CoreException e) {
String message = NLS.bind(Messages.preferences_saveProblems, fileInWorkspace.getFullPath());
log(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
}
}
}
| false | true | protected void save() throws BackingStoreException {
final IFile fileInWorkspace = getFile();
if (fileInWorkspace == null) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Not saving preferences since there is no file for node: " + absolutePath()); //$NON-NLS-1$
return;
}
Properties table = convertToProperties(new SortedProperties(), ""); //$NON-NLS-1$
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResourceRuleFactory factory = workspace.getRuleFactory();
try {
if (table.isEmpty()) {
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
// nothing to save. delete existing file if one exists.
if (fileInWorkspace.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Deleting preference file: " + fileInWorkspace.getFullPath()); //$NON-NLS-1$
if (fileInWorkspace.isReadOnly()) {
IStatus status = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, null);
if (!status.isOK())
throw new CoreException(status);
}
try {
fileInWorkspace.delete(true, null);
} catch (CoreException e) {
String message = NLS.bind(Messages.preferences_deleteException, fileInWorkspace.getFullPath());
log(new Status(IStatus.WARNING, ResourcesPlugin.PI_RESOURCES, IStatus.WARNING, message, null));
}
}
}
};
ISchedulingRule rule = factory.deleteRule(fileInWorkspace);
try {
ResourcesPlugin.getWorkspace().run(operation, rule, IResource.NONE, null);
} catch (OperationCanceledException e) {
throw new BackingStoreException(Messages.preferences_operationCanceled);
}
return;
}
table.put(VERSION_KEY, VERSION_VALUE);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
table.store(output, null);
} catch (IOException e) {
String message = NLS.bind(Messages.preferences_saveProblems, absolutePath());
log(new Status(IStatus.ERROR, Platform.PI_RUNTIME, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
} finally {
try {
output.close();
} catch (IOException e) {
// ignore
}
}
final InputStream input = new BufferedInputStream(new ByteArrayInputStream(output.toByteArray()));
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
if (fileInWorkspace.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Setting preference file contents for: " + fileInWorkspace.getFullPath()); //$NON-NLS-1$
if (fileInWorkspace.isReadOnly()) {
IStatus status = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, null);
if (!status.isOK())
throw new CoreException(status);
}
// set the contents
fileInWorkspace.setContents(input, IResource.KEEP_HISTORY, null);
} else {
// create the file
IFolder folder = (IFolder) fileInWorkspace.getParent();
if (!folder.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Creating parent preference directory: " + folder.getFullPath()); //$NON-NLS-1$
folder.create(IResource.NONE, true, null);
}
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Creating preference file: " + fileInWorkspace.getLocation()); //$NON-NLS-1$
fileInWorkspace.create(input, IResource.NONE, null);
}
}
};
//don't bother with scheduling rules if we are already inside an operation
try {
if (((Workspace) workspace).getWorkManager().isLockAlreadyAcquired()) {
operation.run(null);
} else {
// we might: create the .settings folder, create the file, or modify the file.
ISchedulingRule rule = MultiRule.combine(factory.createRule(fileInWorkspace.getParent()), factory.modifyRule(fileInWorkspace));
workspace.run(operation, rule, IResource.NONE, null);
}
} catch (OperationCanceledException e) {
throw new BackingStoreException(Messages.preferences_operationCanceled);
}
} catch (CoreException e) {
String message = NLS.bind(Messages.preferences_saveProblems, fileInWorkspace.getFullPath());
log(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
}
}
| protected void save() throws BackingStoreException {
final IFile fileInWorkspace = getFile();
if (fileInWorkspace == null) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Not saving preferences since there is no file for node: " + absolutePath()); //$NON-NLS-1$
return;
}
Properties table = convertToProperties(new SortedProperties(), ""); //$NON-NLS-1$
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResourceRuleFactory factory = workspace.getRuleFactory();
try {
if (table.isEmpty()) {
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
// nothing to save. delete existing file if one exists.
if (fileInWorkspace.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Deleting preference file: " + fileInWorkspace.getFullPath()); //$NON-NLS-1$
if (fileInWorkspace.isReadOnly()) {
IStatus status = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, IWorkspace.VALIDATE_PROMPT);
if (!status.isOK())
throw new CoreException(status);
}
try {
fileInWorkspace.delete(true, null);
} catch (CoreException e) {
String message = NLS.bind(Messages.preferences_deleteException, fileInWorkspace.getFullPath());
log(new Status(IStatus.WARNING, ResourcesPlugin.PI_RESOURCES, IStatus.WARNING, message, null));
}
}
}
};
ISchedulingRule rule = factory.deleteRule(fileInWorkspace);
try {
ResourcesPlugin.getWorkspace().run(operation, rule, IResource.NONE, null);
} catch (OperationCanceledException e) {
throw new BackingStoreException(Messages.preferences_operationCanceled);
}
return;
}
table.put(VERSION_KEY, VERSION_VALUE);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
table.store(output, null);
} catch (IOException e) {
String message = NLS.bind(Messages.preferences_saveProblems, absolutePath());
log(new Status(IStatus.ERROR, Platform.PI_RUNTIME, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
} finally {
try {
output.close();
} catch (IOException e) {
// ignore
}
}
final InputStream input = new BufferedInputStream(new ByteArrayInputStream(output.toByteArray()));
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
if (fileInWorkspace.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Setting preference file contents for: " + fileInWorkspace.getFullPath()); //$NON-NLS-1$
if (fileInWorkspace.isReadOnly()) {
IStatus status = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, IWorkspace.VALIDATE_PROMPT);
if (!status.isOK())
throw new CoreException(status);
}
// set the contents
fileInWorkspace.setContents(input, IResource.KEEP_HISTORY, null);
} else {
// create the file
IFolder folder = (IFolder) fileInWorkspace.getParent();
if (!folder.exists()) {
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Creating parent preference directory: " + folder.getFullPath()); //$NON-NLS-1$
folder.create(IResource.NONE, true, null);
}
if (Policy.DEBUG_PREFERENCES)
Policy.debug("Creating preference file: " + fileInWorkspace.getLocation()); //$NON-NLS-1$
fileInWorkspace.create(input, IResource.NONE, null);
}
}
};
//don't bother with scheduling rules if we are already inside an operation
try {
if (((Workspace) workspace).getWorkManager().isLockAlreadyAcquired()) {
operation.run(null);
} else {
// we might: create the .settings folder, create the file, or modify the file.
ISchedulingRule rule = MultiRule.combine(factory.createRule(fileInWorkspace.getParent()), factory.modifyRule(fileInWorkspace));
workspace.run(operation, rule, IResource.NONE, null);
}
} catch (OperationCanceledException e) {
throw new BackingStoreException(Messages.preferences_operationCanceled);
}
} catch (CoreException e) {
String message = NLS.bind(Messages.preferences_saveProblems, fileInWorkspace.getFullPath());
log(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e));
throw new BackingStoreException(message);
}
}
|
diff --git a/src/main/java/com/moandjiezana/tent/essayist/tent/Entities.java b/src/main/java/com/moandjiezana/tent/essayist/tent/Entities.java
index 6468d64..8e8c0db 100644
--- a/src/main/java/com/moandjiezana/tent/essayist/tent/Entities.java
+++ b/src/main/java/com/moandjiezana/tent/essayist/tent/Entities.java
@@ -1,22 +1,22 @@
package com.moandjiezana.tent.essayist.tent;
public class Entities {
public static String getEntityForUrl(String entity) {
String prefix = entity.startsWith("https://") ? "s:" : "";
String urlEntity = entity.replace("http://", "").replace("https://", "");
if (urlEntity.endsWith("/")) {
- urlEntity.substring(0, urlEntity.length() - 1);
+ urlEntity = urlEntity.substring(0, urlEntity.length() - 1);
}
return prefix + urlEntity;
}
public static String expandFromUrl(String entity) {
if (entity.startsWith("s:")) {
return "https://" + entity.substring(2);
} else {
return "http://" + entity;
}
}
}
| true | true | public static String getEntityForUrl(String entity) {
String prefix = entity.startsWith("https://") ? "s:" : "";
String urlEntity = entity.replace("http://", "").replace("https://", "");
if (urlEntity.endsWith("/")) {
urlEntity.substring(0, urlEntity.length() - 1);
}
return prefix + urlEntity;
}
| public static String getEntityForUrl(String entity) {
String prefix = entity.startsWith("https://") ? "s:" : "";
String urlEntity = entity.replace("http://", "").replace("https://", "");
if (urlEntity.endsWith("/")) {
urlEntity = urlEntity.substring(0, urlEntity.length() - 1);
}
return prefix + urlEntity;
}
|
diff --git a/src/org/touchirc/model/Message.java b/src/org/touchirc/model/Message.java
index 674e89f..0e26592 100644
--- a/src/org/touchirc/model/Message.java
+++ b/src/org/touchirc/model/Message.java
@@ -1,56 +1,56 @@
package org.touchirc.model;
import java.sql.Timestamp;
import java.util.Date;
public class Message {
public final static int TYPE_MESSAGE = 0;
public final static int TYPE_NOTICE = 1;
public final static int TYPE_MENTION = 2;
private String content;
private String author;
private int type;
private long timestamp;
public Message(String text) {
this(text, null, TYPE_MESSAGE);
}
public Message(String text, String author) {
this(text, author, TYPE_MESSAGE);
}
public Message(String text, int type) {
this(text,null,type);
}
public Message(String text, String author, int type) {
- this.type = type;
+ this.content = text;
this.author = author;
this.type = type;
this.timestamp = new Date().getTime();
}
public String getAuthor(){
return this.author;
}
public String getMessage(){
return this.content;
}
public int getType(){
return this.type;
}
public long getTime(){
return this.timestamp;
}
public String toString(){
return "<" + this.author + "> " + this.content;
}
}
| true | true | public Message(String text, String author, int type) {
this.type = type;
this.author = author;
this.type = type;
this.timestamp = new Date().getTime();
}
| public Message(String text, String author, int type) {
this.content = text;
this.author = author;
this.type = type;
this.timestamp = new Date().getTime();
}
|
diff --git a/alchemy-midlet/src/alchemy/evm/EtherFunction.java b/alchemy-midlet/src/alchemy/evm/EtherFunction.java
index d6442ba..38f5e14 100644
--- a/alchemy-midlet/src/alchemy/evm/EtherFunction.java
+++ b/alchemy-midlet/src/alchemy/evm/EtherFunction.java
@@ -1,953 +1,953 @@
/*
* This file is a part of Alchemy OS project.
* Copyright (C) 2011-2013, Sergey Basalaev <[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 alchemy.evm;
import alchemy.core.AlchemyException;
import alchemy.core.Context;
import alchemy.core.Function;
import alchemy.core.Int;
/**
* Ether Virtual Machine.
* @author Sergey Basalaev
*/
class EtherFunction extends Function {
private final int stacksize;
private final int localsize;
private final byte[] bcode;
private final char[] dbgtable;
private final char[] errtable;
private final Object[] cpool;
private final String libname;
public EtherFunction(String libname, String funcname, Object[] cpool, int stacksize, int localsize, byte[] code, char[] dbgtable, char[] errtable) {
super(funcname);
this.libname = libname;
this.stacksize = stacksize;
this.localsize = localsize;
this.bcode = code;
this.cpool = cpool;
this.dbgtable = dbgtable;
this.errtable = errtable;
}
public Object exec(Context c, Object[] args) throws AlchemyException {
//initializing
final Object[] stack = new Object[stacksize];
int head = -1;
final byte[] code = this.bcode;
Object[] locals;
if (args.length == localsize) {
locals = args;
} else {
locals = new Object[localsize];
System.arraycopy(args, 0, locals, 0, args.length);
}
int ct = 0;
while (true) {
try {
int instr = code[ct];
ct++;
switch (instr) {
// CONSTANTS
case Opcodes.ACONST_NULL: {
head++;
stack[head] = null;
break;
}
case Opcodes.ICONST_M1: {
head++;
stack[head] = Int.M_ONE;
break;
}
case Opcodes.ICONST_0: {
head++;
stack[head] = Int.ZERO;
break;
}
case Opcodes.ICONST_1: {
head++;
stack[head] = Int.ONE;
break;
}
case Opcodes.ICONST_2: {
head++;
stack[head] = Int.toInt(2);
break;
}
case Opcodes.ICONST_3: {
head++;
stack[head] = Int.toInt(3);
break;
}
case Opcodes.ICONST_4: {
head++;
stack[head] = Int.toInt(4);
break;
}
case Opcodes.ICONST_5: {
head++;
stack[head] = Int.toInt(5);
break;
}
case Opcodes.LCONST_0: {
head++;
stack[head] = Lval(0l);
break;
}
case Opcodes.LCONST_1: {
head++;
stack[head] = Lval(1l);
break;
}
case Opcodes.FCONST_0: {
head++;
stack[head] = Fval(0f);
break;
}
case Opcodes.FCONST_1: {
head++;
stack[head] = Fval(1f);
break;
}
case Opcodes.FCONST_2: {
head++;
stack[head] = Fval(2f);
break;
}
case Opcodes.DCONST_0: {
head++;
stack[head] = Dval(0d);
break;
}
case Opcodes.DCONST_1: {
head++;
stack[head] = Dval(1d);
break;
}
//CONVERSIONS
case Opcodes.I2L: {
stack[head] = Lval(ival(stack[head]));
break;
}
case Opcodes.I2F: {
stack[head] = Fval(ival(stack[head]));
break;
}
case Opcodes.I2D: {
stack[head] = Dval(ival(stack[head]));
break;
}
case Opcodes.L2F: {
stack[head] = Fval(lval(stack[head]));
break;
}
case Opcodes.L2D: {
stack[head] = Dval(lval(stack[head]));
break;
}
case Opcodes.L2I: {
stack[head] = Ival((int)lval(stack[head]));
break;
}
case Opcodes.F2D: {
stack[head] = Dval(fval(stack[head]));
break;
}
case Opcodes.F2I: {
stack[head] = Ival((int)fval(stack[head]));
break;
}
case Opcodes.F2L: {
stack[head] = Lval((long)fval(stack[head]));
break;
}
case Opcodes.D2I: {
stack[head] = Ival((int)dval(stack[head]));
break;
}
case Opcodes.D2L: {
stack[head] = Lval((long)dval(stack[head]));
break;
}
case Opcodes.D2F: {
stack[head] = Fval((float)dval(stack[head]));
break;
}
case Opcodes.I2C: {
stack[head] = Int.toInt((char)ival(stack[head]));
break;
}
case Opcodes.I2B: {
stack[head] = Int.toInt((byte)ival(stack[head]));
break;
}
case Opcodes.I2S: {
stack[head] = Int.toInt((short)ival(stack[head]));
break;
}
//INTEGER ARITHMETICS
case Opcodes.IADD: {
head--;
stack[head] = Ival(ival(stack[head]) + ival(stack[head+1]));
break;
}
case Opcodes.ISUB: {
head--;
stack[head] = Ival(ival(stack[head]) - ival(stack[head+1]));
break;
}
case Opcodes.IMUL: {
head--;
stack[head] = Ival(ival(stack[head]) * ival(stack[head+1]));
break;
}
case Opcodes.IDIV: {
head--;
stack[head] = Ival(ival(stack[head]) / ival(stack[head+1]));
break;
}
case Opcodes.IMOD: {
head--;
stack[head] = Ival(ival(stack[head]) % ival(stack[head+1]));
break;
}
case Opcodes.INEG: {
stack[head] = Ival(-ival(stack[head]));
break;
}
case Opcodes.ICMP: {
head--;
int itmp = ival(stack[head]) - ival(stack[head+1]);
stack[head] = (itmp > 0) ? Int.ONE : (itmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.ISHL: {
head--;
stack[head] = Ival(ival(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.ISHR: {
head--;
stack[head] = Ival(ival(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.IUSHR: {
head--;
stack[head] = Ival(ival(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.IAND: {
head--;
stack[head] = Ival(ival(stack[head]) & ival(stack[head+1]));
break;
}
case Opcodes.IOR: {
head--;
stack[head] = Ival(ival(stack[head]) | ival(stack[head+1]));
break;
}
case Opcodes.IXOR: {
head--;
stack[head] = Ival(ival(stack[head]) ^ ival(stack[head+1]));
break;
}
//LONG ARITHMETICS
case Opcodes.LADD: {
head--;
stack[head] = Lval(lval(stack[head]) + lval(stack[head+1]));
break;
}
case Opcodes.LSUB: {
head--;
stack[head] = Lval(lval(stack[head]) - lval(stack[head+1]));
break;
}
case Opcodes.LMUL: {
head--;
stack[head] = Lval(lval(stack[head]) * lval(stack[head+1]));
break;
}
case Opcodes.LDIV: {
head--;
stack[head] = Lval(lval(stack[head]) / lval(stack[head+1]));
break;
}
case Opcodes.LMOD: {
head--;
stack[head] = Lval(lval(stack[head]) % lval(stack[head+1]));
break;
}
case Opcodes.LNEG: {
stack[head] = Lval(-lval(stack[head]));
break;
}
case Opcodes.LCMP: {
head--;
long ltmp = lval(stack[head]) - lval(stack[head+1]);
stack[head] = (ltmp > 0L) ? Int.ONE : (ltmp == 0L ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.LSHL: {
head--;
stack[head] = Lval(lval(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.LSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.LUSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.LAND: {
head--;
stack[head] = Lval(lval(stack[head]) & lval(stack[head+1]));
break;
}
case Opcodes.LOR: {
head--;
stack[head] = Lval(lval(stack[head]) | lval(stack[head+1]));
break;
}
case Opcodes.LXOR: {
head--;
stack[head] = Lval(lval(stack[head]) ^ lval(stack[head+1]));
break;
}
//FLOAT ARITHMETICS
case Opcodes.FADD: {
head--;
stack[head] = Fval(fval(stack[head]) + fval(stack[head+1]));
break;
}
case Opcodes.FSUB: {
head--;
stack[head] = Fval(fval(stack[head]) - fval(stack[head+1]));
break;
}
case Opcodes.FMUL: {
head--;
stack[head] = Fval(fval(stack[head]) * fval(stack[head+1]));
break;
}
case Opcodes.FDIV: {
head--;
stack[head] = Fval(fval(stack[head]) / fval(stack[head+1]));
break;
}
case Opcodes.FMOD: {
head--;
stack[head] = Fval(fval(stack[head]) % fval(stack[head+1]));
break;
}
case Opcodes.FNEG: {
stack[head] = Fval(-fval(stack[head]));
break;
}
case Opcodes.FCMP: {
head--;
float ftmp = fval(stack[head]) - fval(stack[head+1]);
stack[head] = (ftmp > 0) ? Int.ONE : (ftmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//DOUBLE ARITHMETICS
case Opcodes.DADD: {
head--;
stack[head] = Dval(dval(stack[head]) + dval(stack[head+1]));
break;
}
case Opcodes.DSUB: {
head--;
stack[head] = Dval(dval(stack[head]) - dval(stack[head+1]));
break;
}
case Opcodes.DMUL: {
head--;
stack[head] = Dval(dval(stack[head]) * dval(stack[head+1]));
break;
}
case Opcodes.DDIV: {
head--;
stack[head] = Dval(dval(stack[head]) / dval(stack[head+1]));
break;
}
case Opcodes.DMOD: {
head--;
stack[head] = Dval(dval(stack[head]) % dval(stack[head+1]));
break;
}
case Opcodes.DNEG: {
stack[head] = Dval(-dval(stack[head]));
break;
}
case Opcodes.DCMP: {
head--;
double dtmp = dval(stack[head]) - dval(stack[head+1]);
stack[head] = (dtmp > 0) ? Int.ONE : (dtmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//LOCALS LOADERS AND SAVERS
case Opcodes.LOAD_0:
case Opcodes.LOAD_1:
case Opcodes.LOAD_2:
case Opcodes.LOAD_3:
case Opcodes.LOAD_4:
case Opcodes.LOAD_5:
case Opcodes.LOAD_6:
case Opcodes.LOAD_7: {
head++;
stack[head] = locals[instr & 7];
break;
}
case Opcodes.LOAD: { //load <ubyte>
head++;
stack[head] = locals[code[ct] & 0xff];
ct++;
break;
}
//variable savers
case Opcodes.STORE_0:
case Opcodes.STORE_1:
case Opcodes.STORE_2:
case Opcodes.STORE_3:
case Opcodes.STORE_4:
case Opcodes.STORE_5:
case Opcodes.STORE_6:
case Opcodes.STORE_7: {
locals[instr & 7] = stack[head];
head--;
break;
}
case Opcodes.STORE: { //store <ubyte>
locals[code[ct] & 0xff] = stack[head];
ct++;
head--;
break;
}
//BRANCHING
case Opcodes.IFEQ: { //ifeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) == 0) ct = itmp;
head--;
break;
}
case Opcodes.IFNE: { //ifne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) != 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLT: { //iflt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) < 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGE: { //ifge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) >= 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGT: { //ifgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) > 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLE: { //ifle <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) <= 0) ct = itmp;
head--;
break;
}
case Opcodes.GOTO: { //goto <ushort>
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.IFNULL: { //ifnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] == null) ct = itmp;
head--;
break;
}
case Opcodes.IFNNULL: { //ifnnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] != null) ct = itmp;
head--;
break;
}
case Opcodes.IF_ICMPLT: { //if_icmplt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) < ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGE: { //if_icmpge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) >= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGT: { //if_icmpgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) > ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPLE: { //if_icmple <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) <= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPEQ: { //if_acmpeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? stack[head-1].equals(stack[head])
: stack[head] == null) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPNE: { //if_acmpne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? !stack[head-1].equals(stack[head])
: stack[head] != null) ct = itmp;
head -= 2;
break;
}
case Opcodes.JSR: { //jsr <ushort>
head++;
stack[head] = Ival(ct+2);
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.RET: { //ret
ct = ival(stack[head]);
head--;
break;
}
//FUNCTION CALLS
case Opcodes.CALL_0:
case Opcodes.CALL_1:
case Opcodes.CALL_2:
case Opcodes.CALL_3:
case Opcodes.CALL_4:
case Opcodes.CALL_5:
case Opcodes.CALL_6:
case Opcodes.CALL_7:
case Opcodes.CALV_0:
case Opcodes.CALV_1:
case Opcodes.CALV_2:
case Opcodes.CALV_3:
case Opcodes.CALV_4:
case Opcodes.CALV_5:
case Opcodes.CALV_6:
case Opcodes.CALV_7: {
int paramlen = instr & 7;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
if ((instr & 8) != 0) head--;
break;
}
case Opcodes.CALL: {//call <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
break;
}
case Opcodes.CALV: {//calv <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
((Function)stack[head]).exec(c, params);
head--;
break;
}
//ARRAY INSTRUCTIONS
case Opcodes.NEWAA: {
stack[head] = new Object[ival(stack[head])];
break;
}
case Opcodes.NEWBA: {
stack[head] = new byte[ival(stack[head])];
break;
}
case Opcodes.NEWCA: {
stack[head] = new char[ival(stack[head])];
break;
}
case Opcodes.NEWZA: {
stack[head] = new boolean[ival(stack[head])];
break;
}
case Opcodes.NEWSA: {
stack[head] = new short[ival(stack[head])];
break;
}
case Opcodes.NEWIA: {
stack[head] = new int[ival(stack[head])];
break;
}
case Opcodes.NEWLA: {
stack[head] = new long[ival(stack[head])];
break;
}
case Opcodes.NEWFA: {
stack[head] = new float[ival(stack[head])];
break;
}
case Opcodes.NEWDA: {
stack[head] = new double[ival(stack[head])];
break;
}
case Opcodes.AALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = ((Object[])stack[head])[at];
break;
}
case Opcodes.BALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((byte[])stack[head])[at] );
break;
}
case Opcodes.CALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((char[])stack[head])[at] );
break;
}
case Opcodes.ZALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((boolean[])stack[head])[at] );
break;
}
case Opcodes.SALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((short[])stack[head])[at] );
break;
}
case Opcodes.IALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((int[])stack[head])[at] );
break;
}
case Opcodes.LALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Lval( ((long[])stack[head])[at] );
break;
}
case Opcodes.FALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Fval( ((float[])stack[head])[at] );
break;
}
case Opcodes.DALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Dval( ((double[])stack[head])[at] );
break;
}
case Opcodes.AASTORE: {
Object val = stack[head];
int at = ival(stack[head-1]);
Object[] array = (Object[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.BASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
byte[] array = (byte[])stack[head-2];
array[at] = (byte)val;
head -= 3;
break;
}
case Opcodes.CASTORE: {
char val = (char) ival(stack[head]);
int at = ival(stack[head-1]);
char[] array = (char[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.ZASTORE: {
boolean val = bval(stack[head]);
int at = ival(stack[head-1]);
boolean[] array = (boolean[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.SASTORE: {
short val = (short)ival(stack[head]);
int at = ival(stack[head-1]);
short[] array = (short[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.IASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
int[] array = (int[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.FASTORE: {
float val = fval(stack[head]);
int at = ival(stack[head-1]);
float[] array = (float[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.DASTORE: {
double val = dval(stack[head]);
int at = ival(stack[head-1]);
double[] array = (double[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.AALEN: {
stack[head] = Ival(((Object[])stack[head]).length);
break;
}
case Opcodes.BALEN: {
stack[head] = Ival(((byte[])stack[head]).length);
break;
}
case Opcodes.CALEN: {
stack[head] = Ival(((char[])stack[head]).length);
break;
}
case Opcodes.ZALEN: {
stack[head] = Ival(((boolean[])stack[head]).length);
break;
}
case Opcodes.SALEN: {
stack[head] = Ival(((short[])stack[head]).length);
break;
}
case Opcodes.IALEN: {
stack[head] = Ival(((int[])stack[head]).length);
break;
}
case Opcodes.LALEN: {
stack[head] = Ival(((long[])stack[head]).length);
break;
}
case Opcodes.FALEN: {
stack[head] = Ival(((float[])stack[head]).length);
break;
}
case Opcodes.DALEN: {
stack[head] = Ival(((double[])stack[head]).length);
break;
}
//SWITCH BRANCHING
case Opcodes.TABLESWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int min = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int max = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int val = ival(stack[head]);
head--;
if (val >= min && val <= max) {
ct += (val-min)*2;
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
} else {
ct = dflt;
}
break;
}
case Opcodes.LOOKUPSWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int count = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int val = ival(stack[head]);
head--;
boolean matched = false;
for (int i=0; i<count && !matched; i++) {
int cand = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
if (val == cand) {
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
matched = true;
} else {
ct += 2;
}
}
if (!matched) ct = dflt;
break;
}
//OTHERS
case Opcodes.ACMP: {
head--;
boolean eq = (stack[head] == null) ? stack[head+1] == null : stack[head].equals(stack[head+1]);
stack[head] = Ival(!eq);
break;
}
case Opcodes.RET_NULL:
return null;
case Opcodes.RETURN:
return stack[head];
case Opcodes.DUP: {
stack[head+1] = stack[head];
head++;
break;
}
case Opcodes.DUP2: {
stack[head+2] = stack[head];
stack[head+1] = stack[head-1];
head += 2;
break;
}
case Opcodes.SWAP: {
Object atmp = stack[head-1];
stack[head-1] = stack[head];
stack[head] = atmp;
break;
}
case Opcodes.LDC: { //ldc <ushort>
head++;
stack[head] = cpool[((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff)];
ct += 2;
break;
}
case Opcodes.POP: {
head--;
break;
}
case Opcodes.BIPUSH: { //bipush <byte>
head++;
stack[head] = Ival(code[ct]);
ct++;
break;
}
case Opcodes.SIPUSH: { //sipush <short>
head++;
stack[head] = Ival((code[ct] << 8) | (code[ct+1]& 0xff));
ct += 2;
break;
}
case Opcodes.IINC: { //iinc <ubyte> <byte>
int idx = code[ct] & 0xff;
ct++;
- int inc = code[ct] & 0xff;
+ int inc = code[ct];
ct++;
locals[idx] = Int.toInt(((Int)locals[idx]).value + inc);
}
} /* the big switch */
} catch (Throwable e) {
// the instruction on which error occured
ct--;
// filling exception with debug info
AlchemyException ae = (e instanceof AlchemyException) ? (AlchemyException)e : new AlchemyException(e);
if (dbgtable != null) {
int srcline = 0;
for (int i=1; i<dbgtable.length; i += 2) {
if (dbgtable[i+1] <= ct) srcline = dbgtable[i];
}
ae.addTraceElement(this, cpool[dbgtable[0]]+":"+srcline);
} else {
ae.addTraceElement(this, "+"+ct);
}
// catching or rethrowing
int jumpto = -1;
if (errtable != null) {
for (int i=0; i < errtable.length && jumpto < 0; i += 4)
if (ct >= errtable[i] && ct <= errtable[i+1]) {
jumpto = errtable[i+2];
head = errtable[i+3];
}
}
if (jumpto >= 0) {
stack[head] = ae;
ct = jumpto;
} else {
throw ae;
}
}
} /* the great while */
}
public String toString() {
if (libname != null) return libname+':'+signature;
else return signature;
}
}
| true | true | public Object exec(Context c, Object[] args) throws AlchemyException {
//initializing
final Object[] stack = new Object[stacksize];
int head = -1;
final byte[] code = this.bcode;
Object[] locals;
if (args.length == localsize) {
locals = args;
} else {
locals = new Object[localsize];
System.arraycopy(args, 0, locals, 0, args.length);
}
int ct = 0;
while (true) {
try {
int instr = code[ct];
ct++;
switch (instr) {
// CONSTANTS
case Opcodes.ACONST_NULL: {
head++;
stack[head] = null;
break;
}
case Opcodes.ICONST_M1: {
head++;
stack[head] = Int.M_ONE;
break;
}
case Opcodes.ICONST_0: {
head++;
stack[head] = Int.ZERO;
break;
}
case Opcodes.ICONST_1: {
head++;
stack[head] = Int.ONE;
break;
}
case Opcodes.ICONST_2: {
head++;
stack[head] = Int.toInt(2);
break;
}
case Opcodes.ICONST_3: {
head++;
stack[head] = Int.toInt(3);
break;
}
case Opcodes.ICONST_4: {
head++;
stack[head] = Int.toInt(4);
break;
}
case Opcodes.ICONST_5: {
head++;
stack[head] = Int.toInt(5);
break;
}
case Opcodes.LCONST_0: {
head++;
stack[head] = Lval(0l);
break;
}
case Opcodes.LCONST_1: {
head++;
stack[head] = Lval(1l);
break;
}
case Opcodes.FCONST_0: {
head++;
stack[head] = Fval(0f);
break;
}
case Opcodes.FCONST_1: {
head++;
stack[head] = Fval(1f);
break;
}
case Opcodes.FCONST_2: {
head++;
stack[head] = Fval(2f);
break;
}
case Opcodes.DCONST_0: {
head++;
stack[head] = Dval(0d);
break;
}
case Opcodes.DCONST_1: {
head++;
stack[head] = Dval(1d);
break;
}
//CONVERSIONS
case Opcodes.I2L: {
stack[head] = Lval(ival(stack[head]));
break;
}
case Opcodes.I2F: {
stack[head] = Fval(ival(stack[head]));
break;
}
case Opcodes.I2D: {
stack[head] = Dval(ival(stack[head]));
break;
}
case Opcodes.L2F: {
stack[head] = Fval(lval(stack[head]));
break;
}
case Opcodes.L2D: {
stack[head] = Dval(lval(stack[head]));
break;
}
case Opcodes.L2I: {
stack[head] = Ival((int)lval(stack[head]));
break;
}
case Opcodes.F2D: {
stack[head] = Dval(fval(stack[head]));
break;
}
case Opcodes.F2I: {
stack[head] = Ival((int)fval(stack[head]));
break;
}
case Opcodes.F2L: {
stack[head] = Lval((long)fval(stack[head]));
break;
}
case Opcodes.D2I: {
stack[head] = Ival((int)dval(stack[head]));
break;
}
case Opcodes.D2L: {
stack[head] = Lval((long)dval(stack[head]));
break;
}
case Opcodes.D2F: {
stack[head] = Fval((float)dval(stack[head]));
break;
}
case Opcodes.I2C: {
stack[head] = Int.toInt((char)ival(stack[head]));
break;
}
case Opcodes.I2B: {
stack[head] = Int.toInt((byte)ival(stack[head]));
break;
}
case Opcodes.I2S: {
stack[head] = Int.toInt((short)ival(stack[head]));
break;
}
//INTEGER ARITHMETICS
case Opcodes.IADD: {
head--;
stack[head] = Ival(ival(stack[head]) + ival(stack[head+1]));
break;
}
case Opcodes.ISUB: {
head--;
stack[head] = Ival(ival(stack[head]) - ival(stack[head+1]));
break;
}
case Opcodes.IMUL: {
head--;
stack[head] = Ival(ival(stack[head]) * ival(stack[head+1]));
break;
}
case Opcodes.IDIV: {
head--;
stack[head] = Ival(ival(stack[head]) / ival(stack[head+1]));
break;
}
case Opcodes.IMOD: {
head--;
stack[head] = Ival(ival(stack[head]) % ival(stack[head+1]));
break;
}
case Opcodes.INEG: {
stack[head] = Ival(-ival(stack[head]));
break;
}
case Opcodes.ICMP: {
head--;
int itmp = ival(stack[head]) - ival(stack[head+1]);
stack[head] = (itmp > 0) ? Int.ONE : (itmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.ISHL: {
head--;
stack[head] = Ival(ival(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.ISHR: {
head--;
stack[head] = Ival(ival(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.IUSHR: {
head--;
stack[head] = Ival(ival(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.IAND: {
head--;
stack[head] = Ival(ival(stack[head]) & ival(stack[head+1]));
break;
}
case Opcodes.IOR: {
head--;
stack[head] = Ival(ival(stack[head]) | ival(stack[head+1]));
break;
}
case Opcodes.IXOR: {
head--;
stack[head] = Ival(ival(stack[head]) ^ ival(stack[head+1]));
break;
}
//LONG ARITHMETICS
case Opcodes.LADD: {
head--;
stack[head] = Lval(lval(stack[head]) + lval(stack[head+1]));
break;
}
case Opcodes.LSUB: {
head--;
stack[head] = Lval(lval(stack[head]) - lval(stack[head+1]));
break;
}
case Opcodes.LMUL: {
head--;
stack[head] = Lval(lval(stack[head]) * lval(stack[head+1]));
break;
}
case Opcodes.LDIV: {
head--;
stack[head] = Lval(lval(stack[head]) / lval(stack[head+1]));
break;
}
case Opcodes.LMOD: {
head--;
stack[head] = Lval(lval(stack[head]) % lval(stack[head+1]));
break;
}
case Opcodes.LNEG: {
stack[head] = Lval(-lval(stack[head]));
break;
}
case Opcodes.LCMP: {
head--;
long ltmp = lval(stack[head]) - lval(stack[head+1]);
stack[head] = (ltmp > 0L) ? Int.ONE : (ltmp == 0L ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.LSHL: {
head--;
stack[head] = Lval(lval(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.LSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.LUSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.LAND: {
head--;
stack[head] = Lval(lval(stack[head]) & lval(stack[head+1]));
break;
}
case Opcodes.LOR: {
head--;
stack[head] = Lval(lval(stack[head]) | lval(stack[head+1]));
break;
}
case Opcodes.LXOR: {
head--;
stack[head] = Lval(lval(stack[head]) ^ lval(stack[head+1]));
break;
}
//FLOAT ARITHMETICS
case Opcodes.FADD: {
head--;
stack[head] = Fval(fval(stack[head]) + fval(stack[head+1]));
break;
}
case Opcodes.FSUB: {
head--;
stack[head] = Fval(fval(stack[head]) - fval(stack[head+1]));
break;
}
case Opcodes.FMUL: {
head--;
stack[head] = Fval(fval(stack[head]) * fval(stack[head+1]));
break;
}
case Opcodes.FDIV: {
head--;
stack[head] = Fval(fval(stack[head]) / fval(stack[head+1]));
break;
}
case Opcodes.FMOD: {
head--;
stack[head] = Fval(fval(stack[head]) % fval(stack[head+1]));
break;
}
case Opcodes.FNEG: {
stack[head] = Fval(-fval(stack[head]));
break;
}
case Opcodes.FCMP: {
head--;
float ftmp = fval(stack[head]) - fval(stack[head+1]);
stack[head] = (ftmp > 0) ? Int.ONE : (ftmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//DOUBLE ARITHMETICS
case Opcodes.DADD: {
head--;
stack[head] = Dval(dval(stack[head]) + dval(stack[head+1]));
break;
}
case Opcodes.DSUB: {
head--;
stack[head] = Dval(dval(stack[head]) - dval(stack[head+1]));
break;
}
case Opcodes.DMUL: {
head--;
stack[head] = Dval(dval(stack[head]) * dval(stack[head+1]));
break;
}
case Opcodes.DDIV: {
head--;
stack[head] = Dval(dval(stack[head]) / dval(stack[head+1]));
break;
}
case Opcodes.DMOD: {
head--;
stack[head] = Dval(dval(stack[head]) % dval(stack[head+1]));
break;
}
case Opcodes.DNEG: {
stack[head] = Dval(-dval(stack[head]));
break;
}
case Opcodes.DCMP: {
head--;
double dtmp = dval(stack[head]) - dval(stack[head+1]);
stack[head] = (dtmp > 0) ? Int.ONE : (dtmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//LOCALS LOADERS AND SAVERS
case Opcodes.LOAD_0:
case Opcodes.LOAD_1:
case Opcodes.LOAD_2:
case Opcodes.LOAD_3:
case Opcodes.LOAD_4:
case Opcodes.LOAD_5:
case Opcodes.LOAD_6:
case Opcodes.LOAD_7: {
head++;
stack[head] = locals[instr & 7];
break;
}
case Opcodes.LOAD: { //load <ubyte>
head++;
stack[head] = locals[code[ct] & 0xff];
ct++;
break;
}
//variable savers
case Opcodes.STORE_0:
case Opcodes.STORE_1:
case Opcodes.STORE_2:
case Opcodes.STORE_3:
case Opcodes.STORE_4:
case Opcodes.STORE_5:
case Opcodes.STORE_6:
case Opcodes.STORE_7: {
locals[instr & 7] = stack[head];
head--;
break;
}
case Opcodes.STORE: { //store <ubyte>
locals[code[ct] & 0xff] = stack[head];
ct++;
head--;
break;
}
//BRANCHING
case Opcodes.IFEQ: { //ifeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) == 0) ct = itmp;
head--;
break;
}
case Opcodes.IFNE: { //ifne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) != 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLT: { //iflt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) < 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGE: { //ifge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) >= 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGT: { //ifgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) > 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLE: { //ifle <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) <= 0) ct = itmp;
head--;
break;
}
case Opcodes.GOTO: { //goto <ushort>
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.IFNULL: { //ifnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] == null) ct = itmp;
head--;
break;
}
case Opcodes.IFNNULL: { //ifnnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] != null) ct = itmp;
head--;
break;
}
case Opcodes.IF_ICMPLT: { //if_icmplt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) < ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGE: { //if_icmpge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) >= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGT: { //if_icmpgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) > ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPLE: { //if_icmple <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) <= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPEQ: { //if_acmpeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? stack[head-1].equals(stack[head])
: stack[head] == null) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPNE: { //if_acmpne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? !stack[head-1].equals(stack[head])
: stack[head] != null) ct = itmp;
head -= 2;
break;
}
case Opcodes.JSR: { //jsr <ushort>
head++;
stack[head] = Ival(ct+2);
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.RET: { //ret
ct = ival(stack[head]);
head--;
break;
}
//FUNCTION CALLS
case Opcodes.CALL_0:
case Opcodes.CALL_1:
case Opcodes.CALL_2:
case Opcodes.CALL_3:
case Opcodes.CALL_4:
case Opcodes.CALL_5:
case Opcodes.CALL_6:
case Opcodes.CALL_7:
case Opcodes.CALV_0:
case Opcodes.CALV_1:
case Opcodes.CALV_2:
case Opcodes.CALV_3:
case Opcodes.CALV_4:
case Opcodes.CALV_5:
case Opcodes.CALV_6:
case Opcodes.CALV_7: {
int paramlen = instr & 7;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
if ((instr & 8) != 0) head--;
break;
}
case Opcodes.CALL: {//call <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
break;
}
case Opcodes.CALV: {//calv <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
((Function)stack[head]).exec(c, params);
head--;
break;
}
//ARRAY INSTRUCTIONS
case Opcodes.NEWAA: {
stack[head] = new Object[ival(stack[head])];
break;
}
case Opcodes.NEWBA: {
stack[head] = new byte[ival(stack[head])];
break;
}
case Opcodes.NEWCA: {
stack[head] = new char[ival(stack[head])];
break;
}
case Opcodes.NEWZA: {
stack[head] = new boolean[ival(stack[head])];
break;
}
case Opcodes.NEWSA: {
stack[head] = new short[ival(stack[head])];
break;
}
case Opcodes.NEWIA: {
stack[head] = new int[ival(stack[head])];
break;
}
case Opcodes.NEWLA: {
stack[head] = new long[ival(stack[head])];
break;
}
case Opcodes.NEWFA: {
stack[head] = new float[ival(stack[head])];
break;
}
case Opcodes.NEWDA: {
stack[head] = new double[ival(stack[head])];
break;
}
case Opcodes.AALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = ((Object[])stack[head])[at];
break;
}
case Opcodes.BALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((byte[])stack[head])[at] );
break;
}
case Opcodes.CALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((char[])stack[head])[at] );
break;
}
case Opcodes.ZALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((boolean[])stack[head])[at] );
break;
}
case Opcodes.SALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((short[])stack[head])[at] );
break;
}
case Opcodes.IALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((int[])stack[head])[at] );
break;
}
case Opcodes.LALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Lval( ((long[])stack[head])[at] );
break;
}
case Opcodes.FALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Fval( ((float[])stack[head])[at] );
break;
}
case Opcodes.DALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Dval( ((double[])stack[head])[at] );
break;
}
case Opcodes.AASTORE: {
Object val = stack[head];
int at = ival(stack[head-1]);
Object[] array = (Object[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.BASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
byte[] array = (byte[])stack[head-2];
array[at] = (byte)val;
head -= 3;
break;
}
case Opcodes.CASTORE: {
char val = (char) ival(stack[head]);
int at = ival(stack[head-1]);
char[] array = (char[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.ZASTORE: {
boolean val = bval(stack[head]);
int at = ival(stack[head-1]);
boolean[] array = (boolean[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.SASTORE: {
short val = (short)ival(stack[head]);
int at = ival(stack[head-1]);
short[] array = (short[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.IASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
int[] array = (int[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.FASTORE: {
float val = fval(stack[head]);
int at = ival(stack[head-1]);
float[] array = (float[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.DASTORE: {
double val = dval(stack[head]);
int at = ival(stack[head-1]);
double[] array = (double[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.AALEN: {
stack[head] = Ival(((Object[])stack[head]).length);
break;
}
case Opcodes.BALEN: {
stack[head] = Ival(((byte[])stack[head]).length);
break;
}
case Opcodes.CALEN: {
stack[head] = Ival(((char[])stack[head]).length);
break;
}
case Opcodes.ZALEN: {
stack[head] = Ival(((boolean[])stack[head]).length);
break;
}
case Opcodes.SALEN: {
stack[head] = Ival(((short[])stack[head]).length);
break;
}
case Opcodes.IALEN: {
stack[head] = Ival(((int[])stack[head]).length);
break;
}
case Opcodes.LALEN: {
stack[head] = Ival(((long[])stack[head]).length);
break;
}
case Opcodes.FALEN: {
stack[head] = Ival(((float[])stack[head]).length);
break;
}
case Opcodes.DALEN: {
stack[head] = Ival(((double[])stack[head]).length);
break;
}
//SWITCH BRANCHING
case Opcodes.TABLESWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int min = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int max = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int val = ival(stack[head]);
head--;
if (val >= min && val <= max) {
ct += (val-min)*2;
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
} else {
ct = dflt;
}
break;
}
case Opcodes.LOOKUPSWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int count = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int val = ival(stack[head]);
head--;
boolean matched = false;
for (int i=0; i<count && !matched; i++) {
int cand = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
if (val == cand) {
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
matched = true;
} else {
ct += 2;
}
}
if (!matched) ct = dflt;
break;
}
//OTHERS
case Opcodes.ACMP: {
head--;
boolean eq = (stack[head] == null) ? stack[head+1] == null : stack[head].equals(stack[head+1]);
stack[head] = Ival(!eq);
break;
}
case Opcodes.RET_NULL:
return null;
case Opcodes.RETURN:
return stack[head];
case Opcodes.DUP: {
stack[head+1] = stack[head];
head++;
break;
}
case Opcodes.DUP2: {
stack[head+2] = stack[head];
stack[head+1] = stack[head-1];
head += 2;
break;
}
case Opcodes.SWAP: {
Object atmp = stack[head-1];
stack[head-1] = stack[head];
stack[head] = atmp;
break;
}
case Opcodes.LDC: { //ldc <ushort>
head++;
stack[head] = cpool[((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff)];
ct += 2;
break;
}
case Opcodes.POP: {
head--;
break;
}
case Opcodes.BIPUSH: { //bipush <byte>
head++;
stack[head] = Ival(code[ct]);
ct++;
break;
}
case Opcodes.SIPUSH: { //sipush <short>
head++;
stack[head] = Ival((code[ct] << 8) | (code[ct+1]& 0xff));
ct += 2;
break;
}
case Opcodes.IINC: { //iinc <ubyte> <byte>
int idx = code[ct] & 0xff;
ct++;
int inc = code[ct] & 0xff;
ct++;
locals[idx] = Int.toInt(((Int)locals[idx]).value + inc);
}
} /* the big switch */
} catch (Throwable e) {
// the instruction on which error occured
ct--;
// filling exception with debug info
AlchemyException ae = (e instanceof AlchemyException) ? (AlchemyException)e : new AlchemyException(e);
if (dbgtable != null) {
int srcline = 0;
for (int i=1; i<dbgtable.length; i += 2) {
if (dbgtable[i+1] <= ct) srcline = dbgtable[i];
}
ae.addTraceElement(this, cpool[dbgtable[0]]+":"+srcline);
} else {
ae.addTraceElement(this, "+"+ct);
}
// catching or rethrowing
int jumpto = -1;
if (errtable != null) {
for (int i=0; i < errtable.length && jumpto < 0; i += 4)
if (ct >= errtable[i] && ct <= errtable[i+1]) {
jumpto = errtable[i+2];
head = errtable[i+3];
}
}
if (jumpto >= 0) {
stack[head] = ae;
ct = jumpto;
} else {
throw ae;
}
}
} /* the great while */
}
| public Object exec(Context c, Object[] args) throws AlchemyException {
//initializing
final Object[] stack = new Object[stacksize];
int head = -1;
final byte[] code = this.bcode;
Object[] locals;
if (args.length == localsize) {
locals = args;
} else {
locals = new Object[localsize];
System.arraycopy(args, 0, locals, 0, args.length);
}
int ct = 0;
while (true) {
try {
int instr = code[ct];
ct++;
switch (instr) {
// CONSTANTS
case Opcodes.ACONST_NULL: {
head++;
stack[head] = null;
break;
}
case Opcodes.ICONST_M1: {
head++;
stack[head] = Int.M_ONE;
break;
}
case Opcodes.ICONST_0: {
head++;
stack[head] = Int.ZERO;
break;
}
case Opcodes.ICONST_1: {
head++;
stack[head] = Int.ONE;
break;
}
case Opcodes.ICONST_2: {
head++;
stack[head] = Int.toInt(2);
break;
}
case Opcodes.ICONST_3: {
head++;
stack[head] = Int.toInt(3);
break;
}
case Opcodes.ICONST_4: {
head++;
stack[head] = Int.toInt(4);
break;
}
case Opcodes.ICONST_5: {
head++;
stack[head] = Int.toInt(5);
break;
}
case Opcodes.LCONST_0: {
head++;
stack[head] = Lval(0l);
break;
}
case Opcodes.LCONST_1: {
head++;
stack[head] = Lval(1l);
break;
}
case Opcodes.FCONST_0: {
head++;
stack[head] = Fval(0f);
break;
}
case Opcodes.FCONST_1: {
head++;
stack[head] = Fval(1f);
break;
}
case Opcodes.FCONST_2: {
head++;
stack[head] = Fval(2f);
break;
}
case Opcodes.DCONST_0: {
head++;
stack[head] = Dval(0d);
break;
}
case Opcodes.DCONST_1: {
head++;
stack[head] = Dval(1d);
break;
}
//CONVERSIONS
case Opcodes.I2L: {
stack[head] = Lval(ival(stack[head]));
break;
}
case Opcodes.I2F: {
stack[head] = Fval(ival(stack[head]));
break;
}
case Opcodes.I2D: {
stack[head] = Dval(ival(stack[head]));
break;
}
case Opcodes.L2F: {
stack[head] = Fval(lval(stack[head]));
break;
}
case Opcodes.L2D: {
stack[head] = Dval(lval(stack[head]));
break;
}
case Opcodes.L2I: {
stack[head] = Ival((int)lval(stack[head]));
break;
}
case Opcodes.F2D: {
stack[head] = Dval(fval(stack[head]));
break;
}
case Opcodes.F2I: {
stack[head] = Ival((int)fval(stack[head]));
break;
}
case Opcodes.F2L: {
stack[head] = Lval((long)fval(stack[head]));
break;
}
case Opcodes.D2I: {
stack[head] = Ival((int)dval(stack[head]));
break;
}
case Opcodes.D2L: {
stack[head] = Lval((long)dval(stack[head]));
break;
}
case Opcodes.D2F: {
stack[head] = Fval((float)dval(stack[head]));
break;
}
case Opcodes.I2C: {
stack[head] = Int.toInt((char)ival(stack[head]));
break;
}
case Opcodes.I2B: {
stack[head] = Int.toInt((byte)ival(stack[head]));
break;
}
case Opcodes.I2S: {
stack[head] = Int.toInt((short)ival(stack[head]));
break;
}
//INTEGER ARITHMETICS
case Opcodes.IADD: {
head--;
stack[head] = Ival(ival(stack[head]) + ival(stack[head+1]));
break;
}
case Opcodes.ISUB: {
head--;
stack[head] = Ival(ival(stack[head]) - ival(stack[head+1]));
break;
}
case Opcodes.IMUL: {
head--;
stack[head] = Ival(ival(stack[head]) * ival(stack[head+1]));
break;
}
case Opcodes.IDIV: {
head--;
stack[head] = Ival(ival(stack[head]) / ival(stack[head+1]));
break;
}
case Opcodes.IMOD: {
head--;
stack[head] = Ival(ival(stack[head]) % ival(stack[head+1]));
break;
}
case Opcodes.INEG: {
stack[head] = Ival(-ival(stack[head]));
break;
}
case Opcodes.ICMP: {
head--;
int itmp = ival(stack[head]) - ival(stack[head+1]);
stack[head] = (itmp > 0) ? Int.ONE : (itmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.ISHL: {
head--;
stack[head] = Ival(ival(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.ISHR: {
head--;
stack[head] = Ival(ival(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.IUSHR: {
head--;
stack[head] = Ival(ival(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.IAND: {
head--;
stack[head] = Ival(ival(stack[head]) & ival(stack[head+1]));
break;
}
case Opcodes.IOR: {
head--;
stack[head] = Ival(ival(stack[head]) | ival(stack[head+1]));
break;
}
case Opcodes.IXOR: {
head--;
stack[head] = Ival(ival(stack[head]) ^ ival(stack[head+1]));
break;
}
//LONG ARITHMETICS
case Opcodes.LADD: {
head--;
stack[head] = Lval(lval(stack[head]) + lval(stack[head+1]));
break;
}
case Opcodes.LSUB: {
head--;
stack[head] = Lval(lval(stack[head]) - lval(stack[head+1]));
break;
}
case Opcodes.LMUL: {
head--;
stack[head] = Lval(lval(stack[head]) * lval(stack[head+1]));
break;
}
case Opcodes.LDIV: {
head--;
stack[head] = Lval(lval(stack[head]) / lval(stack[head+1]));
break;
}
case Opcodes.LMOD: {
head--;
stack[head] = Lval(lval(stack[head]) % lval(stack[head+1]));
break;
}
case Opcodes.LNEG: {
stack[head] = Lval(-lval(stack[head]));
break;
}
case Opcodes.LCMP: {
head--;
long ltmp = lval(stack[head]) - lval(stack[head+1]);
stack[head] = (ltmp > 0L) ? Int.ONE : (ltmp == 0L ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.LSHL: {
head--;
stack[head] = Lval(lval(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.LSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.LUSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.LAND: {
head--;
stack[head] = Lval(lval(stack[head]) & lval(stack[head+1]));
break;
}
case Opcodes.LOR: {
head--;
stack[head] = Lval(lval(stack[head]) | lval(stack[head+1]));
break;
}
case Opcodes.LXOR: {
head--;
stack[head] = Lval(lval(stack[head]) ^ lval(stack[head+1]));
break;
}
//FLOAT ARITHMETICS
case Opcodes.FADD: {
head--;
stack[head] = Fval(fval(stack[head]) + fval(stack[head+1]));
break;
}
case Opcodes.FSUB: {
head--;
stack[head] = Fval(fval(stack[head]) - fval(stack[head+1]));
break;
}
case Opcodes.FMUL: {
head--;
stack[head] = Fval(fval(stack[head]) * fval(stack[head+1]));
break;
}
case Opcodes.FDIV: {
head--;
stack[head] = Fval(fval(stack[head]) / fval(stack[head+1]));
break;
}
case Opcodes.FMOD: {
head--;
stack[head] = Fval(fval(stack[head]) % fval(stack[head+1]));
break;
}
case Opcodes.FNEG: {
stack[head] = Fval(-fval(stack[head]));
break;
}
case Opcodes.FCMP: {
head--;
float ftmp = fval(stack[head]) - fval(stack[head+1]);
stack[head] = (ftmp > 0) ? Int.ONE : (ftmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//DOUBLE ARITHMETICS
case Opcodes.DADD: {
head--;
stack[head] = Dval(dval(stack[head]) + dval(stack[head+1]));
break;
}
case Opcodes.DSUB: {
head--;
stack[head] = Dval(dval(stack[head]) - dval(stack[head+1]));
break;
}
case Opcodes.DMUL: {
head--;
stack[head] = Dval(dval(stack[head]) * dval(stack[head+1]));
break;
}
case Opcodes.DDIV: {
head--;
stack[head] = Dval(dval(stack[head]) / dval(stack[head+1]));
break;
}
case Opcodes.DMOD: {
head--;
stack[head] = Dval(dval(stack[head]) % dval(stack[head+1]));
break;
}
case Opcodes.DNEG: {
stack[head] = Dval(-dval(stack[head]));
break;
}
case Opcodes.DCMP: {
head--;
double dtmp = dval(stack[head]) - dval(stack[head+1]);
stack[head] = (dtmp > 0) ? Int.ONE : (dtmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//LOCALS LOADERS AND SAVERS
case Opcodes.LOAD_0:
case Opcodes.LOAD_1:
case Opcodes.LOAD_2:
case Opcodes.LOAD_3:
case Opcodes.LOAD_4:
case Opcodes.LOAD_5:
case Opcodes.LOAD_6:
case Opcodes.LOAD_7: {
head++;
stack[head] = locals[instr & 7];
break;
}
case Opcodes.LOAD: { //load <ubyte>
head++;
stack[head] = locals[code[ct] & 0xff];
ct++;
break;
}
//variable savers
case Opcodes.STORE_0:
case Opcodes.STORE_1:
case Opcodes.STORE_2:
case Opcodes.STORE_3:
case Opcodes.STORE_4:
case Opcodes.STORE_5:
case Opcodes.STORE_6:
case Opcodes.STORE_7: {
locals[instr & 7] = stack[head];
head--;
break;
}
case Opcodes.STORE: { //store <ubyte>
locals[code[ct] & 0xff] = stack[head];
ct++;
head--;
break;
}
//BRANCHING
case Opcodes.IFEQ: { //ifeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) == 0) ct = itmp;
head--;
break;
}
case Opcodes.IFNE: { //ifne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) != 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLT: { //iflt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) < 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGE: { //ifge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) >= 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGT: { //ifgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) > 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLE: { //ifle <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) <= 0) ct = itmp;
head--;
break;
}
case Opcodes.GOTO: { //goto <ushort>
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.IFNULL: { //ifnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] == null) ct = itmp;
head--;
break;
}
case Opcodes.IFNNULL: { //ifnnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] != null) ct = itmp;
head--;
break;
}
case Opcodes.IF_ICMPLT: { //if_icmplt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) < ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGE: { //if_icmpge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) >= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGT: { //if_icmpgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) > ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPLE: { //if_icmple <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) <= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPEQ: { //if_acmpeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? stack[head-1].equals(stack[head])
: stack[head] == null) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPNE: { //if_acmpne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? !stack[head-1].equals(stack[head])
: stack[head] != null) ct = itmp;
head -= 2;
break;
}
case Opcodes.JSR: { //jsr <ushort>
head++;
stack[head] = Ival(ct+2);
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.RET: { //ret
ct = ival(stack[head]);
head--;
break;
}
//FUNCTION CALLS
case Opcodes.CALL_0:
case Opcodes.CALL_1:
case Opcodes.CALL_2:
case Opcodes.CALL_3:
case Opcodes.CALL_4:
case Opcodes.CALL_5:
case Opcodes.CALL_6:
case Opcodes.CALL_7:
case Opcodes.CALV_0:
case Opcodes.CALV_1:
case Opcodes.CALV_2:
case Opcodes.CALV_3:
case Opcodes.CALV_4:
case Opcodes.CALV_5:
case Opcodes.CALV_6:
case Opcodes.CALV_7: {
int paramlen = instr & 7;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
if ((instr & 8) != 0) head--;
break;
}
case Opcodes.CALL: {//call <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
break;
}
case Opcodes.CALV: {//calv <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
((Function)stack[head]).exec(c, params);
head--;
break;
}
//ARRAY INSTRUCTIONS
case Opcodes.NEWAA: {
stack[head] = new Object[ival(stack[head])];
break;
}
case Opcodes.NEWBA: {
stack[head] = new byte[ival(stack[head])];
break;
}
case Opcodes.NEWCA: {
stack[head] = new char[ival(stack[head])];
break;
}
case Opcodes.NEWZA: {
stack[head] = new boolean[ival(stack[head])];
break;
}
case Opcodes.NEWSA: {
stack[head] = new short[ival(stack[head])];
break;
}
case Opcodes.NEWIA: {
stack[head] = new int[ival(stack[head])];
break;
}
case Opcodes.NEWLA: {
stack[head] = new long[ival(stack[head])];
break;
}
case Opcodes.NEWFA: {
stack[head] = new float[ival(stack[head])];
break;
}
case Opcodes.NEWDA: {
stack[head] = new double[ival(stack[head])];
break;
}
case Opcodes.AALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = ((Object[])stack[head])[at];
break;
}
case Opcodes.BALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((byte[])stack[head])[at] );
break;
}
case Opcodes.CALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((char[])stack[head])[at] );
break;
}
case Opcodes.ZALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((boolean[])stack[head])[at] );
break;
}
case Opcodes.SALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((short[])stack[head])[at] );
break;
}
case Opcodes.IALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((int[])stack[head])[at] );
break;
}
case Opcodes.LALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Lval( ((long[])stack[head])[at] );
break;
}
case Opcodes.FALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Fval( ((float[])stack[head])[at] );
break;
}
case Opcodes.DALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Dval( ((double[])stack[head])[at] );
break;
}
case Opcodes.AASTORE: {
Object val = stack[head];
int at = ival(stack[head-1]);
Object[] array = (Object[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.BASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
byte[] array = (byte[])stack[head-2];
array[at] = (byte)val;
head -= 3;
break;
}
case Opcodes.CASTORE: {
char val = (char) ival(stack[head]);
int at = ival(stack[head-1]);
char[] array = (char[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.ZASTORE: {
boolean val = bval(stack[head]);
int at = ival(stack[head-1]);
boolean[] array = (boolean[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.SASTORE: {
short val = (short)ival(stack[head]);
int at = ival(stack[head-1]);
short[] array = (short[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.IASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
int[] array = (int[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.FASTORE: {
float val = fval(stack[head]);
int at = ival(stack[head-1]);
float[] array = (float[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.DASTORE: {
double val = dval(stack[head]);
int at = ival(stack[head-1]);
double[] array = (double[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.AALEN: {
stack[head] = Ival(((Object[])stack[head]).length);
break;
}
case Opcodes.BALEN: {
stack[head] = Ival(((byte[])stack[head]).length);
break;
}
case Opcodes.CALEN: {
stack[head] = Ival(((char[])stack[head]).length);
break;
}
case Opcodes.ZALEN: {
stack[head] = Ival(((boolean[])stack[head]).length);
break;
}
case Opcodes.SALEN: {
stack[head] = Ival(((short[])stack[head]).length);
break;
}
case Opcodes.IALEN: {
stack[head] = Ival(((int[])stack[head]).length);
break;
}
case Opcodes.LALEN: {
stack[head] = Ival(((long[])stack[head]).length);
break;
}
case Opcodes.FALEN: {
stack[head] = Ival(((float[])stack[head]).length);
break;
}
case Opcodes.DALEN: {
stack[head] = Ival(((double[])stack[head]).length);
break;
}
//SWITCH BRANCHING
case Opcodes.TABLESWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int min = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int max = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int val = ival(stack[head]);
head--;
if (val >= min && val <= max) {
ct += (val-min)*2;
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
} else {
ct = dflt;
}
break;
}
case Opcodes.LOOKUPSWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int count = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int val = ival(stack[head]);
head--;
boolean matched = false;
for (int i=0; i<count && !matched; i++) {
int cand = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
if (val == cand) {
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
matched = true;
} else {
ct += 2;
}
}
if (!matched) ct = dflt;
break;
}
//OTHERS
case Opcodes.ACMP: {
head--;
boolean eq = (stack[head] == null) ? stack[head+1] == null : stack[head].equals(stack[head+1]);
stack[head] = Ival(!eq);
break;
}
case Opcodes.RET_NULL:
return null;
case Opcodes.RETURN:
return stack[head];
case Opcodes.DUP: {
stack[head+1] = stack[head];
head++;
break;
}
case Opcodes.DUP2: {
stack[head+2] = stack[head];
stack[head+1] = stack[head-1];
head += 2;
break;
}
case Opcodes.SWAP: {
Object atmp = stack[head-1];
stack[head-1] = stack[head];
stack[head] = atmp;
break;
}
case Opcodes.LDC: { //ldc <ushort>
head++;
stack[head] = cpool[((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff)];
ct += 2;
break;
}
case Opcodes.POP: {
head--;
break;
}
case Opcodes.BIPUSH: { //bipush <byte>
head++;
stack[head] = Ival(code[ct]);
ct++;
break;
}
case Opcodes.SIPUSH: { //sipush <short>
head++;
stack[head] = Ival((code[ct] << 8) | (code[ct+1]& 0xff));
ct += 2;
break;
}
case Opcodes.IINC: { //iinc <ubyte> <byte>
int idx = code[ct] & 0xff;
ct++;
int inc = code[ct];
ct++;
locals[idx] = Int.toInt(((Int)locals[idx]).value + inc);
}
} /* the big switch */
} catch (Throwable e) {
// the instruction on which error occured
ct--;
// filling exception with debug info
AlchemyException ae = (e instanceof AlchemyException) ? (AlchemyException)e : new AlchemyException(e);
if (dbgtable != null) {
int srcline = 0;
for (int i=1; i<dbgtable.length; i += 2) {
if (dbgtable[i+1] <= ct) srcline = dbgtable[i];
}
ae.addTraceElement(this, cpool[dbgtable[0]]+":"+srcline);
} else {
ae.addTraceElement(this, "+"+ct);
}
// catching or rethrowing
int jumpto = -1;
if (errtable != null) {
for (int i=0; i < errtable.length && jumpto < 0; i += 4)
if (ct >= errtable[i] && ct <= errtable[i+1]) {
jumpto = errtable[i+2];
head = errtable[i+3];
}
}
if (jumpto >= 0) {
stack[head] = ae;
ct = jumpto;
} else {
throw ae;
}
}
} /* the great while */
}
|
diff --git a/portal/src/hot/org/vamdc/portal/session/queryBuilder/forms/TransitionsForm.java b/portal/src/hot/org/vamdc/portal/session/queryBuilder/forms/TransitionsForm.java
index ce17f1b..8ab9cc5 100644
--- a/portal/src/hot/org/vamdc/portal/session/queryBuilder/forms/TransitionsForm.java
+++ b/portal/src/hot/org/vamdc/portal/session/queryBuilder/forms/TransitionsForm.java
@@ -1,36 +1,36 @@
package org.vamdc.portal.session.queryBuilder.forms;
import java.util.ArrayList;
import org.vamdc.dictionary.Restrictable;
import org.vamdc.portal.session.queryBuilder.QueryData;
import org.vamdc.portal.session.queryBuilder.fields.AbstractField;
import org.vamdc.portal.session.queryBuilder.fields.RangeField;
import org.vamdc.portal.session.queryBuilder.fields.UnitConvRangeField;
import org.vamdc.portal.session.queryBuilder.unitConv.EnergyUnitConverter;
public class TransitionsForm extends AbstractForm implements Form{
public String getTitle() { return "Transitions"; }
public Integer getOrder() { return Order.Transitions; }
public String getView() { return "/xhtml/query/forms/standardForm.xhtml"; }
public TransitionsForm(QueryData queryData){
super(queryData);
fields = new ArrayList<AbstractField>();
fields.add(new RangeField(Restrictable.RadTransWavelength,"Wavelength"));
AbstractField field = new UnitConvRangeField(Restrictable.StateEnergy, "Upper state energy", new EnergyUnitConverter());
- field.setPrefix("upper");
+ field.setPrefix("upper.");
fields.add(field);
//fields.add(new RangeField("upper",Restrictable.StateEnergy,"Upper state energy"));
field = new UnitConvRangeField(Restrictable.StateEnergy, "Lower state energy", new EnergyUnitConverter());
- field.setPrefix("lower");
+ field.setPrefix("lower.");
fields.add(field);
//fields.add(new RangeField("lower",Restrictable.StateEnergy,"Lower state energy"));
fields.add(new RangeField(Restrictable.RadTransProbabilityA,"Probability, A"));
}
}
| false | true | public TransitionsForm(QueryData queryData){
super(queryData);
fields = new ArrayList<AbstractField>();
fields.add(new RangeField(Restrictable.RadTransWavelength,"Wavelength"));
AbstractField field = new UnitConvRangeField(Restrictable.StateEnergy, "Upper state energy", new EnergyUnitConverter());
field.setPrefix("upper");
fields.add(field);
//fields.add(new RangeField("upper",Restrictable.StateEnergy,"Upper state energy"));
field = new UnitConvRangeField(Restrictable.StateEnergy, "Lower state energy", new EnergyUnitConverter());
field.setPrefix("lower");
fields.add(field);
//fields.add(new RangeField("lower",Restrictable.StateEnergy,"Lower state energy"));
fields.add(new RangeField(Restrictable.RadTransProbabilityA,"Probability, A"));
}
| public TransitionsForm(QueryData queryData){
super(queryData);
fields = new ArrayList<AbstractField>();
fields.add(new RangeField(Restrictable.RadTransWavelength,"Wavelength"));
AbstractField field = new UnitConvRangeField(Restrictable.StateEnergy, "Upper state energy", new EnergyUnitConverter());
field.setPrefix("upper.");
fields.add(field);
//fields.add(new RangeField("upper",Restrictable.StateEnergy,"Upper state energy"));
field = new UnitConvRangeField(Restrictable.StateEnergy, "Lower state energy", new EnergyUnitConverter());
field.setPrefix("lower.");
fields.add(field);
//fields.add(new RangeField("lower",Restrictable.StateEnergy,"Lower state energy"));
fields.add(new RangeField(Restrictable.RadTransProbabilityA,"Probability, A"));
}
|
diff --git a/src/org/rascalmpl/interpreter/Typeifier.java b/src/org/rascalmpl/interpreter/Typeifier.java
index a5b672e301..aa571d50ba 100644
--- a/src/org/rascalmpl/interpreter/Typeifier.java
+++ b/src/org/rascalmpl/interpreter/Typeifier.java
@@ -1,244 +1,246 @@
package org.rascalmpl.interpreter;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IList;
import org.eclipse.imp.pdb.facts.IString;
import org.eclipse.imp.pdb.facts.ITuple;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.type.ITypeVisitor;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.eclipse.imp.pdb.facts.type.TypeStore;
import org.rascalmpl.interpreter.asserts.ImplementationError;
import org.rascalmpl.interpreter.types.ReifiedType;
/**
* This class helps transforming reified types back to types and to extract type
* declarations from reified types.
*
* See also {@link TypeReifier}.
*/
public class Typeifier {
private Typeifier(){
super();
}
/**
* Retrieve the type that is reified by the given value
*
* @param typeValue a reified type value produced by {@link TypeReifier}.
* @return the plain Type that typeValue represented
*/
public static Type toType(IConstructor typeValue) {
Type anonymous = typeValue.getType();
if (anonymous instanceof ReifiedType) {
ReifiedType reified = (ReifiedType) anonymous;
return reified.getTypeParameters().getFieldType(0);
}
throw new UnsupportedOperationException("Not a reified type: " + typeValue.getType());
}
/**
* Locate all declared types in a reified type value, such as abstract data types
* constructors and aliases and stores them in the given TypeStore.
*
* @param typeValue a reified type which is produced by {@link TypeReifier}
* @param store a TypeStore to collect declarations in
* @return the plain Type that typeValue represented
*/
public static Type declare(IConstructor typeValue, final TypeStore store) {
final List<IConstructor> todo = new LinkedList<IConstructor>();
todo.add(typeValue);
while (!todo.isEmpty()) {
final IConstructor next = todo.get(0); todo.remove(0);
Type type = toType(next);
// We dispatch on the real type which is isomorphic to the typeValue.
type.accept(new ITypeVisitor<Type>() {
private final TypeFactory tf = TypeFactory.getInstance();
public Type visitAbstractData(Type type) {
Type formal = declareADT(next);
declareConstructors(formal, next);
declareADTParameters(next);
return type;
}
public Type visitAlias(Type type) {
IConstructor aliased = getAliased(next);
todo.add(aliased);
// TODO: type parameterized aliases are broken still
declareAliasParameters(aliased);
return type;
}
public Type visitBool(Type boolType) {
return boolType;
}
public Type visitConstructor(Type type) {
throw new ImplementationError("should not have to typeify this: " + type);
}
public Type visitExternal(Type externalType) {
throw new ImplementationError("should not have to typeify this: " + externalType);
}
public Type visitInteger(Type type) {
return type;
}
public Type visitNumber(Type type) {
return type;
}
public Type visitList(Type type) {
todo.add(getElement(next));
return type;
}
public Type visitMap(Type type) {
todo.add(getKey(next));
todo.add(getValue(next));
return type;
}
public Type visitNode(Type type) {
return type;
}
public Type visitParameter(Type parameterType) {
return parameterType;
}
public Type visitReal(Type type) {
return type;
}
public Type visitRelationType(Type type) {
- for (IValue child : next) {
- todo.add((IConstructor) child);
+ IList fields = (IList) next.get("fields");
+ for (IValue child : fields) {
+ ITuple field = (ITuple) child;
+ todo.add((IConstructor) field.get(0));
}
return type;
}
public Type visitSet(Type type) {
todo.add(getElement(next));
return type;
}
public Type visitSourceLocation(Type type) {
return type;
}
public Type visitString(Type type) {
return type;
}
public Type visitTuple(Type type) {
for (IValue child : (IList) next.get(0)) {
todo.add((IConstructor) child);
}
return type;
}
public Type visitValue(Type type) {
return type;
}
public Type visitVoid(Type type) {
return type;
}
public Type visitDateTime(Type type) {
return type;
}
private Type declareADT(IConstructor next) {
IString name = (IString) next.get("name");
IList bindings = (IList) next.get("bindings");
Type[] parameters = new Type[bindings.length()];
int i = 0;
for (IValue elem : bindings) {
ITuple tuple = (ITuple) elem;
parameters[i++] = toType((IConstructor) tuple.get(0));
}
return tf.abstractDataType(store, name.getValue(), parameters);
}
private void declareADTParameters(IConstructor next) {
IList bindings = (IList) next.get("bindings");
for (IValue elem : bindings) {
ITuple tuple = (ITuple) elem;
declare((IConstructor) tuple.get(1), store);
}
}
private void declareAliasParameters(IConstructor next) {
if (next.has("parameters")) {
for (IValue p : ((IList) next.get("parameters"))) {
todo.add((IConstructor) p);
}
}
}
private void declareConstructors(Type adt, IConstructor next) {
IList constructors = getConstructors(next);
for (IValue c : constructors) {
IConstructor cons = (IConstructor) c;
IList fields = (IList) cons.get(1);
String name = getName(cons);
Object[] args = new Object[fields.length() * 2];
int i = 0;
for (IValue field : fields) {
ITuple tuple = (ITuple) field;
IConstructor fieldType = (IConstructor) tuple.get(0);
todo.add(fieldType);
args[i++] = toType(fieldType);
args[i++] = ((IString) tuple.get(1)).getValue();
}
tf.constructor(store, adt, name, args);
}
}
private IConstructor getElement(IConstructor next) {
return (IConstructor) next.get("element");
}
private String getName(final IConstructor next) {
return ((IString) next.get("name")).getValue();
}
private IConstructor getValue(IConstructor next) {
return (IConstructor) next.get("key");
}
private IConstructor getAliased(IConstructor next) {
return (IConstructor) next.get("aliased");
}
private IConstructor getKey(IConstructor next) {
return (IConstructor) next.get("value");
}
private IList getConstructors(IConstructor next) {
return (IList) next.get("constructors");
}
});
}
return toType(typeValue);
}
}
| true | true | public static Type declare(IConstructor typeValue, final TypeStore store) {
final List<IConstructor> todo = new LinkedList<IConstructor>();
todo.add(typeValue);
while (!todo.isEmpty()) {
final IConstructor next = todo.get(0); todo.remove(0);
Type type = toType(next);
// We dispatch on the real type which is isomorphic to the typeValue.
type.accept(new ITypeVisitor<Type>() {
private final TypeFactory tf = TypeFactory.getInstance();
public Type visitAbstractData(Type type) {
Type formal = declareADT(next);
declareConstructors(formal, next);
declareADTParameters(next);
return type;
}
public Type visitAlias(Type type) {
IConstructor aliased = getAliased(next);
todo.add(aliased);
// TODO: type parameterized aliases are broken still
declareAliasParameters(aliased);
return type;
}
public Type visitBool(Type boolType) {
return boolType;
}
public Type visitConstructor(Type type) {
throw new ImplementationError("should not have to typeify this: " + type);
}
public Type visitExternal(Type externalType) {
throw new ImplementationError("should not have to typeify this: " + externalType);
}
public Type visitInteger(Type type) {
return type;
}
public Type visitNumber(Type type) {
return type;
}
public Type visitList(Type type) {
todo.add(getElement(next));
return type;
}
public Type visitMap(Type type) {
todo.add(getKey(next));
todo.add(getValue(next));
return type;
}
public Type visitNode(Type type) {
return type;
}
public Type visitParameter(Type parameterType) {
return parameterType;
}
public Type visitReal(Type type) {
return type;
}
public Type visitRelationType(Type type) {
for (IValue child : next) {
todo.add((IConstructor) child);
}
return type;
}
public Type visitSet(Type type) {
todo.add(getElement(next));
return type;
}
public Type visitSourceLocation(Type type) {
return type;
}
public Type visitString(Type type) {
return type;
}
public Type visitTuple(Type type) {
for (IValue child : (IList) next.get(0)) {
todo.add((IConstructor) child);
}
return type;
}
public Type visitValue(Type type) {
return type;
}
public Type visitVoid(Type type) {
return type;
}
public Type visitDateTime(Type type) {
return type;
}
private Type declareADT(IConstructor next) {
IString name = (IString) next.get("name");
IList bindings = (IList) next.get("bindings");
Type[] parameters = new Type[bindings.length()];
int i = 0;
for (IValue elem : bindings) {
ITuple tuple = (ITuple) elem;
parameters[i++] = toType((IConstructor) tuple.get(0));
}
return tf.abstractDataType(store, name.getValue(), parameters);
}
private void declareADTParameters(IConstructor next) {
IList bindings = (IList) next.get("bindings");
for (IValue elem : bindings) {
ITuple tuple = (ITuple) elem;
declare((IConstructor) tuple.get(1), store);
}
}
private void declareAliasParameters(IConstructor next) {
if (next.has("parameters")) {
for (IValue p : ((IList) next.get("parameters"))) {
todo.add((IConstructor) p);
}
}
}
private void declareConstructors(Type adt, IConstructor next) {
IList constructors = getConstructors(next);
for (IValue c : constructors) {
IConstructor cons = (IConstructor) c;
IList fields = (IList) cons.get(1);
String name = getName(cons);
Object[] args = new Object[fields.length() * 2];
int i = 0;
for (IValue field : fields) {
ITuple tuple = (ITuple) field;
IConstructor fieldType = (IConstructor) tuple.get(0);
todo.add(fieldType);
args[i++] = toType(fieldType);
args[i++] = ((IString) tuple.get(1)).getValue();
}
tf.constructor(store, adt, name, args);
}
}
private IConstructor getElement(IConstructor next) {
return (IConstructor) next.get("element");
}
private String getName(final IConstructor next) {
return ((IString) next.get("name")).getValue();
}
private IConstructor getValue(IConstructor next) {
return (IConstructor) next.get("key");
}
private IConstructor getAliased(IConstructor next) {
return (IConstructor) next.get("aliased");
}
private IConstructor getKey(IConstructor next) {
return (IConstructor) next.get("value");
}
private IList getConstructors(IConstructor next) {
return (IList) next.get("constructors");
}
});
}
return toType(typeValue);
}
| public static Type declare(IConstructor typeValue, final TypeStore store) {
final List<IConstructor> todo = new LinkedList<IConstructor>();
todo.add(typeValue);
while (!todo.isEmpty()) {
final IConstructor next = todo.get(0); todo.remove(0);
Type type = toType(next);
// We dispatch on the real type which is isomorphic to the typeValue.
type.accept(new ITypeVisitor<Type>() {
private final TypeFactory tf = TypeFactory.getInstance();
public Type visitAbstractData(Type type) {
Type formal = declareADT(next);
declareConstructors(formal, next);
declareADTParameters(next);
return type;
}
public Type visitAlias(Type type) {
IConstructor aliased = getAliased(next);
todo.add(aliased);
// TODO: type parameterized aliases are broken still
declareAliasParameters(aliased);
return type;
}
public Type visitBool(Type boolType) {
return boolType;
}
public Type visitConstructor(Type type) {
throw new ImplementationError("should not have to typeify this: " + type);
}
public Type visitExternal(Type externalType) {
throw new ImplementationError("should not have to typeify this: " + externalType);
}
public Type visitInteger(Type type) {
return type;
}
public Type visitNumber(Type type) {
return type;
}
public Type visitList(Type type) {
todo.add(getElement(next));
return type;
}
public Type visitMap(Type type) {
todo.add(getKey(next));
todo.add(getValue(next));
return type;
}
public Type visitNode(Type type) {
return type;
}
public Type visitParameter(Type parameterType) {
return parameterType;
}
public Type visitReal(Type type) {
return type;
}
public Type visitRelationType(Type type) {
IList fields = (IList) next.get("fields");
for (IValue child : fields) {
ITuple field = (ITuple) child;
todo.add((IConstructor) field.get(0));
}
return type;
}
public Type visitSet(Type type) {
todo.add(getElement(next));
return type;
}
public Type visitSourceLocation(Type type) {
return type;
}
public Type visitString(Type type) {
return type;
}
public Type visitTuple(Type type) {
for (IValue child : (IList) next.get(0)) {
todo.add((IConstructor) child);
}
return type;
}
public Type visitValue(Type type) {
return type;
}
public Type visitVoid(Type type) {
return type;
}
public Type visitDateTime(Type type) {
return type;
}
private Type declareADT(IConstructor next) {
IString name = (IString) next.get("name");
IList bindings = (IList) next.get("bindings");
Type[] parameters = new Type[bindings.length()];
int i = 0;
for (IValue elem : bindings) {
ITuple tuple = (ITuple) elem;
parameters[i++] = toType((IConstructor) tuple.get(0));
}
return tf.abstractDataType(store, name.getValue(), parameters);
}
private void declareADTParameters(IConstructor next) {
IList bindings = (IList) next.get("bindings");
for (IValue elem : bindings) {
ITuple tuple = (ITuple) elem;
declare((IConstructor) tuple.get(1), store);
}
}
private void declareAliasParameters(IConstructor next) {
if (next.has("parameters")) {
for (IValue p : ((IList) next.get("parameters"))) {
todo.add((IConstructor) p);
}
}
}
private void declareConstructors(Type adt, IConstructor next) {
IList constructors = getConstructors(next);
for (IValue c : constructors) {
IConstructor cons = (IConstructor) c;
IList fields = (IList) cons.get(1);
String name = getName(cons);
Object[] args = new Object[fields.length() * 2];
int i = 0;
for (IValue field : fields) {
ITuple tuple = (ITuple) field;
IConstructor fieldType = (IConstructor) tuple.get(0);
todo.add(fieldType);
args[i++] = toType(fieldType);
args[i++] = ((IString) tuple.get(1)).getValue();
}
tf.constructor(store, adt, name, args);
}
}
private IConstructor getElement(IConstructor next) {
return (IConstructor) next.get("element");
}
private String getName(final IConstructor next) {
return ((IString) next.get("name")).getValue();
}
private IConstructor getValue(IConstructor next) {
return (IConstructor) next.get("key");
}
private IConstructor getAliased(IConstructor next) {
return (IConstructor) next.get("aliased");
}
private IConstructor getKey(IConstructor next) {
return (IConstructor) next.get("value");
}
private IList getConstructors(IConstructor next) {
return (IList) next.get("constructors");
}
});
}
return toType(typeValue);
}
|
diff --git a/ardor3d-ui/src/main/java/com/ardor3d/extension/ui/AbstractLabelUIComponent.java b/ardor3d-ui/src/main/java/com/ardor3d/extension/ui/AbstractLabelUIComponent.java
index 2e8904d..448bb72 100755
--- a/ardor3d-ui/src/main/java/com/ardor3d/extension/ui/AbstractLabelUIComponent.java
+++ b/ardor3d-ui/src/main/java/com/ardor3d/extension/ui/AbstractLabelUIComponent.java
@@ -1,329 +1,330 @@
/**
* Copyright (c) 2008-2009 Ardor Labs, Inc.
*
* This file is part of Ardor3D.
*
* Ardor3D is free software: you can redistribute it and/or modify it
* under the terms of its license which may be found in the accompanying
* LICENSE file or at <http://www.ardor3d.com/LICENSE>.
*/
package com.ardor3d.extension.ui;
import com.ardor3d.extension.ui.util.Alignment;
import com.ardor3d.extension.ui.util.Dimension;
import com.ardor3d.extension.ui.util.SubTex;
import com.ardor3d.extension.ui.util.SubTexUtil;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.Matrix3;
import com.ardor3d.math.Transform;
import com.ardor3d.math.Vector3;
import com.ardor3d.renderer.Renderer;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.BlendState;
import com.ardor3d.renderer.state.CullState;
import com.ardor3d.renderer.state.ZBufferState;
import com.ardor3d.renderer.state.BlendState.DestinationFunction;
import com.ardor3d.renderer.state.BlendState.SourceFunction;
import com.ardor3d.renderer.state.BlendState.TestFunction;
import com.ardor3d.scenegraph.hint.LightCombineMode;
import com.ardor3d.scenegraph.hint.TextureCombineMode;
import com.ardor3d.ui.text.BMFont;
import com.ardor3d.ui.text.BMText;
import com.ardor3d.ui.text.BMText.AutoFade;
import com.ardor3d.ui.text.BMText.AutoScale;
/**
* A state component containing a text label and an icon. These are separated by an optional gap and can also be given a
* specific alignment. By default, the text is aligned LEFT and has no icon or gap.
*/
public abstract class AbstractLabelUIComponent extends StateBasedUIComponent implements Textable {
/** Distance between text and icon if both are present. */
private int _gap = 0;
/** Alignment value to use to position the icon/text within the overall dimensions of this component. */
private Alignment _alignment = Alignment.LEFT;
/** The icon the draw on this icon. */
private SubTex _icon = null;
/** The size to draw our icon at. */
private final Dimension _iconDimensions = new Dimension();
/** The text object to use for drawing label text. */
private BMText _text;
@Override
public void updateMinimumSizeFromContents() {
int width = 0;
int height = 0;
final String textVal = getText();
if (textVal != null && textVal.length() > 0) {
width += Math.round(_text.getWidth());
height += Math.round(_text.getHeight());
}
if (_iconDimensions != null) {
width += _iconDimensions.getWidth();
if (textVal != null && textVal.length() > 0) {
width += _gap;
}
height = Math.max(_iconDimensions.getHeight(), height);
}
setMinimumContentSize(width, height);
if (getContentWidth() < width) {
setContentWidth(width);
}
if (getContentHeight() < height) {
setContentHeight(height);
}
fireComponentDirty();
}
/**
* @return the currently set text value of this label.
*/
public String getText() {
return _text != null ? _text.getText() : null;
}
/**
* Set the text for this component. Also updates the minimum size of the component.
*
* @param text
* the new text
*/
public void setText(String text) {
if (text != null && text.length() == 0) {
text = null;
}
if (text != null) {
if (text.equals(getText())) {
return;
}
if (_text != null) {
_text.setText(text);
} else {
_text = AbstractLabelUIComponent.createText(text, getFont());
_text.getSceneHints().setRenderBucketType(RenderBucketType.Skip);
_text.updateGeometricState(0);
}
} else {
_text = null;
}
updateMinimumSizeFromContents();
}
@Override
protected void updateChildren(final double time) {
super.updateChildren(time);
if (_text != null) {
_text.updateGeometricState(time);
}
}
@Override
public void setFont(final BMFont font) {
super.setFont(font);
// Reset our BMText object, using the new font.
final String text = getText();
_text = null;
setText(text);
}
public Alignment getAlignment() {
return _alignment;
}
public void setAlignment(final Alignment alignment) {
_alignment = alignment;
}
public int getGap() {
return _gap;
}
/**
* Note: Also updates the minimum size of the component.
*
* @param gap
* the size of the gap, in pixels, between the text and the label text. This is only used if both icon
* and text are set.
*/
public void setGap(final int gap) {
_gap = gap;
updateMinimumSizeFromContents();
}
public SubTex getIcon() {
return _icon;
}
/**
* Note: Also updates the minimum size of the component.
*
* @param icon
* the new icon for this label.
*/
public void setIcon(final SubTex icon) {
_icon = icon;
updateMinimumSizeFromContents();
if (icon != null && _iconDimensions.getHeight() == 0 && _iconDimensions.getWidth() == 0) {
updateIconDimensionsFromIcon();
}
}
/**
* Set the icon dimensions from the currently set icon. If no icon is set, the dimensions are set to 0x0.
*/
public void updateIconDimensionsFromIcon() {
if (_icon != null) {
_iconDimensions.set(_icon.getWidth(), _icon.getHeight());
} else {
_iconDimensions.set(0, 0);
}
updateMinimumSizeFromContents();
}
/**
* Overrides any currently set icon size. Call this after setting the icon to prevent overriding.
*
* @param dimensions
* a new icon size.
*/
public void setIconDimensions(final Dimension dimensions) {
_iconDimensions.set(dimensions);
updateMinimumSizeFromContents();
}
public Dimension getIconDimensions() {
return _iconDimensions;
}
@Override
protected void drawComponent(final Renderer renderer) {
double x = 0;
double y = 0;
int width = 0;
+ final boolean hasText = _text != null && _text.getText() != null;
// Gather our width... check for icon and text and gap.
if (_icon != null) {
width = _iconDimensions.getWidth();
if (getText() != null && getText().length() > 0) {
width += _gap;
}
- } else if (getText() == null) {
- // not text OR icon, so no content to render.
+ } else if (!hasText) {
+ // no text OR icon, so no content to render.
return;
}
- if (getText() != null) {
+ if (hasText) {
width += Math.round(_text.getWidth());
}
// find left most x location of content (icon+text) based on alignment.
x = _alignment.alignX(getContentWidth(), width);
if (_icon != null) {
// find bottom most y location of icon based on alignment.
- if (_text != null && _text.getHeight() > _iconDimensions.getHeight()) {
+ if (hasText && _text.getHeight() > _iconDimensions.getHeight()) {
final int trailing = _text.getFont().getLineHeight() - _text.getFont().getBaseHeight();
y = _alignment.alignY(getContentHeight() - trailing, _iconDimensions.getHeight()) + trailing - 1;
} else {
y = _alignment.alignY(getContentHeight(), _iconDimensions.getHeight());
}
final double dix = getTotalLeft();
final double diy = getTotalBottom();
// draw icon
SubTexUtil
.drawSubTex(renderer, _icon, dix + x, diy + y, _iconDimensions.getWidth() * getWorldScale().getX(),
_iconDimensions.getHeight() * getWorldScale().getY(), getWorldTransform());
// shift X over by width of icon and gap
x += (_iconDimensions.getWidth() + _gap) * getWorldScale().getX();
}
- if (getText() != null) {
+ if (hasText) {
// find bottom most y location of text based on alignment.
y = _alignment.alignY(getContentHeight(), Math.round(_text.getHeight())) * getWorldScale().getY();
// set our text location
final Vector3 v = Vector3.fetchTempInstance();
v.set(x + getTotalLeft(), y + getTotalBottom(), 0);
final Transform t = Transform.fetchTempInstance();
final Matrix3 m = Matrix3.fetchTempInstance();
t.set(getWorldTransform());
t.applyForwardVector(v);
// Add correction matrix to put text into XY plane.
t.getMatrix().multiply(AbstractLabelUIComponent.textCorrectionMat, m);
if (t.isRotationMatrix()) {
t.setRotation(m);
} else {
t.setMatrix(m);
}
t.translate(v);
Vector3.releaseTempInstance(v);
_text.setWorldTransform(t);
Transform.releaseTempInstance(t);
// draw text using current foreground color and alpha.
final ColorRGBA color = ColorRGBA.fetchTempInstance();
color.set(getForegroundColor());
color.setAlpha(color.getAlpha() * UIComponent.getCurrentOpacity());
_text.setTextColor(color);
_text.render(renderer);
ColorRGBA.releaseTempInstance(color);
}
}
public BMText getTextObject() {
return _text;
}
static Matrix3 textCorrectionMat = new Matrix3().fromAngles(MathUtils.HALF_PI, 0, 0);
// Create an instance of BMText for text rendering.
private static BMText createText(final String text, final BMFont font) {
final BMText tComp = new BMText("", text, font);
tComp.setAutoFade(AutoFade.Off);
tComp.setAutoScale(AutoScale.Off);
tComp.setAutoRotate(false);
tComp.setFontScale(font.getSize());
tComp.setRotation(AbstractLabelUIComponent.textCorrectionMat);
final ZBufferState zState = new ZBufferState();
zState.setEnabled(false);
zState.setWritable(false);
tComp.setRenderState(zState);
final CullState cState = new CullState();
cState.setEnabled(false);
tComp.setRenderState(cState);
final BlendState blend = new BlendState();
blend.setBlendEnabled(true);
blend.setSourceFunction(SourceFunction.SourceAlpha);
blend.setDestinationFunction(DestinationFunction.OneMinusSourceAlpha);
blend.setTestEnabled(true);
blend.setReference(0f);
blend.setTestFunction(TestFunction.GreaterThan);
tComp.setRenderState(blend);
tComp.getSceneHints().setLightCombineMode(LightCombineMode.Off);
tComp.getSceneHints().setTextureCombineMode(TextureCombineMode.Replace);
tComp.updateModelBound();
return tComp;
}
}
| false | true | protected void drawComponent(final Renderer renderer) {
double x = 0;
double y = 0;
int width = 0;
// Gather our width... check for icon and text and gap.
if (_icon != null) {
width = _iconDimensions.getWidth();
if (getText() != null && getText().length() > 0) {
width += _gap;
}
} else if (getText() == null) {
// not text OR icon, so no content to render.
return;
}
if (getText() != null) {
width += Math.round(_text.getWidth());
}
// find left most x location of content (icon+text) based on alignment.
x = _alignment.alignX(getContentWidth(), width);
if (_icon != null) {
// find bottom most y location of icon based on alignment.
if (_text != null && _text.getHeight() > _iconDimensions.getHeight()) {
final int trailing = _text.getFont().getLineHeight() - _text.getFont().getBaseHeight();
y = _alignment.alignY(getContentHeight() - trailing, _iconDimensions.getHeight()) + trailing - 1;
} else {
y = _alignment.alignY(getContentHeight(), _iconDimensions.getHeight());
}
final double dix = getTotalLeft();
final double diy = getTotalBottom();
// draw icon
SubTexUtil
.drawSubTex(renderer, _icon, dix + x, diy + y, _iconDimensions.getWidth() * getWorldScale().getX(),
_iconDimensions.getHeight() * getWorldScale().getY(), getWorldTransform());
// shift X over by width of icon and gap
x += (_iconDimensions.getWidth() + _gap) * getWorldScale().getX();
}
if (getText() != null) {
// find bottom most y location of text based on alignment.
y = _alignment.alignY(getContentHeight(), Math.round(_text.getHeight())) * getWorldScale().getY();
// set our text location
final Vector3 v = Vector3.fetchTempInstance();
v.set(x + getTotalLeft(), y + getTotalBottom(), 0);
final Transform t = Transform.fetchTempInstance();
final Matrix3 m = Matrix3.fetchTempInstance();
t.set(getWorldTransform());
t.applyForwardVector(v);
// Add correction matrix to put text into XY plane.
t.getMatrix().multiply(AbstractLabelUIComponent.textCorrectionMat, m);
if (t.isRotationMatrix()) {
t.setRotation(m);
} else {
t.setMatrix(m);
}
t.translate(v);
Vector3.releaseTempInstance(v);
_text.setWorldTransform(t);
Transform.releaseTempInstance(t);
// draw text using current foreground color and alpha.
final ColorRGBA color = ColorRGBA.fetchTempInstance();
color.set(getForegroundColor());
color.setAlpha(color.getAlpha() * UIComponent.getCurrentOpacity());
_text.setTextColor(color);
_text.render(renderer);
ColorRGBA.releaseTempInstance(color);
}
}
| protected void drawComponent(final Renderer renderer) {
double x = 0;
double y = 0;
int width = 0;
final boolean hasText = _text != null && _text.getText() != null;
// Gather our width... check for icon and text and gap.
if (_icon != null) {
width = _iconDimensions.getWidth();
if (getText() != null && getText().length() > 0) {
width += _gap;
}
} else if (!hasText) {
// no text OR icon, so no content to render.
return;
}
if (hasText) {
width += Math.round(_text.getWidth());
}
// find left most x location of content (icon+text) based on alignment.
x = _alignment.alignX(getContentWidth(), width);
if (_icon != null) {
// find bottom most y location of icon based on alignment.
if (hasText && _text.getHeight() > _iconDimensions.getHeight()) {
final int trailing = _text.getFont().getLineHeight() - _text.getFont().getBaseHeight();
y = _alignment.alignY(getContentHeight() - trailing, _iconDimensions.getHeight()) + trailing - 1;
} else {
y = _alignment.alignY(getContentHeight(), _iconDimensions.getHeight());
}
final double dix = getTotalLeft();
final double diy = getTotalBottom();
// draw icon
SubTexUtil
.drawSubTex(renderer, _icon, dix + x, diy + y, _iconDimensions.getWidth() * getWorldScale().getX(),
_iconDimensions.getHeight() * getWorldScale().getY(), getWorldTransform());
// shift X over by width of icon and gap
x += (_iconDimensions.getWidth() + _gap) * getWorldScale().getX();
}
if (hasText) {
// find bottom most y location of text based on alignment.
y = _alignment.alignY(getContentHeight(), Math.round(_text.getHeight())) * getWorldScale().getY();
// set our text location
final Vector3 v = Vector3.fetchTempInstance();
v.set(x + getTotalLeft(), y + getTotalBottom(), 0);
final Transform t = Transform.fetchTempInstance();
final Matrix3 m = Matrix3.fetchTempInstance();
t.set(getWorldTransform());
t.applyForwardVector(v);
// Add correction matrix to put text into XY plane.
t.getMatrix().multiply(AbstractLabelUIComponent.textCorrectionMat, m);
if (t.isRotationMatrix()) {
t.setRotation(m);
} else {
t.setMatrix(m);
}
t.translate(v);
Vector3.releaseTempInstance(v);
_text.setWorldTransform(t);
Transform.releaseTempInstance(t);
// draw text using current foreground color and alpha.
final ColorRGBA color = ColorRGBA.fetchTempInstance();
color.set(getForegroundColor());
color.setAlpha(color.getAlpha() * UIComponent.getCurrentOpacity());
_text.setTextColor(color);
_text.render(renderer);
ColorRGBA.releaseTempInstance(color);
}
}
|
diff --git a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityWeather.java b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityWeather.java
index 218efeab..c041e73f 100644
--- a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityWeather.java
+++ b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityWeather.java
@@ -1,201 +1,202 @@
package powercrystals.minefactoryreloaded.tile.machine;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import powercrystals.minefactoryreloaded.core.MFRInventoryUtil;
import powercrystals.minefactoryreloaded.core.MFRLiquidMover;
import powercrystals.minefactoryreloaded.core.ITankContainerBucketable;
import powercrystals.minefactoryreloaded.gui.client.GuiFactoryInventory;
import powercrystals.minefactoryreloaded.gui.client.GuiFactoryPowered;
import powercrystals.minefactoryreloaded.gui.container.ContainerFactoryPowered;
import powercrystals.minefactoryreloaded.tile.base.TileEntityFactoryPowered;
import net.minecraft.block.Block;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.liquids.ILiquidTank;
import net.minecraftforge.liquids.LiquidContainerRegistry;
import net.minecraftforge.liquids.LiquidStack;
import net.minecraftforge.liquids.LiquidTank;
public class TileEntityWeather extends TileEntityFactoryPowered implements ITankContainerBucketable
{
private LiquidTank _tank;
public TileEntityWeather()
{
super(40);
_tank = new LiquidTank(4 * LiquidContainerRegistry.BUCKET_VOLUME);
}
@Override
public String getGuiBackground()
{
return "weathercollector.png";
}
@Override
@SideOnly(Side.CLIENT)
public GuiFactoryInventory getGui(InventoryPlayer inventoryPlayer)
{
return new GuiFactoryPowered(getContainer(inventoryPlayer), this);
}
@Override
public ContainerFactoryPowered getContainer(InventoryPlayer inventoryPlayer)
{
return new ContainerFactoryPowered(this, inventoryPlayer);
}
@Override
public boolean canRotate()
{
return false;
}
@Override
public ILiquidTank getTank()
{
return _tank;
}
@Override
public int getEnergyStoredMax()
{
return 64000;
}
@Override
public int getWorkMax()
{
return 50;
}
@Override
public int getIdleTicksMax()
{
return 600;
}
@Override
public boolean activateMachine()
{
MFRLiquidMover.pumpLiquid(_tank, this);
if(worldObj.getWorldInfo().isRaining() && canSeeSky())
{
BiomeGenBase bgb = worldObj.getBiomeGenForCoords(this.xCoord, this.zCoord);
if(!bgb.canSpawnLightningBolt() && !bgb.getEnableSnow())
{
setIdleTicks(getIdleTicksMax());
return false;
}
setWorkDone(getWorkDone() + 1);
if(getWorkDone() >= getWorkMax())
{
if(bgb.getFloatTemperature() >= 0.15F)
{
if(_tank.fill(new LiquidStack(Block.waterStill.blockID, LiquidContainerRegistry.BUCKET_VOLUME), true) > 0)
{
setWorkDone(0);
return true;
}
else
{
+ setWorkDone(getWorkMax());
return false;
}
}
else
{
MFRInventoryUtil.dropStack(this, new ItemStack(Item.snowball), this.getDropDirection());
}
}
return true;
}
setIdleTicks(getIdleTicksMax());
return false;
}
@Override
public ForgeDirection getDropDirection()
{
return ForgeDirection.DOWN;
}
private boolean canSeeSky()
{
for(int y = yCoord + 1; y <= 256; y++)
{
int blockId = worldObj.getBlockId(xCoord, y, zCoord);
if(Block.blocksList[blockId] != null && !Block.blocksList[blockId].isAirBlock(worldObj, xCoord, y, zCoord))
{
return false;
}
}
return true;
}
@Override
public int fill(ForgeDirection from, LiquidStack resource, boolean doFill)
{
return 0;
}
@Override
public int fill(int tankIndex, LiquidStack resource, boolean doFill)
{
return 0;
}
@Override
public boolean allowBucketDrain()
{
return true;
}
@Override
public LiquidStack drain(ForgeDirection from, int maxDrain, boolean doDrain)
{
return null;
}
@Override
public LiquidStack drain(int tankIndex, int maxDrain, boolean doDrain)
{
return null;
}
@Override
public ILiquidTank[] getTanks(ForgeDirection direction)
{
return new ILiquidTank[] { _tank };
}
@Override
public ILiquidTank getTank(ForgeDirection direction, LiquidStack type)
{
return _tank;
}
@Override
public String getInvName()
{
return "Weather Collector";
}
@Override
public int getSizeInventory()
{
return 0;
}
@Override
public boolean manageSolids()
{
return true;
}
}
| true | true | public boolean activateMachine()
{
MFRLiquidMover.pumpLiquid(_tank, this);
if(worldObj.getWorldInfo().isRaining() && canSeeSky())
{
BiomeGenBase bgb = worldObj.getBiomeGenForCoords(this.xCoord, this.zCoord);
if(!bgb.canSpawnLightningBolt() && !bgb.getEnableSnow())
{
setIdleTicks(getIdleTicksMax());
return false;
}
setWorkDone(getWorkDone() + 1);
if(getWorkDone() >= getWorkMax())
{
if(bgb.getFloatTemperature() >= 0.15F)
{
if(_tank.fill(new LiquidStack(Block.waterStill.blockID, LiquidContainerRegistry.BUCKET_VOLUME), true) > 0)
{
setWorkDone(0);
return true;
}
else
{
return false;
}
}
else
{
MFRInventoryUtil.dropStack(this, new ItemStack(Item.snowball), this.getDropDirection());
}
}
return true;
}
setIdleTicks(getIdleTicksMax());
return false;
}
| public boolean activateMachine()
{
MFRLiquidMover.pumpLiquid(_tank, this);
if(worldObj.getWorldInfo().isRaining() && canSeeSky())
{
BiomeGenBase bgb = worldObj.getBiomeGenForCoords(this.xCoord, this.zCoord);
if(!bgb.canSpawnLightningBolt() && !bgb.getEnableSnow())
{
setIdleTicks(getIdleTicksMax());
return false;
}
setWorkDone(getWorkDone() + 1);
if(getWorkDone() >= getWorkMax())
{
if(bgb.getFloatTemperature() >= 0.15F)
{
if(_tank.fill(new LiquidStack(Block.waterStill.blockID, LiquidContainerRegistry.BUCKET_VOLUME), true) > 0)
{
setWorkDone(0);
return true;
}
else
{
setWorkDone(getWorkMax());
return false;
}
}
else
{
MFRInventoryUtil.dropStack(this, new ItemStack(Item.snowball), this.getDropDirection());
}
}
return true;
}
setIdleTicks(getIdleTicksMax());
return false;
}
|
diff --git a/jsword/src/main/java/org/crosswire/jsword/book/filter/thml/DivTag.java b/jsword/src/main/java/org/crosswire/jsword/book/filter/thml/DivTag.java
index 3708400b..2c25de10 100644
--- a/jsword/src/main/java/org/crosswire/jsword/book/filter/thml/DivTag.java
+++ b/jsword/src/main/java/org/crosswire/jsword/book/filter/thml/DivTag.java
@@ -1,80 +1,80 @@
/**
* Distribution License:
* JSword is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License, version 2.1 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.
*
* The License is available on the internet at:
* http://www.gnu.org/copyleft/lgpl.html
* or by writing to:
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307, USA
*
* Copyright: 2005
* The copyright to this program is held by it's authors.
*
* ID: $Id$
*/
package org.crosswire.jsword.book.filter.thml;
import org.crosswire.jsword.book.OSISUtil;
import org.jdom.Element;
import org.xml.sax.Attributes;
/**
* THML Tag to process the div element.
*
* @see gnu.lgpl.License for license details.
* The copyright to this program is held by it's authors.
* @author Joe Walker [joe at eireneh dot com]
*/
public class DivTag extends AbstractTag
{
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.thml.Tag#getTagName()
*/
public String getTagName()
{
return "div"; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.thml.Tag#processTag(org.jdom.Element, org.xml.sax.Attributes)
*/
/* @Override */
public Element processTag(Element ele, Attributes attrs)
{
// See if there are variant readings e.g. WHNU Mat 1.9
String typeAttr = attrs.getValue("type"); //$NON-NLS-1$
if ("variant".equals(typeAttr)) //$NON-NLS-1$
{
Element seg = OSISUtil.factory().createSeg();
seg.setAttribute(OSISUtil.OSIS_ATTR_TYPE, OSISUtil.VARIANT_TYPE);
String classAttr = attrs.getValue("class"); //$NON-NLS-1$
if (classAttr != null)
{
- seg.setAttribute(OSISUtil.OSIS_ATTR_SUBTYPE, OSISUtil.VARIANT_CLASS + classAttr);
+ seg.setAttribute(OSISUtil.OSIS_ATTR_SUBTYPE, OSISUtil.VARIANT_CLASS + '-' + classAttr);
}
if (ele != null)
{
ele.addContent(seg);
}
return seg;
}
Element div = OSISUtil.factory().createDiv();
if (ele != null)
{
ele.addContent(div);
}
return div;
}
}
| true | true | public Element processTag(Element ele, Attributes attrs)
{
// See if there are variant readings e.g. WHNU Mat 1.9
String typeAttr = attrs.getValue("type"); //$NON-NLS-1$
if ("variant".equals(typeAttr)) //$NON-NLS-1$
{
Element seg = OSISUtil.factory().createSeg();
seg.setAttribute(OSISUtil.OSIS_ATTR_TYPE, OSISUtil.VARIANT_TYPE);
String classAttr = attrs.getValue("class"); //$NON-NLS-1$
if (classAttr != null)
{
seg.setAttribute(OSISUtil.OSIS_ATTR_SUBTYPE, OSISUtil.VARIANT_CLASS + classAttr);
}
if (ele != null)
{
ele.addContent(seg);
}
return seg;
}
Element div = OSISUtil.factory().createDiv();
if (ele != null)
{
ele.addContent(div);
}
return div;
}
| public Element processTag(Element ele, Attributes attrs)
{
// See if there are variant readings e.g. WHNU Mat 1.9
String typeAttr = attrs.getValue("type"); //$NON-NLS-1$
if ("variant".equals(typeAttr)) //$NON-NLS-1$
{
Element seg = OSISUtil.factory().createSeg();
seg.setAttribute(OSISUtil.OSIS_ATTR_TYPE, OSISUtil.VARIANT_TYPE);
String classAttr = attrs.getValue("class"); //$NON-NLS-1$
if (classAttr != null)
{
seg.setAttribute(OSISUtil.OSIS_ATTR_SUBTYPE, OSISUtil.VARIANT_CLASS + '-' + classAttr);
}
if (ele != null)
{
ele.addContent(seg);
}
return seg;
}
Element div = OSISUtil.factory().createDiv();
if (ele != null)
{
ele.addContent(div);
}
return div;
}
|
diff --git a/pluginsource/org/enigma/EnigmaRunner.java b/pluginsource/org/enigma/EnigmaRunner.java
index fa2450ee..ac00e7de 100644
--- a/pluginsource/org/enigma/EnigmaRunner.java
+++ b/pluginsource/org/enigma/EnigmaRunner.java
@@ -1,841 +1,841 @@
/*
* Copyright (C) 2008, 2009, 2010 IsmAvatar <[email protected]>
*
* This file is part of Enigma Plugin.
*
* Enigma Plugin 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.
*
* Enigma Plugin 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 (COPYING) 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 org.enigma;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.prefs.Preferences;
import java.util.regex.Pattern;
import javax.swing.AbstractListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.enigma.EYamlParser.YamlNode;
import org.enigma.backend.EnigmaCallbacks;
import org.enigma.backend.EnigmaDriver;
import org.enigma.backend.EnigmaSettings;
import org.enigma.backend.EnigmaStruct;
import org.enigma.backend.EnigmaDriver.SyntaxError;
import org.lateralgm.components.ErrorDialog;
import org.lateralgm.components.GMLTextArea;
import org.lateralgm.components.impl.CustomFileFilter;
import org.lateralgm.components.impl.ResNode;
import org.lateralgm.components.mdi.MDIFrame;
import org.lateralgm.file.GmFormatException;
import org.lateralgm.main.LGM;
import org.lateralgm.main.LGM.ReloadListener;
import org.lateralgm.messages.Messages;
import org.lateralgm.resources.Resource;
import org.lateralgm.resources.Script;
import org.lateralgm.subframes.ActionFrame;
import org.lateralgm.subframes.CodeFrame;
import org.lateralgm.subframes.ScriptFrame;
import org.lateralgm.subframes.SubframeInformer;
import org.lateralgm.subframes.SubframeInformer.SubframeListener;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.StringArray;
public class EnigmaRunner implements ActionListener,SubframeListener,ReloadListener
{
public static final String ENIGMA = "compileEGMf.exe";
public EnigmaFrame ef = new EnigmaFrame();
/** This is global scoped so that it doesn't get GC'd */
private EnigmaCallbacks ec = new EnigmaCallbacks(ef);
public EnigmaSettings es = new EnigmaSettings();
public EnigmaSettingsFrame esf = new EnigmaSettingsFrame(es);
public JMenuItem run, debug, design, compile, rebuild;
public JMenuItem showFunctions, showGlobals, showTypes;
public static EnigmaDriver DRIVER;
/** This is static because it belongs to EnigmaStruct's dll, which is statically loaded. */
public static boolean GCC_LOCATED = false, ENIGMA_READY = false;
public final EnigmaNode node = new EnigmaNode();
static final int MODE_RUN = 0, MODE_DEBUG = 1, MODE_DESIGN = 2;
static final int MODE_COMPILE = 3, MODE_REBUILD = 4;
public EnigmaRunner()
{
populateMenu();
populateTree();
LGM.addReloadListener(this);
SubframeInformer.addSubframeListener(this);
applyBackground("org/enigma/enigma.png");
LGM.mdi.add(esf);
new Thread()
{
public void run()
{
//TODO: Let Linux packages handle updates
//if (!Platform.isLinux())
boolean rebuild = Preferences.userRoot().node("/org/enigma").getBoolean("NEEDS_REBUILD",
false);
if (attemptUpdate() || attemptLib() != null || rebuild) make();
Error e = attemptLib();
if (e != null)
{
String err = "ENIGMA: Unable to communicate with the library,\n"
+ "either because it could not be found or uses methods different from those expected.\n"
+ "The exact error is:\n" + e.getMessage();
JOptionPane.showMessageDialog(null,err);
return;
}
ENIGMA_READY = true;
initEnigmaLib();
if (GCC_LOCATED) DRIVER.whitespaceModified(es.definitions);
}
}.start();
}
private UnsatisfiedLinkError attemptLib()
{
try
{
String lib = "compileEGMf";
NativeLibrary.addSearchPath(lib,".");
NativeLibrary.addSearchPath(lib,LGM.workDir.getParent());
DRIVER = (EnigmaDriver) Native.loadLibrary(lib,EnigmaDriver.class);
return null;
}
catch (UnsatisfiedLinkError e)
{
return e;
}
}
public boolean make()
{
File f = new File("winmake.txt");
Process p;
InputStream stdin, stder;
try
{
BufferedReader in = new BufferedReader(new FileReader(f));
String make = in.readLine();
in.close();
//prepend root
p = Runtime.getRuntime().exec(make,null,LGM.workDir.getParentFile());
stdin = p.getInputStream();
stder = p.getErrorStream();
}
catch (IOException e)
{
try
{
p = Runtime.getRuntime().exec("make",null,LGM.workDir.getParentFile());
stdin = p.getInputStream();
stder = p.getErrorStream();
}
catch (IOException e1)
{
GmFormatException e2 = new GmFormatException(null,e);
e2.printStackTrace();
new ErrorDialog(
null,
"Unable to Update Enigma",
"Enigma cannot run because it requires the `make` tool, which could not be found.\n"
+ "Please ensure that `make` is properly installed and then restart the application.",
Messages.format("Listener.DEBUG_INFO", //$NON-NLS-1$
e2.getClass().getName(),e2.getMessage(),e2.stackAsString())).setVisible(true);
return false;
}
}
System.out.println("Calling `make`");
ef.ta.append("Calling `make`");
new EnigmaThread(ef,stdin);
new EnigmaThread(ef,stder);
ef.setVisible(true);
try
{
System.out.println(p.waitFor()); //p cannot be null at this point
}
catch (InterruptedException e)
{
System.out.println("wut?");
e.printStackTrace();
}
ef.setVisible(false);
return true;
}
private void initEnigmaLib()
{
System.out.println("Initializing Enigma: ");
int ret = DRIVER.libInit(ec);
if (ret == 0)
{
GCC_LOCATED = true;
return;
}
if (ret == 1) ret = locateGCC();
if (ret != 0)
{
String err;
switch (ret)
{
case 1:
err = "ENIGMA: GCC not found";
break;
case 2:
err = "ENIGMA: No output gained from call to GCC";
break;
case 3:
err = "ENIGMA: Output from GCC doesn't make sense";
break;
default:
err = "ENIGMA: Undefined error " + ret;
break;
}
JOptionPane.showMessageDialog(null,err);
}
}
public int locateGCC()
{
//this is my sad attempt at trying to get the user to locate GCC
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setDialogTitle("ENIGMA: Please locate the GCC directory (containing bin/, lib/ etc)");
fc.setAcceptAllFileFilterUsed(false);
if (fc.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) return 0;
int ret = DRIVER.gccDefinePath(fc.getSelectedFile().getAbsolutePath());
if (ret == 0) GCC_LOCATED = true;
return ret;
}
//target is one of ""Platforms","Audio_Systems","Graphics_Systems","Collision_Systems"
static List<TargetSelection> findTargets(String target, String current)
{
ArrayList<TargetSelection> targets = new ArrayList<TargetSelection>();
if (current == null || current.isEmpty()) return targets;
File f = new File(LGM.workDir.getParentFile(),"ENIGMAsystem");
f = new File(f,"SHELL");
f = new File(f,target);
File files[] = f.listFiles();
for (File dir : files)
{
if (!dir.isDirectory()) continue;
//technically this could stand to be a .properties file, rather than e-yaml
File prop = new File(dir,"About.ey");
try
{
boolean match = false;
if (!target.equals("Platforms"))
{
String[] configs = new File(dir,"Config").list();
if (configs == null) continue;
for (String conf : configs)
- if (conf.equals(current + ".ey"))
+ if (conf.equalsIgnoreCase(current + ".ey"))
{
match = true;
break;
}
if (!match) continue;
}
YamlNode node = EYamlParser.parse(new Scanner(prop));
if (target.equals("Platforms"))
{
for (String s : normalize(node.getMC("Build-Platforms")).split(","))
if (current.startsWith(s))
{
match = true;
break;
}
}
if (!match) continue;
TargetSelection ps = new TargetSelection();
ps.name = node.getMC("Name");
ps.id = node.getMC("Identifier");
ps.rep = node.getMC("Represents",null);
ps.desc = node.getMC("Description",null);
ps.auth = node.getMC("Author",null);
ps.ext = node.getMC("Build-Extension",null);
targets.add(ps);
}
catch (FileNotFoundException e)
{
//yaml file missing, skip to next file
}
catch (IndexOutOfBoundsException e)
{
//insufficient yaml, skip to next file
}
}
//if not empty, we may safely assume that the first one is the default selection,
//or technically, that any of them is the default. The user can/will change it in UI.
return targets;
}
static class TargetSelection
{
public String name, id; //mandatory
public String rep, desc, auth, ext; //optional
public String toString()
{
return name;
}
}
static String normalize(String s)
{
return s.toLowerCase().replaceAll("[ _\\-]","");
}
public void populateMenu()
{
JMenu menu = new JMenu("Enigma");
run = new JMenuItem("Run");
run.addActionListener(this);
menu.add(run);
debug = new JMenuItem("Debug");
debug.addActionListener(this);
menu.add(debug);
design = new JMenuItem("Design");
design.addActionListener(this);
menu.add(design);
compile = new JMenuItem("Compile");
compile.addActionListener(this);
menu.add(compile);
rebuild = new JMenuItem("Rebuild All");
rebuild.addActionListener(this);
menu.add(rebuild);
menu.addSeparator();
JMenuItem mi = new JMenuItem("Settings");
mi.addActionListener(node);
menu.add(mi);
JMenu sub = new JMenu("Keyword List");
menu.add(sub);
showFunctions = new JMenuItem("Functions");
showFunctions.addActionListener(this);
sub.add(showFunctions);
showGlobals = new JMenuItem("Globals");
showGlobals.addActionListener(this);
sub.add(showGlobals);
showTypes = new JMenuItem("Types");
showTypes.addActionListener(this);
sub.add(showTypes);
LGM.frame.getJMenuBar().add(menu,1);
}
public void populateTree()
{
LGM.root.add(node);
/*EnigmaGroup node = new EnigmaGroup();
LGM.root.add(node);
node.add(new EnigmaNode("Whitespace"));
node.add(new EnigmaNode("Enigma Init"));
node.add(new EnigmaNode("Enigma Term"));*/
LGM.tree.updateUI();
}
public void applyBackground(String bgloc)
{
ImageIcon bg = findIcon(bgloc);
LGM.mdi.add(new MDIBackground(bg),JLayeredPane.FRAME_CONTENT_LAYER);
}
/** Attempts to update, and returns whether it needed one. Also returns false on error. */
public boolean attemptUpdate()
{
try
{
boolean up = EnigmaUpdater.checkForUpdates(ef);
if (EnigmaUpdater.needsRestart)
{
Preferences.userRoot().node("/org/enigma").putBoolean("NEEDS_REBUILD",true);
JOptionPane.showMessageDialog(null,
"Update completed. The program will need to be restarted to complete the process.");
System.exit(0);
}
return up;
}
/**
* Usually you shouldn't catch an Error, however,
* in this case we catch it to abort the module,
* rather than allowing the failed module to cause
* the entire program/plugin to fail
*/
catch (NoClassDefFoundError e)
{
String error = "Auto-update disabled: SvnKit missing, corrupted, or unusable."
+ "Please download to plugins/shared/svnkit.jar in order to enable auto-update.";
System.err.println(error);
return false;
}
}
public class MDIBackground extends JComponent
{
private static final long serialVersionUID = 1L;
ImageIcon image;
public MDIBackground(ImageIcon icon)
{
image = icon;
if (image == null) return;
if (image.getIconWidth() <= 0) image = null;
}
public int getWidth()
{
return LGM.mdi.getWidth();
}
public int getHeight()
{
return LGM.mdi.getHeight();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image == null) return;
for (int y = 0; y < getHeight(); y += image.getIconHeight())
for (int x = 0; x < getWidth(); x += image.getIconWidth())
g.drawImage(image.getImage(),x,y,null);
}
}
public class EnigmaNode extends ResNode implements ActionListener
{
private static final long serialVersionUID = 1L;
private JPopupMenu pm;
public EnigmaNode()
{
super("Enigma Settings",ResNode.STATUS_SECONDARY,Resource.Kind.GAMESETTINGS);
pm = new JPopupMenu();
pm.add(new JMenuItem("Edit")).addActionListener(this);
}
public void openFrame()
{
esf.toTop();
}
public void showMenu(MouseEvent e)
{
pm.show(e.getComponent(),e.getX(),e.getY());
}
public void actionPerformed(ActionEvent e)
{
openFrame();
}
public DataFlavor[] getTransferDataFlavors()
{
return new DataFlavor[0];
}
public boolean isDataFlavorSupported(DataFlavor flavor)
{
return false;
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException
{
throw new UnsupportedFlavorException(flavor);
}
}
public void compile(final int mode)
{
if (!GCC_LOCATED)
{
JOptionPane.showMessageDialog(null,"You can't compile without GCC.");
return;
}
//determine `outname` (rebuild has no `outname`)
File outname = null;
try
{
if (mode < MODE_DESIGN) //run/debug
outname = File.createTempFile("egm",".exe");
else if (mode == MODE_DESIGN) outname = File.createTempFile("egm",".emd"); //design
if (outname != null) outname.deleteOnExit();
}
catch (IOException e)
{
e.printStackTrace();
return;
}
if (mode == MODE_COMPILE)
{
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new CustomFileFilter(".exe","Executable files"));
if (fc.showSaveDialog(LGM.frame) != JFileChooser.APPROVE_OPTION) return;
outname = fc.getSelectedFile();
}
LGM.commitAll();
//System.out.println("Compiling with " + enigma);
final File ef = outname;
new Thread()
{
public void run()
{
EnigmaStruct es = EnigmaWriter.prepareStruct(LGM.currentFile);
System.out.println(DRIVER.compileEGMf(es,ef == null ? null : ef.getAbsolutePath(),mode));
}
}.start();
if (mode == MODE_DESIGN) //design
{
try
{
EnigmaReader.readChanges(outname);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
//This can be static since the GCC_LOCATED and Enigma dll are both static.
public static SyntaxError checkSyntax(String code)
{
if (!ENIGMA_READY)
{
JOptionPane.showMessageDialog(null,"ENIGMA isn't ready yet.");
return null;
}
if (!GCC_LOCATED)
{
JOptionPane.showMessageDialog(null,"You can't compile without GCC.");
return null;
}
String osl[] = new String[LGM.currentFile.scripts.size()];
Script isl[] = LGM.currentFile.scripts.toArray(new Script[0]);
for (int i = 0; i < osl.length; i++)
osl[i] = isl[i].getName();
return DRIVER.syntaxCheck(osl.length,new StringArray(osl),code);
}
public void actionPerformed(ActionEvent e)
{
if (!ENIGMA_READY)
{
JOptionPane.showMessageDialog(null,"ENIGMA isn't ready yet.");
return;
}
Object s = e.getSource();
if (s == run) compile(MODE_RUN);
if (s == debug) compile(MODE_DEBUG);
if (s == design) compile(MODE_DESIGN);
if (s == compile) compile(MODE_COMPILE);
if (s == rebuild) compile(MODE_REBUILD);
if (s == showFunctions) showKeywordListFrame(0);
if (s == showGlobals) showKeywordListFrame(1);
if (s == showTypes) showKeywordListFrame(2);
}
private MDIFrame keywordListFrames[] = new MDIFrame[3];
private KeywordListModel keywordLists[] = new KeywordListModel[3];
private final static Pattern nameRegex = Pattern.compile("[a-zA-][a-zA-Z0-9_]*");
public void showKeywordListFrame(final int mode)
{
String[] modes = { "Functions","Globals","Types" };
if (keywordListFrames[mode] == null)
{
keywordListFrames[mode] = new MDIFrame(modes[mode],true,true,true,true);
keywordListFrames[mode].setSize(200,400);
keywordListFrames[mode].setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);
LGM.mdi.add(keywordListFrames[mode]);
keywordLists[mode] = new KeywordListModel();
final JList list = new JList(keywordLists[mode]);
// keywordLists[mode].setEditable(false);
// keywordLists[mode].setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
list.setFont(new Font(Font.MONOSPACED,Font.PLAIN,12));
final JTextField filter = new JTextField();
filter.getDocument().addDocumentListener(new DocumentListener()
{
@Override
public void changedUpdate(DocumentEvent e)
{
keywordLists[mode].setFilter(filter.getText());
}
@Override
public void insertUpdate(DocumentEvent e)
{
keywordLists[mode].setFilter(filter.getText());
}
@Override
public void removeUpdate(DocumentEvent e)
{
keywordLists[mode].setFilter(filter.getText());
}
});
keywordListFrames[mode].add(new JScrollPane(filter),BorderLayout.NORTH);
keywordListFrames[mode].add(new JScrollPane(list),BorderLayout.CENTER);
// keywordListFrames[mode].setFocusTraversalPolicy(new TextAreaFocusTraversalPolicy(list));
}
//TODO: should only repopulate when whitespace changes
keywordLists[mode].setKeywords(getKeywordList(mode));
keywordListFrames[mode].toTop();
}
public class KeywordListModel extends AbstractListModel
{
private static final long serialVersionUID = 1L;
public List<String> keywords;
private List<String> filteredKeywords = new ArrayList<String>();
private String filter = "";
public void setKeywords(List<String> keywords)
{
this.keywords = keywords;
applyFilter();
}
public void setFilter(String filter)
{
this.filter = filter;
applyFilter();
}
private void applyFilter()
{
filteredKeywords.clear();
if (filter.isEmpty() && keywords != null)
filteredKeywords.addAll(keywords);
else
{
for (String s : keywords)
if (s.startsWith(filter)) filteredKeywords.add(s);
for (String s : keywords)
if (s.contains(filter) && !s.startsWith(filter)) filteredKeywords.add(s);
}
this.fireContentsChanged(this,0,getSize());
}
@Override
public Object getElementAt(int index)
{
return filteredKeywords.get(index);
}
@Override
public int getSize()
{
return filteredKeywords.size();
}
}
/**
* Generates a newline (\n) delimited list of keywords of given type
* @param type 0 for functions, 1 for globals, 2 for types
* @return The keyword list
*/
public static List<String> getKeywordList(int type)
{
List<String> rl = new ArrayList<String>();
String res = DRIVER.first_available_resource();
while (res != null)
{
if (nameRegex.matcher(res).matches()) switch (type)
{
case 0:
if (DRIVER.resource_isFunction())
{
int min = DRIVER.resource_argCountMin();
int max = DRIVER.resource_argCountMax();
res += "(" + DRIVER.resource_argCountMin();
if (min != max) res += "-" + DRIVER.resource_argCountMax();
res += ")";
rl.add(res);
}
break;
case 1:
if (DRIVER.resource_isGlobal()) rl.add(res);
break;
case 2:
if (DRIVER.resource_isTypeName()) rl.add(res);
break;
}
res = DRIVER.next_available_resource();
}
return rl;
}
public void subframeAppeared(MDIFrame source)
{
JToolBar tool;
final GMLTextArea code;
final JPanel status;
if (source instanceof ScriptFrame)
{
ScriptFrame sf = (ScriptFrame) source;
tool = sf.tool;
code = sf.code;
status = sf.status;
}
else if (source instanceof CodeFrame)
{
CodeFrame cf = (CodeFrame) source;
tool = cf.tool;
code = cf.code;
status = cf.status;
}
else if (source instanceof ActionFrame && ((ActionFrame) source).code != null)
{
ActionFrame af = (ActionFrame) source;
tool = af.tool;
code = af.code;
status = af.status;
}
else
return;
status.add(new JLabel(" | ")); //$NON-NLS-1$
//visible divider ^ since JSeparator isn't visible and takes up the whole thing...
final JLabel errors = new JLabel("No errors");
status.add(errors);
JButton syntaxCheck;
ImageIcon i = findIcon("syntax.png");
if (i == null)
syntaxCheck = new JButton("Syntax");
else
{
syntaxCheck = new JButton(i);
syntaxCheck.setToolTipText("Syntax");
}
syntaxCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SyntaxError se = checkSyntax(code.getText());
if (se == null) return;
int max = code.getDocumentLength() - 1;
if (se.absoluteIndex > max) se.absoluteIndex = max;
if (se.absoluteIndex != -1) //-1 = no error
{
code.setCaretPosition(se.absoluteIndex);
code.setSelectionStart(se.absoluteIndex);
code.setSelectionEnd(se.absoluteIndex + 1);
errors.setText(se.line + ":" + se.position + "::" + se.errorString);
}
else
errors.setText("No errors");
code.requestFocus();
}
});
tool.add(syntaxCheck,5);
}
@Override
public void reloadPerformed(boolean newRoot)
{
if (newRoot) populateTree();
es = new EnigmaSettings();
esf.setComponents(es);
}
public ImageIcon findIcon(String loc)
{
ImageIcon ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
URL url = this.getClass().getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
if (ico.getIconWidth() != -1) return ico;
loc = "org/enigma/" + loc;
ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
url = this.getClass().getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
return ico;
}
public boolean subframeRequested(Resource<?,?> res, ResNode node)
{
return false;
}
public static void main(String[] args)
{
LGM.main(args);
new EnigmaRunner();
}
}
| true | true | static List<TargetSelection> findTargets(String target, String current)
{
ArrayList<TargetSelection> targets = new ArrayList<TargetSelection>();
if (current == null || current.isEmpty()) return targets;
File f = new File(LGM.workDir.getParentFile(),"ENIGMAsystem");
f = new File(f,"SHELL");
f = new File(f,target);
File files[] = f.listFiles();
for (File dir : files)
{
if (!dir.isDirectory()) continue;
//technically this could stand to be a .properties file, rather than e-yaml
File prop = new File(dir,"About.ey");
try
{
boolean match = false;
if (!target.equals("Platforms"))
{
String[] configs = new File(dir,"Config").list();
if (configs == null) continue;
for (String conf : configs)
if (conf.equals(current + ".ey"))
{
match = true;
break;
}
if (!match) continue;
}
YamlNode node = EYamlParser.parse(new Scanner(prop));
if (target.equals("Platforms"))
{
for (String s : normalize(node.getMC("Build-Platforms")).split(","))
if (current.startsWith(s))
{
match = true;
break;
}
}
if (!match) continue;
TargetSelection ps = new TargetSelection();
ps.name = node.getMC("Name");
ps.id = node.getMC("Identifier");
ps.rep = node.getMC("Represents",null);
ps.desc = node.getMC("Description",null);
ps.auth = node.getMC("Author",null);
ps.ext = node.getMC("Build-Extension",null);
targets.add(ps);
}
catch (FileNotFoundException e)
{
//yaml file missing, skip to next file
}
catch (IndexOutOfBoundsException e)
{
//insufficient yaml, skip to next file
}
}
//if not empty, we may safely assume that the first one is the default selection,
//or technically, that any of them is the default. The user can/will change it in UI.
return targets;
}
| static List<TargetSelection> findTargets(String target, String current)
{
ArrayList<TargetSelection> targets = new ArrayList<TargetSelection>();
if (current == null || current.isEmpty()) return targets;
File f = new File(LGM.workDir.getParentFile(),"ENIGMAsystem");
f = new File(f,"SHELL");
f = new File(f,target);
File files[] = f.listFiles();
for (File dir : files)
{
if (!dir.isDirectory()) continue;
//technically this could stand to be a .properties file, rather than e-yaml
File prop = new File(dir,"About.ey");
try
{
boolean match = false;
if (!target.equals("Platforms"))
{
String[] configs = new File(dir,"Config").list();
if (configs == null) continue;
for (String conf : configs)
if (conf.equalsIgnoreCase(current + ".ey"))
{
match = true;
break;
}
if (!match) continue;
}
YamlNode node = EYamlParser.parse(new Scanner(prop));
if (target.equals("Platforms"))
{
for (String s : normalize(node.getMC("Build-Platforms")).split(","))
if (current.startsWith(s))
{
match = true;
break;
}
}
if (!match) continue;
TargetSelection ps = new TargetSelection();
ps.name = node.getMC("Name");
ps.id = node.getMC("Identifier");
ps.rep = node.getMC("Represents",null);
ps.desc = node.getMC("Description",null);
ps.auth = node.getMC("Author",null);
ps.ext = node.getMC("Build-Extension",null);
targets.add(ps);
}
catch (FileNotFoundException e)
{
//yaml file missing, skip to next file
}
catch (IndexOutOfBoundsException e)
{
//insufficient yaml, skip to next file
}
}
//if not empty, we may safely assume that the first one is the default selection,
//or technically, that any of them is the default. The user can/will change it in UI.
return targets;
}
|
diff --git a/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_tploc.java b/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_tploc.java
index b333096..58d4f28 100644
--- a/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_tploc.java
+++ b/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_tploc.java
@@ -1,85 +1,84 @@
package com.github.zathrus_writer.commandsex.commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.github.zathrus_writer.commandsex.CommandsEX;
import com.github.zathrus_writer.commandsex.helpers.Commands;
import com.github.zathrus_writer.commandsex.helpers.LogHelper;
import com.github.zathrus_writer.commandsex.helpers.Permissions;
import com.github.zathrus_writer.commandsex.helpers.PlayerHelper;
import com.github.zathrus_writer.commandsex.helpers.Teleportation;
import com.github.zathrus_writer.commandsex.helpers.Utils;
public class Command_cex_tploc extends Teleportation {
/***
* TPLOC - teleports player to given coordinates
* @param sender
* @param args
* @return
*/
public static Boolean run(CommandSender sender, String alias, String[] args) {
if (PlayerHelper.checkIsPlayer(sender)) {
Player player = (Player)sender;
if (!Utils.checkCommandSpam(player, "tp-tploc")) {
// first of all, check permissions
if (Permissions.checkPerms(player, "cex.tploc")) {
// alternative usage, all 3 coords separated by comma in 1 argument
if (args.length == 1) {
if (args[0].contains(",")) {
args = args[0].split(",");
} else {
- // no commas found in the argument, return error
- LogHelper.showWarning("tpInvalidArgument", sender);
- return false;
+ Commands.showCommandHelpAndUsage(sender, "cex_tploc", alias);
+ return true;
}
}
if (args.length <= 0) {
// no coordinates
Commands.showCommandHelpAndUsage(sender, "cex_tploc", alias);
} else if (!(args.length == 3 || args.length == 4)) {
// too few or too many arguments
LogHelper.showWarning("tpMissingCoords", sender);
return false;
} else if (!args[0].matches(CommandsEX.intRegex) || !args[1].matches(CommandsEX.intRegex) || !args[2].matches(CommandsEX.intRegex)) {
// one of the coordinates is not a number
LogHelper.showWarning("tpCoordsMustBeNumeric", sender);
} else {
try {
Player target = null;
if (args.length == 4){
if (Bukkit.getPlayer(args[3]) != null){
target = Bukkit.getPlayer(args[3]);
} else {
LogHelper.showInfo("invalidPlayer", player, ChatColor.RED);
return true;
}
} else {
target = player;
}
delayedTeleport(target, new Location(player.getWorld(), new Double(args[0]), new Double(args[1]), new Double(args[2])));
LogHelper.showInfo("tpLocMsgToTarget#####[" + args[0].toString() + " " + args[1].toString() + " " + args[2].toString(), sender, ChatColor.AQUA);
if (player != target){
LogHelper.showInfo("tpLocSuccess#####[" + target.getName() + " #####tpLocToCoords#####[" + args[0].toString() + " " + args[1].toString() + " " + args[2].toString(), sender, ChatColor.GREEN);
}
} catch (Throwable e) {
LogHelper.showWarning("internalError", sender);
LogHelper.logSevere("[CommandsEX]: TPLOC returned an unexpected error for player " + player.getName() + ".");
LogHelper.logDebug("Message: " + e.getMessage() + ", cause: " + e.getCause());
e.printStackTrace();
return false;
}
}
}
}
}
return true;
}
}
| true | true | public static Boolean run(CommandSender sender, String alias, String[] args) {
if (PlayerHelper.checkIsPlayer(sender)) {
Player player = (Player)sender;
if (!Utils.checkCommandSpam(player, "tp-tploc")) {
// first of all, check permissions
if (Permissions.checkPerms(player, "cex.tploc")) {
// alternative usage, all 3 coords separated by comma in 1 argument
if (args.length == 1) {
if (args[0].contains(",")) {
args = args[0].split(",");
} else {
// no commas found in the argument, return error
LogHelper.showWarning("tpInvalidArgument", sender);
return false;
}
}
if (args.length <= 0) {
// no coordinates
Commands.showCommandHelpAndUsage(sender, "cex_tploc", alias);
} else if (!(args.length == 3 || args.length == 4)) {
// too few or too many arguments
LogHelper.showWarning("tpMissingCoords", sender);
return false;
} else if (!args[0].matches(CommandsEX.intRegex) || !args[1].matches(CommandsEX.intRegex) || !args[2].matches(CommandsEX.intRegex)) {
// one of the coordinates is not a number
LogHelper.showWarning("tpCoordsMustBeNumeric", sender);
} else {
try {
Player target = null;
if (args.length == 4){
if (Bukkit.getPlayer(args[3]) != null){
target = Bukkit.getPlayer(args[3]);
} else {
LogHelper.showInfo("invalidPlayer", player, ChatColor.RED);
return true;
}
} else {
target = player;
}
delayedTeleport(target, new Location(player.getWorld(), new Double(args[0]), new Double(args[1]), new Double(args[2])));
LogHelper.showInfo("tpLocMsgToTarget#####[" + args[0].toString() + " " + args[1].toString() + " " + args[2].toString(), sender, ChatColor.AQUA);
if (player != target){
LogHelper.showInfo("tpLocSuccess#####[" + target.getName() + " #####tpLocToCoords#####[" + args[0].toString() + " " + args[1].toString() + " " + args[2].toString(), sender, ChatColor.GREEN);
}
} catch (Throwable e) {
LogHelper.showWarning("internalError", sender);
LogHelper.logSevere("[CommandsEX]: TPLOC returned an unexpected error for player " + player.getName() + ".");
LogHelper.logDebug("Message: " + e.getMessage() + ", cause: " + e.getCause());
e.printStackTrace();
return false;
}
}
}
}
}
return true;
}
| public static Boolean run(CommandSender sender, String alias, String[] args) {
if (PlayerHelper.checkIsPlayer(sender)) {
Player player = (Player)sender;
if (!Utils.checkCommandSpam(player, "tp-tploc")) {
// first of all, check permissions
if (Permissions.checkPerms(player, "cex.tploc")) {
// alternative usage, all 3 coords separated by comma in 1 argument
if (args.length == 1) {
if (args[0].contains(",")) {
args = args[0].split(",");
} else {
Commands.showCommandHelpAndUsage(sender, "cex_tploc", alias);
return true;
}
}
if (args.length <= 0) {
// no coordinates
Commands.showCommandHelpAndUsage(sender, "cex_tploc", alias);
} else if (!(args.length == 3 || args.length == 4)) {
// too few or too many arguments
LogHelper.showWarning("tpMissingCoords", sender);
return false;
} else if (!args[0].matches(CommandsEX.intRegex) || !args[1].matches(CommandsEX.intRegex) || !args[2].matches(CommandsEX.intRegex)) {
// one of the coordinates is not a number
LogHelper.showWarning("tpCoordsMustBeNumeric", sender);
} else {
try {
Player target = null;
if (args.length == 4){
if (Bukkit.getPlayer(args[3]) != null){
target = Bukkit.getPlayer(args[3]);
} else {
LogHelper.showInfo("invalidPlayer", player, ChatColor.RED);
return true;
}
} else {
target = player;
}
delayedTeleport(target, new Location(player.getWorld(), new Double(args[0]), new Double(args[1]), new Double(args[2])));
LogHelper.showInfo("tpLocMsgToTarget#####[" + args[0].toString() + " " + args[1].toString() + " " + args[2].toString(), sender, ChatColor.AQUA);
if (player != target){
LogHelper.showInfo("tpLocSuccess#####[" + target.getName() + " #####tpLocToCoords#####[" + args[0].toString() + " " + args[1].toString() + " " + args[2].toString(), sender, ChatColor.GREEN);
}
} catch (Throwable e) {
LogHelper.showWarning("internalError", sender);
LogHelper.logSevere("[CommandsEX]: TPLOC returned an unexpected error for player " + player.getName() + ".");
LogHelper.logDebug("Message: " + e.getMessage() + ", cause: " + e.getCause());
e.printStackTrace();
return false;
}
}
}
}
}
return true;
}
|
diff --git a/src/main/java/com/salesforce/dataloader/client/HttpClientTransport.java b/src/main/java/com/salesforce/dataloader/client/HttpClientTransport.java
index a421222..f489483 100644
--- a/src/main/java/com/salesforce/dataloader/client/HttpClientTransport.java
+++ b/src/main/java/com/salesforce/dataloader/client/HttpClientTransport.java
@@ -1,200 +1,202 @@
/*
* Copyright (c) 2012, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dataloader.client;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.auth.*;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.tools.VersionInfo;
import com.sforce.ws.transport.*;
/**
*
* This class implements the Transport interface for WSC with HttpClient in order to properly
* work with NTLM proxies. The existing JdkHttpTransport in WSC does not work with NTLM
* proxies when compiled on Java 1.6
*
* @author Jeff Lai
* @since 25.0.2
*/
public class HttpClientTransport implements Transport {
private ConnectorConfig config;
private boolean successful;
private HttpPost post;
private OutputStream output;
private ByteArrayOutputStream entityByteOut;
public HttpClientTransport() {
}
public HttpClientTransport(ConnectorConfig config) {
setConfig(config);
}
@Override
public void setConfig(ConnectorConfig config) {
this.config = config;
}
@Override
public OutputStream connect(String url, String soapAction) throws IOException {
if (soapAction == null) {
soapAction = "";
}
HashMap<String, String> header = new HashMap<String, String>();
header.put("SOAPAction", "\"" + soapAction + "\"");
header.put("Content-Type", "text/xml; charset=UTF-8");
header.put("Accept", "text/xml");
return connect(url, header);
}
@Override
public InputStream getContent() throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
- if (config.getProxy() != null) {
+ if (config.getProxy().address() != null) {
String proxyUser = config.getProxyUsername() == null ? "" : config.getProxyUsername();
String proxyPassword = config.getProxyPassword() == null ? "" : config.getProxyPassword();
Credentials credentials;
if (config.getNtlmDomain() != null && !config.getNtlmDomain().equals("")) {
String computerName = InetAddress.getLocalHost().getCanonicalHostName();
credentials = new NTCredentials(proxyUser, proxyPassword, computerName, config.getNtlmDomain());
} else {
credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
}
InetSocketAddress proxyAddress = (InetSocketAddress) config.getProxy().address();
HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort(), "http");
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
AuthScope scope = new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort(), null, null);
client.getCredentialsProvider().setCredentials(scope, credentials);
}
InputStream input = null;
byte[] entityBytes = entityByteOut.toByteArray();
HttpEntity entity = new ByteArrayEntity(entityBytes);
post.setEntity(entity);
try {
if (config.getNtlmDomain() != null && !config.getNtlmDomain().equals("")) {
// need to send a HEAD request to trigger NTLM authentication
HttpHead head = new HttpHead("http://salesforce.com");
client.execute(head);
+ head.releaseConnection();
}
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() > 399) {
successful = false;
+ throw new RuntimeException(response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
} else {
successful = true;
}
// copy input stream data into a new input stream because releasing the connection will close the input stream
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
IOUtils.copy(response.getEntity().getContent(), bOut);
input = new ByteArrayInputStream(bOut.toByteArray());
if (response.containsHeader("Content-Encoding") && response.getHeaders("Content-Encoding")[0].getValue().equals("gzip")) {
input = new GZIPInputStream(input);
}
} finally {
post.releaseConnection();
}
return input;
}
@Override
public boolean isSuccessful() {
return successful;
}
@Override
public OutputStream connect(String endpoint, HashMap<String, String> httpHeaders) throws IOException {
return connect(endpoint, httpHeaders, true);
}
@Override
public OutputStream connect(String endpoint, HashMap<String, String> httpHeaders, boolean enableCompression) throws IOException {
post = new HttpPost(endpoint);
for (String name : httpHeaders.keySet()) {
post.addHeader(name, httpHeaders.get(name));
}
post.addHeader("User-Agent", VersionInfo.info());
if (enableCompression) {
post.addHeader("Content-Encoding", "gzip");
post.addHeader("Accept-Encoding", "gzip");
}
entityByteOut = new ByteArrayOutputStream();
output = entityByteOut;
if (config.getMaxRequestSize() > 0) {
output = new LimitingOutputStream(config.getMaxRequestSize(), output);
}
if (enableCompression && config.isCompression()) {
output = new GZIPOutputStream(output);
}
if (config.isTraceMessage()) {
output = config.teeOutputStream(output);
}
if (config.hasMessageHandlers()) {
URL url = new URL(endpoint);
output = new MessageHandlerOutputStream(config, url, output);
}
return output;
}
}
| false | true | public InputStream getContent() throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
if (config.getProxy() != null) {
String proxyUser = config.getProxyUsername() == null ? "" : config.getProxyUsername();
String proxyPassword = config.getProxyPassword() == null ? "" : config.getProxyPassword();
Credentials credentials;
if (config.getNtlmDomain() != null && !config.getNtlmDomain().equals("")) {
String computerName = InetAddress.getLocalHost().getCanonicalHostName();
credentials = new NTCredentials(proxyUser, proxyPassword, computerName, config.getNtlmDomain());
} else {
credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
}
InetSocketAddress proxyAddress = (InetSocketAddress) config.getProxy().address();
HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort(), "http");
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
AuthScope scope = new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort(), null, null);
client.getCredentialsProvider().setCredentials(scope, credentials);
}
InputStream input = null;
byte[] entityBytes = entityByteOut.toByteArray();
HttpEntity entity = new ByteArrayEntity(entityBytes);
post.setEntity(entity);
try {
if (config.getNtlmDomain() != null && !config.getNtlmDomain().equals("")) {
// need to send a HEAD request to trigger NTLM authentication
HttpHead head = new HttpHead("http://salesforce.com");
client.execute(head);
}
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() > 399) {
successful = false;
} else {
successful = true;
}
// copy input stream data into a new input stream because releasing the connection will close the input stream
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
IOUtils.copy(response.getEntity().getContent(), bOut);
input = new ByteArrayInputStream(bOut.toByteArray());
if (response.containsHeader("Content-Encoding") && response.getHeaders("Content-Encoding")[0].getValue().equals("gzip")) {
input = new GZIPInputStream(input);
}
} finally {
post.releaseConnection();
}
return input;
}
| public InputStream getContent() throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
if (config.getProxy().address() != null) {
String proxyUser = config.getProxyUsername() == null ? "" : config.getProxyUsername();
String proxyPassword = config.getProxyPassword() == null ? "" : config.getProxyPassword();
Credentials credentials;
if (config.getNtlmDomain() != null && !config.getNtlmDomain().equals("")) {
String computerName = InetAddress.getLocalHost().getCanonicalHostName();
credentials = new NTCredentials(proxyUser, proxyPassword, computerName, config.getNtlmDomain());
} else {
credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
}
InetSocketAddress proxyAddress = (InetSocketAddress) config.getProxy().address();
HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort(), "http");
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
AuthScope scope = new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort(), null, null);
client.getCredentialsProvider().setCredentials(scope, credentials);
}
InputStream input = null;
byte[] entityBytes = entityByteOut.toByteArray();
HttpEntity entity = new ByteArrayEntity(entityBytes);
post.setEntity(entity);
try {
if (config.getNtlmDomain() != null && !config.getNtlmDomain().equals("")) {
// need to send a HEAD request to trigger NTLM authentication
HttpHead head = new HttpHead("http://salesforce.com");
client.execute(head);
head.releaseConnection();
}
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() > 399) {
successful = false;
throw new RuntimeException(response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
} else {
successful = true;
}
// copy input stream data into a new input stream because releasing the connection will close the input stream
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
IOUtils.copy(response.getEntity().getContent(), bOut);
input = new ByteArrayInputStream(bOut.toByteArray());
if (response.containsHeader("Content-Encoding") && response.getHeaders("Content-Encoding")[0].getValue().equals("gzip")) {
input = new GZIPInputStream(input);
}
} finally {
post.releaseConnection();
}
return input;
}
|
diff --git a/carrot2/components/carrot2-input-snippet-reader/src/com/dawidweiss/carrot/input/snippetreader/extractors/regexp/SnippetDescription.java b/carrot2/components/carrot2-input-snippet-reader/src/com/dawidweiss/carrot/input/snippetreader/extractors/regexp/SnippetDescription.java
index f145108ff..5da99d127 100644
--- a/carrot2/components/carrot2-input-snippet-reader/src/com/dawidweiss/carrot/input/snippetreader/extractors/regexp/SnippetDescription.java
+++ b/carrot2/components/carrot2-input-snippet-reader/src/com/dawidweiss/carrot/input/snippetreader/extractors/regexp/SnippetDescription.java
@@ -1,122 +1,122 @@
/*
* Carrot2 project.
*
* Copyright (C) 2002-2006, Dawid Weiss, Stanisław Osiński.
* Portions (C) Contributors listed in "carrot2.CONTRIBUTORS" file.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.cs.put.poznan.pl/dweiss/carrot2.LICENSE
*/
package com.dawidweiss.carrot.input.snippetreader.extractors.regexp;
import org.dom4j.Element;
/**
* Objects of this class describe how to extract a single snippet from some
* string using regular expressions.
*
* @author Dawid Weiss
*/
public class SnippetDescription {
protected boolean valid;
protected RegularExpression snippetMatch;
protected RegularExpression titleStart;
protected RegularExpression titleEnd;
protected RegularExpression urlStart;
protected RegularExpression urlEnd;
protected RegularExpression summaryStart;
protected RegularExpression summaryEnd;
/**
* Use factory methods to acquire objects of this class.
*/
protected SnippetDescription() {
valid = false;
}
/**
* Initialize using an XML Element.
*
* @param snippetDescription
*/
public SnippetDescription(Element snippetDescription) {
this();
initInstanceFromXML(snippetDescription);
}
/**
* Returns a regular expression token matching an entire snippet.
*/
public RegularExpression getSnippetMatch() {
return snippetMatch;
}
/**
* Returns a regular expression token matching the start of a title.
*/
public RegularExpression getTitleStartMatch() {
return titleStart;
}
/**
* Returns a regular expression token matching the end of a title.
*/
public RegularExpression getTitleEndMatch() {
return titleEnd;
}
/**
* Returns a regular expression token matching the start of an URL.
*/
public RegularExpression getURLStartMatch() {
return urlStart;
}
/**
* Returns a regular expression token matching the end of an URL.
*/
public RegularExpression getURLEndMatch() {
return urlEnd;
}
/**
* Returns a regular expression token matching the start of a summary.
*/
public RegularExpression getSummaryStartMatch() {
return summaryStart;
}
/**
* Returns a regular expression token matching the end of a summary.
*/
public RegularExpression getSummaryEndMatch() {
return summaryEnd;
}
/**
* Initializes this object using an XML Element. See descriptors in
* the component's folder for examples.
*
* @param snippet The root Element of the description.
*/
protected void initInstanceFromXML(Element snippet) {
snippetMatch = new RegularExpression(snippet.element("match"));
titleStart = new RegularExpression((Element) snippet.selectSingleNode("title/start"));
titleEnd = new RegularExpression((Element) snippet.selectSingleNode("title/end"));
urlStart = new RegularExpression((Element) snippet.selectSingleNode("url/start"));
- urlEnd = new RegularExpression((Element) snippet.selectSingleNode("title/end"));
+ urlEnd = new RegularExpression((Element) snippet.selectSingleNode("url/end"));
summaryStart = new RegularExpression((Element) snippet.selectSingleNode("summary/start"));
summaryEnd = new RegularExpression((Element) snippet.selectSingleNode("summary/end"));
valid = true;
}
}
| true | true | protected void initInstanceFromXML(Element snippet) {
snippetMatch = new RegularExpression(snippet.element("match"));
titleStart = new RegularExpression((Element) snippet.selectSingleNode("title/start"));
titleEnd = new RegularExpression((Element) snippet.selectSingleNode("title/end"));
urlStart = new RegularExpression((Element) snippet.selectSingleNode("url/start"));
urlEnd = new RegularExpression((Element) snippet.selectSingleNode("title/end"));
summaryStart = new RegularExpression((Element) snippet.selectSingleNode("summary/start"));
summaryEnd = new RegularExpression((Element) snippet.selectSingleNode("summary/end"));
valid = true;
}
| protected void initInstanceFromXML(Element snippet) {
snippetMatch = new RegularExpression(snippet.element("match"));
titleStart = new RegularExpression((Element) snippet.selectSingleNode("title/start"));
titleEnd = new RegularExpression((Element) snippet.selectSingleNode("title/end"));
urlStart = new RegularExpression((Element) snippet.selectSingleNode("url/start"));
urlEnd = new RegularExpression((Element) snippet.selectSingleNode("url/end"));
summaryStart = new RegularExpression((Element) snippet.selectSingleNode("summary/start"));
summaryEnd = new RegularExpression((Element) snippet.selectSingleNode("summary/end"));
valid = true;
}
|
diff --git a/src/freemail/transport/Channel.java b/src/freemail/transport/Channel.java
index da164a7..919c731 100644
--- a/src/freemail/transport/Channel.java
+++ b/src/freemail/transport/Channel.java
@@ -1,1028 +1,1033 @@
/*
* Channel.java
* This file is part of Freemail
* Copyright (C) 2006,2007,2008 Dave Baker
* Copyright (C) 2007 Alexander Lehmann
* Copyright (C) 2009 Martin Nyhus
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package freemail.transport;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.SequenceInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.archive.util.Base32;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import freemail.AccountManager;
import freemail.AckProcrastinator;
import freemail.Freemail;
import freemail.FreemailAccount;
import freemail.MessageBank;
import freemail.Postman;
import freemail.SlotManager;
import freemail.SlotSaveCallback;
import freemail.fcp.ConnectionTerminatedException;
import freemail.fcp.FCPBadFileException;
import freemail.fcp.FCPFetchException;
import freemail.fcp.FCPInsertErrorMessage;
import freemail.fcp.HighLevelFCPClient;
import freemail.fcp.SSKKeyPair;
import freemail.utils.DateStringFactory;
import freemail.utils.Logger;
import freemail.utils.PropsFile;
import freemail.wot.Identity;
import freemail.wot.WoTConnection;
import freenet.support.SimpleFieldSet;
//FIXME: The message id gives away how many messages has been sent over the channel.
// Could it be replaced by a different solution that gives away less information?
public class Channel extends Postman {
private static final String CHANNEL_PROPS_NAME = "props";
private static final int POLL_AHEAD = 6;
private static final String OUTBOX_DIR_NAME = "outbox";
//The keys used in the props file
private static class PropsKeys {
private static final String PRIVATE_KEY = "privateKey";
private static final String PUBLIC_KEY = "publicKey";
private static final String FETCH_SLOT = "fetchSlot";
private static final String SEND_SLOT = "sendSlot";
private static final String IS_INITIATOR = "isInitiator";
private static final String MESSAGE_ID = "messageId";
private static final String SENDER_STATE = "sender-state";
private static final String RECIPIENT_STATE = "recipient-state";
private static final String RTS_SENT_AT = "rts-sent-at";
}
private final File channelDir;
private final PropsFile channelProps;
private final Set<Observer> observers = new HashSet<Observer>();
private final ScheduledExecutorService executor;
private final HighLevelFCPClient fcpClient;
private final Freemail freemail;
private final FreemailAccount account;
private Fetcher fetcher;
private final Object fetcherLock = new Object();
private Sender sender;
private final Object senderLock = new Object();
public Channel(File channelDir, ScheduledExecutorService executor, HighLevelFCPClient fcpClient, Freemail freemail, FreemailAccount account) {
if(executor == null) throw new NullPointerException();
this.executor = executor;
this.fcpClient = fcpClient;
this.account = account;
if(freemail == null) throw new NullPointerException();
this.freemail = freemail;
assert channelDir.isDirectory();
this.channelDir = channelDir;
File channelPropsFile = new File(channelDir, CHANNEL_PROPS_NAME);
if(!channelPropsFile.exists()) {
try {
if(!channelPropsFile.createNewFile()) {
Logger.error(this, "Could not create new props file in " + channelDir);
}
} catch(IOException e) {
Logger.error(this, "Could not create new props file in " + channelDir);
}
}
channelProps = PropsFile.createPropsFile(channelPropsFile);
//Message id is needed for queuing messages so it must be present
if(channelProps.get(PropsKeys.MESSAGE_ID) == null) {
channelProps.put(PropsKeys.MESSAGE_ID, "0");
}
}
public void processRTS(PropsFile rtsProps) {
Logger.debug(this, "Processing RTS");
//TODO: Set public key using private key
//TODO: Handle cases where we get a second RTS
synchronized(channelProps) {
if(channelProps.get(PropsKeys.IS_INITIATOR) == null) {
Logger.debug(this, "Setting " + PropsKeys.IS_INITIATOR + " to false");
channelProps.put(PropsKeys.IS_INITIATOR, "false");
} else {
Logger.debug(this, PropsKeys.IS_INITIATOR + " is already set to " + channelProps.get(PropsKeys.IS_INITIATOR));
}
if(channelProps.get(PropsKeys.PRIVATE_KEY) == null) {
Logger.debug(this, "Setting " + PropsKeys.PRIVATE_KEY + " to " + rtsProps.get("channel"));
channelProps.put(PropsKeys.PRIVATE_KEY, rtsProps.get("channel"));
} else {
Logger.debug(this, PropsKeys.PRIVATE_KEY + " is already set to " + channelProps.get(PropsKeys.PRIVATE_KEY));
}
if(channelProps.get(PropsKeys.FETCH_SLOT) == null) {
Logger.debug(this, "Setting " + PropsKeys.FETCH_SLOT + " to " + rtsProps.get("initiatorSlot"));
channelProps.put(PropsKeys.FETCH_SLOT, rtsProps.get("initiatorSlot"));
} else {
Logger.debug(this, PropsKeys.FETCH_SLOT + " is already set to " + channelProps.get(PropsKeys.FETCH_SLOT));
}
if(channelProps.get(PropsKeys.SEND_SLOT) == null) {
Logger.debug(this, "Setting " + PropsKeys.SEND_SLOT + " to " + rtsProps.get("responderSlot"));
channelProps.put(PropsKeys.SEND_SLOT, rtsProps.get("responderSlot"));
} else {
Logger.debug(this, PropsKeys.SEND_SLOT + " is already set to " + channelProps.get(PropsKeys.SEND_SLOT));
}
if(channelProps.get(PropsKeys.MESSAGE_ID) == null) {
Logger.debug(this, "Setting " + PropsKeys.MESSAGE_ID + " to 0");
channelProps.put(PropsKeys.MESSAGE_ID, "0");
} else {
Logger.debug(this, PropsKeys.MESSAGE_ID + " is already set to " + channelProps.get(PropsKeys.MESSAGE_ID));
}
if(channelProps.get(PropsKeys.RECIPIENT_STATE) == null) {
Logger.debug(this, "Setting " + PropsKeys.RECIPIENT_STATE + " to rts-received");
channelProps.put(PropsKeys.RECIPIENT_STATE, "rts-received");
} else {
Logger.debug(this, PropsKeys.RECIPIENT_STATE + " is already set to " + channelProps.get(PropsKeys.RECIPIENT_STATE));
}
}
}
public void startTasks() {
startFetcher();
startSender();
startRTSSender();
}
private void startFetcher() {
//Start fetcher if possible
String fetchSlot;
String isInitiator;
String publicKey;
synchronized(channelProps) {
fetchSlot = channelProps.get(PropsKeys.FETCH_SLOT);
isInitiator = channelProps.get(PropsKeys.IS_INITIATOR);
publicKey = channelProps.get(PropsKeys.PUBLIC_KEY);
}
if((fetchSlot != null) && (isInitiator != null) && (publicKey != null)) {
Fetcher f;
synchronized(fetcherLock) {
fetcher = new Fetcher();
f = fetcher;
}
executor.execute(f);
}
}
private void startSender() {
//Start sender if possible
String sendSlot;
String isInitiator;
String privateKey;
synchronized(channelProps) {
sendSlot = channelProps.get(PropsKeys.SEND_SLOT);
isInitiator = channelProps.get(PropsKeys.IS_INITIATOR);
privateKey = channelProps.get(PropsKeys.PRIVATE_KEY);
}
if((sendSlot != null) && (isInitiator != null) && (privateKey != null)) {
Sender s;
synchronized(senderLock) {
sender = new Sender();
s = sender;
}
executor.execute(s);
}
}
private void startRTSSender() {
String state;
synchronized(channelProps) {
state = channelProps.get(PropsKeys.SENDER_STATE);
}
if((state != null) && state.equals("cts-received")) {
return;
}
executor.execute(new RTSSender());
}
/**
* Places the data read from {@code message} on the send queue
* @param message the data to be sent
* @return {@code true} if the message was placed on the queue
* @throws NullPointerException if {@code message} is {@code null}
*/
public boolean sendMessage(InputStream message) {
if(message == null) throw new NullPointerException("Parameter message was null");
long messageId;
synchronized(channelProps) {
messageId = Long.parseLong(channelProps.get(PropsKeys.MESSAGE_ID));
channelProps.put(PropsKeys.MESSAGE_ID, messageId + 1);
}
//Write the message and attributes to the outbox
File outbox = new File(channelDir, OUTBOX_DIR_NAME);
if(!outbox.exists()) {
if(!outbox.mkdir()) {
Logger.error(this, "Couldn't create outbox directory: " + outbox);
return false;
}
}
File messageFile = new File(outbox, "message-" + messageId);
if(messageFile.exists()) {
//TODO: Pick next message id?
Logger.error(this, "Message id already in use");
return false;
}
try {
if(!messageFile.createNewFile()) {
Logger.error(this, "Couldn't create message file: " + messageFile);
return false;
}
OutputStream os = new FileOutputStream(messageFile);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
//Write the header that will be sent later
pw.print("messagetype=message\r\n");
pw.print("messageid=" + messageId + "\r\n");
pw.print("\r\n");
pw.flush();
//And the message contents
byte[] buffer = new byte[1024];
while(true) {
int count = message.read(buffer, 0, buffer.length);
if(count == -1) break;
os.write(buffer, 0, count);
}
} catch(IOException e) {
if(messageFile.exists()) {
if(!messageFile.delete()) {
Logger.error(this, "Couldn't delete message file (" + messageFile + ") after IOException");
}
}
return false;
}
Sender s;
synchronized(senderLock) {
s = sender;
}
if(s != null) {
executor.execute(s);
}
return true;
}
/**
* Sends a message to the remote side of the channel containing the given headers and the data
* read from {@code message}. "messagetype" must be set in {@code header}. If message is
* {@code null} no data will be sent after the header.
* @param fcpClient the HighLevelFCPClient used to send the message
* @param header the headers to prepend to the message
* @param message the data to be sent
* @return {@code true} if the message was sent successfully
* @throws ConnectionTerminatedException if the FCP connection is terminated while sending
* @throws IOException if the InputStream throws an IOException
*/
boolean sendMessage(HighLevelFCPClient fcpClient, SimpleFieldSet header, InputStream message) throws ConnectionTerminatedException, IOException {
assert (fcpClient != null);
assert (header.get("messagetype") != null);
String baseKey;
synchronized(channelProps) {
baseKey = channelProps.get(PropsKeys.PRIVATE_KEY);
}
//SimpleFieldSet seems to only output using \n,
//but we need \n\r so we need to do it manually
StringBuilder headerString = new StringBuilder();
Iterator<String> headerKeyIterator = header.keyIterator();
while(headerKeyIterator.hasNext()) {
String key = headerKeyIterator.next();
String value = header.get(key);
headerString.append(key + "=" + value + "\r\n");
}
headerString.append("\r\n");
ByteArrayInputStream headerBytes = new ByteArrayInputStream(headerString.toString().getBytes("UTF-8"));
InputStream data = (message == null) ? headerBytes : new SequenceInputStream(headerBytes, message);
while(true) {
String slot;
synchronized(channelProps) {
slot = channelProps.get(PropsKeys.SEND_SLOT);
}
FCPInsertErrorMessage fcpMessage;
try {
fcpMessage = fcpClient.put(data, baseKey + slot);
} catch(FCPBadFileException e) {
throw new IOException(e);
}
if(fcpMessage == null) {
slot = calculateNextSlot(slot);
synchronized(channelProps) {
channelProps.put(PropsKeys.SEND_SLOT, slot);
}
return true;
}
if(fcpMessage.errorcode == FCPInsertErrorMessage.COLLISION) {
slot = calculateNextSlot(slot);
//Write the new slot each round so we won't have
//to check all of them again if we fail
synchronized(channelProps) {
channelProps.put(PropsKeys.SEND_SLOT, slot);
}
Logger.debug(this, "Insert collided, trying slot " + slot);
continue;
}
Logger.debug(this, "Insert to slot " + slot + " failed: " + fcpMessage);
return false;
}
}
private String calculateNextSlot(String slot) {
byte[] buf = Base32.decode(slot);
SHA256Digest sha256 = new SHA256Digest();
sha256.update(buf, 0, buf.length);
sha256.doFinal(buf, 0);
return Base32.encode(buf);
}
private String generateRandomSlot() {
SHA256Digest sha256 = new SHA256Digest();
byte[] buf = new byte[sha256.getDigestSize()];
SecureRandom rnd = new SecureRandom();
rnd.nextBytes(buf);
return Base32.encode(buf);
}
private class Fetcher implements Runnable {
@Override
public void run() {
Logger.debug(this, "Fetcher running");
String slots;
synchronized(channelProps) {
slots = channelProps.get(PropsKeys.FETCH_SLOT);
}
if(slots == null) {
Logger.error(this, "Channel " + channelDir.getName() + " is corrupt - account file has no '" + PropsKeys.FETCH_SLOT + "' entry!");
//TODO: Either delete the channel or resend the RTS
return;
}
HashSlotManager slotManager = new HashSlotManager(new ChannelSlotSaveImpl(channelProps, PropsKeys.FETCH_SLOT), null, slots);
slotManager.setPollAhead(POLL_AHEAD);
String basekey;
synchronized(channelProps) {
basekey = channelProps.get(PropsKeys.PRIVATE_KEY);
}
if(basekey == null) {
Logger.error(this, "Contact " + channelDir.getName() + " is corrupt - account file has no '" + PropsKeys.PRIVATE_KEY + "' entry!");
//TODO: Either delete the channel or resend the RTS
return;
}
String isInitiator;
synchronized(channelProps) {
isInitiator = channelProps.get(PropsKeys.IS_INITIATOR);
}
if(isInitiator == null) {
Logger.error(this, "Contact " + channelDir.getName() + " is corrupt - account file has no '" + PropsKeys.IS_INITIATOR + "' entry!");
//TODO: Either delete the channel or resend the RTS
return;
}
if(isInitiator.equalsIgnoreCase("true")) {
basekey += "i-";
} else if(isInitiator.equalsIgnoreCase("false")) {
basekey += "r-";
} else {
Logger.error(this, "Contact " + channelDir.getName() + " is corrupt - '" + PropsKeys.IS_INITIATOR + "' entry contains an invalid value: " + isInitiator);
//TODO: Either delete the channel or resend the RTS
return;
}
String slot;
while((slot = slotManager.getNextSlot()) != null) {
String key = basekey + slot;
Logger.minor(this, "Attempting to fetch mail on key " + key);
File result;
try {
result = fcpClient.fetch(key);
} catch(ConnectionTerminatedException e) {
return;
} catch(FCPFetchException e) {
if(e.isFatal()) {
Logger.normal(this, "Fatal fetch failure, marking slot as used");
slotManager.slotUsed();
}
Logger.minor(this, "No mail in slot (fetch returned " + e.getMessage() + ")");
continue;
}
PropsFile messageProps = PropsFile.createPropsFile(result, true);
String messageType = messageProps.get("messagetype");
if(messageType == null) {
Logger.error(this, "Got message without messagetype, discarding");
result.delete();
continue;
}
if(messageType.equals("message")) {
try {
if(handleMessage(result, null)) {
slotManager.slotUsed();
}
} catch(ConnectionTerminatedException e) {
result.delete();
return;
}
} else if(messageType.equals("cts")) {
Logger.minor(this, "Successfully received CTS");
boolean success;
synchronized(channelProps) {
success = channelProps.put("status", "cts-received");
}
if(success) {
slotManager.slotUsed();
}
} else if(messageType.equals("ack")) {
if(handleAck(result)) {
slotManager.slotUsed();
}
} else {
Logger.error(this, "Got message of unknown type: " + messageType);
slotManager.slotUsed();
}
if(!result.delete()) {
Logger.error(this, "Deletion of " + result + " failed");
}
}
//Reschedule
executor.schedule(this, 5, TimeUnit.MINUTES);
}
}
private class Sender implements Runnable {
@Override
public void run() {
Logger.debug(this, "Sender running");
//TODO: Try sending messages
}
}
private class RTSSender implements Runnable {
@Override
public void run() {
Logger.debug(this, "RTSSender running");
//Check when the RTS should be sent
long sendRtsIn = sendRTSIn();
if(sendRtsIn < 0) {
return;
}
if(sendRtsIn > 0) {
Logger.debug(this, "Rescheduling RTSSender in " + sendRtsIn + " ms when the RTS is due to be inserted");
executor.schedule(this, sendRtsIn, TimeUnit.MILLISECONDS);
return;
}
//Get mailsite key from WoT
WoTConnection wotConnection = freemail.getWotConnection();
if(wotConnection == null) {
//WoT isn't loaded, so try again later
Logger.debug(this, "WoT not loaded, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//FIXME: Get the truster id in a better way
String senderId = channelDir.getParentFile().getParentFile().getName();
Logger.debug(this, "Getting identity from WoT");
Identity recipient = wotConnection.getIdentity(channelDir.getName(), senderId);
if(recipient == null) {
Logger.debug(this, "Didn't get identity from WoT, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//Strip the WoT part from the key and add the Freemail path
String mailsiteKey = recipient.getRequestURI();
mailsiteKey = mailsiteKey.substring(0, mailsiteKey.indexOf("/"));
mailsiteKey = mailsiteKey + "/mailsite/0/mailpage";
//Fetch the mailsite
File mailsite;
try {
Logger.debug(this, "Fetching mailsite from " + mailsiteKey);
mailsite = fcpClient.fetch(mailsiteKey);
} catch(ConnectionTerminatedException e) {
Logger.debug(this, "FCP connection has been terminated");
return;
} catch(FCPFetchException e) {
Logger.debug(this, "Mailsite fetch failed (" + e + "), trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//Get RTS KSK
PropsFile mailsiteProps = PropsFile.createPropsFile(mailsite, false);
String rtsKey = mailsiteProps.get("rtsksk");
//Get or generate RTS values
String privateKey;
String publicKey;
String initiatorSlot;
String responderSlot;
synchronized(channelProps) {
privateKey = channelProps.get(PropsKeys.PRIVATE_KEY);
publicKey = channelProps.get(PropsKeys.PUBLIC_KEY);
initiatorSlot = channelProps.get(PropsKeys.SEND_SLOT);
responderSlot = channelProps.get(PropsKeys.FETCH_SLOT);
if((privateKey == null) || (publicKey == null)) {
SSKKeyPair keyPair;
try {
Logger.debug(this, "Making new key pair");
keyPair = fcpClient.makeSSK();
} catch(ConnectionTerminatedException e) {
Logger.debug(this, "FCP connection has been terminated");
return;
}
privateKey = keyPair.privkey;
publicKey = keyPair.pubkey;
}
if(initiatorSlot == null) {
initiatorSlot = generateRandomSlot();
}
if(responderSlot == null) {
responderSlot = generateRandomSlot();
}
channelProps.put(PropsKeys.PUBLIC_KEY, publicKey);
channelProps.put(PropsKeys.PRIVATE_KEY, privateKey);
channelProps.put(PropsKeys.SEND_SLOT, initiatorSlot);
channelProps.put(PropsKeys.FETCH_SLOT, responderSlot);
}
//Get the senders mailsite key
Logger.debug(this, "Getting sender identity from WoT");
Identity senderIdentity = wotConnection.getIdentity(senderId, senderId);
if(senderIdentity == null) {
Logger.debug(this, "Didn't get identity from WoT, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
String senderMailsiteKey = recipient.getRequestURI();
senderMailsiteKey = senderMailsiteKey.substring(0, senderMailsiteKey.indexOf("/"));
senderMailsiteKey = senderMailsiteKey + "/mailsite/0/mailpage";
//Now build the RTS
byte[] rtsMessageBytes = buildRTSMessage(senderMailsiteKey, recipient.getIdentityID(), privateKey, initiatorSlot, responderSlot);
if(rtsMessageBytes == null) {
return;
}
//Sign the message
byte[] signedMessage = signRtsMessage(rtsMessageBytes);
if(signedMessage == null) {
return;
}
//Encrypt the message using the recipients public key
String keyModulus = mailsiteProps.get("asymkey.modulus");
if(keyModulus == null) {
Logger.error(this, "Mailsite is missing public key modulus");
executor.schedule(this, 1, TimeUnit.HOURS);
return;
}
String keyExponent = mailsiteProps.get("asymkey.pubexponent");
if(keyExponent == null) {
Logger.error(this, "Mailsite is missing public key exponent");
executor.schedule(this, 1, TimeUnit.HOURS);
return;
}
byte[] rtsMessage = encryptMessage(signedMessage, keyModulus, keyExponent);
//Insert
int slot;
try {
String key = "KSK@" + rtsKey + "-" + DateStringFactory.getKeyString();
Logger.debug(this, "Inserting RTS to " + key);
slot = fcpClient.slotInsert(rtsMessage, key, 1, "");
} catch(ConnectionTerminatedException e) {
return;
}
if(slot < 0) {
Logger.debug(this, "Slot insert failed, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//Update channel props file
synchronized(channelProps) {
- //TODO: What if we've gotten the CTS while inserting the RTS?
- channelProps.put(PropsKeys.SENDER_STATE, "rts-sent");
+ //Check if we've gotten the CTS while inserting the RTS
+ if(!"cts-received".equals(channelProps.get(PropsKeys.SENDER_STATE))) {
+ channelProps.put(PropsKeys.SENDER_STATE, "rts-sent");
+ }
channelProps.put(PropsKeys.RTS_SENT_AT, Long.toString(System.currentTimeMillis()));
}
long delay = sendRTSIn();
+ if(delay < 0) {
+ return;
+ }
Logger.debug(this, "Rescheduling RTSSender to run in " + delay + " ms when the reinsert is due");
executor.schedule(this, delay, TimeUnit.MILLISECONDS);
}
/**
* Returns the number of milliseconds left to when the RTS should be sent, or -1 if it
* should not be sent.
* @return the number of milliseconds left to when the RTS should be sent
*/
private long sendRTSIn() {
//Check if the CTS has been received
String channelState;
synchronized(channelProps) {
channelState = channelProps.get(PropsKeys.SENDER_STATE);
}
if((channelState != null) && channelState.equals("cts-received")) {
Logger.debug(this, "CTS has been received");
return -1;
}
//Check when the RTS should be (re)sent
String rtsSentAt;
synchronized(channelProps) {
rtsSentAt = channelProps.get(PropsKeys.RTS_SENT_AT);
}
if(rtsSentAt != null) {
long sendTime;
try {
sendTime = Long.parseLong(rtsSentAt);
} catch(NumberFormatException e) {
Logger.debug(this, "Illegal value in " + PropsKeys.RTS_SENT_AT + " field, assuming 0");
sendTime = 0;
}
long timeToResend = (24 * 60 * 60 * 1000) - (System.currentTimeMillis() - sendTime);
if(timeToResend > 0) {
return timeToResend;
}
}
//Send the RTS immediately
return 0;
}
private byte[] buildRTSMessage(String senderMailsiteKey, String recipientIdentityID, String channelPrivateKey, String initiatorSlot, String responderSlot) {
StringBuffer rtsMessage = new StringBuffer();
rtsMessage.append("mailsite=" + senderMailsiteKey + "\r\n");
rtsMessage.append("to=" + recipientIdentityID + "\r\n");
rtsMessage.append("channel=" + channelPrivateKey + "\r\n");
rtsMessage.append("initiatorSlot=" + initiatorSlot + "\r\n");
rtsMessage.append("responderSlot=" + responderSlot + "\r\n");
rtsMessage.append("\r\n");
byte[] rtsMessageBytes;
try {
rtsMessageBytes = rtsMessage.toString().getBytes("UTF-8");
} catch(UnsupportedEncodingException e) {
Logger.error(this, "JVM doesn't support UTF-8 charset");
e.printStackTrace();
return null;
}
return rtsMessageBytes;
}
private byte[] signRtsMessage(byte[] rtsMessageBytes) {
SHA256Digest sha256 = new SHA256Digest();
sha256.update(rtsMessageBytes, 0, rtsMessageBytes.length);
byte[] hash = new byte[sha256.getDigestSize()];
sha256.doFinal(hash, 0);
RSAKeyParameters ourPrivateKey = AccountManager.getPrivateKey(account.getProps());
AsymmetricBlockCipher signatureCipher = new RSAEngine();
signatureCipher.init(true, ourPrivateKey);
byte[] signature = null;
try {
signature = signatureCipher.processBlock(hash, 0, hash.length);
} catch(InvalidCipherTextException e) {
Logger.error(this, "Failed to RSA encrypt hash: " + e.getMessage());
e.printStackTrace();
return null;
}
byte[] signedMessage = new byte[rtsMessageBytes.length + signature.length];
System.arraycopy(rtsMessageBytes, 0, signedMessage, 0, rtsMessageBytes.length);
System.arraycopy(signature, 0, signedMessage, rtsMessageBytes.length, signature.length);
return signedMessage;
}
private byte[] encryptMessage(byte[] signedMessage, String keyModulus, String keyExponent) {
//Make a new symmetric key for the message
byte[] aesKeyAndIV = new byte[32 + 16];
SecureRandom rnd = new SecureRandom();
rnd.nextBytes(aesKeyAndIV);
//Encrypt the message with the new symmetric key
PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
KeyParameter aesKeyParameters = new KeyParameter(aesKeyAndIV, 16, 32);
ParametersWithIV aesParameters = new ParametersWithIV(aesKeyParameters, aesKeyAndIV, 0, 16);
aesCipher.init(true, aesParameters);
byte[] encryptedMessage = new byte[aesCipher.getOutputSize(signedMessage.length)];
int offset = aesCipher.processBytes(signedMessage, 0, signedMessage.length, encryptedMessage, 0);
try {
aesCipher.doFinal(encryptedMessage, offset);
} catch(InvalidCipherTextException e) {
Logger.error(this, "Failed to perform symmertic encryption on RTS data: " + e.getMessage());
e.printStackTrace();
return null;
}
RSAKeyParameters recipientPublicKey = new RSAKeyParameters(false, new BigInteger(keyModulus, 32), new BigInteger(keyExponent, 32));
AsymmetricBlockCipher keyCipher = new RSAEngine();
keyCipher.init(true, recipientPublicKey);
byte[] encryptedAesParameters = null;
try {
encryptedAesParameters = keyCipher.processBlock(aesKeyAndIV, 0, aesKeyAndIV.length);
} catch(InvalidCipherTextException e) {
Logger.error(this, "Failed to perform asymmertic encryption on RTS symmetric key: " + e.getMessage());
e.printStackTrace();
return null;
}
//Assemble the final message
byte[] rtsMessage = new byte[encryptedAesParameters.length + encryptedMessage.length];
System.arraycopy(encryptedAesParameters, 0, rtsMessage, 0, encryptedAesParameters.length);
System.arraycopy(encryptedMessage, 0, rtsMessage, encryptedAesParameters.length, encryptedMessage.length);
return rtsMessage;
}
}
/**
* Adds an observer to this Channel.
* @param observer the observer that should be added
* @throws NullPointerException if {@code observer} is {@code null}
*/
public void addObserver(Observer observer) {
if(observer == null) throw new NullPointerException();
synchronized(observers) {
observers.add(observer);
}
}
/**
* Removes an observer from this Channel.
* @param observer the observer that should be removed
*/
public void removeObserver(Observer observer) {
//This is a bug in the caller, but leave it as an assert since it won't corrupt any state
assert (observer != null);
synchronized(observers) {
observers.remove(observer);
}
}
public interface Observer {
public void fetched(InputStream data);
}
private boolean handleMessage(File msg, MessageBank mb) throws ConnectionTerminatedException {
// parse the Freemail header(s) out.
PropsFile msgprops = PropsFile.createPropsFile(msg, true);
String s_id = msgprops.get("id");
if (s_id == null) {
Logger.error(this,"Got a message with an invalid header. Discarding.");
msgprops.closeReader();
return true;
}
int id;
try {
id = Integer.parseInt(s_id);
} catch (NumberFormatException nfe) {
Logger.error(this,"Got a message with an invalid (non-integer) id. Discarding.");
msgprops.closeReader();
return true;
}
MessageLog msglog = new MessageLog(this.channelDir);
boolean isDupe;
try {
isDupe = msglog.isPresent(id);
} catch (IOException ioe) {
Logger.error(this,"Couldn't read logfile, so don't know whether received message is a duplicate or not. Leaving in the queue to try later.");
msgprops.closeReader();
return false;
}
if (isDupe) {
Logger.normal(this,"Got a message, but we've already logged that message ID as received. Discarding.");
msgprops.closeReader();
return true;
}
BufferedReader br = msgprops.getReader();
if (br == null) {
Logger.error(this,"Got an invalid message. Discarding.");
msgprops.closeReader();
return true;
}
try {
this.storeMessage(br, mb);
} catch (IOException ioe) {
return false;
}
Logger.normal(this,"You've got mail!");
try {
msglog.add(id);
} catch (IOException ioe) {
// how should we handle this? Remove the message from the inbox again?
Logger.error(this,"warning: failed to write log file!");
}
String ack_key;
synchronized(this.channelProps) {
ack_key = this.channelProps.get("ackssk");
}
if (ack_key == null) {
Logger.error(this,"Warning! Can't send message acknowledgement - don't have an 'ackssk' entry! This message will eventually bounce, even though you've received it.");
return true;
}
ack_key += "ack-"+id;
AckProcrastinator.put(ack_key);
return true;
}
private boolean handleAck(File result) {
PropsFile ackProps = PropsFile.createPropsFile(result);
String id = ackProps.get("id");
File outbox = new File(channelDir, OUTBOX_DIR_NAME);
if(!outbox.exists()) {
Logger.minor(this, "Got ack for message " + id + ", but the outbox doesn't exist");
return true;
}
File message = new File(outbox, "message-" + id);
if(!message.exists()) {
Logger.minor(this, "Got ack for message " + id + ", but the message doesn't exist");
return true;
}
if(!message.delete()) {
Logger.error(this, "Couldn't delete " + message);
return false;
}
return true;
}
private class HashSlotManager extends SlotManager {
HashSlotManager(SlotSaveCallback cb, Object userdata, String slotlist) {
super(cb, userdata, slotlist);
}
@Override
protected String incSlot(String slot) {
return calculateNextSlot(slot);
}
}
private static class MessageLog {
private static final String LOGFILE = "log";
private final File logfile;
public MessageLog(File ibctdir) {
this.logfile = new File(ibctdir, LOGFILE);
}
public boolean isPresent(int targetid) throws IOException {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(this.logfile));
} catch (FileNotFoundException fnfe) {
return false;
}
String line;
while ( (line = br.readLine()) != null) {
int curid = Integer.parseInt(line);
if (curid == targetid) {
br.close();
return true;
}
}
br.close();
return false;
}
public void add(int id) throws IOException {
FileOutputStream fos = new FileOutputStream(this.logfile, true);
PrintStream ps = new PrintStream(fos);
ps.println(id);
ps.close();
}
}
private static class ChannelSlotSaveImpl implements SlotSaveCallback {
private final PropsFile propsFile;
private final String keyName;
private ChannelSlotSaveImpl(PropsFile propsFile, String keyName) {
this.propsFile = propsFile;
this.keyName = keyName;
}
@Override
public void saveSlots(String slots, Object userdata) {
synchronized(propsFile) {
propsFile.put(keyName, slots);
}
}
}
}
| false | true | public void run() {
Logger.debug(this, "RTSSender running");
//Check when the RTS should be sent
long sendRtsIn = sendRTSIn();
if(sendRtsIn < 0) {
return;
}
if(sendRtsIn > 0) {
Logger.debug(this, "Rescheduling RTSSender in " + sendRtsIn + " ms when the RTS is due to be inserted");
executor.schedule(this, sendRtsIn, TimeUnit.MILLISECONDS);
return;
}
//Get mailsite key from WoT
WoTConnection wotConnection = freemail.getWotConnection();
if(wotConnection == null) {
//WoT isn't loaded, so try again later
Logger.debug(this, "WoT not loaded, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//FIXME: Get the truster id in a better way
String senderId = channelDir.getParentFile().getParentFile().getName();
Logger.debug(this, "Getting identity from WoT");
Identity recipient = wotConnection.getIdentity(channelDir.getName(), senderId);
if(recipient == null) {
Logger.debug(this, "Didn't get identity from WoT, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//Strip the WoT part from the key and add the Freemail path
String mailsiteKey = recipient.getRequestURI();
mailsiteKey = mailsiteKey.substring(0, mailsiteKey.indexOf("/"));
mailsiteKey = mailsiteKey + "/mailsite/0/mailpage";
//Fetch the mailsite
File mailsite;
try {
Logger.debug(this, "Fetching mailsite from " + mailsiteKey);
mailsite = fcpClient.fetch(mailsiteKey);
} catch(ConnectionTerminatedException e) {
Logger.debug(this, "FCP connection has been terminated");
return;
} catch(FCPFetchException e) {
Logger.debug(this, "Mailsite fetch failed (" + e + "), trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//Get RTS KSK
PropsFile mailsiteProps = PropsFile.createPropsFile(mailsite, false);
String rtsKey = mailsiteProps.get("rtsksk");
//Get or generate RTS values
String privateKey;
String publicKey;
String initiatorSlot;
String responderSlot;
synchronized(channelProps) {
privateKey = channelProps.get(PropsKeys.PRIVATE_KEY);
publicKey = channelProps.get(PropsKeys.PUBLIC_KEY);
initiatorSlot = channelProps.get(PropsKeys.SEND_SLOT);
responderSlot = channelProps.get(PropsKeys.FETCH_SLOT);
if((privateKey == null) || (publicKey == null)) {
SSKKeyPair keyPair;
try {
Logger.debug(this, "Making new key pair");
keyPair = fcpClient.makeSSK();
} catch(ConnectionTerminatedException e) {
Logger.debug(this, "FCP connection has been terminated");
return;
}
privateKey = keyPair.privkey;
publicKey = keyPair.pubkey;
}
if(initiatorSlot == null) {
initiatorSlot = generateRandomSlot();
}
if(responderSlot == null) {
responderSlot = generateRandomSlot();
}
channelProps.put(PropsKeys.PUBLIC_KEY, publicKey);
channelProps.put(PropsKeys.PRIVATE_KEY, privateKey);
channelProps.put(PropsKeys.SEND_SLOT, initiatorSlot);
channelProps.put(PropsKeys.FETCH_SLOT, responderSlot);
}
//Get the senders mailsite key
Logger.debug(this, "Getting sender identity from WoT");
Identity senderIdentity = wotConnection.getIdentity(senderId, senderId);
if(senderIdentity == null) {
Logger.debug(this, "Didn't get identity from WoT, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
String senderMailsiteKey = recipient.getRequestURI();
senderMailsiteKey = senderMailsiteKey.substring(0, senderMailsiteKey.indexOf("/"));
senderMailsiteKey = senderMailsiteKey + "/mailsite/0/mailpage";
//Now build the RTS
byte[] rtsMessageBytes = buildRTSMessage(senderMailsiteKey, recipient.getIdentityID(), privateKey, initiatorSlot, responderSlot);
if(rtsMessageBytes == null) {
return;
}
//Sign the message
byte[] signedMessage = signRtsMessage(rtsMessageBytes);
if(signedMessage == null) {
return;
}
//Encrypt the message using the recipients public key
String keyModulus = mailsiteProps.get("asymkey.modulus");
if(keyModulus == null) {
Logger.error(this, "Mailsite is missing public key modulus");
executor.schedule(this, 1, TimeUnit.HOURS);
return;
}
String keyExponent = mailsiteProps.get("asymkey.pubexponent");
if(keyExponent == null) {
Logger.error(this, "Mailsite is missing public key exponent");
executor.schedule(this, 1, TimeUnit.HOURS);
return;
}
byte[] rtsMessage = encryptMessage(signedMessage, keyModulus, keyExponent);
//Insert
int slot;
try {
String key = "KSK@" + rtsKey + "-" + DateStringFactory.getKeyString();
Logger.debug(this, "Inserting RTS to " + key);
slot = fcpClient.slotInsert(rtsMessage, key, 1, "");
} catch(ConnectionTerminatedException e) {
return;
}
if(slot < 0) {
Logger.debug(this, "Slot insert failed, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//Update channel props file
synchronized(channelProps) {
//TODO: What if we've gotten the CTS while inserting the RTS?
channelProps.put(PropsKeys.SENDER_STATE, "rts-sent");
channelProps.put(PropsKeys.RTS_SENT_AT, Long.toString(System.currentTimeMillis()));
}
long delay = sendRTSIn();
Logger.debug(this, "Rescheduling RTSSender to run in " + delay + " ms when the reinsert is due");
executor.schedule(this, delay, TimeUnit.MILLISECONDS);
}
| public void run() {
Logger.debug(this, "RTSSender running");
//Check when the RTS should be sent
long sendRtsIn = sendRTSIn();
if(sendRtsIn < 0) {
return;
}
if(sendRtsIn > 0) {
Logger.debug(this, "Rescheduling RTSSender in " + sendRtsIn + " ms when the RTS is due to be inserted");
executor.schedule(this, sendRtsIn, TimeUnit.MILLISECONDS);
return;
}
//Get mailsite key from WoT
WoTConnection wotConnection = freemail.getWotConnection();
if(wotConnection == null) {
//WoT isn't loaded, so try again later
Logger.debug(this, "WoT not loaded, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//FIXME: Get the truster id in a better way
String senderId = channelDir.getParentFile().getParentFile().getName();
Logger.debug(this, "Getting identity from WoT");
Identity recipient = wotConnection.getIdentity(channelDir.getName(), senderId);
if(recipient == null) {
Logger.debug(this, "Didn't get identity from WoT, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//Strip the WoT part from the key and add the Freemail path
String mailsiteKey = recipient.getRequestURI();
mailsiteKey = mailsiteKey.substring(0, mailsiteKey.indexOf("/"));
mailsiteKey = mailsiteKey + "/mailsite/0/mailpage";
//Fetch the mailsite
File mailsite;
try {
Logger.debug(this, "Fetching mailsite from " + mailsiteKey);
mailsite = fcpClient.fetch(mailsiteKey);
} catch(ConnectionTerminatedException e) {
Logger.debug(this, "FCP connection has been terminated");
return;
} catch(FCPFetchException e) {
Logger.debug(this, "Mailsite fetch failed (" + e + "), trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//Get RTS KSK
PropsFile mailsiteProps = PropsFile.createPropsFile(mailsite, false);
String rtsKey = mailsiteProps.get("rtsksk");
//Get or generate RTS values
String privateKey;
String publicKey;
String initiatorSlot;
String responderSlot;
synchronized(channelProps) {
privateKey = channelProps.get(PropsKeys.PRIVATE_KEY);
publicKey = channelProps.get(PropsKeys.PUBLIC_KEY);
initiatorSlot = channelProps.get(PropsKeys.SEND_SLOT);
responderSlot = channelProps.get(PropsKeys.FETCH_SLOT);
if((privateKey == null) || (publicKey == null)) {
SSKKeyPair keyPair;
try {
Logger.debug(this, "Making new key pair");
keyPair = fcpClient.makeSSK();
} catch(ConnectionTerminatedException e) {
Logger.debug(this, "FCP connection has been terminated");
return;
}
privateKey = keyPair.privkey;
publicKey = keyPair.pubkey;
}
if(initiatorSlot == null) {
initiatorSlot = generateRandomSlot();
}
if(responderSlot == null) {
responderSlot = generateRandomSlot();
}
channelProps.put(PropsKeys.PUBLIC_KEY, publicKey);
channelProps.put(PropsKeys.PRIVATE_KEY, privateKey);
channelProps.put(PropsKeys.SEND_SLOT, initiatorSlot);
channelProps.put(PropsKeys.FETCH_SLOT, responderSlot);
}
//Get the senders mailsite key
Logger.debug(this, "Getting sender identity from WoT");
Identity senderIdentity = wotConnection.getIdentity(senderId, senderId);
if(senderIdentity == null) {
Logger.debug(this, "Didn't get identity from WoT, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
String senderMailsiteKey = recipient.getRequestURI();
senderMailsiteKey = senderMailsiteKey.substring(0, senderMailsiteKey.indexOf("/"));
senderMailsiteKey = senderMailsiteKey + "/mailsite/0/mailpage";
//Now build the RTS
byte[] rtsMessageBytes = buildRTSMessage(senderMailsiteKey, recipient.getIdentityID(), privateKey, initiatorSlot, responderSlot);
if(rtsMessageBytes == null) {
return;
}
//Sign the message
byte[] signedMessage = signRtsMessage(rtsMessageBytes);
if(signedMessage == null) {
return;
}
//Encrypt the message using the recipients public key
String keyModulus = mailsiteProps.get("asymkey.modulus");
if(keyModulus == null) {
Logger.error(this, "Mailsite is missing public key modulus");
executor.schedule(this, 1, TimeUnit.HOURS);
return;
}
String keyExponent = mailsiteProps.get("asymkey.pubexponent");
if(keyExponent == null) {
Logger.error(this, "Mailsite is missing public key exponent");
executor.schedule(this, 1, TimeUnit.HOURS);
return;
}
byte[] rtsMessage = encryptMessage(signedMessage, keyModulus, keyExponent);
//Insert
int slot;
try {
String key = "KSK@" + rtsKey + "-" + DateStringFactory.getKeyString();
Logger.debug(this, "Inserting RTS to " + key);
slot = fcpClient.slotInsert(rtsMessage, key, 1, "");
} catch(ConnectionTerminatedException e) {
return;
}
if(slot < 0) {
Logger.debug(this, "Slot insert failed, trying again in 5 minutes");
executor.schedule(this, 5, TimeUnit.MINUTES);
return;
}
//Update channel props file
synchronized(channelProps) {
//Check if we've gotten the CTS while inserting the RTS
if(!"cts-received".equals(channelProps.get(PropsKeys.SENDER_STATE))) {
channelProps.put(PropsKeys.SENDER_STATE, "rts-sent");
}
channelProps.put(PropsKeys.RTS_SENT_AT, Long.toString(System.currentTimeMillis()));
}
long delay = sendRTSIn();
if(delay < 0) {
return;
}
Logger.debug(this, "Rescheduling RTSSender to run in " + delay + " ms when the reinsert is due");
executor.schedule(this, delay, TimeUnit.MILLISECONDS);
}
|
diff --git a/OsmAnd/src/net/osmand/plus/views/MapInfoLayer.java b/OsmAnd/src/net/osmand/plus/views/MapInfoLayer.java
index 31ebe7f0..ccb9632a 100644
--- a/OsmAnd/src/net/osmand/plus/views/MapInfoLayer.java
+++ b/OsmAnd/src/net/osmand/plus/views/MapInfoLayer.java
@@ -1,831 +1,831 @@
package net.osmand.plus.views;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.LinkedHashSet;
import java.util.Set;
import net.osmand.Algoritms;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.OsmandSettings.CommonPreference;
import net.osmand.plus.R;
import net.osmand.plus.activities.ApplicationMode;
import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.activities.SettingsActivity;
import net.osmand.plus.extrasettings.OsmandExtraSettings;
import net.osmand.plus.routing.RouteDirectionInfo;
import net.osmand.plus.routing.RoutingHelper;
import net.osmand.plus.views.MapInfoControls.MapInfoControlRegInfo;
import net.osmand.render.RenderingRuleProperty;
import net.osmand.render.RenderingRulesStorage;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MapInfoLayer extends OsmandMapLayer {
public static float scaleCoefficient = 1;
private final MapActivity map;
private final RouteLayer routeLayer;
private OsmandMapTileView view;
private Paint paintText;
private Paint paintSubText;
private Paint paintSmallText;
private Paint paintSmallSubText;
private Paint paintImg;
// layout pseudo-constants
private int STATUS_BAR_MARGIN_X = -4;
private ImageView backToLocation;
private View progressBar;
// groups
private MapStackControl rightStack;
private MapStackControl leftStack;
private LinearLayout statusBar;
private MapInfoControl lanesControl;
private MapInfoControl alarmControl;
private MapInfoControls mapInfoControls;
private TopTextView topText;
private LockInfoControl lockInfoControl;
private String ADDITIONAL_VECTOR_RENDERING_CATEGORY;
public MapInfoLayer(MapActivity map, RouteLayer layer){
this.map = map;
this.routeLayer = layer;
WindowManager mgr = (WindowManager) map.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
mgr.getDefaultDisplay().getMetrics(dm);
scaleCoefficient = dm.density;
if (Math.min(dm.widthPixels / (dm.density * 160), dm.heightPixels / (dm.density * 160)) > 2.5f) {
// large screen
scaleCoefficient *= 1.5f;
}
ADDITIONAL_VECTOR_RENDERING_CATEGORY = map.getString(R.string.map_widget_vector_attributes);
paintText = new Paint();
paintText.setStyle(Style.FILL_AND_STROKE);
paintText.setColor(Color.BLACK);
paintText.setTextSize(23 * scaleCoefficient);
paintText.setAntiAlias(true);
paintText.setStrokeWidth(4);
paintSubText = new Paint();
paintSubText.setStyle(Style.FILL_AND_STROKE);
paintSubText.setColor(Color.BLACK);
paintSubText.setTextSize(15 * scaleCoefficient);
paintSubText.setAntiAlias(true);
paintSmallText = new Paint();
paintSmallText.setStyle(Style.FILL_AND_STROKE);
paintSmallText.setColor(Color.BLACK);
paintSmallText.setTextSize(19 * scaleCoefficient);
paintSmallText.setAntiAlias(true);
paintSmallText.setStrokeWidth(4);
paintSmallSubText = new Paint();
paintSmallSubText.setStyle(Style.FILL_AND_STROKE);
paintSmallSubText.setColor(Color.BLACK);
paintSmallSubText.setTextSize(13 * scaleCoefficient);
paintSmallSubText.setAntiAlias(true);
paintImg = new Paint();
paintImg.setDither(true);
paintImg.setFilterBitmap(true);
paintImg.setAntiAlias(true);
mapInfoControls = new MapInfoControls(map.getMyApplication().getSettings());
lockInfoControl = new LockInfoControl();
}
public Paint getPaintSmallSubText() {
return paintSmallSubText;
}
public Paint getPaintText() {
return paintText;
}
public Paint getPaintSmallText() {
return paintSmallText;
}
public Paint getPaintSubText() {
return paintSubText;
}
public LockInfoControl getLockInfoControl() {
return lockInfoControl;
}
public MapInfoControls getMapInfoControls() {
return mapInfoControls;
}
@Override
public void initLayer(final OsmandMapTileView view) {
this.view = view;
registerAllControls();
createControls();
}
private void applyTheme() {
int boxTop = R.drawable.box_top_stack;
int boxTopR = R.drawable.box_top_r;
int boxTopL = R.drawable.box_top_l;
int expand = R.drawable.box_expand;
if(view.getSettings().TRANSPARENT_MAP_THEME.get()){
boxTop = R.drawable.box_top_t_stack;
boxTopR = R.drawable.box_top_rt;
boxTopL = R.drawable.box_top_lt;
expand = R.drawable.box_expand_t;
}
rightStack.setTopDrawable(view.getResources().getDrawable(boxTopR));
rightStack.setStackDrawable(boxTop);
leftStack.setTopDrawable(view.getResources().getDrawable(boxTopL));
leftStack.setStackDrawable(boxTop);
leftStack.setExpandImageDrawable(view.getResources().getDrawable(expand));
rightStack.setExpandImageDrawable(view.getResources().getDrawable(expand));
statusBar.setBackgroundDrawable(view.getResources().getDrawable(boxTop));
int color = Color.BLACK;
int shadowColor = !view.getSettings().TRANSPARENT_MAP_THEME.get() ? Color.TRANSPARENT : Color.WHITE;
if(paintText.getColor() != color) {
paintText.setColor(color);
topText.setTextColor(color);
paintSubText.setColor(color);
paintSmallText.setColor(color);
paintSmallSubText.setColor(color);
}
if(topText.getShadowColor() != shadowColor) {
topText.setShadowColor(shadowColor);
}
}
public void registerAllControls(){
statusBar = new LinearLayout(view.getContext());
statusBar.setOrientation(LinearLayout.HORIZONTAL);
RouteInfoControls ric = new RouteInfoControls(scaleCoefficient);
lanesControl = ric.createLanesControl(view.getApplication().getRoutingHelper(), view);
lanesControl.setBackgroundDrawable(view.getResources().getDrawable(R.drawable.box_free));
alarmControl = ric.createAlarmInfoControl(view.getApplication().getRoutingHelper(),
view.getContext(), view.getSettings());
// register right stack
EnumSet<ApplicationMode> all = EnumSet.allOf(ApplicationMode.class);
EnumSet<ApplicationMode> bicyclePedestrian = EnumSet.of(ApplicationMode.BICYCLE, ApplicationMode.PEDESTRIAN);
EnumSet<ApplicationMode> none = EnumSet.noneOf(ApplicationMode.class);
RoutingHelper routingHelper = view.getApplication().getRoutingHelper();
NextTurnInfoControl bigInfoControl = ric.createNextInfoControl(routingHelper, view.getApplication(), view.getSettings(), paintText,
paintSubText, false);
mapInfoControls.registerSideWidget(bigInfoControl, R.drawable.widget_next_turn, R.string.map_widget_next_turn,"next_turn", true, all, none, 5);
NextTurnInfoControl smallInfoControl = ric.createNextInfoControl(routingHelper, view.getApplication(), view.getSettings(),
paintSmallText, paintSmallSubText, true);
mapInfoControls.registerSideWidget(smallInfoControl, R.drawable.widget_next_turn, R.string.map_widget_next_turn_small, "next_turn_small", true, bicyclePedestrian, none, 10);
NextTurnInfoControl nextNextInfoControl = ric.createNextNextInfoControl(routingHelper, view.getApplication(), view.getSettings(),
paintSmallText, paintSmallSubText, true);
mapInfoControls.registerSideWidget(nextNextInfoControl, R.drawable.widget_next_turn, R.string.map_widget_next_next_turn, "next_next_turn",true, all, none, 15);
//MiniMapControl miniMap = ric.createMiniMapControl(routingHelper, view);
//mapInfoControls.registerSideWidget(miniMap, R.drawable.widget_next_turn, R.string.map_widget_mini_route, "mini_route", true, none, none, 20);
// right stack
TextInfoControl dist = ric.createDistanceControl(map, paintText, paintSubText);
mapInfoControls.registerSideWidget(dist, R.drawable.info_target, R.string.map_widget_distance, "distance", false, all, none, 5);
TextInfoControl time = ric.createTimeControl(map, paintText, paintSubText);
mapInfoControls.registerSideWidget(time, R.drawable.info_time, R.string.map_widget_time, "time",false, all, none, 10);
TextInfoControl speed = ric.createSpeedControl(map, paintText, paintSubText);
mapInfoControls.registerSideWidget(speed, R.drawable.info_speed, R.string.map_widget_speed, "speed", false, all, none, 15);
TextInfoControl alt = ric.createAltitudeControl(map, paintText, paintSubText);
mapInfoControls.registerSideWidget(alt, R.drawable.ic_altitude, R.string.map_widget_altitude, "altitude", false, EnumSet.of(ApplicationMode.PEDESTRIAN), none, 20);
// Top widgets
ImageViewControl compassView = createCompassView(map);
mapInfoControls.registerTopWidget(compassView, R.drawable.compass, R.string.map_widget_compass, "compass", MapInfoControls.LEFT_CONTROL, all, 5);
View config = createConfiguration();
mapInfoControls.registerTopWidget(config, R.drawable.widget_config, R.string.map_widget_config, "config", MapInfoControls.RIGHT_CONTROL, all, 10).required(ApplicationMode.values());
ImageView lockView = lockInfoControl.createLockScreenWidget(view, map);
mapInfoControls.registerTopWidget(lockView, R.drawable.lock_enabled, R.string.bg_service_screen_lock, "bgService", MapInfoControls.LEFT_CONTROL, all, 15);
backToLocation = createBackToLocation(map);
mapInfoControls.registerTopWidget(backToLocation, R.drawable.default_location, R.string.map_widget_back_to_loc, "back_to_location", MapInfoControls.RIGHT_CONTROL, all, 5);
View globus = createGlobus();
mapInfoControls.registerTopWidget(globus, R.drawable.globus, R.string.map_widget_map_select, "progress", MapInfoControls.RIGHT_CONTROL, none, 15);
topText = new TopTextView(routingHelper, map);
mapInfoControls.registerTopWidget(topText, R.drawable.street_name, R.string.map_widget_top_text, "street_name", MapInfoControls.MAIN_CONTROL, all, 100);
// Register appearance widgets
registerAppearanceWidgets();
}
private void registerAppearanceWidgets() {
final MapInfoControlRegInfo vectorRenderer = mapInfoControls.registerAppearanceWidget(R.drawable.widget_rendering_style, R.string.map_widget_renderer,
"renderer", view.getSettings().RENDERER);
final OsmandApplication app = view.getApplication();
vectorRenderer.setStateChangeListener(new Runnable() {
@Override
public void run() {
Builder bld = new AlertDialog.Builder(view.getContext());
bld.setTitle(R.string.renderers);
Collection<String> rendererNames = app.getRendererRegistry().getRendererNames();
final String[] items = rendererNames.toArray(new String[rendererNames.size()]);
int i = -1;
for(int j = 0; j< items.length; j++) {
if(items[j].equals(app.getRendererRegistry().getCurrentSelectedRenderer().getName())) {
i = j;
break;
}
}
bld.setSingleChoiceItems(items, i, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String renderer = items[which];
RenderingRulesStorage loaded = app.getRendererRegistry().getRenderer(renderer);
if (loaded != null) {
view.getSettings().RENDERER.set(renderer);
app.getRendererRegistry().setCurrentSelectedRender(loaded);
app.getResourceManager().getRenderer().clearCache();
view.refreshMap(true);
} else {
AccessibleToast.makeText(app, R.string.renderer_load_exception, Toast.LENGTH_SHORT).show();
}
createCustomRenderingProperties(loaded);
dialog.dismiss();
}
});
bld.show();
}
});
final MapInfoControlRegInfo dayNight = mapInfoControls.registerAppearanceWidget(R.drawable.widget_day_night_mode, R.string.map_widget_day_night,
"dayNight", view.getSettings().DAYNIGHT_MODE);
dayNight.setStateChangeListener(new Runnable() {
@Override
public void run() {
Builder bld = new AlertDialog.Builder(view.getContext());
bld.setTitle(R.string.daynight);
final String[] items = new String[OsmandSettings.DayNightMode.values().length];
for (int i = 0; i < items.length; i++) {
items[i] = OsmandSettings.DayNightMode.values()[i].toHumanString(map);
}
int i = view.getSettings().DAYNIGHT_MODE.get().ordinal();
bld.setSingleChoiceItems(items, i, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
view.getSettings().DAYNIGHT_MODE.set(OsmandSettings.DayNightMode.values()[which]);
app.getResourceManager().getRenderer().clearCache();
view.refreshMap(true);
dialog.dismiss();
}
});
bld.show();
}
});
final MapInfoControlRegInfo displayViewDirections = mapInfoControls.registerAppearanceWidget(R.drawable.widget_viewing_direction, R.string.map_widget_view_direction,
"viewDirection", view.getSettings().SHOW_VIEW_ANGLE);
displayViewDirections.setStateChangeListener(new Runnable() {
@Override
public void run() {
view.getSettings().SHOW_VIEW_ANGLE.set(!view.getSettings().SHOW_VIEW_ANGLE.get());
map.updateApplicationModeSettings();
}
});
createCustomRenderingProperties(app.getRendererRegistry().getCurrentSelectedRenderer());
}
private void createCustomRenderingProperties(RenderingRulesStorage renderer) {
String categoryName = ADDITIONAL_VECTOR_RENDERING_CATEGORY;
mapInfoControls.removeApperanceWidgets(categoryName);
final OsmandApplication app = view.getApplication();
for (final RenderingRuleProperty p : renderer.PROPS.getCustomRules()) {
String propertyName = SettingsActivity.getStringPropertyName(view.getContext(), p.getAttrName(), p.getName());
if(p.isBoolean()) {
final CommonPreference<Boolean> pref = view.getApplication().getSettings().getCustomRenderBooleanProperty(p.getAttrName());
int icon = 0;
try {
Field f = R.drawable.class.getField("widget_" + p.getAttrName().toLowerCase());
icon = f.getInt(null);
} catch(Exception e){
}
MapInfoControlRegInfo w = mapInfoControls.registerAppearanceWidget(icon, propertyName, "rend_"+p.getAttrName(), pref, categoryName);
w.setStateChangeListener(new Runnable() {
@Override
public void run() {
pref.set(!pref.get());
app.getResourceManager().getRenderer().clearCache();
view.refreshMap(true);
}
});
} else {
final CommonPreference<String> pref = view.getApplication().getSettings().getCustomRenderProperty(p.getAttrName());
int icon = 0;
try {
Field f = R.drawable.class.getField("widget_" + p.getAttrName().toLowerCase());
icon = f.getInt(null);
} catch(Exception e){
}
MapInfoControlRegInfo w = mapInfoControls.registerAppearanceWidget(icon, propertyName, "rend_"+p.getAttrName(), pref, categoryName);
w.setStateChangeListener(new Runnable() {
@Override
public void run() {
Builder b = new AlertDialog.Builder(view.getContext());
int i = Arrays.asList(p.getPossibleValues()).indexOf(pref.get());
b.setSingleChoiceItems(p.getPossibleValues(), i, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pref.set(p.getPossibleValues()[which]);
app.getResourceManager().getRenderer().clearCache();
view.refreshMap(true);
dialog.dismiss();
}
});
b.show();
}
});
}
}
}
public void recreateControls(){
rightStack.clearAllViews();
mapInfoControls.populateStackControl(rightStack, view, false);
leftStack.clearAllViews();
mapInfoControls.populateStackControl(leftStack, view, true);
leftStack.requestLayout();
rightStack.requestLayout();
statusBar.removeAllViews();
mapInfoControls.populateStatusBar(statusBar);
applyTheme();
}
public void createControls() {
// 1. Create view groups and controls
statusBar.setBackgroundDrawable(view.getResources().getDrawable(R.drawable.box_top));
rightStack = new MapStackControl(view.getContext());
leftStack = new MapStackControl(view.getContext());
// 2. Preparations
Rect topRectPadding = new Rect();
view.getResources().getDrawable(R.drawable.box_top).getPadding(topRectPadding);
// for measurement
statusBar.addView(backToLocation);
STATUS_BAR_MARGIN_X = (int) (STATUS_BAR_MARGIN_X * scaleCoefficient);
statusBar.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
Rect statusBarPadding = new Rect();
statusBar.getBackground().getPadding(statusBarPadding);
// 3. put into frame parent layout controls
FrameLayout parent = (FrameLayout) view.getParent();
// status bar hides own top part
int topMargin = statusBar.getMeasuredHeight() - statusBarPadding.top - statusBarPadding.bottom;
// we want that status bar lays over map stack controls
topMargin -= topRectPadding.top;
FrameLayout.LayoutParams flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT);
flp.rightMargin = STATUS_BAR_MARGIN_X;
flp.topMargin = topMargin;
rightStack.setLayoutParams(flp);
flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP);
flp.topMargin = (int) (topMargin + scaleCoefficient * 8);
lanesControl.setLayoutParams(flp);
flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.LEFT);
flp.leftMargin = STATUS_BAR_MARGIN_X;
flp.topMargin = topMargin;
leftStack.setLayoutParams(flp);
flp = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP);
flp.leftMargin = STATUS_BAR_MARGIN_X;
flp.rightMargin = STATUS_BAR_MARGIN_X;
flp.topMargin = -topRectPadding.top;
statusBar.setLayoutParams(flp);
flp = new FrameLayout.LayoutParams((int)(78 * scaleCoefficient),
(int)(78 * scaleCoefficient), Gravity.RIGHT | Gravity.BOTTOM);
flp.rightMargin = (int) (10*scaleCoefficient);
flp.bottomMargin = (int) (85*scaleCoefficient);
alarmControl.setLayoutParams(flp);
parent.addView(rightStack);
parent.addView(leftStack);
parent.addView(statusBar);
parent.addView(lanesControl);
parent.addView(alarmControl);
alarmControl.setVisibility(View.GONE);
lanesControl.setVisibility(View.GONE);
// update and create controls
recreateControls();
}
public Set<String> getSpecificVisibleCategories(Set<MapInfoControlRegInfo> m) {
Set<String> s = new LinkedHashSet<String>();
for(MapInfoControlRegInfo ms : m){
if(ms.getCategory() != null) {
s.add(ms.getCategory());
}
}
if(OsmandPlugin.getEnabledPlugin(OsmandExtraSettings.class) == null){
s.remove(ADDITIONAL_VECTOR_RENDERING_CATEGORY);
}
return s;
}
public void fillAppearanceWidgets(Set<MapInfoControlRegInfo> widgets, String category, ArrayList<Object> registry) {
for(MapInfoControlRegInfo w : widgets ) {
if(Algoritms.objectEquals(w.getCategory(), category)) {
registry.add(w);
}
}
}
public void openViewConfigureDialog() {
final OsmandSettings settings = view.getSettings();
final ArrayList<Object> list = new ArrayList<Object>();
String appMode = settings.getApplicationMode().toHumanString(view.getContext());
list.add(map.getString(R.string.map_widget_reset) + " [" + appMode +"] ");
list.add(map.getString(R.string.map_widget_top_stack));
list.addAll(mapInfoControls.getTop());
list.add(map.getString(R.string.map_widget_right_stack));
list.addAll(mapInfoControls.getRight());
list.add(map.getString(R.string.map_widget_left_stack));
list.addAll(mapInfoControls.getLeft());
Set<MapInfoControlRegInfo> widgets = mapInfoControls.getAppearanceWidgets();
Set<String> cats = getSpecificVisibleCategories(widgets);
list.add(map.getString(R.string.map_widget_appearance));
fillAppearanceWidgets(widgets, null, list);
for(String cat : cats) {
list.add(cat);
fillAppearanceWidgets(widgets, cat, list);
}
// final LayerMenuListener listener = new LayerMenuListener(adapter, mapView, settings);
final ApplicationMode mode = settings.getApplicationMode();
ListAdapter listAdapter = new ArrayAdapter<Object>(map, R.layout.layers_list_activity_item, R.id.title, list) {
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = map.getLayoutInflater().inflate(R.layout.layers_list_activity_item, null);
}
final TextView tv = (TextView) v.findViewById(R.id.title);
final CheckBox ch = ((CheckBox) v.findViewById(R.id.check_item));
Object o = list.get(position);
if(o instanceof MapInfoControlRegInfo) {
final MapInfoControlRegInfo mi = (MapInfoControlRegInfo) o;
String s = mi.visibleCollapsed(mode)? " - " : " ";
if(mi.message != null) {
tv.setText(s +mi.message +s);
} else {
tv.setText(s +map.getString(mi.messageId) +s);
}
// Put the image on the TextView
if (mi.drawable != 0) {
tv.setPadding((int) (12 *scaleCoefficient), 0, 0, 0);
tv.setCompoundDrawablesWithIntrinsicBounds(mi.drawable, 0, 0, 0);
} else {
tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
tv.setPadding((int) (30 *scaleCoefficient), 0, 0, 0);
}
final boolean selecteable = mi.selecteable();
ch.setOnCheckedChangeListener(null);
if(!mi.selecteable()) {
ch.setVisibility(View.INVISIBLE);
} else {
boolean check = mi.visibleCollapsed(mode) || mi.visible(mode);
ch.setChecked(check);
ch.setVisibility(View.VISIBLE);
}
ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mapInfoControls.changeVisibility(mi);
if (selecteable) {
ch.setChecked(mi.visible(mode) || mi.visibleCollapsed(mode));
}
String s = mi.visibleCollapsed(mode) ? " - " : " ";
if(mi.message != null) {
tv.setText(s +mi.message +s);
} else {
tv.setText(s +map.getString(mi.messageId) +s);
}
recreateControls();
}
});
} else {
tv.setText(o.toString());
tv.setPadding((int) (5 *scaleCoefficient), 0, 0, 0);
// reset
if (position == 0) {
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_reset_to_default, 0, 0, 0);
} else {
tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
ch.setVisibility(View.INVISIBLE);
}
return v;
}
};
Builder b = new AlertDialog.Builder(map);
b.setAdapter(listAdapter, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Object o = list.get(which);
if (o instanceof MapInfoControlRegInfo) {
final MapInfoControlRegInfo mi = (MapInfoControlRegInfo) o;
final boolean selecteable = mi.selecteable();
boolean check = mi.visibleCollapsed(mode) || mi.visible(mode);
if (check || selecteable) {
mapInfoControls.changeVisibility(mi);
}
recreateControls();
- } else if(o.toString().equals(map.getString(R.string.map_widget_reset))) {
+ } else if(which == 0) {
mapInfoControls.resetToDefault();
recreateControls();
}
}
});
final AlertDialog dlg = b.create();
// listener.setDialog(dlg);
dlg.setCanceledOnTouchOutside(true);
dlg.show();
}
@Override
public void onDraw(Canvas canvas, RectF latlonBounds, RectF tilesRect, DrawSettings nightMode) {
boolean bold = routeLayer.getHelper().isFollowingMode();
if(paintText.isFakeBoldText() != bold) {
paintText.setFakeBoldText(bold);
topText.getPaint().setFakeBoldText(bold);
paintSubText.setFakeBoldText(bold);
paintSmallText.setFakeBoldText(bold);
paintSmallSubText.setFakeBoldText(bold);
}
// update data on draw
rightStack.updateInfo();
leftStack.updateInfo();
lanesControl.updateInfo();
alarmControl.updateInfo();
for (int i = 0; i < statusBar.getChildCount(); i++) {
View v = statusBar.getChildAt(i);
if (v instanceof MapControlUpdateable) {
((MapControlUpdateable) v).updateInfo();
}
}
}
@Override
public void destroyLayer() {
}
@Override
public boolean drawInScreenPixels() {
return true;
}
public ImageView getBackToLocation() {
return backToLocation;
}
public View getProgressBar() {
return progressBar;
}
private View createConfiguration(){
final OsmandMapTileView view = map.getMapView();
FrameLayout fl = new FrameLayout(view.getContext());
FrameLayout.LayoutParams fparams = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ImageView configuration = new ImageView(map);
Drawable drawable = view.getResources().getDrawable(R.drawable.widget_config);
configuration.setBackgroundDrawable(drawable);
configuration.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openViewConfigureDialog();
}
});
fl.addView(configuration, fparams);
fparams = new FrameLayout.LayoutParams(drawable.getMinimumWidth(), drawable.getMinimumHeight());
progressBar = new View(view.getContext());
progressBar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openViewConfigureDialog();
}
});
fl.addView(progressBar, fparams);
return fl;
}
private View createGlobus(){
Drawable globusDrawable = view.getResources().getDrawable(R.drawable.globus);
ImageView globus = new ImageView(view.getContext());
globus.setImageDrawable(globusDrawable);
globus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
map.getMapLayers().openLayerSelectionDialog(view);
//map.getMapLayers().selectMapLayer(view);
}
});
return globus;
}
private ImageView createBackToLocation(final MapActivity map){
ImageView backToLocation = new ImageView(view.getContext());
backToLocation.setPadding((int) (5 * scaleCoefficient), 0, (int) (5 * scaleCoefficient), 0);
backToLocation.setImageDrawable(map.getResources().getDrawable(R.drawable.back_to_loc));
backToLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
map.backToLocationImpl();
}
});
return backToLocation;
}
private ImageViewControl createCompassView(final MapActivity map){
final Drawable compass = map.getResources().getDrawable(R.drawable.compass);
final int mw = (int) compass.getMinimumWidth() ;
final int mh = (int) compass.getMinimumHeight() ;
final OsmandMapTileView view = map.getMapView();
ImageViewControl compassView = new ImageViewControl(map) {
private float cachedRotate = 0;
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate(view.getRotate(), mw / 2, mh / 2);
compass.draw(canvas);
canvas.restore();
}
@Override
public boolean updateInfo() {
if(view.getRotate() != cachedRotate) {
cachedRotate = view.getRotate();
invalidate();
return true;
}
return false;
}
};
compassView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
map.switchRotateMapMode();
}
});
compassView.setImageDrawable(compass);
return compassView;
}
private static class TopTextView extends TextView implements MapControlUpdateable {
private final RoutingHelper routingHelper;
private final MapActivity map;
private int shadowColor = Color.WHITE;
public TopTextView(RoutingHelper routingHelper, MapActivity map) {
super(map);
this.routingHelper = routingHelper;
this.map = map;
getPaint().setTextAlign(Align.CENTER);
setTextColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
ShadowText.draw(getText().toString(), canvas, getWidth() / 2, getHeight() - 4 * scaleCoefficient,
getPaint(), shadowColor);
}
public void setShadowColor(int shadowColor) {
this.shadowColor = shadowColor;
}
public int getShadowColor() {
return shadowColor;
}
@Override
public boolean updateInfo() {
String text = null;
if (routingHelper != null && routingHelper.isRouteCalculated()) {
if (routingHelper.isFollowingMode()) {
text = routingHelper.getCurrentName();
} else {
int di = map.getMapLayers().getRouteInfoLayer().getDirectionInfo();
if (di >= 0 && map.getMapLayers().getRouteInfoLayer().isVisible()) {
RouteDirectionInfo next = routingHelper.getRouteDirections().get(di);
text = routingHelper.formatStreetName(next.getStreetName(), next.getRef());
}
}
}
if(text == null) {
text = "";
}
if (!text.equals(getText().toString())) {
TextPaint pp = new TextPaint(getPaint());
if (!text.equals("")) {
pp.setTextSize(20 * scaleCoefficient);
float ts = pp.measureText(text);
int wth = getWidth();
while (ts > wth && pp.getTextSize() > (14 * scaleCoefficient)) {
pp.setTextSize(pp.getTextSize() - 1);
ts = pp.measureText(text);
}
boolean dots = false;
while (ts > wth) {
dots = true;
text = text.substring(0, text.length() - 2);
ts = pp.measureText(text);
}
if (dots) {
text += "..";
}
setTextSize(TypedValue.COMPLEX_UNIT_PX, pp.getTextSize());
} else {
setTextSize(TypedValue.COMPLEX_UNIT_PX, 7);
}
setText(text);
invalidate();
return true;
}
return false;
}
}
}
| true | true | public void openViewConfigureDialog() {
final OsmandSettings settings = view.getSettings();
final ArrayList<Object> list = new ArrayList<Object>();
String appMode = settings.getApplicationMode().toHumanString(view.getContext());
list.add(map.getString(R.string.map_widget_reset) + " [" + appMode +"] ");
list.add(map.getString(R.string.map_widget_top_stack));
list.addAll(mapInfoControls.getTop());
list.add(map.getString(R.string.map_widget_right_stack));
list.addAll(mapInfoControls.getRight());
list.add(map.getString(R.string.map_widget_left_stack));
list.addAll(mapInfoControls.getLeft());
Set<MapInfoControlRegInfo> widgets = mapInfoControls.getAppearanceWidgets();
Set<String> cats = getSpecificVisibleCategories(widgets);
list.add(map.getString(R.string.map_widget_appearance));
fillAppearanceWidgets(widgets, null, list);
for(String cat : cats) {
list.add(cat);
fillAppearanceWidgets(widgets, cat, list);
}
// final LayerMenuListener listener = new LayerMenuListener(adapter, mapView, settings);
final ApplicationMode mode = settings.getApplicationMode();
ListAdapter listAdapter = new ArrayAdapter<Object>(map, R.layout.layers_list_activity_item, R.id.title, list) {
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = map.getLayoutInflater().inflate(R.layout.layers_list_activity_item, null);
}
final TextView tv = (TextView) v.findViewById(R.id.title);
final CheckBox ch = ((CheckBox) v.findViewById(R.id.check_item));
Object o = list.get(position);
if(o instanceof MapInfoControlRegInfo) {
final MapInfoControlRegInfo mi = (MapInfoControlRegInfo) o;
String s = mi.visibleCollapsed(mode)? " - " : " ";
if(mi.message != null) {
tv.setText(s +mi.message +s);
} else {
tv.setText(s +map.getString(mi.messageId) +s);
}
// Put the image on the TextView
if (mi.drawable != 0) {
tv.setPadding((int) (12 *scaleCoefficient), 0, 0, 0);
tv.setCompoundDrawablesWithIntrinsicBounds(mi.drawable, 0, 0, 0);
} else {
tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
tv.setPadding((int) (30 *scaleCoefficient), 0, 0, 0);
}
final boolean selecteable = mi.selecteable();
ch.setOnCheckedChangeListener(null);
if(!mi.selecteable()) {
ch.setVisibility(View.INVISIBLE);
} else {
boolean check = mi.visibleCollapsed(mode) || mi.visible(mode);
ch.setChecked(check);
ch.setVisibility(View.VISIBLE);
}
ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mapInfoControls.changeVisibility(mi);
if (selecteable) {
ch.setChecked(mi.visible(mode) || mi.visibleCollapsed(mode));
}
String s = mi.visibleCollapsed(mode) ? " - " : " ";
if(mi.message != null) {
tv.setText(s +mi.message +s);
} else {
tv.setText(s +map.getString(mi.messageId) +s);
}
recreateControls();
}
});
} else {
tv.setText(o.toString());
tv.setPadding((int) (5 *scaleCoefficient), 0, 0, 0);
// reset
if (position == 0) {
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_reset_to_default, 0, 0, 0);
} else {
tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
ch.setVisibility(View.INVISIBLE);
}
return v;
}
};
Builder b = new AlertDialog.Builder(map);
b.setAdapter(listAdapter, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Object o = list.get(which);
if (o instanceof MapInfoControlRegInfo) {
final MapInfoControlRegInfo mi = (MapInfoControlRegInfo) o;
final boolean selecteable = mi.selecteable();
boolean check = mi.visibleCollapsed(mode) || mi.visible(mode);
if (check || selecteable) {
mapInfoControls.changeVisibility(mi);
}
recreateControls();
} else if(o.toString().equals(map.getString(R.string.map_widget_reset))) {
mapInfoControls.resetToDefault();
recreateControls();
}
}
});
final AlertDialog dlg = b.create();
// listener.setDialog(dlg);
dlg.setCanceledOnTouchOutside(true);
dlg.show();
}
| public void openViewConfigureDialog() {
final OsmandSettings settings = view.getSettings();
final ArrayList<Object> list = new ArrayList<Object>();
String appMode = settings.getApplicationMode().toHumanString(view.getContext());
list.add(map.getString(R.string.map_widget_reset) + " [" + appMode +"] ");
list.add(map.getString(R.string.map_widget_top_stack));
list.addAll(mapInfoControls.getTop());
list.add(map.getString(R.string.map_widget_right_stack));
list.addAll(mapInfoControls.getRight());
list.add(map.getString(R.string.map_widget_left_stack));
list.addAll(mapInfoControls.getLeft());
Set<MapInfoControlRegInfo> widgets = mapInfoControls.getAppearanceWidgets();
Set<String> cats = getSpecificVisibleCategories(widgets);
list.add(map.getString(R.string.map_widget_appearance));
fillAppearanceWidgets(widgets, null, list);
for(String cat : cats) {
list.add(cat);
fillAppearanceWidgets(widgets, cat, list);
}
// final LayerMenuListener listener = new LayerMenuListener(adapter, mapView, settings);
final ApplicationMode mode = settings.getApplicationMode();
ListAdapter listAdapter = new ArrayAdapter<Object>(map, R.layout.layers_list_activity_item, R.id.title, list) {
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = map.getLayoutInflater().inflate(R.layout.layers_list_activity_item, null);
}
final TextView tv = (TextView) v.findViewById(R.id.title);
final CheckBox ch = ((CheckBox) v.findViewById(R.id.check_item));
Object o = list.get(position);
if(o instanceof MapInfoControlRegInfo) {
final MapInfoControlRegInfo mi = (MapInfoControlRegInfo) o;
String s = mi.visibleCollapsed(mode)? " - " : " ";
if(mi.message != null) {
tv.setText(s +mi.message +s);
} else {
tv.setText(s +map.getString(mi.messageId) +s);
}
// Put the image on the TextView
if (mi.drawable != 0) {
tv.setPadding((int) (12 *scaleCoefficient), 0, 0, 0);
tv.setCompoundDrawablesWithIntrinsicBounds(mi.drawable, 0, 0, 0);
} else {
tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
tv.setPadding((int) (30 *scaleCoefficient), 0, 0, 0);
}
final boolean selecteable = mi.selecteable();
ch.setOnCheckedChangeListener(null);
if(!mi.selecteable()) {
ch.setVisibility(View.INVISIBLE);
} else {
boolean check = mi.visibleCollapsed(mode) || mi.visible(mode);
ch.setChecked(check);
ch.setVisibility(View.VISIBLE);
}
ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mapInfoControls.changeVisibility(mi);
if (selecteable) {
ch.setChecked(mi.visible(mode) || mi.visibleCollapsed(mode));
}
String s = mi.visibleCollapsed(mode) ? " - " : " ";
if(mi.message != null) {
tv.setText(s +mi.message +s);
} else {
tv.setText(s +map.getString(mi.messageId) +s);
}
recreateControls();
}
});
} else {
tv.setText(o.toString());
tv.setPadding((int) (5 *scaleCoefficient), 0, 0, 0);
// reset
if (position == 0) {
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_reset_to_default, 0, 0, 0);
} else {
tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
ch.setVisibility(View.INVISIBLE);
}
return v;
}
};
Builder b = new AlertDialog.Builder(map);
b.setAdapter(listAdapter, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Object o = list.get(which);
if (o instanceof MapInfoControlRegInfo) {
final MapInfoControlRegInfo mi = (MapInfoControlRegInfo) o;
final boolean selecteable = mi.selecteable();
boolean check = mi.visibleCollapsed(mode) || mi.visible(mode);
if (check || selecteable) {
mapInfoControls.changeVisibility(mi);
}
recreateControls();
} else if(which == 0) {
mapInfoControls.resetToDefault();
recreateControls();
}
}
});
final AlertDialog dlg = b.create();
// listener.setDialog(dlg);
dlg.setCanceledOnTouchOutside(true);
dlg.show();
}
|
diff --git a/mmstudio/src/org/micromanager/acquisition/engine/BurstMaker.java b/mmstudio/src/org/micromanager/acquisition/engine/BurstMaker.java
index fd1081102..82df697d2 100644
--- a/mmstudio/src/org/micromanager/acquisition/engine/BurstMaker.java
+++ b/mmstudio/src/org/micromanager/acquisition/engine/BurstMaker.java
@@ -1,42 +1,42 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.micromanager.acquisition.engine;
import org.micromanager.api.DataProcessor;
/**
*
* @author arthur
*/
public class BurstMaker extends DataProcessor<ImageRequest> {
ImageRequest lastRequest_ = null;
boolean currentlyInBurst_ = false;
@Override
protected void process() {
ImageRequest thisRequest = this.poll();
if (lastRequest_ != null) {
boolean burstValid
= ((lastRequest_.exposure == thisRequest.exposure)
&& (lastRequest_.Position == thisRequest.Position)
&& (lastRequest_.SliceIndex == thisRequest.SliceIndex)
&& (lastRequest_.ChannelIndex == thisRequest.ChannelIndex)
&& (thisRequest.WaitTime <= lastRequest_.exposure)
&& (thisRequest.AutoFocus == false));
if (burstValid) {
if (!currentlyInBurst_) {
lastRequest_.startBurst = true;
}
lastRequest_.collectBurst = true;
}
produce(lastRequest_);
}
lastRequest_ = thisRequest;
- if (thisRequest.stop = true)
+ if (thisRequest.stop)
produce(thisRequest);
}
}
| true | true | protected void process() {
ImageRequest thisRequest = this.poll();
if (lastRequest_ != null) {
boolean burstValid
= ((lastRequest_.exposure == thisRequest.exposure)
&& (lastRequest_.Position == thisRequest.Position)
&& (lastRequest_.SliceIndex == thisRequest.SliceIndex)
&& (lastRequest_.ChannelIndex == thisRequest.ChannelIndex)
&& (thisRequest.WaitTime <= lastRequest_.exposure)
&& (thisRequest.AutoFocus == false));
if (burstValid) {
if (!currentlyInBurst_) {
lastRequest_.startBurst = true;
}
lastRequest_.collectBurst = true;
}
produce(lastRequest_);
}
lastRequest_ = thisRequest;
if (thisRequest.stop = true)
produce(thisRequest);
}
| protected void process() {
ImageRequest thisRequest = this.poll();
if (lastRequest_ != null) {
boolean burstValid
= ((lastRequest_.exposure == thisRequest.exposure)
&& (lastRequest_.Position == thisRequest.Position)
&& (lastRequest_.SliceIndex == thisRequest.SliceIndex)
&& (lastRequest_.ChannelIndex == thisRequest.ChannelIndex)
&& (thisRequest.WaitTime <= lastRequest_.exposure)
&& (thisRequest.AutoFocus == false));
if (burstValid) {
if (!currentlyInBurst_) {
lastRequest_.startBurst = true;
}
lastRequest_.collectBurst = true;
}
produce(lastRequest_);
}
lastRequest_ = thisRequest;
if (thisRequest.stop)
produce(thisRequest);
}
|
diff --git a/plugins/org.eclipse.gmf.codegen/src-templates/org/eclipse/gmf/codegen/templates/providers/ModelingAssistantProviderGenerator.java b/plugins/org.eclipse.gmf.codegen/src-templates/org/eclipse/gmf/codegen/templates/providers/ModelingAssistantProviderGenerator.java
index cebfc5c62..ccbee80cf 100644
--- a/plugins/org.eclipse.gmf.codegen/src-templates/org/eclipse/gmf/codegen/templates/providers/ModelingAssistantProviderGenerator.java
+++ b/plugins/org.eclipse.gmf.codegen/src-templates/org/eclipse/gmf/codegen/templates/providers/ModelingAssistantProviderGenerator.java
@@ -1,311 +1,311 @@
package org.eclipse.gmf.codegen.templates.providers;
import java.util.*;
import org.eclipse.gmf.codegen.gmfgen.*;
import org.eclipse.gmf.codegen.util.*;
public class ModelingAssistantProviderGenerator
{
protected static String nl;
public static synchronized ModelingAssistantProviderGenerator create(String lineSeparator)
{
nl = lineSeparator;
ModelingAssistantProviderGenerator result = new ModelingAssistantProviderGenerator();
nl = null;
return result;
}
protected final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
protected final String TEXT_1 = "package ";
protected final String TEXT_2 = ";" + NL;
protected final String TEXT_3 = NL + "import java.util.ArrayList;" + NL + "import java.util.Collection;" + NL + "import java.util.Collections;" + NL + "import java.util.HashSet;" + NL + "import java.util.Iterator;" + NL + "import java.util.List;" + NL + "" + NL + "import org.eclipse.core.runtime.IAdaptable;" + NL + "import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;" + NL + "import org.eclipse.gmf.runtime.emf.type.core.ElementTypeRegistry;" + NL + "import org.eclipse.gmf.runtime.emf.type.core.IElementType;" + NL + "import org.eclipse.gmf.runtime.emf.ui.services.modelingassistant.ModelingAssistantProvider;" + NL + "import org.eclipse.gmf.runtime.notation.Diagram;" + NL + "import org.eclipse.jface.viewers.ILabelProvider;" + NL + "import org.eclipse.jface.window.Window;" + NL + "import org.eclipse.swt.widgets.Display;" + NL + "import org.eclipse.swt.widgets.Shell;" + NL + "import org.eclipse.ui.dialogs.ElementListSelectionDialog;" + NL + "import org.eclipse.emf.ecore.EObject;" + NL + "import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;";
protected final String TEXT_4 = NL + NL + "/**" + NL + " * @generated" + NL + " */" + NL + "public class ";
protected final String TEXT_5 = " extends ModelingAssistantProvider {" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic List getTypesForPopupBar(IAdaptable host) {" + NL + "\t\tIGraphicalEditPart editPart = (IGraphicalEditPart) host.getAdapter(IGraphicalEditPart.class);";
protected final String TEXT_6 = NL + "\t\tif (editPart instanceof ";
protected final String TEXT_7 = ") {" + NL + "\t\t\tList types = new ArrayList();";
protected final String TEXT_8 = NL + "\t\t\ttypes.add(";
protected final String TEXT_9 = ".";
protected final String TEXT_10 = ");";
protected final String TEXT_11 = NL + "\t\t\treturn types;" + NL + "\t\t}";
protected final String TEXT_12 = NL + "\t\treturn Collections.EMPTY_LIST;" + NL + "\t}";
protected final String TEXT_13 = NL + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic List getRelTypesOnSource(IAdaptable source) {";
protected final String TEXT_14 = NL + "\t\tIGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source.getAdapter(IGraphicalEditPart.class);";
protected final String TEXT_15 = NL + "\t\tif (sourceEditPart instanceof ";
protected final String TEXT_16 = ") {" + NL + "\t\t\tList types = new ArrayList();";
protected final String TEXT_17 = NL + "\t\t\ttypes.add(";
protected final String TEXT_18 = ".";
protected final String TEXT_19 = ");";
protected final String TEXT_20 = NL + "\t\t\treturn types;" + NL + "\t\t}";
protected final String TEXT_21 = NL + "\t\treturn Collections.EMPTY_LIST;" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic List getRelTypesOnTarget(IAdaptable target) {";
protected final String TEXT_22 = NL + "\t\tIGraphicalEditPart targetEditPart = (IGraphicalEditPart) target.getAdapter(IGraphicalEditPart.class);";
protected final String TEXT_23 = NL + "\t\tif (targetEditPart instanceof ";
protected final String TEXT_24 = ") {" + NL + "\t\t\tList types = new ArrayList();";
protected final String TEXT_25 = NL + "\t\t\ttypes.add(";
protected final String TEXT_26 = ".";
protected final String TEXT_27 = ");";
protected final String TEXT_28 = NL + "\t\t\treturn types;" + NL + "\t\t}";
protected final String TEXT_29 = NL + "\t\treturn Collections.EMPTY_LIST;" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic List getRelTypesOnSourceAndTarget(IAdaptable source, IAdaptable target) {";
protected final String TEXT_30 = NL + "\t\tIGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source.getAdapter(IGraphicalEditPart.class);" + NL + "\t\tIGraphicalEditPart targetEditPart = (IGraphicalEditPart) target.getAdapter(IGraphicalEditPart.class);";
protected final String TEXT_31 = NL + "\t\tif (sourceEditPart instanceof ";
protected final String TEXT_32 = ") {" + NL + "\t\t\tList types = new ArrayList();";
protected final String TEXT_33 = NL + "\t\t\tif (targetEditPart instanceof ";
protected final String TEXT_34 = ") {" + NL + "\t\t\t\ttypes.add(";
protected final String TEXT_35 = ".";
protected final String TEXT_36 = ");" + NL + "\t\t\t}";
protected final String TEXT_37 = NL + "\t\t\treturn types;" + NL + "\t\t}";
protected final String TEXT_38 = NL + "\t\treturn Collections.EMPTY_LIST;" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic List getTypesForSource(IAdaptable target, IElementType relationshipType) {";
protected final String TEXT_39 = NL + "\t\tIGraphicalEditPart targetEditPart = (IGraphicalEditPart) target.getAdapter(IGraphicalEditPart.class);";
protected final String TEXT_40 = NL + "\t\tif (targetEditPart instanceof ";
protected final String TEXT_41 = ") {" + NL + "\t\t\tList types = new ArrayList();";
protected final String TEXT_42 = NL + "\t\t\tif (relationshipType == ";
protected final String TEXT_43 = ".";
protected final String TEXT_44 = ") {" + NL + "\t\t\t\ttypes.add(";
protected final String TEXT_45 = ".";
protected final String TEXT_46 = ");" + NL + "\t\t\t}";
protected final String TEXT_47 = NL + "\t\t\treturn types;" + NL + "\t\t}";
protected final String TEXT_48 = NL + "\t\treturn Collections.EMPTY_LIST;" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic List getTypesForTarget(IAdaptable source, IElementType relationshipType) {";
protected final String TEXT_49 = NL + "\t\tIGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source.getAdapter(IGraphicalEditPart.class);";
protected final String TEXT_50 = NL + "\t\tif (sourceEditPart instanceof ";
protected final String TEXT_51 = ") {" + NL + "\t\t\tList types = new ArrayList();";
protected final String TEXT_52 = NL + "\t\t\tif (relationshipType == ";
protected final String TEXT_53 = ".";
protected final String TEXT_54 = ") {" + NL + "\t\t\t\ttypes.add(";
protected final String TEXT_55 = ".";
protected final String TEXT_56 = ");" + NL + "\t\t\t}";
protected final String TEXT_57 = NL + "\t\t\treturn types;" + NL + "\t\t}";
protected final String TEXT_58 = NL + "\t\treturn Collections.EMPTY_LIST;" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic EObject selectExistingElementForSource(IAdaptable target, IElementType relationshipType) {" + NL + "\t\treturn selectExistingElement(target, getTypesForSource(target, relationshipType));" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic EObject selectExistingElementForTarget(IAdaptable source, IElementType relationshipType) {" + NL + "\t\treturn selectExistingElement(source, getTypesForTarget(source, relationshipType));" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected EObject selectExistingElement(IAdaptable host, Collection types) {" + NL + "\t\tif (types.isEmpty()) {" + NL + "\t\t\treturn null;" + NL + "\t\t}" + NL + "\t\tIGraphicalEditPart editPart = (IGraphicalEditPart) host.getAdapter(IGraphicalEditPart.class);" + NL + "\t\tif (editPart == null) {" + NL + "\t\t\treturn null;" + NL + "\t\t}" + NL + "\t\tDiagram diagram = (Diagram) editPart.getRoot().getContents().getModel();" + NL + "\t\tCollection elements = new HashSet();" + NL + "\t\tfor (Iterator it = diagram.getElement().eAllContents(); it.hasNext();) {" + NL + "\t\t\tEObject element = (EObject) it.next();" + NL + "\t\t\tif (isApplicableElement(element, types)) {" + NL + "\t\t\t\telements.add(element);" + NL + "\t\t\t}" + NL + "\t\t}" + NL + "\t\tif (elements.isEmpty()) {" + NL + "\t\t\treturn null;" + NL + "\t\t}" + NL + "\t\treturn selectElement((EObject[]) elements.toArray(new EObject[elements.size()]));" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected boolean isApplicableElement(EObject element, Collection types) {" + NL + "\t\tIElementType type = ElementTypeRegistry.getInstance().getElementType(element);" + NL + "\t\treturn types.contains(type);" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected EObject selectElement(EObject[] elements) {" + NL + "\t\tShell shell = Display.getCurrent().getActiveShell();" + NL + "\t\tILabelProvider labelProvider = new AdapterFactoryLabelProvider(";
protected final String TEXT_59 = ".getInstance().getItemProvidersAdapterFactory());" + NL + "\t\tElementListSelectionDialog dialog = new ElementListSelectionDialog(shell, labelProvider);" + NL + "\t\tdialog.setMessage(\"Available domain model elements:\");" + NL + "\t\tdialog.setTitle(\"Select domain model element\");" + NL + "\t\tdialog.setMultipleSelection(false);" + NL + "\t\tdialog.setElements(elements);" + NL + "\t\tEObject selected = null;" + NL + "\t\tif (dialog.open() == Window.OK) {" + NL + "\t\t\tselected = (EObject) dialog.getFirstResult();" + NL + "\t\t}" + NL + "\t\treturn selected;" + NL + "\t}" + NL + "}";
protected final String TEXT_60 = NL;
public String generate(Object argument)
{
StringBuffer stringBuffer = new StringBuffer();
GenDiagram genDiagram = (GenDiagram) argument;
stringBuffer.append(TEXT_1);
stringBuffer.append(genDiagram.getProvidersPackageName());
stringBuffer.append(TEXT_2);
ImportUtil importManager = new ImportUtil(genDiagram.getProvidersPackageName());
stringBuffer.append(TEXT_3);
importManager.markImportLocation(stringBuffer);
stringBuffer.append(TEXT_4);
stringBuffer.append(genDiagram.getModelingAssistantProviderClassName());
stringBuffer.append(TEXT_5);
for (Iterator contents = genDiagram.getAllContainers().iterator(); contents.hasNext(); ) {
GenContainerBase genContainer = (GenContainerBase) contents.next();
if (genContainer instanceof GenCompartment && ((GenCompartment) genContainer).isListLayout()) {
continue;
}
List children = new ArrayList(genContainer.getContainedNodes());
if (genContainer instanceof GenNode) {
for (Iterator compartments = ((GenNode) genContainer).getCompartments().iterator(); compartments.hasNext(); ) {
GenCompartment compartment = (GenCompartment) compartments.next();
if (compartment.isListLayout()) {
children.addAll(compartment.getContainedNodes());
}
}
}
if (!children.isEmpty()) {
stringBuffer.append(TEXT_6);
stringBuffer.append(importManager.getImportedName(genContainer.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_7);
for (int i = 0; i < children.size(); i++) {
String id = ((GenNode) children.get(i)).getUniqueIdentifier();
stringBuffer.append(TEXT_8);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_9);
stringBuffer.append(id);
stringBuffer.append(TEXT_10);
}
stringBuffer.append(TEXT_11);
}
}
stringBuffer.append(TEXT_12);
Map outgoingLinks = new LinkedHashMap(); // source -> links going from the source
Map incomingLinks = new LinkedHashMap(); // target -> links coming to the target
for (Iterator links = genDiagram.getLinks().iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator sources = genLink.getSources().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
Collection value = (Collection) outgoingLinks.get(source);
if (value == null) {
- value = new HashSet();
+ value = new LinkedHashSet();
outgoingLinks.put(source, value);
}
value.add(genLink);
}
for (Iterator targets = genLink.getTargets().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
Collection value = (Collection) incomingLinks.get(target);
if (value == null) {
- value = new HashSet();
+ value = new LinkedHashSet();
incomingLinks.put(target, value);
}
value.add(genLink);
}
}
stringBuffer.append(TEXT_13);
if (!outgoingLinks.isEmpty()) {
stringBuffer.append(TEXT_14);
for (Iterator sources = outgoingLinks.keySet().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_15);
stringBuffer.append(importManager.getImportedName(source.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_16);
for (Iterator links = ((Collection) outgoingLinks.get(source)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
stringBuffer.append(TEXT_17);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_18);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_19);
}
stringBuffer.append(TEXT_20);
}
}
stringBuffer.append(TEXT_21);
if (!incomingLinks.isEmpty()) {
stringBuffer.append(TEXT_22);
for (Iterator targets = incomingLinks.keySet().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_23);
stringBuffer.append(importManager.getImportedName(target.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_24);
for (Iterator links = ((Collection) incomingLinks.get(target)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
stringBuffer.append(TEXT_25);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_26);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_27);
}
stringBuffer.append(TEXT_28);
}
}
stringBuffer.append(TEXT_29);
if (!outgoingLinks.isEmpty()) {
stringBuffer.append(TEXT_30);
for (Iterator sources = outgoingLinks.keySet().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_31);
stringBuffer.append(importManager.getImportedName(source.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_32);
for (Iterator links = ((Collection) outgoingLinks.get(source)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator targets = genLink.getTargets().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_33);
stringBuffer.append(importManager.getImportedName(target.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_34);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_35);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_36);
}
}
stringBuffer.append(TEXT_37);
}
}
stringBuffer.append(TEXT_38);
if (!incomingLinks.isEmpty()) {
stringBuffer.append(TEXT_39);
for (Iterator targets = incomingLinks.keySet().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_40);
stringBuffer.append(importManager.getImportedName(target.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_41);
for (Iterator links = ((Collection) incomingLinks.get(target)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator sources = genLink.getSources().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_42);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_43);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_44);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_45);
stringBuffer.append(source.getUniqueIdentifier());
stringBuffer.append(TEXT_46);
}
}
stringBuffer.append(TEXT_47);
}
}
stringBuffer.append(TEXT_48);
if (!outgoingLinks.isEmpty()) {
stringBuffer.append(TEXT_49);
for (Iterator sources = outgoingLinks.keySet().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_50);
stringBuffer.append(importManager.getImportedName(source.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_51);
for (Iterator links = ((Collection) outgoingLinks.get(source)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator targets = genLink.getTargets().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_52);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_53);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_54);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_55);
stringBuffer.append(target.getUniqueIdentifier());
stringBuffer.append(TEXT_56);
}
}
stringBuffer.append(TEXT_57);
}
}
stringBuffer.append(TEXT_58);
stringBuffer.append(importManager.getImportedName(genDiagram.getPlugin().getActivatorQualifiedClassName()));
stringBuffer.append(TEXT_59);
importManager.emitSortedImports();
stringBuffer.append(TEXT_60);
return stringBuffer.toString();
}
}
| false | true | public String generate(Object argument)
{
StringBuffer stringBuffer = new StringBuffer();
GenDiagram genDiagram = (GenDiagram) argument;
stringBuffer.append(TEXT_1);
stringBuffer.append(genDiagram.getProvidersPackageName());
stringBuffer.append(TEXT_2);
ImportUtil importManager = new ImportUtil(genDiagram.getProvidersPackageName());
stringBuffer.append(TEXT_3);
importManager.markImportLocation(stringBuffer);
stringBuffer.append(TEXT_4);
stringBuffer.append(genDiagram.getModelingAssistantProviderClassName());
stringBuffer.append(TEXT_5);
for (Iterator contents = genDiagram.getAllContainers().iterator(); contents.hasNext(); ) {
GenContainerBase genContainer = (GenContainerBase) contents.next();
if (genContainer instanceof GenCompartment && ((GenCompartment) genContainer).isListLayout()) {
continue;
}
List children = new ArrayList(genContainer.getContainedNodes());
if (genContainer instanceof GenNode) {
for (Iterator compartments = ((GenNode) genContainer).getCompartments().iterator(); compartments.hasNext(); ) {
GenCompartment compartment = (GenCompartment) compartments.next();
if (compartment.isListLayout()) {
children.addAll(compartment.getContainedNodes());
}
}
}
if (!children.isEmpty()) {
stringBuffer.append(TEXT_6);
stringBuffer.append(importManager.getImportedName(genContainer.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_7);
for (int i = 0; i < children.size(); i++) {
String id = ((GenNode) children.get(i)).getUniqueIdentifier();
stringBuffer.append(TEXT_8);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_9);
stringBuffer.append(id);
stringBuffer.append(TEXT_10);
}
stringBuffer.append(TEXT_11);
}
}
stringBuffer.append(TEXT_12);
Map outgoingLinks = new LinkedHashMap(); // source -> links going from the source
Map incomingLinks = new LinkedHashMap(); // target -> links coming to the target
for (Iterator links = genDiagram.getLinks().iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator sources = genLink.getSources().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
Collection value = (Collection) outgoingLinks.get(source);
if (value == null) {
value = new HashSet();
outgoingLinks.put(source, value);
}
value.add(genLink);
}
for (Iterator targets = genLink.getTargets().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
Collection value = (Collection) incomingLinks.get(target);
if (value == null) {
value = new HashSet();
incomingLinks.put(target, value);
}
value.add(genLink);
}
}
stringBuffer.append(TEXT_13);
if (!outgoingLinks.isEmpty()) {
stringBuffer.append(TEXT_14);
for (Iterator sources = outgoingLinks.keySet().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_15);
stringBuffer.append(importManager.getImportedName(source.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_16);
for (Iterator links = ((Collection) outgoingLinks.get(source)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
stringBuffer.append(TEXT_17);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_18);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_19);
}
stringBuffer.append(TEXT_20);
}
}
stringBuffer.append(TEXT_21);
if (!incomingLinks.isEmpty()) {
stringBuffer.append(TEXT_22);
for (Iterator targets = incomingLinks.keySet().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_23);
stringBuffer.append(importManager.getImportedName(target.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_24);
for (Iterator links = ((Collection) incomingLinks.get(target)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
stringBuffer.append(TEXT_25);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_26);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_27);
}
stringBuffer.append(TEXT_28);
}
}
stringBuffer.append(TEXT_29);
if (!outgoingLinks.isEmpty()) {
stringBuffer.append(TEXT_30);
for (Iterator sources = outgoingLinks.keySet().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_31);
stringBuffer.append(importManager.getImportedName(source.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_32);
for (Iterator links = ((Collection) outgoingLinks.get(source)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator targets = genLink.getTargets().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_33);
stringBuffer.append(importManager.getImportedName(target.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_34);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_35);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_36);
}
}
stringBuffer.append(TEXT_37);
}
}
stringBuffer.append(TEXT_38);
if (!incomingLinks.isEmpty()) {
stringBuffer.append(TEXT_39);
for (Iterator targets = incomingLinks.keySet().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_40);
stringBuffer.append(importManager.getImportedName(target.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_41);
for (Iterator links = ((Collection) incomingLinks.get(target)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator sources = genLink.getSources().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_42);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_43);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_44);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_45);
stringBuffer.append(source.getUniqueIdentifier());
stringBuffer.append(TEXT_46);
}
}
stringBuffer.append(TEXT_47);
}
}
stringBuffer.append(TEXT_48);
if (!outgoingLinks.isEmpty()) {
stringBuffer.append(TEXT_49);
for (Iterator sources = outgoingLinks.keySet().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_50);
stringBuffer.append(importManager.getImportedName(source.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_51);
for (Iterator links = ((Collection) outgoingLinks.get(source)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator targets = genLink.getTargets().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_52);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_53);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_54);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_55);
stringBuffer.append(target.getUniqueIdentifier());
stringBuffer.append(TEXT_56);
}
}
stringBuffer.append(TEXT_57);
}
}
stringBuffer.append(TEXT_58);
stringBuffer.append(importManager.getImportedName(genDiagram.getPlugin().getActivatorQualifiedClassName()));
stringBuffer.append(TEXT_59);
importManager.emitSortedImports();
stringBuffer.append(TEXT_60);
return stringBuffer.toString();
}
| public String generate(Object argument)
{
StringBuffer stringBuffer = new StringBuffer();
GenDiagram genDiagram = (GenDiagram) argument;
stringBuffer.append(TEXT_1);
stringBuffer.append(genDiagram.getProvidersPackageName());
stringBuffer.append(TEXT_2);
ImportUtil importManager = new ImportUtil(genDiagram.getProvidersPackageName());
stringBuffer.append(TEXT_3);
importManager.markImportLocation(stringBuffer);
stringBuffer.append(TEXT_4);
stringBuffer.append(genDiagram.getModelingAssistantProviderClassName());
stringBuffer.append(TEXT_5);
for (Iterator contents = genDiagram.getAllContainers().iterator(); contents.hasNext(); ) {
GenContainerBase genContainer = (GenContainerBase) contents.next();
if (genContainer instanceof GenCompartment && ((GenCompartment) genContainer).isListLayout()) {
continue;
}
List children = new ArrayList(genContainer.getContainedNodes());
if (genContainer instanceof GenNode) {
for (Iterator compartments = ((GenNode) genContainer).getCompartments().iterator(); compartments.hasNext(); ) {
GenCompartment compartment = (GenCompartment) compartments.next();
if (compartment.isListLayout()) {
children.addAll(compartment.getContainedNodes());
}
}
}
if (!children.isEmpty()) {
stringBuffer.append(TEXT_6);
stringBuffer.append(importManager.getImportedName(genContainer.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_7);
for (int i = 0; i < children.size(); i++) {
String id = ((GenNode) children.get(i)).getUniqueIdentifier();
stringBuffer.append(TEXT_8);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_9);
stringBuffer.append(id);
stringBuffer.append(TEXT_10);
}
stringBuffer.append(TEXT_11);
}
}
stringBuffer.append(TEXT_12);
Map outgoingLinks = new LinkedHashMap(); // source -> links going from the source
Map incomingLinks = new LinkedHashMap(); // target -> links coming to the target
for (Iterator links = genDiagram.getLinks().iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator sources = genLink.getSources().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
Collection value = (Collection) outgoingLinks.get(source);
if (value == null) {
value = new LinkedHashSet();
outgoingLinks.put(source, value);
}
value.add(genLink);
}
for (Iterator targets = genLink.getTargets().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
Collection value = (Collection) incomingLinks.get(target);
if (value == null) {
value = new LinkedHashSet();
incomingLinks.put(target, value);
}
value.add(genLink);
}
}
stringBuffer.append(TEXT_13);
if (!outgoingLinks.isEmpty()) {
stringBuffer.append(TEXT_14);
for (Iterator sources = outgoingLinks.keySet().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_15);
stringBuffer.append(importManager.getImportedName(source.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_16);
for (Iterator links = ((Collection) outgoingLinks.get(source)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
stringBuffer.append(TEXT_17);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_18);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_19);
}
stringBuffer.append(TEXT_20);
}
}
stringBuffer.append(TEXT_21);
if (!incomingLinks.isEmpty()) {
stringBuffer.append(TEXT_22);
for (Iterator targets = incomingLinks.keySet().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_23);
stringBuffer.append(importManager.getImportedName(target.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_24);
for (Iterator links = ((Collection) incomingLinks.get(target)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
stringBuffer.append(TEXT_25);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_26);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_27);
}
stringBuffer.append(TEXT_28);
}
}
stringBuffer.append(TEXT_29);
if (!outgoingLinks.isEmpty()) {
stringBuffer.append(TEXT_30);
for (Iterator sources = outgoingLinks.keySet().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_31);
stringBuffer.append(importManager.getImportedName(source.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_32);
for (Iterator links = ((Collection) outgoingLinks.get(source)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator targets = genLink.getTargets().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_33);
stringBuffer.append(importManager.getImportedName(target.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_34);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_35);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_36);
}
}
stringBuffer.append(TEXT_37);
}
}
stringBuffer.append(TEXT_38);
if (!incomingLinks.isEmpty()) {
stringBuffer.append(TEXT_39);
for (Iterator targets = incomingLinks.keySet().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_40);
stringBuffer.append(importManager.getImportedName(target.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_41);
for (Iterator links = ((Collection) incomingLinks.get(target)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator sources = genLink.getSources().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_42);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_43);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_44);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_45);
stringBuffer.append(source.getUniqueIdentifier());
stringBuffer.append(TEXT_46);
}
}
stringBuffer.append(TEXT_47);
}
}
stringBuffer.append(TEXT_48);
if (!outgoingLinks.isEmpty()) {
stringBuffer.append(TEXT_49);
for (Iterator sources = outgoingLinks.keySet().iterator(); sources.hasNext(); ) {
GenCommonBase source = (GenCommonBase) sources.next();
stringBuffer.append(TEXT_50);
stringBuffer.append(importManager.getImportedName(source.getEditPartQualifiedClassName()));
stringBuffer.append(TEXT_51);
for (Iterator links = ((Collection) outgoingLinks.get(source)).iterator(); links.hasNext(); ) {
GenLink genLink = (GenLink) links.next();
for (Iterator targets = genLink.getTargets().iterator(); targets.hasNext(); ) {
GenCommonBase target = (GenCommonBase) targets.next();
stringBuffer.append(TEXT_52);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_53);
stringBuffer.append(genLink.getUniqueIdentifier());
stringBuffer.append(TEXT_54);
stringBuffer.append(importManager.getImportedName(genDiagram.getElementTypesQualifiedClassName()));
stringBuffer.append(TEXT_55);
stringBuffer.append(target.getUniqueIdentifier());
stringBuffer.append(TEXT_56);
}
}
stringBuffer.append(TEXT_57);
}
}
stringBuffer.append(TEXT_58);
stringBuffer.append(importManager.getImportedName(genDiagram.getPlugin().getActivatorQualifiedClassName()));
stringBuffer.append(TEXT_59);
importManager.emitSortedImports();
stringBuffer.append(TEXT_60);
return stringBuffer.toString();
}
|
diff --git a/src/main/java/freemarker/core/Macro.java b/src/main/java/freemarker/core/Macro.java
index 4c7edc39..44ac1c92 100644
--- a/src/main/java/freemarker/core/Macro.java
+++ b/src/main/java/freemarker/core/Macro.java
@@ -1,271 +1,272 @@
/*
* Copyright (c) 2003 The Visigoth Software Society. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Visigoth Software Society (http://www.visigoths.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
* project contributors may be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "FreeMarker" or "Visigoth"
* nor may "FreeMarker" or "Visigoth" appear in their names
* without prior written permission of the Visigoth Software Society.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE VISIGOTH SOFTWARE SOCIETY OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Visigoth Software Society. For more
* information on the Visigoth Software Society, please see
* http://www.visigoths.org/
*/
package freemarker.core;
import java.io.IOException;
import java.util.*;
import freemarker.template.*;
import freemarker.template.utility.StringUtil;
/**
* An element representing a macro declaration.
*/
public final class Macro extends TemplateElement implements TemplateModel {
private final String name;
private final String[] argumentNames;
private Map args;
private String catchAll;
boolean isFunction;
static final Macro DO_NOTHING_MACRO = new Macro(".pass",
Collections.EMPTY_LIST,
freemarker.template.utility.Collections12.EMPTY_MAP,
TextBlock.EMPTY_BLOCK);
Macro(String name, List argumentNames, Map args,
TemplateElement nestedBlock)
{
this.name = name;
this.argumentNames = (String[])argumentNames.toArray(
new String[argumentNames.size()]);
this.args = args;
this.nestedBlock = nestedBlock;
}
public String getCatchAll() {
return catchAll;
}
public void setCatchAll(String value) {
catchAll = value;
}
public String[] getArgumentNames() {
return (String[])argumentNames.clone();
}
String[] getArgumentNamesInternal() {
return argumentNames;
}
boolean hasArgNamed(String name) {
return args.containsKey(name);
}
public String getName() {
return name;
}
void accept(Environment env) {
env.visitMacroDef(this);
}
public String getCanonicalForm() {
String directiveName = isFunction ? "function" : "macro";
StringBuffer buf = new StringBuffer("<#");
buf.append(directiveName);
buf.append(' ');
buf.append(name);
buf.append('(');
int size = argumentNames.length;
for (int i = 0; i<size; i++) {
buf.append(argumentNames[i]);
if (i != (size-1)) {
buf.append(",");
}
}
buf.append(")>");
if (nestedBlock != null) {
buf.append(nestedBlock.getCanonicalForm());
}
buf.append("</#");
buf.append(directiveName);
buf.append('>');
return buf.toString();
}
public String getDescription() {
return (isFunction() ? "function " : "macro ") + name;
}
public boolean isFunction() {
return isFunction;
}
class Context implements LocalContext {
Environment.Namespace localVars;
TemplateElement body;
Environment.Namespace bodyNamespace;
List bodyParameterNames;
Context prevMacroContext;
ArrayList prevLocalContextStack;
Context(Environment env,
TemplateElement body,
List bodyParameterNames)
{
this.localVars = env.new Namespace();
this.prevMacroContext = env.getCurrentMacroContext();
this.bodyNamespace = env.getCurrentNamespace();
this.prevLocalContextStack = env.getLocalContextStack();
this.body = body;
this.bodyParameterNames = bodyParameterNames;
}
Macro getMacro() {
return Macro.this;
}
void runMacro(Environment env) throws TemplateException, IOException {
sanityCheck(env);
// Set default values for unspecified parameters
if (nestedBlock != null) {
env.visit(nestedBlock);
}
}
// Set default parameters, check if all the required parameters are defined.
void sanityCheck(Environment env) throws TemplateException {
boolean resolvedAnArg, hasUnresolvedArg;
Expression firstUnresolvedExpression;
InvalidReferenceException firstReferenceException;
do {
firstUnresolvedExpression = null;
firstReferenceException = null;
resolvedAnArg = hasUnresolvedArg = false;
for(int i = 0; i < argumentNames.length; ++i) {
String argName = argumentNames[i];
if(localVars.get(argName) == null) {
Expression valueExp = (Expression) args.get(argName);
if (valueExp != null) {
try {
TemplateModel tm = valueExp.getAsTemplateModel(env);
if(tm == null) {
if(!hasUnresolvedArg) {
firstUnresolvedExpression = valueExp;
hasUnresolvedArg = true;
}
}
else {
localVars.put(argName, tm);
resolvedAnArg = true;
}
}
catch(InvalidReferenceException e) {
if(!hasUnresolvedArg) {
hasUnresolvedArg = true;
firstReferenceException = e;
}
}
}
else {
throw new TemplateException(
"When calling macro " + StringUtil.jQuote(name)
+ ", required parameter " + StringUtil.jQuote(argName)
+ " (parameter #" + (i + 1) + ") was "
+ (localVars.containsKey(argName)
? "specified, but had null/missing value.\n"
- + "(Tip: If the parameter value expression is known to be legally "
- + "null/missing, you may want to specify a default value with the \"!\" "
- + "operator, like paramValueExpression!defaultValueExpression.)"
+ + "(Tip: If the parameter value expression on the caller side is known "
+ + "to be legally null/missing, you may want to specify a default value "
+ + "for it with the \"!\" operator, like "
+ + "paramValueExpression!defaultValueExpression.)"
: "not specified.\n"
+ "(Tip: If the omission was deliberate, you may consider making "
+ "the parameter optional in the macro by specifying a default value for "
+ "it, like "
+ StringUtil.encloseAsTag(
getTemplate(), "#macro myMacro paramName=defaultExpr")
+ ".)"),
env);
}
}
}
}
while(resolvedAnArg && hasUnresolvedArg);
if(hasUnresolvedArg) {
if(firstReferenceException != null) {
throw firstReferenceException;
}
else {
firstUnresolvedExpression.invalidReferenceException(env);
}
}
}
/**
* @return the local variable of the given name
* or null if it doesn't exist.
*/
public TemplateModel getLocalVariable(String name) throws TemplateModelException {
return localVars.get(name);
}
Environment.Namespace getLocals() {
return localVars;
}
/**
* Set a local variable in this macro
*/
void setLocalVar(String name, TemplateModel var) {
localVars.put(name, var);
}
public Collection getLocalVariableNames() throws TemplateModelException {
HashSet result = new HashSet();
for (TemplateModelIterator it = localVars.keys().iterator(); it.hasNext();) {
result.add(it.next().toString());
}
return result;
}
}
}
| true | true | void sanityCheck(Environment env) throws TemplateException {
boolean resolvedAnArg, hasUnresolvedArg;
Expression firstUnresolvedExpression;
InvalidReferenceException firstReferenceException;
do {
firstUnresolvedExpression = null;
firstReferenceException = null;
resolvedAnArg = hasUnresolvedArg = false;
for(int i = 0; i < argumentNames.length; ++i) {
String argName = argumentNames[i];
if(localVars.get(argName) == null) {
Expression valueExp = (Expression) args.get(argName);
if (valueExp != null) {
try {
TemplateModel tm = valueExp.getAsTemplateModel(env);
if(tm == null) {
if(!hasUnresolvedArg) {
firstUnresolvedExpression = valueExp;
hasUnresolvedArg = true;
}
}
else {
localVars.put(argName, tm);
resolvedAnArg = true;
}
}
catch(InvalidReferenceException e) {
if(!hasUnresolvedArg) {
hasUnresolvedArg = true;
firstReferenceException = e;
}
}
}
else {
throw new TemplateException(
"When calling macro " + StringUtil.jQuote(name)
+ ", required parameter " + StringUtil.jQuote(argName)
+ " (parameter #" + (i + 1) + ") was "
+ (localVars.containsKey(argName)
? "specified, but had null/missing value.\n"
+ "(Tip: If the parameter value expression is known to be legally "
+ "null/missing, you may want to specify a default value with the \"!\" "
+ "operator, like paramValueExpression!defaultValueExpression.)"
: "not specified.\n"
+ "(Tip: If the omission was deliberate, you may consider making "
+ "the parameter optional in the macro by specifying a default value for "
+ "it, like "
+ StringUtil.encloseAsTag(
getTemplate(), "#macro myMacro paramName=defaultExpr")
+ ".)"),
env);
}
}
}
}
while(resolvedAnArg && hasUnresolvedArg);
if(hasUnresolvedArg) {
if(firstReferenceException != null) {
throw firstReferenceException;
}
else {
firstUnresolvedExpression.invalidReferenceException(env);
}
}
}
| void sanityCheck(Environment env) throws TemplateException {
boolean resolvedAnArg, hasUnresolvedArg;
Expression firstUnresolvedExpression;
InvalidReferenceException firstReferenceException;
do {
firstUnresolvedExpression = null;
firstReferenceException = null;
resolvedAnArg = hasUnresolvedArg = false;
for(int i = 0; i < argumentNames.length; ++i) {
String argName = argumentNames[i];
if(localVars.get(argName) == null) {
Expression valueExp = (Expression) args.get(argName);
if (valueExp != null) {
try {
TemplateModel tm = valueExp.getAsTemplateModel(env);
if(tm == null) {
if(!hasUnresolvedArg) {
firstUnresolvedExpression = valueExp;
hasUnresolvedArg = true;
}
}
else {
localVars.put(argName, tm);
resolvedAnArg = true;
}
}
catch(InvalidReferenceException e) {
if(!hasUnresolvedArg) {
hasUnresolvedArg = true;
firstReferenceException = e;
}
}
}
else {
throw new TemplateException(
"When calling macro " + StringUtil.jQuote(name)
+ ", required parameter " + StringUtil.jQuote(argName)
+ " (parameter #" + (i + 1) + ") was "
+ (localVars.containsKey(argName)
? "specified, but had null/missing value.\n"
+ "(Tip: If the parameter value expression on the caller side is known "
+ "to be legally null/missing, you may want to specify a default value "
+ "for it with the \"!\" operator, like "
+ "paramValueExpression!defaultValueExpression.)"
: "not specified.\n"
+ "(Tip: If the omission was deliberate, you may consider making "
+ "the parameter optional in the macro by specifying a default value for "
+ "it, like "
+ StringUtil.encloseAsTag(
getTemplate(), "#macro myMacro paramName=defaultExpr")
+ ".)"),
env);
}
}
}
}
while(resolvedAnArg && hasUnresolvedArg);
if(hasUnresolvedArg) {
if(firstReferenceException != null) {
throw firstReferenceException;
}
else {
firstUnresolvedExpression.invalidReferenceException(env);
}
}
}
|
diff --git a/java/src/org/broadinstitute/sting/playground/gatk/walkers/PickSequenomProbes.java b/java/src/org/broadinstitute/sting/playground/gatk/walkers/PickSequenomProbes.java
index 343a4c0d9..7e651c7d0 100755
--- a/java/src/org/broadinstitute/sting/playground/gatk/walkers/PickSequenomProbes.java
+++ b/java/src/org/broadinstitute/sting/playground/gatk/walkers/PickSequenomProbes.java
@@ -1,108 +1,108 @@
package org.broadinstitute.sting.playground.gatk.walkers;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.*;
import org.broadinstitute.sting.gatk.walkers.*;
import org.broadinstitute.sting.utils.*;
import org.broadinstitute.sting.utils.cmdLine.Argument;
import org.broadinstitute.sting.utils.genotype.Variation;
import java.io.*;
import java.util.*;
@WalkerName("PickSequenomProbes")
@Requires(value={DataSource.REFERENCE})
@Reference(window=@Window(start=-200,stop=200))
public class PickSequenomProbes extends RefWalker<String, String>
{
@Argument(required=false, shortName="snp_mask", doc="positions to be masked with N's") public String SNP_MASK = null;
ArrayList<GenomeLoc> mask = null;
Object[] mask_array = null;
public void initialize()
{
System.out.printf("Loading SNP mask... ");
if (SNP_MASK != null)
{
mask = new ArrayList<GenomeLoc>();
mask.addAll(GenomeLocParser.intervalFileToList(SNP_MASK));
Object[] temp_array = mask.toArray();
mask_array = new GenomeLoc[temp_array.length];
for (int i = 0; i < temp_array.length; i++) { mask_array[i] = (GenomeLoc)temp_array[i]; }
Arrays.sort(mask_array);
}
System.out.printf("Done.\n");
}
private boolean in_mask(GenomeLoc loc)
{
return (Arrays.binarySearch(mask_array, loc) >= 0);
}
public String map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context)
{
String refBase = String.valueOf(ref.getBase());
System.out.printf("Probing " + ref.getLocus() + " " + ref.getWindow() + "\n");
Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator();
Variation snp = null;
while (rods.hasNext())
{
ReferenceOrderedDatum rod = rods.next();
if (!(rod instanceof Variation))
continue;
Variation variant = (Variation) rod;
if (variant.isSNP())
{
snp = variant;
}
}
String contig = context.getLocation().getContig();
long offset = context.getLocation().getStart();
char[] context_bases = ref.getBases();
- long true_offset = offset - 400;
+ long true_offset = offset - 200;
for (long i = 0; i < 401; i++)
{
GenomeLoc loc = GenomeLocParser.parseGenomeLoc(context.getLocation().getContig() + ":" + true_offset + "-" + true_offset);
if (in_mask(loc)) { context_bases[(int)i] = 'N'; }
true_offset += 1;
}
char[] leading_bases = Arrays.copyOfRange(context_bases, 0, 200);
char[] trailing_bases = Arrays.copyOfRange(context_bases, 201, 401);
if (snp != null)
{
String snp_string = new String(leading_bases) + new String("[" + refBase + "/" + snp.getAlternativeBaseForSNP() + "]") + new String(trailing_bases);
String fasta_string = new String(">" + context.getLocation().toString() + "_" + ref.getWindow().toString());
return fasta_string + "\n" + snp_string + "\n";
}
else
{
return "";
}
}
public String reduceInit()
{
return "";
}
public String reduce(String data, String sum)
{
out.print(data);
return "";
}
public void onTraversalDone(String sum)
{
}
}
| true | true | public String map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context)
{
String refBase = String.valueOf(ref.getBase());
System.out.printf("Probing " + ref.getLocus() + " " + ref.getWindow() + "\n");
Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator();
Variation snp = null;
while (rods.hasNext())
{
ReferenceOrderedDatum rod = rods.next();
if (!(rod instanceof Variation))
continue;
Variation variant = (Variation) rod;
if (variant.isSNP())
{
snp = variant;
}
}
String contig = context.getLocation().getContig();
long offset = context.getLocation().getStart();
char[] context_bases = ref.getBases();
long true_offset = offset - 400;
for (long i = 0; i < 401; i++)
{
GenomeLoc loc = GenomeLocParser.parseGenomeLoc(context.getLocation().getContig() + ":" + true_offset + "-" + true_offset);
if (in_mask(loc)) { context_bases[(int)i] = 'N'; }
true_offset += 1;
}
char[] leading_bases = Arrays.copyOfRange(context_bases, 0, 200);
char[] trailing_bases = Arrays.copyOfRange(context_bases, 201, 401);
if (snp != null)
{
String snp_string = new String(leading_bases) + new String("[" + refBase + "/" + snp.getAlternativeBaseForSNP() + "]") + new String(trailing_bases);
String fasta_string = new String(">" + context.getLocation().toString() + "_" + ref.getWindow().toString());
return fasta_string + "\n" + snp_string + "\n";
}
else
{
return "";
}
}
| public String map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context)
{
String refBase = String.valueOf(ref.getBase());
System.out.printf("Probing " + ref.getLocus() + " " + ref.getWindow() + "\n");
Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator();
Variation snp = null;
while (rods.hasNext())
{
ReferenceOrderedDatum rod = rods.next();
if (!(rod instanceof Variation))
continue;
Variation variant = (Variation) rod;
if (variant.isSNP())
{
snp = variant;
}
}
String contig = context.getLocation().getContig();
long offset = context.getLocation().getStart();
char[] context_bases = ref.getBases();
long true_offset = offset - 200;
for (long i = 0; i < 401; i++)
{
GenomeLoc loc = GenomeLocParser.parseGenomeLoc(context.getLocation().getContig() + ":" + true_offset + "-" + true_offset);
if (in_mask(loc)) { context_bases[(int)i] = 'N'; }
true_offset += 1;
}
char[] leading_bases = Arrays.copyOfRange(context_bases, 0, 200);
char[] trailing_bases = Arrays.copyOfRange(context_bases, 201, 401);
if (snp != null)
{
String snp_string = new String(leading_bases) + new String("[" + refBase + "/" + snp.getAlternativeBaseForSNP() + "]") + new String(trailing_bases);
String fasta_string = new String(">" + context.getLocation().toString() + "_" + ref.getWindow().toString());
return fasta_string + "\n" + snp_string + "\n";
}
else
{
return "";
}
}
|
diff --git a/org/nsu/vectoreditor/Main.java b/org/nsu/vectoreditor/Main.java
index 719d6ca..0e7c337 100644
--- a/org/nsu/vectoreditor/Main.java
+++ b/org/nsu/vectoreditor/Main.java
@@ -1,24 +1,24 @@
package org.nsu.vectoreditor;
public class Main {
public static void main(String args[]) {
Shape rect = new Rectangle(50, 100, 260, 200);
Shape circle = new Circle(100, 150, 80);
Shape triangle = new Triangle(250, 250, 400, 300, 100, 350);
Shape dummy = new Circle(10, 10, 5);
Scene scene = new Scene();
scene.addShape(rect);
scene.addShape(triangle);
- scene.addShapeBefore(triangle, dummy);
+ scene.addShapeBefore(dummy, triangle);
scene.removeShape(dummy);
scene.addShapeBefore(circle, triangle);
MainWindow mainWindow = new MainWindow(scene);
mainWindow.setSize(800, 600);
mainWindow.setVisible(true);
}
}
| true | true | public static void main(String args[]) {
Shape rect = new Rectangle(50, 100, 260, 200);
Shape circle = new Circle(100, 150, 80);
Shape triangle = new Triangle(250, 250, 400, 300, 100, 350);
Shape dummy = new Circle(10, 10, 5);
Scene scene = new Scene();
scene.addShape(rect);
scene.addShape(triangle);
scene.addShapeBefore(triangle, dummy);
scene.removeShape(dummy);
scene.addShapeBefore(circle, triangle);
MainWindow mainWindow = new MainWindow(scene);
mainWindow.setSize(800, 600);
mainWindow.setVisible(true);
}
| public static void main(String args[]) {
Shape rect = new Rectangle(50, 100, 260, 200);
Shape circle = new Circle(100, 150, 80);
Shape triangle = new Triangle(250, 250, 400, 300, 100, 350);
Shape dummy = new Circle(10, 10, 5);
Scene scene = new Scene();
scene.addShape(rect);
scene.addShape(triangle);
scene.addShapeBefore(dummy, triangle);
scene.removeShape(dummy);
scene.addShapeBefore(circle, triangle);
MainWindow mainWindow = new MainWindow(scene);
mainWindow.setSize(800, 600);
mainWindow.setVisible(true);
}
|
diff --git a/Basics/src/coolawesomeme/basics_plugin/AutoUpdater.java b/Basics/src/coolawesomeme/basics_plugin/AutoUpdater.java
index 4691058..de6f151 100644
--- a/Basics/src/coolawesomeme/basics_plugin/AutoUpdater.java
+++ b/Basics/src/coolawesomeme/basics_plugin/AutoUpdater.java
@@ -1,107 +1,110 @@
package coolawesomeme.basics_plugin;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class AutoUpdater {
private static String version = Basics.version;
private static int pluginMajor = Basics.versionMajor;
private static int pluginMinor = Basics.versionMinor;
private static int pluginRevision = Basics.versionRevision;
private static String pluginAcquiredVersion;
private static boolean download = Basics.download;
public static void checkForUpdate(Basics basics){
try {
URL url = new URL("https://raw.github.com/coolawesomeme/Basics/master/UPDATE.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((pluginAcquiredVersion = in.readLine()) != null) {
String[] temp;
temp = pluginAcquiredVersion.split("-");
if(temp[0].equals("null") || temp[0].equals("void") || temp[0].equals("missingno") || temp[0].equals("")){
temp[0] = version;
temp[0].equals(version);
}else{
System.out.println("Latest plugin version found: Basics " + temp[0] + ".");
if(!isOutdated(Integer.parseInt(temp[3]), Integer.parseInt(temp[4]), Integer.parseInt(temp[5]))){
System.out.println("[Basics] Plugin up to date!");
}else{
boolean isDownloaded = downloadLatestModFile(basics, temp[6], temp[0]);
- basics.getLogger().info("");
+ basics.getLogger().info("******************************************************");
+ basics.getLogger().info("******************************************************");
basics.getLogger().info("An update of " + "Basics (Version " + temp[0] + ") " + "is available!");
if(isDownloaded){
- basics.getLogger().info("Located at: " + basics.getDataFolder() + "/updates");
+ basics.getLogger().info("Located at: " + basics.getDataFolder() + "\\updates");
}else{
basics.getLogger().info("http://coolawesomeme.github.io/Basics");
}
+ basics.getLogger().info("******************************************************");
+ basics.getLogger().info("******************************************************");
if(!temp[1].isEmpty()){
basics.getLogger().info(temp[1]);
} if(!temp[2].isEmpty()){
basics.getLogger().info(temp[2]);
}
System.out.println("An update of " + "Basics (Version " + temp[0] + ") " + "is available!");
if(isDownloaded){
- System.out.println("Located at: " + basics.getDataFolder() + "/updates");
+ System.out.println("Located at: " + basics.getDataFolder() + "\\updates");
}else{
System.out.println("http://coolawesomeme.github.io/Basics");
}
}
}
}
in.close();
} catch (Exception e) {
System.err.println("[Basics] Error: " + e);
}
}
private static boolean isOutdated(int release, int build, int revision){
if(pluginMajor <= release && pluginMinor <= build && pluginRevision < revision){
return true;
}else{
return false;
}
}
private static boolean isUpdated(int release, int build, int revision){
if(pluginMajor == release && pluginMinor == build && pluginRevision == revision){
return true;
}else{
return false;
}
}
private static boolean downloadLatestModFile(Basics basics, String updateURL, String pluginVersion){
if(download){
String saveTo = basics.getDataFolder() + "/updates";
File saveFolder = new File(saveTo);
saveFolder.mkdirs();
try {
URL url = new URL(updateURL);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
FileOutputStream out = new FileOutputStream(saveTo + "/Basics " + pluginVersion + ".jar");
byte[] b = new byte[1024];
int count;
while ((count = in.read(b)) >= 0) {
out.write(b, 0, count);
}
out.flush(); out.close(); in.close();
System.out.println("Latest plugin version is downloaded!");
System.out.println("Located here: " + saveTo + "/Basics "+ pluginVersion + ".jar");
System.out.println("Put in 'plugins' folder & delete the old version.");
return true;
} catch (Exception e) {
e.printStackTrace();
}
}else{
return false;
}
return false;
}
}
| false | true | public static void checkForUpdate(Basics basics){
try {
URL url = new URL("https://raw.github.com/coolawesomeme/Basics/master/UPDATE.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((pluginAcquiredVersion = in.readLine()) != null) {
String[] temp;
temp = pluginAcquiredVersion.split("-");
if(temp[0].equals("null") || temp[0].equals("void") || temp[0].equals("missingno") || temp[0].equals("")){
temp[0] = version;
temp[0].equals(version);
}else{
System.out.println("Latest plugin version found: Basics " + temp[0] + ".");
if(!isOutdated(Integer.parseInt(temp[3]), Integer.parseInt(temp[4]), Integer.parseInt(temp[5]))){
System.out.println("[Basics] Plugin up to date!");
}else{
boolean isDownloaded = downloadLatestModFile(basics, temp[6], temp[0]);
basics.getLogger().info("");
basics.getLogger().info("An update of " + "Basics (Version " + temp[0] + ") " + "is available!");
if(isDownloaded){
basics.getLogger().info("Located at: " + basics.getDataFolder() + "/updates");
}else{
basics.getLogger().info("http://coolawesomeme.github.io/Basics");
}
if(!temp[1].isEmpty()){
basics.getLogger().info(temp[1]);
} if(!temp[2].isEmpty()){
basics.getLogger().info(temp[2]);
}
System.out.println("An update of " + "Basics (Version " + temp[0] + ") " + "is available!");
if(isDownloaded){
System.out.println("Located at: " + basics.getDataFolder() + "/updates");
}else{
System.out.println("http://coolawesomeme.github.io/Basics");
}
}
}
}
in.close();
} catch (Exception e) {
System.err.println("[Basics] Error: " + e);
}
}
| public static void checkForUpdate(Basics basics){
try {
URL url = new URL("https://raw.github.com/coolawesomeme/Basics/master/UPDATE.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((pluginAcquiredVersion = in.readLine()) != null) {
String[] temp;
temp = pluginAcquiredVersion.split("-");
if(temp[0].equals("null") || temp[0].equals("void") || temp[0].equals("missingno") || temp[0].equals("")){
temp[0] = version;
temp[0].equals(version);
}else{
System.out.println("Latest plugin version found: Basics " + temp[0] + ".");
if(!isOutdated(Integer.parseInt(temp[3]), Integer.parseInt(temp[4]), Integer.parseInt(temp[5]))){
System.out.println("[Basics] Plugin up to date!");
}else{
boolean isDownloaded = downloadLatestModFile(basics, temp[6], temp[0]);
basics.getLogger().info("******************************************************");
basics.getLogger().info("******************************************************");
basics.getLogger().info("An update of " + "Basics (Version " + temp[0] + ") " + "is available!");
if(isDownloaded){
basics.getLogger().info("Located at: " + basics.getDataFolder() + "\\updates");
}else{
basics.getLogger().info("http://coolawesomeme.github.io/Basics");
}
basics.getLogger().info("******************************************************");
basics.getLogger().info("******************************************************");
if(!temp[1].isEmpty()){
basics.getLogger().info(temp[1]);
} if(!temp[2].isEmpty()){
basics.getLogger().info(temp[2]);
}
System.out.println("An update of " + "Basics (Version " + temp[0] + ") " + "is available!");
if(isDownloaded){
System.out.println("Located at: " + basics.getDataFolder() + "\\updates");
}else{
System.out.println("http://coolawesomeme.github.io/Basics");
}
}
}
}
in.close();
} catch (Exception e) {
System.err.println("[Basics] Error: " + e);
}
}
|
diff --git a/src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java b/src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java
index 2eff1f859..c420b296b 100644
--- a/src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java
+++ b/src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java
@@ -1,686 +1,676 @@
/**
* 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.hadoop.hdfs.server.namenode;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
import org.apache.hadoop.http.HttpServer;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.metrics.jvm.JvmMetrics;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.Krb5AndCertsSslSocketConnector;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.util.StringUtils;
/**********************************************************
* The Secondary NameNode is a helper to the primary NameNode.
* The Secondary is responsible for supporting periodic checkpoints
* of the HDFS metadata. The current design allows only one Secondary
* NameNode per HDFs cluster.
*
* The Secondary NameNode is a daemon that periodically wakes
* up (determined by the schedule specified in the configuration),
* triggers a periodic checkpoint and then goes back to sleep.
* The Secondary NameNode uses the ClientProtocol to talk to the
* primary NameNode.
*
**********************************************************/
public class SecondaryNameNode implements Runnable {
static{
Configuration.addDefaultResource("hdfs-default.xml");
Configuration.addDefaultResource("hdfs-site.xml");
}
public static final Log LOG =
LogFactory.getLog(SecondaryNameNode.class.getName());
private String fsName;
private CheckpointStorage checkpointImage;
private NamenodeProtocol namenode;
private Configuration conf;
private InetSocketAddress nameNodeAddr;
private volatile boolean shouldRun;
private HttpServer infoServer;
private int infoPort;
private int imagePort;
private String infoBindAddress;
private Collection<File> checkpointDirs;
private Collection<File> checkpointEditsDirs;
private long checkpointPeriod; // in seconds
private long checkpointSize; // size (in MB) of current Edit Log
/**
* Utility class to facilitate junit test error simulation.
*/
static class ErrorSimulator {
private static boolean[] simulation = null; // error simulation events
static void initializeErrorSimulationEvent(int numberOfEvents) {
simulation = new boolean[numberOfEvents];
for (int i = 0; i < numberOfEvents; i++) {
simulation[i] = false;
}
}
static boolean getErrorSimulation(int index) {
if(simulation == null)
return false;
assert(index < simulation.length);
return simulation[index];
}
static void setErrorSimulation(int index) {
assert(index < simulation.length);
simulation[index] = true;
}
static void clearErrorSimulation(int index) {
assert(index < simulation.length);
simulation[index] = false;
}
}
FSImage getFSImage() {
return checkpointImage;
}
/**
* Create a connection to the primary namenode.
*/
public SecondaryNameNode(Configuration conf) throws IOException {
try {
initialize(conf);
} catch(IOException e) {
shutdown();
throw e;
}
}
@SuppressWarnings("deprecation")
public static InetSocketAddress getHttpAddress(Configuration conf) {
String infoAddr = NetUtils.getServerAddress(conf,
"dfs.secondary.info.bindAddress", "dfs.secondary.info.port",
"dfs.secondary.http.address");
return NetUtils.createSocketAddr(infoAddr);
}
/**
* Initialize SecondaryNameNode.
*/
private void initialize(final Configuration conf) throws IOException {
final InetSocketAddress infoSocAddr = getHttpAddress(conf);
infoBindAddress = infoSocAddr.getHostName();
if (UserGroupInformation.isSecurityEnabled()) {
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
infoBindAddress);
}
// initiate Java VM metrics
JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));
// Create connection to the namenode.
shouldRun = true;
nameNodeAddr = NameNode.getAddress(conf);
this.conf = conf;
this.namenode =
(NamenodeProtocol) RPC.waitForProxy(NamenodeProtocol.class,
NamenodeProtocol.versionID, nameNodeAddr, conf);
// initialize checkpoint directories
fsName = getInfoServer();
checkpointDirs = FSImage.getCheckpointDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointImage = new CheckpointStorage();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
// Initialize other scheduling parameters from the configuration
checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);
// initialize the webserver for uploading files.
// Kerberized SSL servers must be run from the host principal...
- if (UserGroupInformation.isSecurityEnabled()) {
- SecurityUtil.login(conf,
- DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
- DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY,
- infoBindAddress);
- }
- UserGroupInformation ugi = UserGroupInformation.getLoginUser();
+ UserGroupInformation httpUGI =
+ UserGroupInformation.loginUserFromKeytabAndReturnUGI(
+ SecurityUtil.getServerPrincipal(conf
+ .get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY),
+ infoBindAddress),
+ conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY));
try {
- infoServer = ugi.doAs(new PrivilegedExceptionAction<HttpServer>() {
+ infoServer = httpUGI.doAs(new PrivilegedExceptionAction<HttpServer>() {
@Override
public HttpServer run() throws IOException, InterruptedException {
LOG.info("Starting web server as: " +
- UserGroupInformation.getLoginUser().getUserName());
+ UserGroupInformation.getCurrentUser().getUserName());
int tmpInfoPort = infoSocAddr.getPort();
infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
tmpInfoPort == 0, conf);
if(UserGroupInformation.isSecurityEnabled()) {
System.setProperty("https.cipherSuites",
Krb5AndCertsSslSocketConnector.KRB5_CIPHER_SUITES.get(0));
InetSocketAddress secInfoSocAddr =
NetUtils.createSocketAddr(infoBindAddress + ":"+ conf.get(
"dfs.secondary.https.port", infoBindAddress + ":" + 0));
imagePort = secInfoSocAddr.getPort();
infoServer.addSslListener(secInfoSocAddr, conf, false, true);
}
infoServer.setAttribute("name.system.image", checkpointImage);
infoServer.setAttribute(JspHelper.CURRENT_CONF, conf);
infoServer.addInternalServlet("getimage", "/getimage",
GetImageServlet.class, true);
infoServer.start();
return infoServer;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
- } finally {
- if (UserGroupInformation.isSecurityEnabled()) {
- // Go back to being the correct Namenode principal
- SecurityUtil.login(conf,
- DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
- DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
- infoBindAddress);
- LOG.info("Web server init done, returning to: " +
- UserGroupInformation.getLoginUser().getUserName());
- }
}
+ LOG.info("Web server init done");
// The web-server port can be ephemeral... ensure we have the correct info
infoPort = infoServer.getPort();
if(!UserGroupInformation.isSecurityEnabled())
imagePort = infoPort;
conf.set("dfs.secondary.http.address", infoBindAddress + ":" +infoPort);
LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" +infoPort);
LOG.info("Secondary image servlet up at: " + infoBindAddress + ":" + imagePort);
LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " +
"(" + checkpointPeriod/60 + " min)");
LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " +
"(" + checkpointSize/1024 + " KB)");
}
/**
* Shut down this instance of the datanode.
* Returns only after shutdown is complete.
*/
public void shutdown() {
shouldRun = false;
try {
if (infoServer != null) infoServer.stop();
} catch (Exception e) {
LOG.warn("Exception shutting down SecondaryNameNode", e);
}
try {
if (checkpointImage != null) checkpointImage.close();
} catch(IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
}
public void run() {
if (UserGroupInformation.isSecurityEnabled()) {
UserGroupInformation ugi = null;
try {
ugi = UserGroupInformation.getLoginUser();
} catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
ugi.doAs(new PrivilegedAction<Object>() {
@Override
public Object run() {
doWork();
return null;
}
});
} else {
doWork();
}
}
//
// The main work loop
//
public void doWork() {
//
// Poll the Namenode (once every 5 minutes) to find the size of the
// pending edit log.
//
long period = 5 * 60; // 5 minutes
long lastCheckpointTime = 0;
if (checkpointPeriod < period) {
period = checkpointPeriod;
}
while (shouldRun) {
try {
Thread.sleep(1000 * period);
} catch (InterruptedException ie) {
// do nothing
}
if (!shouldRun) {
break;
}
try {
// We may have lost our ticket since last checkpoint, log in again, just in case
if(UserGroupInformation.isSecurityEnabled())
UserGroupInformation.getCurrentUser().reloginFromKeytab();
long now = System.currentTimeMillis();
long size = namenode.getEditLogSize();
if (size >= checkpointSize ||
now >= lastCheckpointTime + 1000 * checkpointPeriod) {
doCheckpoint();
lastCheckpointTime = now;
}
} catch (IOException e) {
LOG.error("Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
} catch (Throwable e) {
LOG.error("Throwable Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
}
}
/**
* Download <code>fsimage</code> and <code>edits</code>
* files from the name-node.
* @throws IOException
*/
private void downloadCheckpointFiles(final CheckpointSignature sig
) throws IOException {
try {
UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkpointImage.cTime = sig.cTime;
checkpointImage.checkpointTime = sig.checkpointTime;
// get fsimage
String fileid = "getimage=1";
File[] srcNames = checkpointImage.getImageFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size " +
srcNames[0].length() + " bytes.");
// get edits file
fileid = "getedit=1";
srcNames = checkpointImage.getEditsFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size " +
srcNames[0].length() + " bytes.");
checkpointImage.checkpointUploadDone();
return null;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* Copy the new fsimage into the NameNode
*/
private void putFSImage(CheckpointSignature sig) throws IOException {
String fileid = "putimage=1&port=" + imagePort +
"&machine=" + infoBindAddress +
"&token=" + sig.toString();
LOG.info("Posted URL " + fsName + fileid);
TransferFsImage.getFileClient(fsName, fileid, (File[])null);
}
/**
* Returns the Jetty server that the Namenode is listening on.
*/
private String getInfoServer() throws IOException {
URI fsName = FileSystem.getDefaultUri(conf);
if (!"hdfs".equals(fsName.getScheme())) {
throw new IOException("This is not a DFS");
}
String infoAddr = NameNode.getInfoServer(conf);
LOG.debug("infoAddr = " + infoAddr);
return infoAddr;
}
/**
* Create a new checkpoint
*/
void doCheckpoint() throws IOException {
// Do the required initialization of the merge work area.
startCheckpoint();
// Tell the namenode to start logging transactions in a new edit file
// Retuns a token that would be used to upload the merged image.
CheckpointSignature sig = (CheckpointSignature)namenode.rollEditLog();
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(0)) {
throw new IOException("Simulating error0 " +
"after creating edits.new");
}
downloadCheckpointFiles(sig); // Fetch fsimage and edits
doMerge(sig); // Do the merge
//
// Upload the new image into the NameNode. Then tell the Namenode
// to make this new uploaded image as the most current image.
//
putFSImage(sig);
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(1)) {
throw new IOException("Simulating error1 " +
"after uploading new image to NameNode");
}
namenode.rollFsImage();
checkpointImage.endCheckpoint();
LOG.warn("Checkpoint done. New Image Size: "
+ checkpointImage.getFsImageName().length());
}
private void startCheckpoint() throws IOException {
checkpointImage.unlockAll();
checkpointImage.getEditLog().close();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
checkpointImage.startCheckpoint();
}
/**
* Merge downloaded image and edits and write the new image into
* current storage directory.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
FSNamesystem namesystem =
new FSNamesystem(checkpointImage, conf);
assert namesystem.dir.fsImage == checkpointImage;
checkpointImage.doMerge(sig);
}
/**
* @param argv The parameters passed to this program.
* @exception Exception if the filesystem does not exist.
* @return 0 on success, non zero on error.
*/
private int processArgs(String[] argv) throws Exception {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-geteditsize".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-checkpoint".equals(cmd)) {
if (argv.length != 1 && argv.length != 2) {
printUsage(cmd);
return exitCode;
}
if (argv.length == 2 && !"force".equals(argv[i])) {
printUsage(cmd);
return exitCode;
}
}
exitCode = 0;
try {
if ("-checkpoint".equals(cmd)) {
long size = namenode.getEditLogSize();
if (size >= checkpointSize ||
argv.length == 2 && "force".equals(argv[i])) {
doCheckpoint();
} else {
System.err.println("EditLog size " + size + " bytes is " +
"smaller than configured checkpoint " +
"size " + checkpointSize + " bytes.");
System.err.println("Skipping checkpoint.");
}
} else if ("-geteditsize".equals(cmd)) {
long size = namenode.getEditLogSize();
System.out.println("EditLog size is " + size + " bytes");
} else {
exitCode = -1;
LOG.error(cmd.substring(1) + ": Unknown command");
printUsage("");
}
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage, ignore the stack trace.
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
LOG.error(cmd.substring(1) + ": "
+ content[0]);
} catch (Exception ex) {
LOG.error(cmd.substring(1) + ": "
+ ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
LOG.error(cmd.substring(1) + ": "
+ e.getLocalizedMessage());
} finally {
// Does the RPC connection need to be closed?
}
return exitCode;
}
/**
* Displays format of commands.
* @param cmd The command that is being executed.
*/
private void printUsage(String cmd) {
if ("-geteditsize".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-geteditsize]");
} else if ("-checkpoint".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-checkpoint [force]]");
} else {
System.err.println("Usage: java SecondaryNameNode " +
"[-checkpoint [force]] " +
"[-geteditsize] ");
}
}
/**
* main() has some simple utility methods.
* @param argv Command line parameters.
* @exception Exception if the filesystem does not exist.
*/
public static void main(String[] argv) throws Exception {
StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);
Configuration tconf = new Configuration();
if (argv.length >= 1) {
SecondaryNameNode secondary = new SecondaryNameNode(tconf);
int ret = secondary.processArgs(argv);
System.exit(ret);
}
// Create a never ending deamon
Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));
checkpointThread.start();
}
static class CheckpointStorage extends FSImage {
/**
*/
CheckpointStorage() throws IOException {
super();
}
@Override
public
boolean isConversionNeeded(StorageDirectory sd) {
return false;
}
/**
* Analyze checkpoint directories.
* Create directories if they do not exist.
* Recover from an unsuccessful checkpoint is necessary.
*
* @param dataDirs
* @param editsDirs
* @throws IOException
*/
void recoverCreate(Collection<File> dataDirs,
Collection<File> editsDirs) throws IOException {
Collection<File> tempDataDirs = new ArrayList<File>(dataDirs);
Collection<File> tempEditsDirs = new ArrayList<File>(editsDirs);
this.storageDirs = new ArrayList<StorageDirectory>();
setStorageDirectories(tempDataDirs, tempEditsDirs);
for (Iterator<StorageDirectory> it =
dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
boolean isAccessible = true;
try { // create directories if don't exist yet
if(!sd.getRoot().mkdirs()) {
// do nothing, directory is already created
}
} catch(SecurityException se) {
isAccessible = false;
}
if(!isAccessible)
throw new InconsistentFSStateException(sd.getRoot(),
"cannot access checkpoint directory.");
StorageState curState;
try {
curState = sd.analyzeStorage(HdfsConstants.StartupOption.REGULAR);
// sd is locked but not opened
switch(curState) {
case NON_EXISTENT:
// fail if any of the configured checkpoint dirs are inaccessible
throw new InconsistentFSStateException(sd.getRoot(),
"checkpoint directory does not exist or is not accessible.");
case NOT_FORMATTED:
break; // it's ok since initially there is no current and VERSION
case NORMAL:
break;
default: // recovery is possible
sd.doRecover(curState);
}
} catch (IOException ioe) {
sd.unlock();
throw ioe;
}
}
}
/**
* Prepare directories for a new checkpoint.
* <p>
* Rename <code>current</code> to <code>lastcheckpoint.tmp</code>
* and recreate <code>current</code>.
* @throws IOException
*/
void startCheckpoint() throws IOException {
for(StorageDirectory sd : storageDirs) {
moveCurrent(sd);
}
}
void endCheckpoint() throws IOException {
for(StorageDirectory sd : storageDirs) {
moveLastCheckpoint(sd);
}
}
/**
* Merge image and edits, and verify consistency with the signature.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
getEditLog().open();
StorageDirectory sdName = null;
StorageDirectory sdEdits = null;
Iterator<StorageDirectory> it = null;
it = dirIterator(NameNodeDirType.IMAGE);
if (it.hasNext())
sdName = it.next();
it = dirIterator(NameNodeDirType.EDITS);
if (it.hasNext())
sdEdits = it.next();
if ((sdName == null) || (sdEdits == null))
throw new IOException("Could not locate checkpoint directories");
loadFSImage(FSImage.getImageFile(sdName, NameNodeFile.IMAGE));
loadFSEdits(sdEdits);
sig.validateStorageInfo(this);
saveNamespace(false);
}
}
}
| false | true | private void initialize(final Configuration conf) throws IOException {
final InetSocketAddress infoSocAddr = getHttpAddress(conf);
infoBindAddress = infoSocAddr.getHostName();
if (UserGroupInformation.isSecurityEnabled()) {
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
infoBindAddress);
}
// initiate Java VM metrics
JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));
// Create connection to the namenode.
shouldRun = true;
nameNodeAddr = NameNode.getAddress(conf);
this.conf = conf;
this.namenode =
(NamenodeProtocol) RPC.waitForProxy(NamenodeProtocol.class,
NamenodeProtocol.versionID, nameNodeAddr, conf);
// initialize checkpoint directories
fsName = getInfoServer();
checkpointDirs = FSImage.getCheckpointDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointImage = new CheckpointStorage();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
// Initialize other scheduling parameters from the configuration
checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);
// initialize the webserver for uploading files.
// Kerberized SSL servers must be run from the host principal...
if (UserGroupInformation.isSecurityEnabled()) {
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY,
infoBindAddress);
}
UserGroupInformation ugi = UserGroupInformation.getLoginUser();
try {
infoServer = ugi.doAs(new PrivilegedExceptionAction<HttpServer>() {
@Override
public HttpServer run() throws IOException, InterruptedException {
LOG.info("Starting web server as: " +
UserGroupInformation.getLoginUser().getUserName());
int tmpInfoPort = infoSocAddr.getPort();
infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
tmpInfoPort == 0, conf);
if(UserGroupInformation.isSecurityEnabled()) {
System.setProperty("https.cipherSuites",
Krb5AndCertsSslSocketConnector.KRB5_CIPHER_SUITES.get(0));
InetSocketAddress secInfoSocAddr =
NetUtils.createSocketAddr(infoBindAddress + ":"+ conf.get(
"dfs.secondary.https.port", infoBindAddress + ":" + 0));
imagePort = secInfoSocAddr.getPort();
infoServer.addSslListener(secInfoSocAddr, conf, false, true);
}
infoServer.setAttribute("name.system.image", checkpointImage);
infoServer.setAttribute(JspHelper.CURRENT_CONF, conf);
infoServer.addInternalServlet("getimage", "/getimage",
GetImageServlet.class, true);
infoServer.start();
return infoServer;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
if (UserGroupInformation.isSecurityEnabled()) {
// Go back to being the correct Namenode principal
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
infoBindAddress);
LOG.info("Web server init done, returning to: " +
UserGroupInformation.getLoginUser().getUserName());
}
}
// The web-server port can be ephemeral... ensure we have the correct info
infoPort = infoServer.getPort();
if(!UserGroupInformation.isSecurityEnabled())
imagePort = infoPort;
conf.set("dfs.secondary.http.address", infoBindAddress + ":" +infoPort);
LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" +infoPort);
LOG.info("Secondary image servlet up at: " + infoBindAddress + ":" + imagePort);
LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " +
"(" + checkpointPeriod/60 + " min)");
LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " +
"(" + checkpointSize/1024 + " KB)");
}
| private void initialize(final Configuration conf) throws IOException {
final InetSocketAddress infoSocAddr = getHttpAddress(conf);
infoBindAddress = infoSocAddr.getHostName();
if (UserGroupInformation.isSecurityEnabled()) {
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
infoBindAddress);
}
// initiate Java VM metrics
JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));
// Create connection to the namenode.
shouldRun = true;
nameNodeAddr = NameNode.getAddress(conf);
this.conf = conf;
this.namenode =
(NamenodeProtocol) RPC.waitForProxy(NamenodeProtocol.class,
NamenodeProtocol.versionID, nameNodeAddr, conf);
// initialize checkpoint directories
fsName = getInfoServer();
checkpointDirs = FSImage.getCheckpointDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointImage = new CheckpointStorage();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
// Initialize other scheduling parameters from the configuration
checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);
// initialize the webserver for uploading files.
// Kerberized SSL servers must be run from the host principal...
UserGroupInformation httpUGI =
UserGroupInformation.loginUserFromKeytabAndReturnUGI(
SecurityUtil.getServerPrincipal(conf
.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY),
infoBindAddress),
conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY));
try {
infoServer = httpUGI.doAs(new PrivilegedExceptionAction<HttpServer>() {
@Override
public HttpServer run() throws IOException, InterruptedException {
LOG.info("Starting web server as: " +
UserGroupInformation.getCurrentUser().getUserName());
int tmpInfoPort = infoSocAddr.getPort();
infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
tmpInfoPort == 0, conf);
if(UserGroupInformation.isSecurityEnabled()) {
System.setProperty("https.cipherSuites",
Krb5AndCertsSslSocketConnector.KRB5_CIPHER_SUITES.get(0));
InetSocketAddress secInfoSocAddr =
NetUtils.createSocketAddr(infoBindAddress + ":"+ conf.get(
"dfs.secondary.https.port", infoBindAddress + ":" + 0));
imagePort = secInfoSocAddr.getPort();
infoServer.addSslListener(secInfoSocAddr, conf, false, true);
}
infoServer.setAttribute("name.system.image", checkpointImage);
infoServer.setAttribute(JspHelper.CURRENT_CONF, conf);
infoServer.addInternalServlet("getimage", "/getimage",
GetImageServlet.class, true);
infoServer.start();
return infoServer;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
LOG.info("Web server init done");
// The web-server port can be ephemeral... ensure we have the correct info
infoPort = infoServer.getPort();
if(!UserGroupInformation.isSecurityEnabled())
imagePort = infoPort;
conf.set("dfs.secondary.http.address", infoBindAddress + ":" +infoPort);
LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" +infoPort);
LOG.info("Secondary image servlet up at: " + infoBindAddress + ":" + imagePort);
LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " +
"(" + checkpointPeriod/60 + " min)");
LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " +
"(" + checkpointSize/1024 + " KB)");
}
|
diff --git a/SpagoBIGeoReportEngine/src/it/eng/spagobi/engines/georeport/features/provider/FeaturesProviderDAOFileImpl.java b/SpagoBIGeoReportEngine/src/it/eng/spagobi/engines/georeport/features/provider/FeaturesProviderDAOFileImpl.java
index eeea22599..e84e61030 100644
--- a/SpagoBIGeoReportEngine/src/it/eng/spagobi/engines/georeport/features/provider/FeaturesProviderDAOFileImpl.java
+++ b/SpagoBIGeoReportEngine/src/it/eng/spagobi/engines/georeport/features/provider/FeaturesProviderDAOFileImpl.java
@@ -1,161 +1,161 @@
/* SpagoBI, the Open Source Business Intelligence suite
* Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice.
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package it.eng.spagobi.engines.georeport.features.provider;
import it.eng.spagobi.commons.utilities.StringUtilities;
import it.eng.spagobi.engines.georeport.GeoReportEngine;
import it.eng.spagobi.utilities.assertion.Assert;
import it.eng.spagobi.utilities.assertion.NullReferenceException;
import it.eng.spagobi.utilities.exceptions.SpagoBIRuntimeException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.FeatureIterator;
import org.geotools.geojson.feature.FeatureJSON;
import org.opengis.feature.simple.SimpleFeature;
/**
* @authors Andrea Gioia ([email protected])
*/
public class FeaturesProviderDAOFileImpl implements IFeaturesProviderDAO {
String indexOnAttribute;
Map<Object, SimpleFeature> lookupTable;
public static final String GEOID_PNAME = "geoIdPName";
public static final String GEOID_PVALUE = "geoIdPValue";
/** Logger component. */
private static transient Logger logger = Logger.getLogger(FeaturesProviderDAOFileImpl.class);
public FeatureCollection getFeatures(Object featureProviderEndPoint, Map parameters) {
SimpleFeatureCollection featureCollection = FeatureCollections.newCollection();
String geoIdPName;
String geoIdPValue;
SimpleFeature feature;
logger.debug("IN");
try {
geoIdPName = (String)parameters.get(GEOID_PNAME);
logger.debug("Parameter [" + GEOID_PNAME + "] is equal to [" + geoIdPName + "]");
geoIdPValue = (String)parameters.get(GEOID_PVALUE);
logger.debug("Parameter [" + GEOID_PVALUE + "] is equal to [" + geoIdPValue + "]");
if(!geoIdPName.equalsIgnoreCase(indexOnAttribute)) {
createIndex((String)featureProviderEndPoint, geoIdPName);
}
feature = lookupTable.get(geoIdPValue);
logger.debug("Feature [" + geoIdPValue +"] is equal to [" + feature + "]");
if(feature != null) {
featureCollection.add(feature);
logger.debug("Decoded object is of type [" + feature.getClass().getName() + "]");
logger.debug("Feature [" + geoIdPValue + "] added to result features' collection");
} else {
logger.warn("Impossible to find feature [" + geoIdPValue + "]");
}
} catch(Throwable t) {
throw new SpagoBIRuntimeException(t);
} finally {
logger.debug("OUT");
}
return featureCollection;
}
private void createIndex(String filename, String geoIdPName) {
String resourcesDir;
File targetFile;
logger.debug("IN");
try {
Assert.assertTrue(!StringUtilities.isEmpty(filename), "Input parameter [filename] cannot be null or empty");
Assert.assertTrue(!StringUtilities.isEmpty(geoIdPName), "Input parameter [filename] cannot be null or empty");
logger.debug("Indexing file [" + filename + "] on attribute [" + geoIdPName + "] ...");
indexOnAttribute = geoIdPName;
lookupTable = new HashMap();
resourcesDir = GeoReportEngine.getConfig().getEngineConfig().getResourcePath() + "/georeport";
logger.debug("Resource dir is equal to [" + resourcesDir + "]");
targetFile = new File(resourcesDir, filename);
logger.debug("Target file full name is equal to [" + targetFile + "]");
FeatureCollection fc = loadFile( targetFile );
logger.debug("Target file contains [" + fc.size() + "] features to index");
if ( fc.size() == 0){
throw new NullReferenceException("Impossible to find attribute [features in file [" + filename +"]");
}
FeatureIterator iterator = fc.features();
while (iterator.hasNext()) {
SimpleFeature feature = (SimpleFeature) iterator.next();
Object idx = feature.getProperty(geoIdPName).getValue();
- lookupTable.put(idx, feature);
+ lookupTable.put(idx.toString(), feature);
logger.debug("Feature [" + idx + "] added to the index");
}
logger.debug("File [" + filename + "] indexed succesfully on attribute [" + geoIdPName + "]");
} catch(Throwable t) {
indexOnAttribute = null;
lookupTable = null;
throw new SpagoBIRuntimeException(t);
} finally {
logger.debug("OUT");
}
}
private FeatureCollection loadFile(File targetFile) {
FeatureCollection result;
BufferedReader reader;
StringBuffer buffer;
String line;
try {
reader = new BufferedReader(new FileReader( targetFile ));
buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
String featureStr = buffer.toString();
Reader strReader = new StringReader( featureStr );
FeatureJSON featureJ = new FeatureJSON();
result = featureJ.readFeatureCollection(strReader);
} catch(Throwable t) {
throw new SpagoBIRuntimeException(t);
}
return result;
}
}
| true | true | private void createIndex(String filename, String geoIdPName) {
String resourcesDir;
File targetFile;
logger.debug("IN");
try {
Assert.assertTrue(!StringUtilities.isEmpty(filename), "Input parameter [filename] cannot be null or empty");
Assert.assertTrue(!StringUtilities.isEmpty(geoIdPName), "Input parameter [filename] cannot be null or empty");
logger.debug("Indexing file [" + filename + "] on attribute [" + geoIdPName + "] ...");
indexOnAttribute = geoIdPName;
lookupTable = new HashMap();
resourcesDir = GeoReportEngine.getConfig().getEngineConfig().getResourcePath() + "/georeport";
logger.debug("Resource dir is equal to [" + resourcesDir + "]");
targetFile = new File(resourcesDir, filename);
logger.debug("Target file full name is equal to [" + targetFile + "]");
FeatureCollection fc = loadFile( targetFile );
logger.debug("Target file contains [" + fc.size() + "] features to index");
if ( fc.size() == 0){
throw new NullReferenceException("Impossible to find attribute [features in file [" + filename +"]");
}
FeatureIterator iterator = fc.features();
while (iterator.hasNext()) {
SimpleFeature feature = (SimpleFeature) iterator.next();
Object idx = feature.getProperty(geoIdPName).getValue();
lookupTable.put(idx, feature);
logger.debug("Feature [" + idx + "] added to the index");
}
logger.debug("File [" + filename + "] indexed succesfully on attribute [" + geoIdPName + "]");
} catch(Throwable t) {
indexOnAttribute = null;
lookupTable = null;
throw new SpagoBIRuntimeException(t);
} finally {
logger.debug("OUT");
}
}
| private void createIndex(String filename, String geoIdPName) {
String resourcesDir;
File targetFile;
logger.debug("IN");
try {
Assert.assertTrue(!StringUtilities.isEmpty(filename), "Input parameter [filename] cannot be null or empty");
Assert.assertTrue(!StringUtilities.isEmpty(geoIdPName), "Input parameter [filename] cannot be null or empty");
logger.debug("Indexing file [" + filename + "] on attribute [" + geoIdPName + "] ...");
indexOnAttribute = geoIdPName;
lookupTable = new HashMap();
resourcesDir = GeoReportEngine.getConfig().getEngineConfig().getResourcePath() + "/georeport";
logger.debug("Resource dir is equal to [" + resourcesDir + "]");
targetFile = new File(resourcesDir, filename);
logger.debug("Target file full name is equal to [" + targetFile + "]");
FeatureCollection fc = loadFile( targetFile );
logger.debug("Target file contains [" + fc.size() + "] features to index");
if ( fc.size() == 0){
throw new NullReferenceException("Impossible to find attribute [features in file [" + filename +"]");
}
FeatureIterator iterator = fc.features();
while (iterator.hasNext()) {
SimpleFeature feature = (SimpleFeature) iterator.next();
Object idx = feature.getProperty(geoIdPName).getValue();
lookupTable.put(idx.toString(), feature);
logger.debug("Feature [" + idx + "] added to the index");
}
logger.debug("File [" + filename + "] indexed succesfully on attribute [" + geoIdPName + "]");
} catch(Throwable t) {
indexOnAttribute = null;
lookupTable = null;
throw new SpagoBIRuntimeException(t);
} finally {
logger.debug("OUT");
}
}
|
diff --git a/src/org/melonbrew/fe/API.java b/src/org/melonbrew/fe/API.java
index cec4540..05cc2ef 100755
--- a/src/org/melonbrew/fe/API.java
+++ b/src/org/melonbrew/fe/API.java
@@ -1,103 +1,103 @@
package org.melonbrew.fe;
import java.text.DecimalFormat;
import java.util.List;
import org.bukkit.ChatColor;
import org.melonbrew.fe.database.Account;
public class API {
private final Fe plugin;
private final DecimalFormat moneyFormat;
public API(Fe plugin){
this.plugin = plugin;
moneyFormat = new DecimalFormat("###,###.###");
}
public List<Account> getTopAccounts(){
return plugin.getFeDatabase().getTopAccounts();
}
public double getDefaultHoldings(){
return plugin.getConfig().getDouble("holdings");
}
public double getMaxHoldings(){
return plugin.getConfig().getDouble("maxholdings");
}
public String getCurrencyPrefix(){
return plugin.getConfig().getString("currency.prefix");
}
public String getCurrencySingle(){
return plugin.getConfig().getString("currency.single");
}
public String getCurrencyMultiple(){
return plugin.getConfig().getString("currency.multiple");
}
public Account createAccount(String name){
return plugin.getFeDatabase().createAccount(name.toLowerCase());
}
public void removeAccount(String name){
plugin.getFeDatabase().removeAccount(name.toLowerCase());
}
public Account getAccount(String name){
return plugin.getFeDatabase().getAccount(name.toLowerCase());
}
public boolean accountExists(String name){
return plugin.getFeDatabase().accountExists(name.toLowerCase());
}
public String formatNoColor(double amount){
return ChatColor.stripColor(format(amount));
}
public String format(double amount){
amount = getMoneyRounded(amount);
String suffix = " ";
if (amount == 1.0){
- suffix = getCurrencySingle();
+ suffix += getCurrencySingle();
}else {
- suffix = getCurrencyMultiple();
+ suffix += getCurrencyMultiple();
}
if (suffix.equalsIgnoreCase(" ")){
suffix = "";
}
return Phrase.SECONDARY_COLOR.parse() + getCurrencyPrefix() + Phrase.PRIMARY_COLOR.parse() + moneyFormat.format(amount) + Phrase.SECONDARY_COLOR.parse() + suffix;
}
public double getMoneyRounded(double amount){
DecimalFormat twoDForm = new DecimalFormat("#.##");
String formattedAmount = twoDForm.format(amount);
formattedAmount = formattedAmount.replace(",", ".");
return Double.valueOf(formattedAmount);
}
public String formatNoColor(Account account){
return ChatColor.stripColor(format(account));
}
public String format(Account account){
return format(account.getMoney());
}
public void clean(){
plugin.getFeDatabase().clean();
}
}
| false | true | public String format(double amount){
amount = getMoneyRounded(amount);
String suffix = " ";
if (amount == 1.0){
suffix = getCurrencySingle();
}else {
suffix = getCurrencyMultiple();
}
if (suffix.equalsIgnoreCase(" ")){
suffix = "";
}
return Phrase.SECONDARY_COLOR.parse() + getCurrencyPrefix() + Phrase.PRIMARY_COLOR.parse() + moneyFormat.format(amount) + Phrase.SECONDARY_COLOR.parse() + suffix;
}
| public String format(double amount){
amount = getMoneyRounded(amount);
String suffix = " ";
if (amount == 1.0){
suffix += getCurrencySingle();
}else {
suffix += getCurrencyMultiple();
}
if (suffix.equalsIgnoreCase(" ")){
suffix = "";
}
return Phrase.SECONDARY_COLOR.parse() + getCurrencyPrefix() + Phrase.PRIMARY_COLOR.parse() + moneyFormat.format(amount) + Phrase.SECONDARY_COLOR.parse() + suffix;
}
|
diff --git a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/ImageView.java b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/ImageView.java
index d7801747..057e47a9 100644
--- a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/ImageView.java
+++ b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/ImageView.java
@@ -1,169 +1,169 @@
package ch.cern.atlas.apvs.client.ui;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.cern.atlas.apvs.client.ClientFactory;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.media.client.Video;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
public class ImageView extends SimplePanel {
private Logger log = LoggerFactory.getLogger(getClass().getName());
private String currentCameraUrl;
private String videoWidth;
private String videoHeight;
private String videoPoster = "Default-640x480.jpg";
protected Image image;
private boolean isMovingJPEG;
private ClientFactory factory;
// FIXME #644 can use
// private final static String quickTime = "/quicktime/AC_QuickTime.js";
private final static String quickTime = "http://localhost:8095/quicktime/AC_QuickTime.js";
protected ImageView() {
}
public ImageView(ClientFactory factory, String cameraUrl) {
init(factory, "100%", "");
setUrl(cameraUrl);
}
protected void init(ClientFactory factory, String width, String height) {
this.factory = factory;
this.videoWidth = width;
this.videoHeight = height;
image = new Image();
image.setWidth(videoWidth);
image.setHeight(videoHeight);
// keep setting URL for video not to get stuck, FIXME #425 find a better
// way...
// FIX seems to keep adding resources in Safari (WebKit), so avoid this
boolean keepSettingUrl = !Window.Navigator.getUserAgent().contains("WebKit");
if (keepSettingUrl) {
Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() {
@Override
public boolean execute() {
if (!isAttached()) {
return false;
}
if ((currentCameraUrl != null) && isMovingJPEG) {
image.setUrl(currentCameraUrl);
// Window.alert("Set URL to "+currentCameraUrl);
}
return true;
}
}, 30000);
}
}
public boolean setUrl(String cameraUrl) {
if ((cameraUrl == null) || cameraUrl.trim().equals("")) {
currentCameraUrl = null;
if (image != null) {
image.setUrl("");
}
image = new Image();
image.setWidth(videoWidth);
image.setHeight(videoHeight);
image.setUrl(videoPoster);
image.setTitle("");
setWidget(image);
isMovingJPEG = false;
return false;
}
if (cameraUrl.equals(currentCameraUrl)) {
return false;
}
currentCameraUrl = cameraUrl;
- if (cameraUrl.startsWith("http://")) {
+ if (cameraUrl.startsWith("http://") || cameraUrl.startsWith("https://")) {
if (cameraUrl.endsWith(".mjpg")) {
log.info(cameraUrl);
if (image != null) {
image.setUrl("");
}
image = new Image();
image.setWidth(videoWidth);
image.setHeight(videoHeight);
image.setUrl(cameraUrl);
image.setTitle(cameraUrl);
setWidget(image);
isMovingJPEG = true;
} else {
Video video = Video.createIfSupported();
if (video != null) {
video.setWidth(videoWidth);
video.setHeight(videoHeight);
video.setControls(true);
video.setAutoplay(true);
video.setPoster(videoPoster);
video.setMuted(true);
video.setLoop(true);
video.addSource(cameraUrl);
}
log.info(video.toString());
video.setTitle(cameraUrl);
setWidget(video);
isMovingJPEG = false;
}
} else if (cameraUrl.startsWith("rtsp://")) {
Widget video = new HTML(
"<embed width=\""
+ getOffsetWidth()
+ "\" height=\""
+ getOffsetHeight()
+ "\" src=\""
+ cameraUrl
+ "\" autoplay=\"true\" type=\"video/quicktime\" controller=\"true\" quitwhendone=\"false\" loop=\"false\"/></embed>");
log.info(video.toString());
video.setTitle(cameraUrl);
setWidget(video);
isMovingJPEG = false;
} else {
Widget video = new HTML(
getQuickTime()
+ "<script language=\"javascript\" type=\"text/javascript\">"
+ "QT_WriteOBJECT('"
+ videoPoster
+ "', '"
+ videoWidth
+ "', '"
+ videoHeight
+ "', '', 'href', '"
+ cameraUrl
+ "', 'autohref', 'true', 'target', 'myself', 'controller', 'true', 'autoplay', 'true');</script>");
log.info(video.toString());
video.setTitle(cameraUrl);
setWidget(video);
isMovingJPEG = false;
}
return true;
}
private String getQuickTime() {
return "<script type=\"text/javascript\" language=\"javascript\" src=\""+factory.getProxy().getReverseUrl(quickTime)+"\"></script>";
}
}
| true | true | public boolean setUrl(String cameraUrl) {
if ((cameraUrl == null) || cameraUrl.trim().equals("")) {
currentCameraUrl = null;
if (image != null) {
image.setUrl("");
}
image = new Image();
image.setWidth(videoWidth);
image.setHeight(videoHeight);
image.setUrl(videoPoster);
image.setTitle("");
setWidget(image);
isMovingJPEG = false;
return false;
}
if (cameraUrl.equals(currentCameraUrl)) {
return false;
}
currentCameraUrl = cameraUrl;
if (cameraUrl.startsWith("http://")) {
if (cameraUrl.endsWith(".mjpg")) {
log.info(cameraUrl);
if (image != null) {
image.setUrl("");
}
image = new Image();
image.setWidth(videoWidth);
image.setHeight(videoHeight);
image.setUrl(cameraUrl);
image.setTitle(cameraUrl);
setWidget(image);
isMovingJPEG = true;
} else {
Video video = Video.createIfSupported();
if (video != null) {
video.setWidth(videoWidth);
video.setHeight(videoHeight);
video.setControls(true);
video.setAutoplay(true);
video.setPoster(videoPoster);
video.setMuted(true);
video.setLoop(true);
video.addSource(cameraUrl);
}
log.info(video.toString());
video.setTitle(cameraUrl);
setWidget(video);
isMovingJPEG = false;
}
} else if (cameraUrl.startsWith("rtsp://")) {
Widget video = new HTML(
"<embed width=\""
+ getOffsetWidth()
+ "\" height=\""
+ getOffsetHeight()
+ "\" src=\""
+ cameraUrl
+ "\" autoplay=\"true\" type=\"video/quicktime\" controller=\"true\" quitwhendone=\"false\" loop=\"false\"/></embed>");
log.info(video.toString());
video.setTitle(cameraUrl);
setWidget(video);
isMovingJPEG = false;
} else {
Widget video = new HTML(
getQuickTime()
+ "<script language=\"javascript\" type=\"text/javascript\">"
+ "QT_WriteOBJECT('"
+ videoPoster
+ "', '"
+ videoWidth
+ "', '"
+ videoHeight
+ "', '', 'href', '"
+ cameraUrl
+ "', 'autohref', 'true', 'target', 'myself', 'controller', 'true', 'autoplay', 'true');</script>");
log.info(video.toString());
video.setTitle(cameraUrl);
setWidget(video);
isMovingJPEG = false;
}
return true;
}
| public boolean setUrl(String cameraUrl) {
if ((cameraUrl == null) || cameraUrl.trim().equals("")) {
currentCameraUrl = null;
if (image != null) {
image.setUrl("");
}
image = new Image();
image.setWidth(videoWidth);
image.setHeight(videoHeight);
image.setUrl(videoPoster);
image.setTitle("");
setWidget(image);
isMovingJPEG = false;
return false;
}
if (cameraUrl.equals(currentCameraUrl)) {
return false;
}
currentCameraUrl = cameraUrl;
if (cameraUrl.startsWith("http://") || cameraUrl.startsWith("https://")) {
if (cameraUrl.endsWith(".mjpg")) {
log.info(cameraUrl);
if (image != null) {
image.setUrl("");
}
image = new Image();
image.setWidth(videoWidth);
image.setHeight(videoHeight);
image.setUrl(cameraUrl);
image.setTitle(cameraUrl);
setWidget(image);
isMovingJPEG = true;
} else {
Video video = Video.createIfSupported();
if (video != null) {
video.setWidth(videoWidth);
video.setHeight(videoHeight);
video.setControls(true);
video.setAutoplay(true);
video.setPoster(videoPoster);
video.setMuted(true);
video.setLoop(true);
video.addSource(cameraUrl);
}
log.info(video.toString());
video.setTitle(cameraUrl);
setWidget(video);
isMovingJPEG = false;
}
} else if (cameraUrl.startsWith("rtsp://")) {
Widget video = new HTML(
"<embed width=\""
+ getOffsetWidth()
+ "\" height=\""
+ getOffsetHeight()
+ "\" src=\""
+ cameraUrl
+ "\" autoplay=\"true\" type=\"video/quicktime\" controller=\"true\" quitwhendone=\"false\" loop=\"false\"/></embed>");
log.info(video.toString());
video.setTitle(cameraUrl);
setWidget(video);
isMovingJPEG = false;
} else {
Widget video = new HTML(
getQuickTime()
+ "<script language=\"javascript\" type=\"text/javascript\">"
+ "QT_WriteOBJECT('"
+ videoPoster
+ "', '"
+ videoWidth
+ "', '"
+ videoHeight
+ "', '', 'href', '"
+ cameraUrl
+ "', 'autohref', 'true', 'target', 'myself', 'controller', 'true', 'autoplay', 'true');</script>");
log.info(video.toString());
video.setTitle(cameraUrl);
setWidget(video);
isMovingJPEG = false;
}
return true;
}
|
diff --git a/aura/src/main/java/org/auraframework/http/AuraFrameworkServlet.java b/aura/src/main/java/org/auraframework/http/AuraFrameworkServlet.java
index fc13901121..214b2fe252 100644
--- a/aura/src/main/java/org/auraframework/http/AuraFrameworkServlet.java
+++ b/aura/src/main/java/org/auraframework/http/AuraFrameworkServlet.java
@@ -1,244 +1,248 @@
/*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.http;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpHeaders;
import org.auraframework.Aura;
import org.auraframework.http.RequestParam.StringParam;
import org.auraframework.util.IOUtil;
import org.auraframework.util.resource.ResourceLoader;
public class AuraFrameworkServlet extends AuraBaseServlet {
private static final long serialVersionUID = 6034969764380397480L;
private static final ResourceLoader resourceLoader = Aura.getConfigAdapter().getResourceLoader();
private final static StringParam fwUIDParam = new StringParam(AURA_PREFIX + "fwuid", 0, false);
private static final String MINIFIED_FILE_SUFFIX = ".min";
// RESOURCES_PATTERN format:
// /required_root/optional_nonce/required_rest_of_path
private static final Pattern RESOURCES_PATTERN = Pattern.compile("^/([^/]+)(/[-_0-9a-zA-Z]+)?(/.*)$");
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// defend against directory traversal attack
// getPathInfo() has already resolved all ".." * "%2E%2E" relative
// references in the path
// and ensured that no directory reference has moved above the root
// (returns 404 if attempted).
String path = request.getPathInfo();
if (path == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String fwUid = fwUIDParam.get(request);
- String currentFwUid = Aura.getConfigAdapter().getAuraFrameworkNonce();
long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
InputStream in = null;
try {
+ //
+ // Careful with race conditions here, we should only call regenerateAuraJS
+ // _before_ we get the nonce.
+ //
Aura.getConfigAdapter().regenerateAuraJS();
+ String currentFwUid = Aura.getConfigAdapter().getAuraFrameworkNonce();
// process path (not in a function because can't use non-synced
// member vars in servlet)
String format = null;
// match entire path once, looking for root, optional nonce, and
// rest-of-path
Matcher matcher = RESOURCES_PATTERN.matcher(path);
if (!matcher.matches()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String nonceUid = matcher.group(2);
String file = null;
boolean haveUid = false;
boolean matchedUid = false;
file = matcher.group(3);
if (nonceUid != null) {
nonceUid = nonceUid.substring(1);
}
//
// This is ugly. We can't really distinguish here between a nonce
// and a path. So rather than try to be cute, if the nonce doesn't
// match, we just use it as part of the path. In practice this will
// do exactly the same thing.
//
if (fwUid != null) {
if (!fwUid.equals(nonceUid) && nonceUid != null) {
//
// This is the case where there is an fwUid, and there is no real
// nonce. We reconnect the falsely matched nonce & file. Note that
// fwUid should never be null for new fetches of the framework js.
//
file = "/"+nonceUid+file;
}
//
// In any case, if we have an fwUid as a parameter, we can erase the
// nonceUid.
//
haveUid = true;
nonceUid = null;
}
if (currentFwUid.equals(fwUid) || currentFwUid.equals(nonceUid)) {
//
// If we match the nonce and we have an if-modified-since, we
// can just send back a not modified. Timestamps don't matter.
// Note that this fails to check existence, but browsers
// shouldn't ask for things that don't exist with an
// if-modified-since.
//
// This is the earliest that we can check for the nonce, since
// we only have the nonce after calling regenerate...
//
// DANGER: we have to be sure that the framework nonce actually
// includes all of the resources that may be requested...
//
if (ifModifiedSince != -1) {
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
matchedUid = true;
haveUid = true;
nonceUid = null;
} else if (fwUid != null) {
//
// Whoops, we have a mismatched nonce. Note that a mismatch of the nonce
// does _not_ mean we definitely mismatched.
//
matchedUid = false;
}
String root = matcher.group(1);
if (root.equals("resources")) {
format = "/aura/resources%s";
} else if (root.equals("javascript")) {
format = "/aura/javascript%s";
}
if (format == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String resStr = String.format(format, file);
//
// This will attempt to get the file without the nonce. This is the normal case where the
// nonce was not stripped.
//
// TODO: once we have deployed the aura.fwuid=<blah> for a while, we can change this logic to make
// it simpler, as nonce will always be null... in fact, we'll be able to put it inside the
// if, and never have it exist out here.
//
in = resourceLoader.getResourceAsStream(resStr);
if (nonceUid != null) {
if (in == null) {
//
// In this case the nonce was actually part of the file path, so
// we act as if we got none. This is actually very dangerous. as
// if there was a nonce, and it mismatched, we will give the wrong
// content for the nonce.
//
resStr = String.format(format, "/"+nonceUid+file);
in = resourceLoader.getResourceAsStream(resStr);
if (in != null) {
haveUid = false;
}
} else {
haveUid = true;
matchedUid = false;
}
}
// Checks for a minified version of the external resource file
// Uses the minified version if in production mode.
if (resStr.startsWith("/aura/resources/") && Aura.getConfigAdapter().isProduction()) {
int extIndex = resStr.lastIndexOf(".");
String minFile = resStr.substring(0, extIndex) + MINIFIED_FILE_SUFFIX + resStr.substring(extIndex);
if (resourceLoader.getResource(minFile) != null) {
in = resourceLoader.getResourceAsStream(minFile);
}
}
//
// Check if it exists. DANGER: if there is a nonce, this is really an
// 'out-of-date' problem, and we may break the browser by telling it a
// lie here.
//
if (in == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
// handle any MIME content type, using only file name (not contents)
String mimeType = mimeTypesMap.getContentType(path);
if (mimeType.equals("application/octet-stream") || mimeType.equals(JAVASCRIPT_CONTENT_TYPE)) /* unidentified */{
mimeType = JAVASCRIPT_CONTENT_TYPE;
}
response.setContentType(mimeType);
if (mimeType.startsWith("text/")) {
response.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING);
}
response.setBufferSize(10240);// 10kb
boolean js = JAVASCRIPT_CONTENT_TYPE.equals(mimeType);
if ((haveUid && !matchedUid) || (!haveUid && js)) {
//
// If we had a mismatched UID or we had none, and are requesting js (legacy) we set a short
// cache response.
//
setNoCache(response);
} else if (matchedUid || js) {
//
// If we have a known good state, we send a long expire. Warning, this means that resources other
// than js may have to impact the MD5, which could make it cycle more than we would like.
//
// TODO: if we want to have things not included in the fw uid use the fw-uid nonce,
// we need to adjust to drop the matchedUid.
//
setLongCache(response);
} else {
//
// By default we use short expire. (1 day)
//
setShortCache(response);
}
IOUtil.copyStream(in, response.getOutputStream());
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable t) {
// totally ignore failure to close.
}
}
}
}
}
| false | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// defend against directory traversal attack
// getPathInfo() has already resolved all ".." * "%2E%2E" relative
// references in the path
// and ensured that no directory reference has moved above the root
// (returns 404 if attempted).
String path = request.getPathInfo();
if (path == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String fwUid = fwUIDParam.get(request);
String currentFwUid = Aura.getConfigAdapter().getAuraFrameworkNonce();
long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
InputStream in = null;
try {
Aura.getConfigAdapter().regenerateAuraJS();
// process path (not in a function because can't use non-synced
// member vars in servlet)
String format = null;
// match entire path once, looking for root, optional nonce, and
// rest-of-path
Matcher matcher = RESOURCES_PATTERN.matcher(path);
if (!matcher.matches()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String nonceUid = matcher.group(2);
String file = null;
boolean haveUid = false;
boolean matchedUid = false;
file = matcher.group(3);
if (nonceUid != null) {
nonceUid = nonceUid.substring(1);
}
//
// This is ugly. We can't really distinguish here between a nonce
// and a path. So rather than try to be cute, if the nonce doesn't
// match, we just use it as part of the path. In practice this will
// do exactly the same thing.
//
if (fwUid != null) {
if (!fwUid.equals(nonceUid) && nonceUid != null) {
//
// This is the case where there is an fwUid, and there is no real
// nonce. We reconnect the falsely matched nonce & file. Note that
// fwUid should never be null for new fetches of the framework js.
//
file = "/"+nonceUid+file;
}
//
// In any case, if we have an fwUid as a parameter, we can erase the
// nonceUid.
//
haveUid = true;
nonceUid = null;
}
if (currentFwUid.equals(fwUid) || currentFwUid.equals(nonceUid)) {
//
// If we match the nonce and we have an if-modified-since, we
// can just send back a not modified. Timestamps don't matter.
// Note that this fails to check existence, but browsers
// shouldn't ask for things that don't exist with an
// if-modified-since.
//
// This is the earliest that we can check for the nonce, since
// we only have the nonce after calling regenerate...
//
// DANGER: we have to be sure that the framework nonce actually
// includes all of the resources that may be requested...
//
if (ifModifiedSince != -1) {
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
matchedUid = true;
haveUid = true;
nonceUid = null;
} else if (fwUid != null) {
//
// Whoops, we have a mismatched nonce. Note that a mismatch of the nonce
// does _not_ mean we definitely mismatched.
//
matchedUid = false;
}
String root = matcher.group(1);
if (root.equals("resources")) {
format = "/aura/resources%s";
} else if (root.equals("javascript")) {
format = "/aura/javascript%s";
}
if (format == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String resStr = String.format(format, file);
//
// This will attempt to get the file without the nonce. This is the normal case where the
// nonce was not stripped.
//
// TODO: once we have deployed the aura.fwuid=<blah> for a while, we can change this logic to make
// it simpler, as nonce will always be null... in fact, we'll be able to put it inside the
// if, and never have it exist out here.
//
in = resourceLoader.getResourceAsStream(resStr);
if (nonceUid != null) {
if (in == null) {
//
// In this case the nonce was actually part of the file path, so
// we act as if we got none. This is actually very dangerous. as
// if there was a nonce, and it mismatched, we will give the wrong
// content for the nonce.
//
resStr = String.format(format, "/"+nonceUid+file);
in = resourceLoader.getResourceAsStream(resStr);
if (in != null) {
haveUid = false;
}
} else {
haveUid = true;
matchedUid = false;
}
}
// Checks for a minified version of the external resource file
// Uses the minified version if in production mode.
if (resStr.startsWith("/aura/resources/") && Aura.getConfigAdapter().isProduction()) {
int extIndex = resStr.lastIndexOf(".");
String minFile = resStr.substring(0, extIndex) + MINIFIED_FILE_SUFFIX + resStr.substring(extIndex);
if (resourceLoader.getResource(minFile) != null) {
in = resourceLoader.getResourceAsStream(minFile);
}
}
//
// Check if it exists. DANGER: if there is a nonce, this is really an
// 'out-of-date' problem, and we may break the browser by telling it a
// lie here.
//
if (in == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
// handle any MIME content type, using only file name (not contents)
String mimeType = mimeTypesMap.getContentType(path);
if (mimeType.equals("application/octet-stream") || mimeType.equals(JAVASCRIPT_CONTENT_TYPE)) /* unidentified */{
mimeType = JAVASCRIPT_CONTENT_TYPE;
}
response.setContentType(mimeType);
if (mimeType.startsWith("text/")) {
response.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING);
}
response.setBufferSize(10240);// 10kb
boolean js = JAVASCRIPT_CONTENT_TYPE.equals(mimeType);
if ((haveUid && !matchedUid) || (!haveUid && js)) {
//
// If we had a mismatched UID or we had none, and are requesting js (legacy) we set a short
// cache response.
//
setNoCache(response);
} else if (matchedUid || js) {
//
// If we have a known good state, we send a long expire. Warning, this means that resources other
// than js may have to impact the MD5, which could make it cycle more than we would like.
//
// TODO: if we want to have things not included in the fw uid use the fw-uid nonce,
// we need to adjust to drop the matchedUid.
//
setLongCache(response);
} else {
//
// By default we use short expire. (1 day)
//
setShortCache(response);
}
IOUtil.copyStream(in, response.getOutputStream());
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable t) {
// totally ignore failure to close.
}
}
}
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// defend against directory traversal attack
// getPathInfo() has already resolved all ".." * "%2E%2E" relative
// references in the path
// and ensured that no directory reference has moved above the root
// (returns 404 if attempted).
String path = request.getPathInfo();
if (path == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String fwUid = fwUIDParam.get(request);
long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
InputStream in = null;
try {
//
// Careful with race conditions here, we should only call regenerateAuraJS
// _before_ we get the nonce.
//
Aura.getConfigAdapter().regenerateAuraJS();
String currentFwUid = Aura.getConfigAdapter().getAuraFrameworkNonce();
// process path (not in a function because can't use non-synced
// member vars in servlet)
String format = null;
// match entire path once, looking for root, optional nonce, and
// rest-of-path
Matcher matcher = RESOURCES_PATTERN.matcher(path);
if (!matcher.matches()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String nonceUid = matcher.group(2);
String file = null;
boolean haveUid = false;
boolean matchedUid = false;
file = matcher.group(3);
if (nonceUid != null) {
nonceUid = nonceUid.substring(1);
}
//
// This is ugly. We can't really distinguish here between a nonce
// and a path. So rather than try to be cute, if the nonce doesn't
// match, we just use it as part of the path. In practice this will
// do exactly the same thing.
//
if (fwUid != null) {
if (!fwUid.equals(nonceUid) && nonceUid != null) {
//
// This is the case where there is an fwUid, and there is no real
// nonce. We reconnect the falsely matched nonce & file. Note that
// fwUid should never be null for new fetches of the framework js.
//
file = "/"+nonceUid+file;
}
//
// In any case, if we have an fwUid as a parameter, we can erase the
// nonceUid.
//
haveUid = true;
nonceUid = null;
}
if (currentFwUid.equals(fwUid) || currentFwUid.equals(nonceUid)) {
//
// If we match the nonce and we have an if-modified-since, we
// can just send back a not modified. Timestamps don't matter.
// Note that this fails to check existence, but browsers
// shouldn't ask for things that don't exist with an
// if-modified-since.
//
// This is the earliest that we can check for the nonce, since
// we only have the nonce after calling regenerate...
//
// DANGER: we have to be sure that the framework nonce actually
// includes all of the resources that may be requested...
//
if (ifModifiedSince != -1) {
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
matchedUid = true;
haveUid = true;
nonceUid = null;
} else if (fwUid != null) {
//
// Whoops, we have a mismatched nonce. Note that a mismatch of the nonce
// does _not_ mean we definitely mismatched.
//
matchedUid = false;
}
String root = matcher.group(1);
if (root.equals("resources")) {
format = "/aura/resources%s";
} else if (root.equals("javascript")) {
format = "/aura/javascript%s";
}
if (format == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String resStr = String.format(format, file);
//
// This will attempt to get the file without the nonce. This is the normal case where the
// nonce was not stripped.
//
// TODO: once we have deployed the aura.fwuid=<blah> for a while, we can change this logic to make
// it simpler, as nonce will always be null... in fact, we'll be able to put it inside the
// if, and never have it exist out here.
//
in = resourceLoader.getResourceAsStream(resStr);
if (nonceUid != null) {
if (in == null) {
//
// In this case the nonce was actually part of the file path, so
// we act as if we got none. This is actually very dangerous. as
// if there was a nonce, and it mismatched, we will give the wrong
// content for the nonce.
//
resStr = String.format(format, "/"+nonceUid+file);
in = resourceLoader.getResourceAsStream(resStr);
if (in != null) {
haveUid = false;
}
} else {
haveUid = true;
matchedUid = false;
}
}
// Checks for a minified version of the external resource file
// Uses the minified version if in production mode.
if (resStr.startsWith("/aura/resources/") && Aura.getConfigAdapter().isProduction()) {
int extIndex = resStr.lastIndexOf(".");
String minFile = resStr.substring(0, extIndex) + MINIFIED_FILE_SUFFIX + resStr.substring(extIndex);
if (resourceLoader.getResource(minFile) != null) {
in = resourceLoader.getResourceAsStream(minFile);
}
}
//
// Check if it exists. DANGER: if there is a nonce, this is really an
// 'out-of-date' problem, and we may break the browser by telling it a
// lie here.
//
if (in == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
// handle any MIME content type, using only file name (not contents)
String mimeType = mimeTypesMap.getContentType(path);
if (mimeType.equals("application/octet-stream") || mimeType.equals(JAVASCRIPT_CONTENT_TYPE)) /* unidentified */{
mimeType = JAVASCRIPT_CONTENT_TYPE;
}
response.setContentType(mimeType);
if (mimeType.startsWith("text/")) {
response.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING);
}
response.setBufferSize(10240);// 10kb
boolean js = JAVASCRIPT_CONTENT_TYPE.equals(mimeType);
if ((haveUid && !matchedUid) || (!haveUid && js)) {
//
// If we had a mismatched UID or we had none, and are requesting js (legacy) we set a short
// cache response.
//
setNoCache(response);
} else if (matchedUid || js) {
//
// If we have a known good state, we send a long expire. Warning, this means that resources other
// than js may have to impact the MD5, which could make it cycle more than we would like.
//
// TODO: if we want to have things not included in the fw uid use the fw-uid nonce,
// we need to adjust to drop the matchedUid.
//
setLongCache(response);
} else {
//
// By default we use short expire. (1 day)
//
setShortCache(response);
}
IOUtil.copyStream(in, response.getOutputStream());
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable t) {
// totally ignore failure to close.
}
}
}
}
|
diff --git a/src/com/android/settings/TextToSpeechSettings.java b/src/com/android/settings/TextToSpeechSettings.java
index 23959c87c..fa9ea583f 100644
--- a/src/com/android/settings/TextToSpeechSettings.java
+++ b/src/com/android/settings/TextToSpeechSettings.java
@@ -1,692 +1,714 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import static android.provider.Settings.Secure.TTS_USE_DEFAULTS;
import static android.provider.Settings.Secure.TTS_DEFAULT_RATE;
import static android.provider.Settings.Secure.TTS_DEFAULT_LANG;
import static android.provider.Settings.Secure.TTS_DEFAULT_COUNTRY;
import static android.provider.Settings.Secure.TTS_DEFAULT_VARIANT;
import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH;
import static android.provider.Settings.Secure.TTS_ENABLED_PLUGINS;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.preference.CheckBoxPreference;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
public class TextToSpeechSettings extends PreferenceActivity implements
Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener,
TextToSpeech.OnInitListener {
private static final String TAG = "TextToSpeechSettings";
private static final String SYSTEM_TTS = "com.svox.pico";
private static final String KEY_TTS_PLAY_EXAMPLE = "tts_play_example";
private static final String KEY_TTS_INSTALL_DATA = "tts_install_data";
private static final String KEY_TTS_USE_DEFAULT = "toggle_use_default_tts_settings";
private static final String KEY_TTS_DEFAULT_RATE = "tts_default_rate";
private static final String KEY_TTS_DEFAULT_LANG = "tts_default_lang";
private static final String KEY_TTS_DEFAULT_COUNTRY = "tts_default_country";
private static final String KEY_TTS_DEFAULT_VARIANT = "tts_default_variant";
private static final String KEY_TTS_DEFAULT_SYNTH = "tts_default_synth";
private static final String KEY_PLUGIN_ENABLED_PREFIX = "ENABLED_";
private static final String KEY_PLUGIN_SETTINGS_PREFIX = "SETTINGS_";
// TODO move default Locale values to TextToSpeech.Engine
private static final String DEFAULT_LANG_VAL = "eng";
private static final String DEFAULT_COUNTRY_VAL = "USA";
private static final String DEFAULT_VARIANT_VAL = "";
private static final String LOCALE_DELIMITER = "-";
private static final String FALLBACK_TTS_DEFAULT_SYNTH =
TextToSpeech.Engine.DEFAULT_SYNTH;
private Preference mPlayExample = null;
private Preference mInstallData = null;
private CheckBoxPreference mUseDefaultPref = null;
private ListPreference mDefaultRatePref = null;
private ListPreference mDefaultLocPref = null;
private ListPreference mDefaultSynthPref = null;
private String mDefaultLanguage = null;
private String mDefaultCountry = null;
private String mDefaultLocVariant = null;
private String mDefaultEng = "";
private int mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE;
// Array of strings used to demonstrate TTS in the different languages.
private String[] mDemoStrings;
// Index of the current string to use for the demo.
private int mDemoStringIndex = 0;
private boolean mEnableDemo = false;
private boolean mVoicesMissing = false;
private TextToSpeech mTts = null;
/**
* Request code (arbitrary value) for voice data check through
* startActivityForResult.
*/
private static final int VOICE_DATA_INTEGRITY_CHECK = 1977;
private static final int GET_SAMPLE_TEXT = 1983;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.tts_settings);
addEngineSpecificSettings();
mDemoStrings = getResources().getStringArray(R.array.tts_demo_strings);
setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM);
mEnableDemo = false;
initClickers();
initDefaultSettings();
mTts = new TextToSpeech(this, this);
}
@Override
protected void onStart() {
super.onStart();
// whenever we return to this screen, we don't know the state of the
// system, so we have to recheck that we can play the demo, or it must be disabled.
// TODO make the TTS service listen to "changes in the system", i.e. sd card un/mount
initClickers();
updateWidgetState();
checkVoiceData();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTts != null) {
mTts.shutdown();
}
}
private void addEngineSpecificSettings() {
PreferenceGroup enginesCategory = (PreferenceGroup) findPreference("tts_engines_section");
Intent intent = new Intent("android.intent.action.START_TTS_ENGINE");
ResolveInfo[] enginesArray = new ResolveInfo[0];
PackageManager pm = getPackageManager();
enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray);
for (int i = 0; i < enginesArray.length; i++) {
String prefKey = "";
final String pluginPackageName = enginesArray[i].activityInfo.packageName;
if (!enginesArray[i].activityInfo.packageName.equals(SYSTEM_TTS)) {
CheckBoxPreference chkbxPref = new CheckBoxPreference(this);
prefKey = KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName;
chkbxPref.setKey(prefKey);
chkbxPref.setTitle(enginesArray[i].loadLabel(pm));
enginesCategory.addPreference(chkbxPref);
}
if (pluginHasSettings(pluginPackageName)) {
Preference pref = new Preference(this);
prefKey = KEY_PLUGIN_SETTINGS_PREFIX + pluginPackageName;
pref.setKey(prefKey);
pref.setTitle(enginesArray[i].loadLabel(pm));
CharSequence settingsLabel = getResources().getString(
R.string.tts_engine_name_settings, enginesArray[i].loadLabel(pm));
pref.setSummary(settingsLabel);
pref.setOnPreferenceClickListener(new OnPreferenceClickListener(){
public boolean onPreferenceClick(Preference preference){
Intent i = new Intent();
i.setClassName(pluginPackageName,
pluginPackageName + ".EngineSettings");
startActivity(i);
return true;
}
});
enginesCategory.addPreference(pref);
}
}
}
private boolean pluginHasSettings(String pluginPackageName) {
PackageManager pm = getPackageManager();
Intent i = new Intent();
i.setClassName(pluginPackageName, pluginPackageName + ".EngineSettings");
if (pm.resolveActivity(i, PackageManager.MATCH_DEFAULT_ONLY) != null){
return true;
}
return false;
}
private void initClickers() {
mPlayExample = findPreference(KEY_TTS_PLAY_EXAMPLE);
mPlayExample.setOnPreferenceClickListener(this);
mInstallData = findPreference(KEY_TTS_INSTALL_DATA);
mInstallData.setOnPreferenceClickListener(this);
}
private void initDefaultSettings() {
ContentResolver resolver = getContentResolver();
// Find the default TTS values in the settings, initialize and store the
// settings if they are not found.
// "Use Defaults"
int useDefault = 0;
mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT);
try {
useDefault = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS);
} catch (SettingNotFoundException e) {
// "use default" setting not found, initialize it
useDefault = TextToSpeech.Engine.USE_DEFAULTS;
Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, useDefault);
}
mUseDefaultPref.setChecked(useDefault == 1);
mUseDefaultPref.setOnPreferenceChangeListener(this);
// Default synthesis engine
mDefaultSynthPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH);
loadEngines();
mDefaultSynthPref.setOnPreferenceChangeListener(this);
String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH);
if (engine == null) {
// TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech
engine = FALLBACK_TTS_DEFAULT_SYNTH;
Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine);
}
mDefaultEng = engine;
// Default rate
mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE);
try {
mDefaultRate = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE);
} catch (SettingNotFoundException e) {
// default rate setting not found, initialize it
mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE;
Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, mDefaultRate);
}
mDefaultRatePref.setValue(String.valueOf(mDefaultRate));
mDefaultRatePref.setOnPreferenceChangeListener(this);
// Default language / country / variant : these three values map to a single ListPref
// representing the matching Locale
mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG);
initDefaultLang();
mDefaultLocPref.setOnPreferenceChangeListener(this);
}
/**
* Ask the current default engine to launch the matching CHECK_TTS_DATA activity
* to check the required TTS files are properly installed.
*/
private void checkVoiceData() {
PackageManager pm = getPackageManager();
Intent intent = new Intent();
intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
// query only the package that matches that of the default engine
for (int i = 0; i < resolveInfos.size(); i++) {
ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo;
if (mDefaultEng.equals(currentActivityInfo.packageName)) {
intent.setClassName(mDefaultEng, currentActivityInfo.name);
this.startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK);
}
}
}
/**
* Ask the current default engine to launch the matching INSTALL_TTS_DATA activity
* so the required TTS files are properly installed.
*/
private void installVoiceData() {
PackageManager pm = getPackageManager();
Intent intent = new Intent();
intent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
// query only the package that matches that of the default engine
for (int i = 0; i < resolveInfos.size(); i++) {
ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo;
if (mDefaultEng.equals(currentActivityInfo.packageName)) {
intent.setClassName(mDefaultEng, currentActivityInfo.name);
this.startActivity(intent);
}
}
}
/**
* Ask the current default engine to return a string of sample text to be
* spoken to the user.
*/
private void getSampleText() {
PackageManager pm = getPackageManager();
Intent intent = new Intent();
// TODO (clchen): Replace Intent string with the actual
// Intent defined in the list of platform Intents.
intent.setAction("android.speech.tts.engine.GET_SAMPLE_TEXT");
intent.putExtra("language", mDefaultLanguage);
intent.putExtra("country", mDefaultCountry);
intent.putExtra("variant", mDefaultLocVariant);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
// query only the package that matches that of the default engine
for (int i = 0; i < resolveInfos.size(); i++) {
ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo;
if (mDefaultEng.equals(currentActivityInfo.packageName)) {
intent.setClassName(mDefaultEng, currentActivityInfo.name);
this.startActivityForResult(intent, GET_SAMPLE_TEXT);
}
}
}
/**
* Called when the TTS engine is initialized.
*/
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Log.v(TAG, "TTS engine for settings screen initialized.");
mEnableDemo = true;
if (mDefaultLanguage == null) {
mDefaultLanguage = Locale.getDefault().getISO3Language();
}
if (mDefaultCountry == null) {
mDefaultCountry = Locale.getDefault().getISO3Country();
}
if (mDefaultLocVariant == null) {
mDefaultLocVariant = new String();
}
mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
mTts.setSpeechRate((float)(mDefaultRate/100.0f));
} else {
Log.v(TAG, "TTS engine for settings screen failed to initialize successfully.");
mEnableDemo = false;
}
updateWidgetState();
}
/**
* Called when voice data integrity check returns
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
if (data == null){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
// TODO (clchen): Add these extras to TextToSpeech.Engine
ArrayList<String> available =
data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES");
ArrayList<String> unavailable =
data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES");
if ((available == null) || (unavailable == null)){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
if (available.size() > 0){
if (mTts == null) {
mTts = new TextToSpeech(this, this);
}
ListPreference ttsLanguagePref =
(ListPreference) findPreference("tts_default_lang");
CharSequence[] entries = new CharSequence[available.size()];
CharSequence[] entryValues = new CharSequence[available.size()];
for (int i=0; i<available.size(); i++){
String[] langCountryVariant = available.get(i).split("-");
Locale loc = null;
if (langCountryVariant.length == 1){
loc = new Locale(langCountryVariant[0]);
} else if (langCountryVariant.length == 2){
loc = new Locale(langCountryVariant[0], langCountryVariant[1]);
} else if (langCountryVariant.length == 3){
loc = new Locale(langCountryVariant[0], langCountryVariant[1],
langCountryVariant[2]);
}
if (loc != null){
entries[i] = loc.getDisplayName();
entryValues[i] = available.get(i);
}
}
ttsLanguagePref.setEntries(entries);
ttsLanguagePref.setEntryValues(entryValues);
mEnableDemo = true;
+ // Make sure that the default language can be used.
+ int languageResult = mTts.setLanguage(
+ new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
+ if (languageResult < TextToSpeech.LANG_AVAILABLE){
+ Locale currentLocale = Locale.getDefault();
+ mDefaultLanguage = currentLocale.getISO3Language();
+ mDefaultCountry = currentLocale.getISO3Country();
+ mDefaultLocVariant = currentLocale.getVariant();
+ languageResult = mTts.setLanguage(
+ new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
+ // If the default Locale isn't supported, just choose the first available
+ // language so that there is at least something.
+ if (languageResult < TextToSpeech.LANG_AVAILABLE){
+ parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString());
+ mTts.setLanguage(
+ new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
+ }
+ ContentResolver resolver = getContentResolver();
+ Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage);
+ Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry);
+ Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant);
+ }
} else {
mEnableDemo = false;
}
if (unavailable.size() > 0){
mVoicesMissing = true;
} else {
mVoicesMissing = false;
}
updateWidgetState();
} else if (requestCode == GET_SAMPLE_TEXT) {
if (resultCode == TextToSpeech.LANG_AVAILABLE) {
String sample = getString(R.string.tts_demo);
if ((data != null) && (data.getStringExtra("sampleText") != null)) {
sample = data.getStringExtra("sampleText");
}
if (mTts != null) {
mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null);
}
} else {
// TODO: Display an error here to the user.
Log.e(TAG, "Did not have a sample string for the requested language");
}
}
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
if (KEY_TTS_USE_DEFAULT.equals(preference.getKey())) {
// "Use Defaults"
int value = (Boolean)objValue ? 1 : 0;
Settings.Secure.putInt(getContentResolver(), TTS_USE_DEFAULTS,
value);
Log.i(TAG, "TTS use default settings is "+objValue.toString());
} else if (KEY_TTS_DEFAULT_RATE.equals(preference.getKey())) {
// Default rate
mDefaultRate = Integer.parseInt((String) objValue);
try {
Settings.Secure.putInt(getContentResolver(),
TTS_DEFAULT_RATE, mDefaultRate);
if (mTts != null) {
mTts.setSpeechRate((float)(mDefaultRate/100.0f));
}
Log.i(TAG, "TTS default rate is " + mDefaultRate);
} catch (NumberFormatException e) {
Log.e(TAG, "could not persist default TTS rate setting", e);
}
} else if (KEY_TTS_DEFAULT_LANG.equals(preference.getKey())) {
// Default locale
ContentResolver resolver = getContentResolver();
parseLocaleInfo((String) objValue);
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant);
Log.v(TAG, "TTS default lang/country/variant set to "
+ mDefaultLanguage + "/" + mDefaultCountry + "/" + mDefaultLocVariant);
if (mTts != null) {
mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
}
int newIndex = mDefaultLocPref.findIndexOfValue((String)objValue);
Log.v("Settings", " selected is " + newIndex);
mDemoStringIndex = newIndex > -1 ? newIndex : 0;
} else if (KEY_TTS_DEFAULT_SYNTH.equals(preference.getKey())) {
mDefaultEng = objValue.toString();
Settings.Secure.putString(getContentResolver(), TTS_DEFAULT_SYNTH, mDefaultEng);
if (mTts != null) {
mTts.setEngineByPackageName(mDefaultEng);
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
checkVoiceData();
}
Log.v("Settings", "The default synth is: " + objValue.toString());
}
return true;
}
/**
* Called when mPlayExample or mInstallData is clicked
*/
public boolean onPreferenceClick(Preference preference) {
if (preference == mPlayExample) {
// Get the sample text from the TTS engine; onActivityResult will do
// the actual speaking
getSampleText();
return true;
}
if (preference == mInstallData) {
installVoiceData();
// quit this activity so it needs to be restarted after installation of the voice data
finish();
return true;
}
return false;
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (Utils.isMonkeyRunning()) {
return false;
}
if (preference instanceof CheckBoxPreference) {
final CheckBoxPreference chkPref = (CheckBoxPreference) preference;
if (!chkPref.getKey().equals(KEY_TTS_USE_DEFAULT)){
if (chkPref.isChecked()) {
chkPref.setChecked(false);
AlertDialog d = (new AlertDialog.Builder(this))
.setTitle(android.R.string.dialog_alert_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(getString(R.string.tts_engine_security_warning,
chkPref.getTitle()))
.setCancelable(true)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
chkPref.setChecked(true);
loadEngines();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
d.show();
} else {
loadEngines();
}
return true;
}
}
return false;
}
private void updateWidgetState() {
mPlayExample.setEnabled(mEnableDemo);
mUseDefaultPref.setEnabled(mEnableDemo);
mDefaultRatePref.setEnabled(mEnableDemo);
mDefaultLocPref.setEnabled(mEnableDemo);
mInstallData.setEnabled(mVoicesMissing);
}
private void parseLocaleInfo(String locale) {
StringTokenizer tokenizer = new StringTokenizer(locale, LOCALE_DELIMITER);
mDefaultLanguage = "";
mDefaultCountry = "";
mDefaultLocVariant = "";
if (tokenizer.hasMoreTokens()) {
mDefaultLanguage = tokenizer.nextToken().trim();
}
if (tokenizer.hasMoreTokens()) {
mDefaultCountry = tokenizer.nextToken().trim();
}
if (tokenizer.hasMoreTokens()) {
mDefaultLocVariant = tokenizer.nextToken().trim();
}
}
/**
* Initialize the default language in the UI and in the preferences.
* After this method has been invoked, the default language is a supported Locale.
*/
private void initDefaultLang() {
// if there isn't already a default language preference
if (!hasLangPref()) {
// if the current Locale is supported
if (isCurrentLocSupported()) {
// then use the current Locale as the default language
useCurrentLocAsDefault();
} else {
// otherwise use a default supported Locale as the default language
useSupportedLocAsDefault();
}
}
// Update the language preference list with the default language and the matching
// demo string (at this stage there is a default language pref)
ContentResolver resolver = getContentResolver();
mDefaultLanguage = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG);
mDefaultCountry = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY);
mDefaultLocVariant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT);
// update the demo string
mDemoStringIndex = mDefaultLocPref.findIndexOfValue(mDefaultLanguage + LOCALE_DELIMITER
+ mDefaultCountry);
if (mDemoStringIndex > -1){
mDefaultLocPref.setValueIndex(mDemoStringIndex);
}
}
/**
* (helper function for initDefaultLang() )
* Returns whether there is a default language in the TTS settings.
*/
private boolean hasLangPref() {
String language = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_LANG);
return (language != null);
}
/**
* (helper function for initDefaultLang() )
* Returns whether the current Locale is supported by this Settings screen
*/
private boolean isCurrentLocSupported() {
String currentLocID = Locale.getDefault().getISO3Language() + LOCALE_DELIMITER
+ Locale.getDefault().getISO3Country();
return (mDefaultLocPref.findIndexOfValue(currentLocID) > -1);
}
/**
* (helper function for initDefaultLang() )
* Sets the default language in TTS settings to be the current Locale.
* This should only be used after checking that the current Locale is supported.
*/
private void useCurrentLocAsDefault() {
Locale currentLocale = Locale.getDefault();
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, currentLocale.getISO3Language());
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, currentLocale.getISO3Country());
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, currentLocale.getVariant());
}
/**
* (helper function for initDefaultLang() )
* Sets the default language in TTS settings to be one known to be supported
*/
private void useSupportedLocAsDefault() {
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, DEFAULT_LANG_VAL);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, DEFAULT_COUNTRY_VAL);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, DEFAULT_VARIANT_VAL);
}
private void loadEngines() {
ListPreference enginesPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH);
// TODO (clchen): Try to see if it is possible to be more efficient here
// and not search for plugins again.
Intent intent = new Intent("android.intent.action.START_TTS_ENGINE");
ResolveInfo[] enginesArray = new ResolveInfo[0];
PackageManager pm = getPackageManager();
enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray);
ArrayList<CharSequence> entries = new ArrayList<CharSequence>();
ArrayList<CharSequence> values = new ArrayList<CharSequence>();
String enabledEngines = "";
for (int i = 0; i < enginesArray.length; i++) {
String pluginPackageName = enginesArray[i].activityInfo.packageName;
if (pluginPackageName.equals(SYSTEM_TTS)) {
entries.add(enginesArray[i].loadLabel(pm));
values.add(pluginPackageName);
} else {
CheckBoxPreference pref = (CheckBoxPreference) findPreference(
KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName);
if ((pref != null) && pref.isChecked()){
entries.add(enginesArray[i].loadLabel(pm));
values.add(pluginPackageName);
enabledEngines = enabledEngines + pluginPackageName + " ";
}
}
}
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_ENABLED_PLUGINS, enabledEngines);
CharSequence entriesArray[] = new CharSequence[entries.size()];
CharSequence valuesArray[] = new CharSequence[values.size()];
enginesPref.setEntries(entries.toArray(entriesArray));
enginesPref.setEntryValues(values.toArray(valuesArray));
// Set the selected engine based on the saved preference
String selectedEngine = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_SYNTH);
int selectedEngineIndex = enginesPref.findIndexOfValue(selectedEngine);
if (selectedEngineIndex == -1){
selectedEngineIndex = enginesPref.findIndexOfValue(SYSTEM_TTS);
}
enginesPref.setValueIndex(selectedEngineIndex);
}
}
| true | true | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
if (data == null){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
// TODO (clchen): Add these extras to TextToSpeech.Engine
ArrayList<String> available =
data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES");
ArrayList<String> unavailable =
data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES");
if ((available == null) || (unavailable == null)){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
if (available.size() > 0){
if (mTts == null) {
mTts = new TextToSpeech(this, this);
}
ListPreference ttsLanguagePref =
(ListPreference) findPreference("tts_default_lang");
CharSequence[] entries = new CharSequence[available.size()];
CharSequence[] entryValues = new CharSequence[available.size()];
for (int i=0; i<available.size(); i++){
String[] langCountryVariant = available.get(i).split("-");
Locale loc = null;
if (langCountryVariant.length == 1){
loc = new Locale(langCountryVariant[0]);
} else if (langCountryVariant.length == 2){
loc = new Locale(langCountryVariant[0], langCountryVariant[1]);
} else if (langCountryVariant.length == 3){
loc = new Locale(langCountryVariant[0], langCountryVariant[1],
langCountryVariant[2]);
}
if (loc != null){
entries[i] = loc.getDisplayName();
entryValues[i] = available.get(i);
}
}
ttsLanguagePref.setEntries(entries);
ttsLanguagePref.setEntryValues(entryValues);
mEnableDemo = true;
} else {
mEnableDemo = false;
}
if (unavailable.size() > 0){
mVoicesMissing = true;
} else {
mVoicesMissing = false;
}
updateWidgetState();
} else if (requestCode == GET_SAMPLE_TEXT) {
if (resultCode == TextToSpeech.LANG_AVAILABLE) {
String sample = getString(R.string.tts_demo);
if ((data != null) && (data.getStringExtra("sampleText") != null)) {
sample = data.getStringExtra("sampleText");
}
if (mTts != null) {
mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null);
}
} else {
// TODO: Display an error here to the user.
Log.e(TAG, "Did not have a sample string for the requested language");
}
}
}
| protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
if (data == null){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
// TODO (clchen): Add these extras to TextToSpeech.Engine
ArrayList<String> available =
data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES");
ArrayList<String> unavailable =
data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES");
if ((available == null) || (unavailable == null)){
// The CHECK_TTS_DATA activity for the plugin did not run properly;
// disable the preview and install controls and return.
mEnableDemo = false;
mVoicesMissing = false;
updateWidgetState();
return;
}
if (available.size() > 0){
if (mTts == null) {
mTts = new TextToSpeech(this, this);
}
ListPreference ttsLanguagePref =
(ListPreference) findPreference("tts_default_lang");
CharSequence[] entries = new CharSequence[available.size()];
CharSequence[] entryValues = new CharSequence[available.size()];
for (int i=0; i<available.size(); i++){
String[] langCountryVariant = available.get(i).split("-");
Locale loc = null;
if (langCountryVariant.length == 1){
loc = new Locale(langCountryVariant[0]);
} else if (langCountryVariant.length == 2){
loc = new Locale(langCountryVariant[0], langCountryVariant[1]);
} else if (langCountryVariant.length == 3){
loc = new Locale(langCountryVariant[0], langCountryVariant[1],
langCountryVariant[2]);
}
if (loc != null){
entries[i] = loc.getDisplayName();
entryValues[i] = available.get(i);
}
}
ttsLanguagePref.setEntries(entries);
ttsLanguagePref.setEntryValues(entryValues);
mEnableDemo = true;
// Make sure that the default language can be used.
int languageResult = mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
if (languageResult < TextToSpeech.LANG_AVAILABLE){
Locale currentLocale = Locale.getDefault();
mDefaultLanguage = currentLocale.getISO3Language();
mDefaultCountry = currentLocale.getISO3Country();
mDefaultLocVariant = currentLocale.getVariant();
languageResult = mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
// If the default Locale isn't supported, just choose the first available
// language so that there is at least something.
if (languageResult < TextToSpeech.LANG_AVAILABLE){
parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString());
mTts.setLanguage(
new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant));
}
ContentResolver resolver = getContentResolver();
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant);
}
} else {
mEnableDemo = false;
}
if (unavailable.size() > 0){
mVoicesMissing = true;
} else {
mVoicesMissing = false;
}
updateWidgetState();
} else if (requestCode == GET_SAMPLE_TEXT) {
if (resultCode == TextToSpeech.LANG_AVAILABLE) {
String sample = getString(R.string.tts_demo);
if ((data != null) && (data.getStringExtra("sampleText") != null)) {
sample = data.getStringExtra("sampleText");
}
if (mTts != null) {
mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null);
}
} else {
// TODO: Display an error here to the user.
Log.e(TAG, "Did not have a sample string for the requested language");
}
}
}
|
diff --git a/android/src/de/hsa/otma/android/map/Board.java b/android/src/de/hsa/otma/android/map/Board.java
index 9a0034b..258abb5 100644
--- a/android/src/de/hsa/otma/android/map/Board.java
+++ b/android/src/de/hsa/otma/android/map/Board.java
@@ -1,175 +1,175 @@
package de.hsa.otma.android.map;
import android.util.Log;
import de.hsa.otma.android.OTMAApplication;
import de.hsa.otma.android.R;
import java.util.*;
import static de.hsa.otma.android.map.Direction.*;
public class Board {
private static final String TAG = Board.class.getSimpleName();
public static final Board INSTANCE = new Board();
private Map<Coordinate, BoardElement> elements = new HashMap<Coordinate, BoardElement>();
private List<Door> doors = new ArrayList<Door>();
private Board() {
buildBoard();
}
public Coordinate getRandomCoordinateOnBoard() {
int x = random.nextInt(5) + 1;
int y = random.nextInt(5) + 1;
return new Coordinate(x, y);
}
private Random random = new Random(System.nanoTime());
private void assignRoomsToRandomDoors() {
Log.d(TAG, "Assigning rooms to doors!");
List<Room> rooms = OTMAApplication.CONFIG.getRooms();
if (doors.size() < rooms.size()) {
rooms = rooms.subList(0, doors.size() - 1);
}
for (Room room : rooms) {
Door door = getRandomDoorWithoutRoom();
door.setRoom(room);
door.setAbbreviation(room.getAbbreviation());
door.setTitle(room.getTitle());
}
Log.i(TAG, rooms.size() + " rooms have been assigned to doors!");
}
private Door getRandomDoorWithoutRoom() {
List<Door> uncheckedDoors = new ArrayList<Door>(doors);
while (uncheckedDoors.size() > 0) {
// int index = random.nextInt(uncheckedDoors.size());
int index = 0;
Door door = uncheckedDoors.get(index);
if (door.getRoom() == null) {
return door;
} else {
uncheckedDoors.remove(index);
}
}
throw new IllegalStateException("more rooms as doors specified, this exception should never occur!");
}
private void createDoorForBoardElementInDirection(BoardElement element, Direction direction) {
int x = -element.getCoordinate().getX();
int y = -element.getCoordinate().getY();
Coordinate coordinate = new Coordinate(x, y);
Door door = new Door(coordinate, element);
elements.put(coordinate, door);
element.setElementForDirection(direction, door);
doors.add(door);
}
public boolean isAccessibleByNPCPlayer(Coordinate coordinate) {
return coordinate.getX() < 0 && coordinate.getY() < 0;
}
private BoardElement createBoardElementAndPutToBoard(int x, int y, int drawable) {
Coordinate coordinate = new Coordinate(x, y);
BoardElement boardElement = new BoardElement(coordinate, drawable);
elements.put(coordinate, boardElement);
return boardElement;
}
public BoardElement getElementFor(Coordinate coordinate) {
return elements.get(coordinate);
}
private void buildBoard() {
BoardElement map1x1 = createBoardElementAndPutToBoard(1, 1, R.drawable.map_1x1);
BoardElement map1x2 = createBoardElementAndPutToBoard(2, 1, R.drawable.map_1x2);
BoardElement map1x3 = createBoardElementAndPutToBoard(3, 1, R.drawable.map_1x3);
BoardElement map1x4 = createBoardElementAndPutToBoard(4, 1, R.drawable.map_1x4);
BoardElement map1x5 = createBoardElementAndPutToBoard(5, 1, R.drawable.map_1x5);
BoardElement map2x1 = createBoardElementAndPutToBoard(1, 2, R.drawable.map_2x1);
BoardElement map2x2 = createBoardElementAndPutToBoard(2, 2, R.drawable.map_2x2);
BoardElement map2x3 = createBoardElementAndPutToBoard(3, 2, R.drawable.map_2x3);
BoardElement map2x4 = createBoardElementAndPutToBoard(4, 2, R.drawable.map_2x4);
BoardElement map2x5 = createBoardElementAndPutToBoard(5, 2, R.drawable.map_2x5);
BoardElement map3x1 = createBoardElementAndPutToBoard(1, 3, R.drawable.map_3x1);
BoardElement map3x2 = createBoardElementAndPutToBoard(2, 3, R.drawable.map_3x2);
BoardElement map3x3 = createBoardElementAndPutToBoard(3, 3, R.drawable.map_3x3);
BoardElement map3x4 = createBoardElementAndPutToBoard(4, 3, R.drawable.map_3x4);
BoardElement map3x5 = createBoardElementAndPutToBoard(5, 3, R.drawable.map_3x5);
BoardElement map4x1 = createBoardElementAndPutToBoard(1, 4, R.drawable.map_4x1);
BoardElement map4x2 = createBoardElementAndPutToBoard(2, 4, R.drawable.map_4x2);
BoardElement map4x3 = createBoardElementAndPutToBoard(3, 4, R.drawable.map_4x3);
BoardElement map4x4 = createBoardElementAndPutToBoard(4, 4, R.drawable.map_4x4);
BoardElement map4x5 = createBoardElementAndPutToBoard(5, 4, R.drawable.map_4x5);
BoardElement map5x1 = createBoardElementAndPutToBoard(1, 5, R.drawable.map_5x1);
BoardElement map5x2 = createBoardElementAndPutToBoard(2, 5, R.drawable.map_5x2);
BoardElement map5x3 = createBoardElementAndPutToBoard(3, 5, R.drawable.map_5x3);
BoardElement map5x4 = createBoardElementAndPutToBoard(4, 5, R.drawable.map_5x4);
BoardElement map5x5 = createBoardElementAndPutToBoard(5, 5, R.drawable.map_5x5);
map1x1.setBoundaryElements(null, null, map2x1, null);
map1x2.setBoundaryElements(null, map1x3, map2x2, null);
map1x3.setBoundaryElements(null, map1x4, map2x3, map1x2);
map1x4.setBoundaryElements(null, map1x5, null, map1x3);
map1x5.setBoundaryElements(null, null, null, map1x4);
map2x1.setBoundaryElements(map1x1, map2x2, map3x1, null);
map2x2.setBoundaryElements(map1x2, null, null, map2x1);
map2x3.setBoundaryElements(map1x3, null, map3x3, null);
map2x4.setBoundaryElements(null, map2x5, null, null);
map2x5.setBoundaryElements(null, null, map3x5, map2x4);
map3x1.setBoundaryElements(map2x1, null, map4x1, null);
map3x2.setBoundaryElements(null, map3x3, map4x2, null);
map3x3.setBoundaryElements(map2x3, map3x4, null, map3x2);
map3x4.setBoundaryElements(null, map3x5, null, map3x3);
map3x5.setBoundaryElements(map2x5, null, map4x5, map3x4);
map4x1.setBoundaryElements(map3x1, map4x2, map5x1, null);
map4x2.setBoundaryElements(map3x2, map4x3, null, map4x1);
map4x3.setBoundaryElements(null, null, map5x3, map4x2);
map4x4.setBoundaryElements(null, map4x5, map5x4, null);
map4x5.setBoundaryElements(map3x5, null, map5x5, map4x4);
map5x1.setBoundaryElements(map4x1, map5x2, null, null);
map5x2.setBoundaryElements(null, map5x3, null, map5x1);
map5x3.setBoundaryElements(map4x3, map5x4, null, map5x2);
map5x4.setBoundaryElements(map4x4, null, null, map5x3);
map5x5.setBoundaryElements(map4x5, null, null, null);
createDoorForBoardElementInDirection(map1x2, NORTH);
createDoorForBoardElementInDirection(map1x5, SOUTH);
createDoorForBoardElementInDirection(map2x1, WEST);
- //createDoorForBoardElementInDirection(map2x2, EAST);
+ createDoorForBoardElementInDirection(map2x2, EAST);
createDoorForBoardElementInDirection(map2x4, WEST);
createDoorForBoardElementInDirection(map2x5, NORTH);
createDoorForBoardElementInDirection(map3x1, EAST);
createDoorForBoardElementInDirection(map3x2, NORTH);
createDoorForBoardElementInDirection(map3x4, SOUTH);
createDoorForBoardElementInDirection(map3x5, EAST);
createDoorForBoardElementInDirection(map4x1, WEST);
createDoorForBoardElementInDirection(map4x3, EAST);
createDoorForBoardElementInDirection(map4x4, NORTH);
createDoorForBoardElementInDirection(map5x2, NORTH);
createDoorForBoardElementInDirection(map5x5, WEST);
assignRoomsToRandomDoors();
}
}
| true | true | private void buildBoard() {
BoardElement map1x1 = createBoardElementAndPutToBoard(1, 1, R.drawable.map_1x1);
BoardElement map1x2 = createBoardElementAndPutToBoard(2, 1, R.drawable.map_1x2);
BoardElement map1x3 = createBoardElementAndPutToBoard(3, 1, R.drawable.map_1x3);
BoardElement map1x4 = createBoardElementAndPutToBoard(4, 1, R.drawable.map_1x4);
BoardElement map1x5 = createBoardElementAndPutToBoard(5, 1, R.drawable.map_1x5);
BoardElement map2x1 = createBoardElementAndPutToBoard(1, 2, R.drawable.map_2x1);
BoardElement map2x2 = createBoardElementAndPutToBoard(2, 2, R.drawable.map_2x2);
BoardElement map2x3 = createBoardElementAndPutToBoard(3, 2, R.drawable.map_2x3);
BoardElement map2x4 = createBoardElementAndPutToBoard(4, 2, R.drawable.map_2x4);
BoardElement map2x5 = createBoardElementAndPutToBoard(5, 2, R.drawable.map_2x5);
BoardElement map3x1 = createBoardElementAndPutToBoard(1, 3, R.drawable.map_3x1);
BoardElement map3x2 = createBoardElementAndPutToBoard(2, 3, R.drawable.map_3x2);
BoardElement map3x3 = createBoardElementAndPutToBoard(3, 3, R.drawable.map_3x3);
BoardElement map3x4 = createBoardElementAndPutToBoard(4, 3, R.drawable.map_3x4);
BoardElement map3x5 = createBoardElementAndPutToBoard(5, 3, R.drawable.map_3x5);
BoardElement map4x1 = createBoardElementAndPutToBoard(1, 4, R.drawable.map_4x1);
BoardElement map4x2 = createBoardElementAndPutToBoard(2, 4, R.drawable.map_4x2);
BoardElement map4x3 = createBoardElementAndPutToBoard(3, 4, R.drawable.map_4x3);
BoardElement map4x4 = createBoardElementAndPutToBoard(4, 4, R.drawable.map_4x4);
BoardElement map4x5 = createBoardElementAndPutToBoard(5, 4, R.drawable.map_4x5);
BoardElement map5x1 = createBoardElementAndPutToBoard(1, 5, R.drawable.map_5x1);
BoardElement map5x2 = createBoardElementAndPutToBoard(2, 5, R.drawable.map_5x2);
BoardElement map5x3 = createBoardElementAndPutToBoard(3, 5, R.drawable.map_5x3);
BoardElement map5x4 = createBoardElementAndPutToBoard(4, 5, R.drawable.map_5x4);
BoardElement map5x5 = createBoardElementAndPutToBoard(5, 5, R.drawable.map_5x5);
map1x1.setBoundaryElements(null, null, map2x1, null);
map1x2.setBoundaryElements(null, map1x3, map2x2, null);
map1x3.setBoundaryElements(null, map1x4, map2x3, map1x2);
map1x4.setBoundaryElements(null, map1x5, null, map1x3);
map1x5.setBoundaryElements(null, null, null, map1x4);
map2x1.setBoundaryElements(map1x1, map2x2, map3x1, null);
map2x2.setBoundaryElements(map1x2, null, null, map2x1);
map2x3.setBoundaryElements(map1x3, null, map3x3, null);
map2x4.setBoundaryElements(null, map2x5, null, null);
map2x5.setBoundaryElements(null, null, map3x5, map2x4);
map3x1.setBoundaryElements(map2x1, null, map4x1, null);
map3x2.setBoundaryElements(null, map3x3, map4x2, null);
map3x3.setBoundaryElements(map2x3, map3x4, null, map3x2);
map3x4.setBoundaryElements(null, map3x5, null, map3x3);
map3x5.setBoundaryElements(map2x5, null, map4x5, map3x4);
map4x1.setBoundaryElements(map3x1, map4x2, map5x1, null);
map4x2.setBoundaryElements(map3x2, map4x3, null, map4x1);
map4x3.setBoundaryElements(null, null, map5x3, map4x2);
map4x4.setBoundaryElements(null, map4x5, map5x4, null);
map4x5.setBoundaryElements(map3x5, null, map5x5, map4x4);
map5x1.setBoundaryElements(map4x1, map5x2, null, null);
map5x2.setBoundaryElements(null, map5x3, null, map5x1);
map5x3.setBoundaryElements(map4x3, map5x4, null, map5x2);
map5x4.setBoundaryElements(map4x4, null, null, map5x3);
map5x5.setBoundaryElements(map4x5, null, null, null);
createDoorForBoardElementInDirection(map1x2, NORTH);
createDoorForBoardElementInDirection(map1x5, SOUTH);
createDoorForBoardElementInDirection(map2x1, WEST);
//createDoorForBoardElementInDirection(map2x2, EAST);
createDoorForBoardElementInDirection(map2x4, WEST);
createDoorForBoardElementInDirection(map2x5, NORTH);
createDoorForBoardElementInDirection(map3x1, EAST);
createDoorForBoardElementInDirection(map3x2, NORTH);
createDoorForBoardElementInDirection(map3x4, SOUTH);
createDoorForBoardElementInDirection(map3x5, EAST);
createDoorForBoardElementInDirection(map4x1, WEST);
createDoorForBoardElementInDirection(map4x3, EAST);
createDoorForBoardElementInDirection(map4x4, NORTH);
createDoorForBoardElementInDirection(map5x2, NORTH);
createDoorForBoardElementInDirection(map5x5, WEST);
assignRoomsToRandomDoors();
}
| private void buildBoard() {
BoardElement map1x1 = createBoardElementAndPutToBoard(1, 1, R.drawable.map_1x1);
BoardElement map1x2 = createBoardElementAndPutToBoard(2, 1, R.drawable.map_1x2);
BoardElement map1x3 = createBoardElementAndPutToBoard(3, 1, R.drawable.map_1x3);
BoardElement map1x4 = createBoardElementAndPutToBoard(4, 1, R.drawable.map_1x4);
BoardElement map1x5 = createBoardElementAndPutToBoard(5, 1, R.drawable.map_1x5);
BoardElement map2x1 = createBoardElementAndPutToBoard(1, 2, R.drawable.map_2x1);
BoardElement map2x2 = createBoardElementAndPutToBoard(2, 2, R.drawable.map_2x2);
BoardElement map2x3 = createBoardElementAndPutToBoard(3, 2, R.drawable.map_2x3);
BoardElement map2x4 = createBoardElementAndPutToBoard(4, 2, R.drawable.map_2x4);
BoardElement map2x5 = createBoardElementAndPutToBoard(5, 2, R.drawable.map_2x5);
BoardElement map3x1 = createBoardElementAndPutToBoard(1, 3, R.drawable.map_3x1);
BoardElement map3x2 = createBoardElementAndPutToBoard(2, 3, R.drawable.map_3x2);
BoardElement map3x3 = createBoardElementAndPutToBoard(3, 3, R.drawable.map_3x3);
BoardElement map3x4 = createBoardElementAndPutToBoard(4, 3, R.drawable.map_3x4);
BoardElement map3x5 = createBoardElementAndPutToBoard(5, 3, R.drawable.map_3x5);
BoardElement map4x1 = createBoardElementAndPutToBoard(1, 4, R.drawable.map_4x1);
BoardElement map4x2 = createBoardElementAndPutToBoard(2, 4, R.drawable.map_4x2);
BoardElement map4x3 = createBoardElementAndPutToBoard(3, 4, R.drawable.map_4x3);
BoardElement map4x4 = createBoardElementAndPutToBoard(4, 4, R.drawable.map_4x4);
BoardElement map4x5 = createBoardElementAndPutToBoard(5, 4, R.drawable.map_4x5);
BoardElement map5x1 = createBoardElementAndPutToBoard(1, 5, R.drawable.map_5x1);
BoardElement map5x2 = createBoardElementAndPutToBoard(2, 5, R.drawable.map_5x2);
BoardElement map5x3 = createBoardElementAndPutToBoard(3, 5, R.drawable.map_5x3);
BoardElement map5x4 = createBoardElementAndPutToBoard(4, 5, R.drawable.map_5x4);
BoardElement map5x5 = createBoardElementAndPutToBoard(5, 5, R.drawable.map_5x5);
map1x1.setBoundaryElements(null, null, map2x1, null);
map1x2.setBoundaryElements(null, map1x3, map2x2, null);
map1x3.setBoundaryElements(null, map1x4, map2x3, map1x2);
map1x4.setBoundaryElements(null, map1x5, null, map1x3);
map1x5.setBoundaryElements(null, null, null, map1x4);
map2x1.setBoundaryElements(map1x1, map2x2, map3x1, null);
map2x2.setBoundaryElements(map1x2, null, null, map2x1);
map2x3.setBoundaryElements(map1x3, null, map3x3, null);
map2x4.setBoundaryElements(null, map2x5, null, null);
map2x5.setBoundaryElements(null, null, map3x5, map2x4);
map3x1.setBoundaryElements(map2x1, null, map4x1, null);
map3x2.setBoundaryElements(null, map3x3, map4x2, null);
map3x3.setBoundaryElements(map2x3, map3x4, null, map3x2);
map3x4.setBoundaryElements(null, map3x5, null, map3x3);
map3x5.setBoundaryElements(map2x5, null, map4x5, map3x4);
map4x1.setBoundaryElements(map3x1, map4x2, map5x1, null);
map4x2.setBoundaryElements(map3x2, map4x3, null, map4x1);
map4x3.setBoundaryElements(null, null, map5x3, map4x2);
map4x4.setBoundaryElements(null, map4x5, map5x4, null);
map4x5.setBoundaryElements(map3x5, null, map5x5, map4x4);
map5x1.setBoundaryElements(map4x1, map5x2, null, null);
map5x2.setBoundaryElements(null, map5x3, null, map5x1);
map5x3.setBoundaryElements(map4x3, map5x4, null, map5x2);
map5x4.setBoundaryElements(map4x4, null, null, map5x3);
map5x5.setBoundaryElements(map4x5, null, null, null);
createDoorForBoardElementInDirection(map1x2, NORTH);
createDoorForBoardElementInDirection(map1x5, SOUTH);
createDoorForBoardElementInDirection(map2x1, WEST);
createDoorForBoardElementInDirection(map2x2, EAST);
createDoorForBoardElementInDirection(map2x4, WEST);
createDoorForBoardElementInDirection(map2x5, NORTH);
createDoorForBoardElementInDirection(map3x1, EAST);
createDoorForBoardElementInDirection(map3x2, NORTH);
createDoorForBoardElementInDirection(map3x4, SOUTH);
createDoorForBoardElementInDirection(map3x5, EAST);
createDoorForBoardElementInDirection(map4x1, WEST);
createDoorForBoardElementInDirection(map4x3, EAST);
createDoorForBoardElementInDirection(map4x4, NORTH);
createDoorForBoardElementInDirection(map5x2, NORTH);
createDoorForBoardElementInDirection(map5x5, WEST);
assignRoomsToRandomDoors();
}
|
diff --git a/deegree-core/deegree-core-cs/src/main/java/org/deegree/cs/transformations/TransformationFactory.java b/deegree-core/deegree-core-cs/src/main/java/org/deegree/cs/transformations/TransformationFactory.java
index 59c495fa15..4eed83eadf 100644
--- a/deegree-core/deegree-core-cs/src/main/java/org/deegree/cs/transformations/TransformationFactory.java
+++ b/deegree-core/deegree-core-cs/src/main/java/org/deegree/cs/transformations/TransformationFactory.java
@@ -1,1339 +1,1339 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
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 information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://CoordinateSystem.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.cs.transformations;
import static org.deegree.cs.coordinatesystems.CRS.CRSType.COMPOUND;
import static org.deegree.cs.coordinatesystems.CRS.CRSType.GEOCENTRIC;
import static org.deegree.cs.coordinatesystems.CRS.CRSType.GEOGRAPHIC;
import static org.deegree.cs.coordinatesystems.CRS.CRSType.PROJECTED;
import static org.deegree.cs.transformations.coordinate.ConcatenatedTransform.concatenate;
import static org.deegree.cs.transformations.coordinate.MatrixTransform.createMatrixTransform;
import static org.deegree.cs.transformations.helmert.Helmert.createAxisAllignedTransformedHelmertTransformation;
import static org.deegree.cs.transformations.ntv2.NTv2Transformation.createAxisAllignedNTv2Transformation;
import static org.deegree.cs.utilities.MappingUtils.updateFromDefinedTransformations;
import static org.deegree.cs.utilities.Matrix.swapAndRotateGeoAxis;
import static org.deegree.cs.utilities.Matrix.swapAxis;
import static org.deegree.cs.utilities.Matrix.toStdValues;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.vecmath.Matrix4d;
import org.deegree.commons.annotations.LoggingNotes;
import org.deegree.crs.store.AbstractStore;
import org.deegree.cs.CRSCodeType;
import org.deegree.cs.CRSIdentifiable;
import org.deegree.cs.components.IEllipsoid;
import org.deegree.cs.components.IGeodeticDatum;
import org.deegree.cs.coordinatesystems.CRS.CRSType;
import org.deegree.cs.coordinatesystems.CompoundCRS;
import org.deegree.cs.coordinatesystems.GeocentricCRS;
import org.deegree.cs.coordinatesystems.GeographicCRS;
import org.deegree.cs.coordinatesystems.ICRS;
import org.deegree.cs.coordinatesystems.ICompoundCRS;
import org.deegree.cs.coordinatesystems.IGeocentricCRS;
import org.deegree.cs.coordinatesystems.IGeographicCRS;
import org.deegree.cs.coordinatesystems.IProjectedCRS;
import org.deegree.cs.coordinatesystems.ProjectedCRS;
import org.deegree.cs.exceptions.TransformationException;
import org.deegree.cs.persistence.CRSStore;
import org.deegree.cs.refs.coordinatesystem.CRSRef;
import org.deegree.cs.transformations.coordinate.GeocentricTransform;
import org.deegree.cs.transformations.coordinate.IdentityTransform;
import org.deegree.cs.transformations.coordinate.MatrixTransform;
import org.deegree.cs.transformations.coordinate.ProjectionTransform;
import org.deegree.cs.transformations.helmert.Helmert;
import org.deegree.cs.transformations.ntv2.NTv2Transformation;
import org.deegree.cs.transformations.polynomial.LeastSquareApproximation;
import org.deegree.cs.utilities.Matrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>TransformationFactory</code> class is the central access point for all transformations between different
* crs's.
* <p>
* It creates a transformation chain for two given ICoordinateSystems by considering their type. For example the
* Transformation chain from EPSG:31466 ( a projected crs with underlying geographic crs epsg:4314 using the DHDN datum
* and the TransverseMercator Projection) to EPSG:28992 (another projected crs with underlying geographic crs epsg:4289
* using the 'new Amersfoort Datum' and the StereographicAzimuthal Projection) would result in following Transformation
* Chain:
* <ol>
* <li>Inverse projection - thus getting the coordinates in lat/lon for geographic crs epsg:4314</li>
* <li>Geodetic transformation - thus getting x-y-z coordinates for geographic crs epsg:4314</li>
* <li>WGS84 transformation -thus getting the x-y-z coordinates for the WGS84 datum</li>
* <li>Inverse WGS84 transformation -thus getting the x-y-z coordinates for the geodetic from epsg:4289</li>
* <li>Inverse geodetic - thus getting the lat/lon for epsg:4289</li>
* <li>projection - getting the coordinates (in meters) for epsg:28992</li>
* </ol>
*
* @author <a href="mailto:[email protected]">Rutger Bezema</a>
*
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*
*/
@LoggingNotes(debug = "Get information about the transformation steps which were 'automatically' created.")
public class TransformationFactory {
private static Logger LOG = LoggerFactory.getLogger( TransformationFactory.class );
private CRSStore provider;
private DSTransform preferredDSTransform;
/**
* Defines the type of transformation to use while switching datums.
*/
public enum DSTransform {
/** use the helmert transformation */
HELMERT,
/** Try to use an ntv2 transformation */
NTv2;
/** The property to use */
public final static String DS_PROP = "PREFERRED_DATUM_TRANSFORM";
/**
* Create a {@link DSTransform} from the {@link AbstractStore} TransformationType property. If <code>null</code>
* {@link #HELMERT} will be returned.
*
* @param store
* the {@link AbstractStore}
* @return the value of key {@link AbstractStore} TransformationType property of {@link #HELMERT} if the value
* was not known.
*/
public static DSTransform fromSchema( AbstractStore store ) {
DSTransform result = DSTransform.HELMERT;
if ( store != null && store.getTransformationType() != null
&& "NTv2".equalsIgnoreCase( store.getTransformationType().value() ) ) {
result = NTv2;
}
return result;
}
/**
* @param transform
* to check for.
* @return true if the name of this data shift transformation hint equals the implementation name of the given
* transformation.
*/
public boolean isPreferred( Transformation transform ) {
if ( transform != null ) {
return name().equalsIgnoreCase( transform.getImplementationName() );
}
return false;
}
}
/**
* The default coordinate transformation factory. Will be constructed only when first needed.
*
* @param provider
* used to do lookups of transformations
*/
public TransformationFactory( CRSStore provider ) {
this.provider = provider;
this.preferredDSTransform = provider.getPreferedTransformationType();
}
/**
* Set the default transformation type to use for datum switching.
*
* @param datumTransform
* to be used preferably.
*/
public void setPreferredTransformation( DSTransform datumTransform ) {
this.preferredDSTransform = datumTransform;
}
/**
* Creates a transformation between two coordinate systems. This method will examine the coordinate systems in order
* to construct a transformation between them.
*
* @param sourceCRS
* Input coordinate system.
* @param targetCRS
* Output coordinate system.
* @return A coordinate transformation from <code>sourceCRS</code> to <code>targetCRS</code>.
* @throws TransformationException
* @throws TransformationException
* if no transformation path has been found.
* @throws IllegalArgumentException
* if the sourceCRS or targetCRS are <code>null</code>.
*
*/
public Transformation createFromCoordinateSystems( final ICRS sourceCRS, final ICRS targetCRS )
throws TransformationException, IllegalArgumentException {
return createFromCoordinateSystems( sourceCRS, targetCRS, null );
}
/**
* Creates a transformation between two coordinate systems. This method will examine the coordinate systems in order
* to construct a transformation between them. The given list of transformations is taken into consideration.
*
* @param sourceCRS
* Input coordinate system.
* @param targetCRS
* Output coordinate system.
* @param transformationsToBeUsed
* @return A coordinate transformation from <code>sourceCRS</code> to <code>targetCRS</code>.
* @throws TransformationException
* @throws TransformationException
* if no transformation path has been found.
* @throws IllegalArgumentException
* if the sourceCRS or targetCRS are <code>null</code>.
*
*/
public Transformation createFromCoordinateSystems( ICRS sourceCRS, ICRS targetCRS,
List<Transformation> transformationsToBeUsed )
throws TransformationException {
if ( sourceCRS == null ) {
throw new IllegalArgumentException( "The source CRS may not be null" );
}
if ( targetCRS == null ) {
throw new IllegalArgumentException( "The target CRS may not be null" );
}
if ( !isSupported( sourceCRS ) || !isSupported( targetCRS ) ) {
throw new TransformationException( sourceCRS, targetCRS,
"Either the target crs type or the source crs type was unknown" );
}
if ( sourceCRS.equals( targetCRS ) ) {
LOG.debug( "Source crs and target crs are equal, no transformation needed (returning identity matrix)." );
final Matrix matrix = new Matrix( sourceCRS.getDimension() + 1 );
matrix.setIdentity();
return new IdentityTransform( sourceCRS, targetCRS );
}
sourceCRS = resolve( sourceCRS );
targetCRS = resolve( targetCRS );
List<Transformation> toBeUsed = copyTransformations( transformationsToBeUsed );
// Do following steps:
// 1) Check if the 'supplied' transformation already contains a path
// from source to target.
// 2) Call crs-config.getTransformation for source and target
// 3) if no 'direct' transformation try to find an inverse.
// 4) if helmert was defined but the provider transformation was NTv2,
// create a chain.
// 5) if source has direct transformation to target use this
// 6) create a chain if none of the above apply.
// check if the list of required transformations contains a 'direct'
// transformation.
Transformation result = getRequiredTransformation( toBeUsed, sourceCRS, targetCRS );
if ( result == null ) {
// create AxisFlipTransformation if only the axis order must be flipped
if ( sourceCRS.equalsWithFlippedAxis( targetCRS ) ) {
return new AxisFlipTransformation( sourceCRS, targetCRS,
new CRSIdentifiable( new CRSCodeType( "tmp_" + sourceCRS.getCode()
+ "_flippedTo_"
+ targetCRS.getCode() ) ) );
}
}
if ( result == null ) {
// check if a 'direct' transformation could be loaded from the
// configuration;
result = getTransformation( sourceCRS, targetCRS );
if ( result == null || "Helmert".equals( result.getImplementationName() ) ) {
result = getTransformation( targetCRS, sourceCRS );
if ( result != null && !"Helmert".equals( result.getImplementationName() ) ) {
result.inverse();
} else {
result = null;
}
}
if ( result == null
|| ( "NTv2".equals( result.getImplementationName() ) && this.preferredDSTransform == DSTransform.HELMERT ) ) {
// no configured transformation
// check if the source crs has an alternative transformation for
// the given target, if so use it
if ( sourceCRS.hasDirectTransformation( targetCRS ) ) {
Transformation direct = sourceCRS.getDirectTransformation( targetCRS );
if ( direct != null ) {
LOG.debug( "Using direct (polynomial) transformation instead of a helmert transformation: "
+ direct.getImplementationName() );
result = direct;
}
} else {
CRSType type = sourceCRS.getType();
switch ( type ) {
case COMPOUND:
/**
* Compound --> Projected, Geographic, Geocentric or Compound
*/
result = createFromCompound( (ICompoundCRS) sourceCRS, targetCRS );
break;
case GEOCENTRIC:
/**
* Geocentric --> Projected, Geographic, Geocentric or Compound
*/
result = createFromGeocentric( (IGeocentricCRS) sourceCRS, targetCRS );
break;
case GEOGRAPHIC:
/**
* Geographic --> Geographic, Projected, Geocentric or Compound
*/
result = createFromGeographic( (IGeographicCRS) sourceCRS, targetCRS );
break;
case PROJECTED:
/**
* Projected --> Projected, Geographic, Geocentric or Compound
*/
result = createFromProjected( (IProjectedCRS) sourceCRS, targetCRS );
break;
case VERTICAL:
break;
}
}
}
if ( result != null ) {
result = updateFromDefinedTransformations( toBeUsed, result );
}
}
if ( result == null ) {
LOG.debug( "The resulting transformation was null, returning an identity matrix." );
final Matrix matrix = new Matrix( sourceCRS.getDimension() + 1 );
matrix.setIdentity();
result = createMatrixTransform( sourceCRS, targetCRS, matrix );
} else {
// allign axis, if NTv2 transformation
if ( "NTv2".equals( result.getImplementationName() ) && this.preferredDSTransform == DSTransform.NTv2 ) {
result = NTv2Transformation.createAxisAllignedNTv2Transformation( (NTv2Transformation) result );
}
LOG.debug( "Concatenating the result, with the conversion matrices." );
result = concatenate( createMatrixTransform( sourceCRS, sourceCRS, toStdValues( sourceCRS, false ) ),
result, createMatrixTransform( targetCRS, targetCRS, toStdValues( targetCRS, true ) ) );
}
if ( LOG.isDebugEnabled() ) {
StringBuilder output = new StringBuilder( "The resulting transformation chain: \n" );
if ( result == null ) {
output.append( " identity transformation (null)" );
} else {
output = result.getTransformationPath( output );
}
LOG.debug( output.toString() );
if ( result instanceof MatrixTransform ) {
LOG.debug( "Resulting matrix transform:\n" + ( (MatrixTransform) result ).getMatrix() );
}
}
return result;
}
/**
* Calls the provider to find a 'configured' transformation, if found a copy will be returned.
*
* @param sourceCRS
* @param targetCRS
* @return a copy of a configured provider.
*/
private Transformation getTransformation( ICRS sourceCRS, ICRS targetCRS ) {
Transformation result = provider.getDirectTransformation( sourceCRS, targetCRS );
if ( result != null ) {
String implName = result.getImplementationName();
// make a copy, so inverse can be called without changing the
// original transformation, which might be cached
// somewhere.
if ( "Helmert".equals( implName ) ) {
Helmert h = (Helmert) result;
result = new Helmert( h.dx, h.dy, h.dz, h.ex, h.ey, h.ez, h.ppm, h.getSourceCRS(), h.getTargetCRS(), h,
h.areRotationsInRad() );
} else if ( "NTv2".equals( implName ) ) {
NTv2Transformation h = (NTv2Transformation) result;
result = new NTv2Transformation( h.getSourceCRS(), h.getTargetCRS(), h, h.getGridfileRef() );
} else if ( "leastsquare".equals( implName ) ) {
LeastSquareApproximation h = (LeastSquareApproximation) result;
result = new LeastSquareApproximation( h.getFirstParams(), h.getSecondParams(), h.getSourceCRS(),
h.getTargetCRS(), h.getScaleX(), h.getScaleY(), h );
} else {
LOG.warn( "The transformation with implementation name: " + implName + " could not be copied." );
}
}
return result;
}
/**
* Iterates over the given transformations and creates a copy of the list without all duplicates.
*
* @param originalRequested
* the original requested transformations.
* @return a copy of the list without any duplicates or <code>null</code> if the given list was null or the empty
* list if the given list was empty.
*/
private List<Transformation> copyTransformations( List<Transformation> originalRequested ) {
if ( originalRequested == null || originalRequested.isEmpty() ) {
return originalRequested;
}
List<Transformation> result = new ArrayList<Transformation>( originalRequested.size() );
// create a none duplicate list of the given transformations, remove all
// 'duplicates'
for ( Transformation tr : originalRequested ) {
if ( tr != null ) {
Iterator<Transformation> it = result.iterator();
boolean isDuplicate = false;
while ( it.hasNext() && !isDuplicate ) {
Transformation tra = it.next();
if ( tra != null ) {
if ( tra.equalOnCRS( tr ) ) {
isDuplicate = true;
}
}
}
if ( !isDuplicate ) {
if ( "NTv2".equalsIgnoreCase( tr.getImplementationName() ) ) {
// rb: dirty hack, ntv2 needs lon/lat incoming
// coordinates, if not set, swap them.
// the axis must be swapped to fit ntv2 (which is
// defined on lon/lat.
tr = createAxisAllignedNTv2Transformation( (NTv2Transformation) tr );
} else if ( "Helmert".equals( tr.getImplementationName() ) ) {
tr = createAxisAllignedTransformedHelmertTransformation( (Helmert) tr );
}
result.add( tr );
// add the transformation as insverse
String newId = tr.getTargetCRS() + "_" + tr.getSourceCRS() + "_inverse";
Transformation trInverse = tr.copyTransformation( new CRSIdentifiable( new CRSCodeType( newId ) ) );
trInverse.inverse();
result.add( trInverse );
}
}
}
return result;
}
/**
* Iterates over the given transformations and removes a 'fitting' transformation from the list.
*
* @param requiredTransformations
* @param sourceCRS
* @param targetCRS
* @return the 'required' transformation or <code>null</code> if no fitting transfromation was found.
*/
private Transformation getRequiredTransformation( List<Transformation> requiredTransformations, ICRS sourceCRS,
ICRS targetCRS ) {
if ( requiredTransformations != null && !requiredTransformations.isEmpty() ) {
Iterator<Transformation> it = requiredTransformations.iterator();
while ( it.hasNext() ) {
Transformation t = it.next();
if ( t != null ) {
boolean matches = ( sourceCRS != null ) ? sourceCRS.equals( t.getSourceCRS() )
: t.getSourceCRS() == null;
matches = matches && ( targetCRS != null ) ? targetCRS.equals( t.getTargetCRS() )
: t.getTargetCRS() == null;
if ( matches ) {
return t;
}
}
}
}
return null;
}
/**
* @param crs
* @return true if the crs is one of the Types defined in ICoordinateSystem.
*/
private boolean isSupported( ICRS crs ) {
CRSType type = crs.getType();
return type == COMPOUND || type == GEOCENTRIC || type == GEOGRAPHIC || type == CRSType.PROJECTED;
}
private Transformation createFromCompound( ICompoundCRS sourceCRS, ICRS targetCRS )
throws TransformationException {
ICompoundCRS target = null;
if ( targetCRS.getType() != COMPOUND ) {
target = new CompoundCRS( sourceCRS.getHeightAxis(), targetCRS, sourceCRS.getDefaultHeight(),
new CRSIdentifiable( new CRSCodeType[] { CRSCodeType.valueOf( targetCRS.getCode()
+ "_compound" ) } ) );
} else {
target = (ICompoundCRS) targetCRS;
}
return createTransformation( sourceCRS, target );
}
private Transformation createFromGeocentric( IGeocentricCRS sourceCRS, ICRS targetCRS )
throws TransformationException {
targetCRS = resolve( targetCRS );
Transformation result = null;
CRSType type = targetCRS.getType();
switch ( type ) {
case COMPOUND:
ICompoundCRS target = (ICompoundCRS) targetCRS;
ICompoundCRS sTmp = new CompoundCRS(
target.getHeightAxis(),
sourceCRS,
target.getDefaultHeight(),
new CRSIdentifiable(
new CRSCodeType[] { CRSCodeType.valueOf( sourceCRS.getCode()
+ "_compound" ) } ) );
result = createTransformation( sTmp, target );
break;
case GEOCENTRIC:
result = createTransformation( sourceCRS, (IGeocentricCRS) targetCRS );
break;
case GEOGRAPHIC:
result = createTransformation( sourceCRS, (IGeographicCRS) targetCRS );
break;
case PROJECTED:
result = createTransformation( sourceCRS, (IProjectedCRS) targetCRS );
break;
case VERTICAL:
break;
}
return result;
}
private Transformation createFromProjected( IProjectedCRS sourceCRS, ICRS targetCRS )
throws TransformationException {
targetCRS = resolve( targetCRS );
Transformation result = null;
CRSType type = targetCRS.getType();
switch ( type ) {
case COMPOUND:
ICompoundCRS target = (ICompoundCRS) targetCRS;
ICompoundCRS sTmp = new CompoundCRS(
target.getHeightAxis(),
sourceCRS,
target.getDefaultHeight(),
new CRSIdentifiable(
new CRSCodeType[] { CRSCodeType.valueOf( sourceCRS.getCode()
+ "_compound" ) } ) );
result = createTransformation( sTmp, target );
break;
case GEOCENTRIC:
result = createTransformation( sourceCRS, (IGeocentricCRS) targetCRS );
break;
case GEOGRAPHIC:
result = createTransformation( sourceCRS, (IGeographicCRS) targetCRS );
break;
case PROJECTED:
result = createTransformation( sourceCRS, (IProjectedCRS) targetCRS );
break;
case VERTICAL:
break;
}
return result;
}
private Transformation createFromGeographic( IGeographicCRS sourceCRS, ICRS targetCRS )
throws TransformationException {
targetCRS = resolve( targetCRS );
Transformation result = null;
CRSType type = targetCRS.getType();
switch ( type ) {
case COMPOUND:
ICompoundCRS target = (ICompoundCRS) targetCRS;
ICompoundCRS sTmp = new CompoundCRS(
target.getHeightAxis(),
sourceCRS,
target.getDefaultHeight(),
new CRSIdentifiable(
new CRSCodeType[] { CRSCodeType.valueOf( sourceCRS.getCode()
+ "_compound" ) } ) );
result = createTransformation( sTmp, target );
break;
case GEOCENTRIC:
result = createTransformation( sourceCRS, (IGeocentricCRS) targetCRS );
break;
case GEOGRAPHIC:
result = createTransformation( sourceCRS, (IGeographicCRS) targetCRS );
break;
case PROJECTED:
result = createTransformation( sourceCRS, (IProjectedCRS) targetCRS );
break;
case VERTICAL:
break;
}
return result;
}
/**
* @param sourceCRS
* @param targetCRS
* @return the transformation chain or <code>null</code> if the transformation operation is the identity.
* @throws TransformationException
*/
private Transformation createTransformation( IGeocentricCRS sourceCRS, IGeographicCRS targetCRS )
throws TransformationException {
final Transformation result = createTransformation( targetCRS, sourceCRS );
if ( result != null ) {
result.inverse();
}
return result;
}
/**
* @param sourceCRS
* @param targetCRS
* @return the transformation chain or <code>null</code> if the transformation operation is the identity.
* @throws TransformationException
*/
private Transformation createTransformation( IGeocentricCRS sourceCRS, IProjectedCRS targetCRS )
throws TransformationException {
final Transformation result = createTransformation( targetCRS, sourceCRS );
if ( result != null ) {
result.inverse();
}
return result;
}
/**
* This method is valid for all transformations which use a compound crs, because the extra heightvalues need to be
* considered throughout the transformation.
*
* @param sourceCRS
* @param targetCRS
* @return the transformation chain or <code>null</code> if the transformation operation is the identity.
* @throws TransformationException
*/
private Transformation createTransformation( ICompoundCRS sourceCRS, ICompoundCRS targetCRS )
throws TransformationException {
if ( sourceCRS.getUnderlyingCRS().equals( targetCRS.getUnderlyingCRS() ) ) {
return null;
}
sourceCRS = ( (CompoundCRS) resolve( sourceCRS ) );
targetCRS = ( (CompoundCRS) resolve( targetCRS ) );
LOG.debug( "Creating compound( " + sourceCRS.getUnderlyingCRS().getCode() + ") ->compound transformation( "
+ targetCRS.getUnderlyingCRS().getCode() + "): from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() );
final CRSType sourceType = sourceCRS.getUnderlyingCRS().getType();
final CRSType targetType = targetCRS.getUnderlyingCRS().getType();
Transformation result = null;
// basic check for simple (invert) projections
if ( sourceType == PROJECTED && targetType == GEOGRAPHIC ) {
if ( ( ( (IProjectedCRS) resolve( sourceCRS.getUnderlyingCRS() ) ).getGeographicCRS() ).equals( targetCRS.getUnderlyingCRS() ) ) {
- result = new ProjectionTransform( (IProjectedCRS) sourceCRS.getUnderlyingCRS() );
+ result = new ProjectionTransform( (IProjectedCRS) resolve( sourceCRS.getUnderlyingCRS() ) );
result.inverse();
}
}
if ( sourceType == GEOGRAPHIC && targetType == PROJECTED ) {
if ( ( ( (IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) ).getGeographicCRS() ).equals( sourceCRS.getUnderlyingCRS() ) ) {
- result = new ProjectionTransform( (IProjectedCRS) targetCRS.getUnderlyingCRS() );
+ result = new ProjectionTransform( (IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) );
}
}
if ( result == null ) {
IGeocentricCRS sourceGeocentric = null;
if ( sourceType == GEOCENTRIC ) {
sourceGeocentric = (IGeocentricCRS) resolve( sourceCRS.getUnderlyingCRS() );
} else {
sourceGeocentric = new GeocentricCRS(
sourceCRS.getGeodeticDatum(),
CRSCodeType.valueOf( "tmp_" + sourceCRS.getCode() + "_geocentric" ),
sourceCRS.getName() + "_Geocentric" );
}
IGeocentricCRS targetGeocentric = null;
if ( targetType == GEOCENTRIC ) {
targetGeocentric = (IGeocentricCRS) resolve( targetCRS.getUnderlyingCRS() );
} else {
targetGeocentric = new GeocentricCRS(
targetCRS.getGeodeticDatum(),
CRSCodeType.valueOf( "tmp_" + targetCRS.getCode() + "_geocentric" ),
targetCRS.getName() + "_Geocentric" );
}
// Transformation helmertTransformation = createTransformation(
// sourceGeocentric, targetGeocentric );
Transformation sourceTransformationChain = null;
Transformation targetTransformationChain = null;
Transformation sourceT = null;
Transformation targetT = null;
IGeographicCRS sourceGeographic = null;
IGeographicCRS targetGeographic = null;
switch ( sourceType ) {
case GEOCENTRIC:
break;
case PROJECTED:
ICRS underlying = resolve( sourceCRS.getUnderlyingCRS() );
sourceTransformationChain = new ProjectionTransform( (ProjectedCRS) underlying );
sourceTransformationChain.inverse();
sourceGeographic = ( (IProjectedCRS) underlying ).getGeographicCRS();
case GEOGRAPHIC:
underlying = sourceCRS.getUnderlyingCRS();
if ( sourceGeographic == null ) {
sourceGeographic = (IGeographicCRS) resolve( underlying );
}
sourceT = getToWGSTransformation( sourceGeographic );
/*
* Only create a geocentric transform if the helmert transformation != null, e.g. the datums and
* ellipsoids are not equal.
*/
// if ( helmertTransformation != null ) {
// create a 2d->3d mapping.
final Transformation axisAligned = createMatrixTransform( sourceGeographic,
sourceGeocentric,
swapAxis( sourceGeographic,
GeographicCRS.WGS84 ) );
if ( LOG.isDebugEnabled() ) {
StringBuilder sb = new StringBuilder(
"Resulting axis alignment between source geographic and source geocentric is:" );
if ( axisAligned == null ) {
sb.append( " not necessary" );
} else {
sb.append( "\n" ).append( ( (MatrixTransform) axisAligned ).getMatrix() );
}
LOG.debug( sb.toString() );
}
final Transformation geoCentricTransform = new GeocentricTransform( sourceCRS, sourceGeocentric );
// concatenate the possible projection with the axis alignment
// and the geocentric transform.
sourceTransformationChain = concatenate( sourceTransformationChain, axisAligned, geoCentricTransform );
// }
break;
case COMPOUND:
// cannot happen.
break;
case VERTICAL:
LOG.warn( "Vertical crs is currently not supported for the Compound crs." );
break;
}
switch ( targetType ) {
case GEOCENTRIC:
break;
case PROJECTED:
targetTransformationChain = new ProjectionTransform(
(IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) );
targetGeographic = ( (IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) ).getGeographicCRS();
case GEOGRAPHIC:
if ( targetGeographic == null ) {
targetGeographic = (IGeographicCRS) resolve( targetCRS.getUnderlyingCRS() );
}
targetT = getToWGSTransformation( targetGeographic );
/*
* Only create a geocentric transform if the helmert transformation != null, e.g. the datums and
* ellipsoids are not equal.
*/
// if ( helmertTransformation != null ) {
// create a 2d->3d mapping.
final Transformation axisAligned = createMatrixTransform( targetGeocentric,
targetGeographic,
swapAxis( GeographicCRS.WGS84,
targetGeographic ) );
final Transformation geoCentricTransform = new GeocentricTransform( targetCRS, targetGeocentric );
geoCentricTransform.inverse();
// concatenate the possible projection with the axis alignment
// and the geocentric transform.
targetTransformationChain = concatenate( geoCentricTransform, axisAligned, targetTransformationChain );
// }
break;
case COMPOUND:
// cannot happen.
break;
case VERTICAL:
LOG.warn( "Vertical crs is currently not supported for the Compound crs." );
break;
}
Transformation helmertTransformation = null;
if ( !isIdentity( sourceT ) || !isIdentity( targetT ) ) {
helmertTransformation = transformUsingPivot( sourceGeocentric, targetGeocentric, (Helmert) sourceT,
(Helmert) targetT );
}
result = concatenate( sourceTransformationChain, helmertTransformation, targetTransformationChain );
}
return result;
}
/**
* Creates a transformation between two geographic coordinate systems. This method is automatically invoked by
* {@link #createFromCoordinateSystems createFromCoordinateSystems(...)}. The default implementation can adjust axis
* order and orientation (e.g. transforming from <code>(NORTH,WEST)</code> to <code>(EAST,NORTH)</code>), performs
* units conversion and apply Bursa Wolf transformation if needed.
*
* @param sourceCRS
* Input coordinate system.
* @param targetCRS
* Output coordinate system.
* @return A coordinate transformation from <code>sourceCRS</code> to <code>targetCRS</code>.
* @throws TransformationException
* if no transformation path has been found.
*/
private Transformation createTransformation( final IGeographicCRS sourceCRS, final IGeographicCRS targetCRS )
throws TransformationException {
// check if a 'direct' transformation could be loaded from the
// configuration;
Transformation result = getTransformation( sourceCRS, targetCRS );
if ( result == null ) {
// maybe an inverse was defined?
result = getTransformation( targetCRS, sourceCRS );
if ( result != null ) {
result.inverse();
}
}
// prepare the found transformation if it is a helmert transfomation
if ( result != null && !isIdentity( result ) && "Helmert".equalsIgnoreCase( result.getImplementationName() )
&& this.preferredDSTransform.isPreferred( result ) ) {
LOG.debug( "Creating geographic -> geographic transformation: from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() + " based on a given Helmert transformation" );
final IGeodeticDatum sourceDatum = sourceCRS.getGeodeticDatum();
final IGeodeticDatum targetDatum = targetCRS.getGeodeticDatum();
String name = sourceCRS.getName() + "_Geocentric";
final IGeocentricCRS sourceGCS = new GeocentricCRS( sourceDatum, sourceCRS.getCode(), name );
name = targetCRS.getName() + "_Geocentric";
final IGeocentricCRS targetGCS = new GeocentricCRS( targetDatum, targetCRS.getCode(), name );
Transformation step1 = null;
Transformation step2 = null;
Transformation step3 = null;
// geographic->geocentric
step1 = createTransformation( sourceCRS, sourceGCS );
// transformation found in configuration
step2 = result;
// geocentric->geographic
step3 = createTransformation( targetCRS, targetGCS );
if ( step3 != null ) {
step3.inverse();// call inverseTransform from step 3.
}
return concatenate( step1, step2, step3 );
} else if ( result == null || "Helmert".equalsIgnoreCase( result.getImplementationName() )
|| !this.preferredDSTransform.isPreferred( result ) ) {
LOG.debug( "Creating geographic ->geographic transformation: from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() );
// if a conversion needs to take place
if ( isEllipsoidTransformNeeded( sourceCRS, targetCRS ) ) {
Transformation sourceT = getToWGSTransformation( sourceCRS );
Transformation targetT = getToWGSTransformation( targetCRS );
if ( ( !isIdentity( sourceT ) ) || ( !isIdentity( targetT ) ) ) {
// the default implementation uses the WGS84 as a pivot for
// helmert transformations.
if ( ( sourceT != null && "Helmert".equals( sourceT.getImplementationName() ) )
|| ( targetT != null && "Helmert".equals( targetT.getImplementationName() ) ) ) {
Helmert sourceH = (Helmert) sourceT;
Helmert targetH = (Helmert) targetT;
final IGeodeticDatum sourceDatum = sourceCRS.getGeodeticDatum();
final IGeodeticDatum targetDatum = targetCRS.getGeodeticDatum();
/*
* If the two geographic coordinate systems use different ellipsoid, convert from the source to
* target ellipsoid through the geocentric coordinate system.
*/
Transformation step1 = null;
Transformation step2 = null;
Transformation step3 = null;
// use the WGS84 Geocentric transform if no toWGS84
// parameters are given and the datums
// ellipsoid is actually a sphere.
String name = sourceCRS.getName() + "_Geocentric";
final IGeocentricCRS sourceGCS = ( sourceDatum.getEllipsoid().isSphere() && isIdentity( sourceH ) ) ? GeocentricCRS.WGS84
: new GeocentricCRS(
sourceDatum,
sourceCRS.getCode(),
name );
name = targetCRS.getName() + "_Geocentric";
final IGeocentricCRS targetGCS = ( targetDatum.getEllipsoid().isSphere() && isIdentity( targetH ) ) ? GeocentricCRS.WGS84
: new GeocentricCRS(
targetDatum,
targetCRS.getCode(),
name );
// geographic->geocentric
step1 = createTransformation( sourceCRS, sourceGCS );
// helmert->inv_helmert
// step2 = createTransformation( sourceGCS, targetGCS );
step2 = transformUsingPivot( sourceGCS, targetGCS, sourceH, targetH );
// geocentric->geographic
step3 = createTransformation( targetCRS, targetGCS );
if ( step3 != null ) {
step3.inverse();// call inverseTransform from step
// 3.
}
return concatenate( step1, step2, step3 );
}
}
}
/*
* Swap axis order, and rotate the longitude coordinate if prime meridians are different.
*/
final Matrix matrix = swapAndRotateGeoAxis( sourceCRS, targetCRS );
result = createMatrixTransform( sourceCRS, targetCRS, matrix );
if ( LOG.isDebugEnabled() ) {
StringBuilder sb = new StringBuilder(
"Resulting axis alignment between source geographic and target geographic is:" );
if ( result == null ) {
sb.append( " not necessary" );
} else {
sb.append( "\n" ).append( ( (MatrixTransform) result ).getMatrix() );
}
LOG.debug( sb.toString() );
}
}
if ( result != null && ( "NTv2".equals( result.getImplementationName() ) ) ) {
result = createAxisAllignedNTv2Transformation( (NTv2Transformation) result );
}
return result;
}
/**
* Creates a transformation between a geographic and a projected coordinate systems. This method is automatically
* invoked by {@link #createFromCoordinateSystems createFromCoordinateSystems(...)}.
*
* @param sourceCRS
* Input coordinate system.
* @param targetCRS
* Output coordinate system.
* @return A coordinate transformation from <code>sourceCRS</code> to <code>targetCRS</code>.
* @throws TransformationException
* if no transformation path has been found.
*/
private Transformation createTransformation( final IGeographicCRS sourceCRS, final IProjectedCRS targetCRS )
throws TransformationException {
Transformation result = getTransformation( sourceCRS, targetCRS );
if ( isIdentity( result ) ) {
LOG.debug( "Creating geographic->projected transformation: from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() );
final IGeographicCRS stepGeoCS = targetCRS.getGeographicCRS();
final Transformation geo2geo = createTransformation( sourceCRS, stepGeoCS );
if ( LOG.isDebugEnabled() ) {
StringBuilder sb = new StringBuilder(
"Resulting axis alignment between target geographic and target projected is:" );
LOG.debug( sb.toString() );
}
final Transformation projection = new ProjectionTransform( targetCRS );
result = concatenate( geo2geo, projection );
}
return result;
}
/**
* Creates a transformation between a geographic and a geocentric coordinate systems. Since the source coordinate
* systems doesn't have a vertical axis, height above the ellipsoid is assumed equals to zero everywhere. This
* method is automatically invoked by {@link #createFromCoordinateSystems createFromCoordinateSystems(...)}.
*
* @param sourceCRS
* Input geographic coordinate system.
* @param targetCRS
* Output coordinate system.
* @return A coordinate transformation from <code>sourceCRS</code> to <code>targetCRS</code>.
* @throws TransformationException
* if no transformation path has been found.
*/
private Transformation createTransformation( final IGeographicCRS sourceCRS, final IGeocentricCRS targetCRS )
throws TransformationException {
LOG.debug( "Creating geographic -> geocentric transformation: from (source): " + sourceCRS.getCode()
+ " to (target): " + targetCRS.getCode() );
Transformation result = getTransformation( sourceCRS, targetCRS );
if ( isIdentity( result ) ) {
IGeocentricCRS sourceGeocentric = new GeocentricCRS( sourceCRS.getGeodeticDatum(),
CRSCodeType.valueOf( "tmp_" + sourceCRS.getCode()
+ "_geocentric" ),
sourceCRS.getName() + "_geocentric" );
Transformation ellipsoidTransform = null;
if ( isEllipsoidTransformNeeded( sourceCRS, targetCRS ) ) {
// create a transformation between the two geocentrics
Transformation sourceT = getToWGSTransformation( sourceCRS );
Transformation targetT = getToWGSTransformation( targetCRS );
if ( !isIdentity( sourceT ) || !isIdentity( targetT ) ) {
if ( isHelmert( sourceT ) && isHelmert( targetT ) ) {
ellipsoidTransform = transformUsingPivot( sourceGeocentric, targetCRS, (Helmert) sourceT,
(Helmert) targetT );
} else {
// another kind of transformation (NTv2?) exist, handle
// this..
if ( !isIdentity( sourceT ) ) {
if ( isHelmert( sourceT ) ) {
ellipsoidTransform = transformUsingPivot( sourceGeocentric, GeocentricCRS.WGS84,
(Helmert) sourceT, null );
} else {
ellipsoidTransform = sourceT;
}
}
if ( !isIdentity( targetT ) ) {
if ( isHelmert( targetT ) ) {
Transformation t = transformUsingPivot( targetCRS, GeocentricCRS.WGS84,
(Helmert) targetT, null );
if ( t != null ) {
// from wgs84 to target
t.inverse();
ellipsoidTransform = concatenate( ellipsoidTransform, t );
}
} else {
// the targetT is going from target to wgs84
targetT.inverse();
ellipsoidTransform = concatenate( ellipsoidTransform, targetT );
}
}
}
} else {
// if no helmert transformation is needed, the targetCRS
// equals the source-geocentric.
sourceGeocentric = targetCRS;
}
}
final Transformation axisAlign = createMatrixTransform( sourceCRS,
createWGSAlligned( sourceCRS ),
swapAndRotateGeoAxis( sourceCRS,
GeographicCRS.WGS84 ) );
if ( LOG.isDebugEnabled() ) {
StringBuilder sb = new StringBuilder(
"Resulting axis alignment between source geographic and target geocentric is:" );
if ( axisAlign == null ) {
sb.append( " not necessary" );
} else {
sb.append( "\n" ).append( ( (MatrixTransform) axisAlign ).getMatrix() );
}
LOG.debug( sb.toString() );
}
final Transformation geocentric = new GeocentricTransform( sourceCRS, sourceGeocentric );
result = concatenate( axisAlign, geocentric, ellipsoidTransform );
}
return result;
}
/**
* Create a new geographic crs with the same axis as the wgs.
*
* @param sourceCRS
* @return a new crs with same axis as wgs84.
*/
public final static IGeographicCRS createWGSAlligned( IGeographicCRS sourceCRS ) {
return new GeographicCRS( sourceCRS.getGeodeticDatum(), GeographicCRS.WGS84.getAxis(),
new CRSCodeType( "wgsalligned" ) );
}
private boolean isHelmert( Transformation transformation ) {
return transformation == null || ( "Helmert".equalsIgnoreCase( transformation.getImplementationName() ) );
}
/**
* Tries to get a WGS84 transformation from the configuratin or the datum.
*
* @param sourceCRS
* to get a wgs84 transformation for.
* @return the helmert transformation for the default (pivot) transformation path
*/
private Transformation getToWGSTransformation( ICRS sourceCRS ) {
Transformation transform = sourceCRS.getGeodeticDatum().getWGS84Conversion();
if ( isIdentity( transform ) ) {
if ( sourceCRS.getType() != GEOCENTRIC ) {
transform = getTransformation( sourceCRS, GeographicCRS.WGS84 );
} else {
transform = getTransformation( sourceCRS, GeocentricCRS.WGS84 );
}
}
return transform;
}
/**
* Creates a transformation between two projected coordinate systems. This method is automatically invoked by
* {@link #createFromCoordinateSystems createFromCoordinateSystems(...)}. The default implementation can adjust axis
* order and orientation. It also performs units conversion if it is the only extra change needed. Otherwise, it
* performs three steps:
*
* <ol>
* <li>Unproject <code>sourceCRS</code>.</li>
* <li>Transform from <code>sourceCRS.geographicCS</code> to <code>
* targetCRS.geographicCS</code>.</li>
* <li>Project <code>targetCRS</code>.</li>
* </ol>
*
* @param sourceCRS
* Input coordinate system.
* @param targetCRS
* Output coordinate system.
* @return A coordinate transformation from <code>sourceCRS</code> to <code>targetCRS</code>.
* @throws TransformationException
* if no transformation path has been found.
*/
private Transformation createTransformation( final IProjectedCRS sourceCRS, final IProjectedCRS targetCRS )
throws TransformationException {
Transformation result = getTransformation( sourceCRS, targetCRS );
if ( isIdentity( result ) ) {
LOG.debug( "Creating projected -> projected transformation: from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() );
if ( sourceCRS.getProjection().equals( targetCRS.getProjection() ) ) {
/*
* Swap axis order, and rotate the longitude coordinate if prime meridians are different.
*/
final Matrix matrix = swapAxis( sourceCRS, targetCRS );
return createMatrixTransform( sourceCRS, targetCRS, matrix );
}
final IGeographicCRS sourceGeo = sourceCRS.getGeographicCRS();
final IGeographicCRS targetGeo = targetCRS.getGeographicCRS();
final Transformation inverseProjection = createTransformation( sourceCRS, sourceGeo );
final Transformation geo2geo = createTransformation( sourceGeo, targetGeo );
final Transformation projection = createTransformation( targetGeo, targetCRS );
result = concatenate( inverseProjection, geo2geo, projection );
}
return result;
}
/**
* Creates a transformation between a projected and a geocentric coordinate systems. This method is automatically
* invoked by {@link #createFromCoordinateSystems createFromCoordinateSystems(...)}. This method doesn't need to be
* public since its decomposition in two step should be general enough.
*
* @param sourceCRS
* Input projected coordinate system.
* @param targetCRS
* Output coordinate system.
* @return A coordinate transformation from <code>sourceCRS</code> to <code>targetCRS</code>.
* @throws TransformationException
* if no transformation path has been found.
*/
private Transformation createTransformation( final IProjectedCRS sourceCRS, final IGeocentricCRS targetCRS )
throws TransformationException {
Transformation result = getTransformation( sourceCRS, targetCRS );
if ( isIdentity( result ) ) {
LOG.debug( "Creating projected -> geocentric transformation: from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() );
final IGeographicCRS sourceGCS = sourceCRS.getGeographicCRS();
final Transformation inverseProjection = createTransformation( sourceCRS, sourceGCS );
final Transformation geocentric = createTransformation( sourceGCS, targetCRS );
result = concatenate( inverseProjection, geocentric );
}
return result;
}
/**
* Creates a transformation between a projected and a geographic coordinate systems. This method is automatically
* invoked by {@link #createFromCoordinateSystems createFromCoordinateSystems(...)}. The default implementation
* returns <code>{@link #createTransformation(IGeographicCRS, IProjectedCRS)} createTransformation}(targetCRS,
* sourceCRS) inverse)</code>.
*
* @param sourceCRS
* Input coordinate system.
* @param targetCRS
* Output coordinate system.
* @return A coordinate transformation from <code>sourceCRS</code> to <code>targetCRS</code> or <code>null</code> if
* {@link ProjectedCRS#getGeographicCRS()}.equals targetCRS.
* @throws TransformationException
* if no transformation path has been found.
*/
private Transformation createTransformation( final IProjectedCRS sourceCRS, final IGeographicCRS targetCRS )
throws TransformationException {
Transformation result = getTransformation( sourceCRS, targetCRS );
if ( isIdentity( result ) ) {
LOG.debug( "Creating projected->geographic transformation: from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() );
result = createTransformation( targetCRS, sourceCRS );
if ( result != null ) {
result.inverse();
}
}
return result;
}
/**
* Creates a transformation between two geocentric coordinate systems. This method is automatically invoked by
* {@link #createFromCoordinateSystems createFromCoordinateSystems(...)}. The default implementation can adjust for
* axis order and orientation, adjust for prime meridian, performs units conversion and apply Bursa Wolf
* transformation if needed.
*
* @param sourceCRS
* Input coordinate system.
* @param targetCRS
* Output coordinate system.
* @return A coordinate transformation from <code>sourceCRS</code> to <code>targetCRS</code>.
* @throws TransformationException
* if no transformation path has been found.
*/
private Transformation createTransformation( final IGeocentricCRS sourceCRS, final IGeocentricCRS targetCRS )
throws TransformationException {
Transformation result = getTransformation( sourceCRS, targetCRS );
if ( isIdentity( result ) ) {
LOG.debug( "Creating geocentric->geocetric transformation: from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() );
if ( isEllipsoidTransformNeeded( sourceCRS, targetCRS ) ) {
final IGeodeticDatum sourceDatum = sourceCRS.getGeodeticDatum();
final IGeodeticDatum targetDatum = targetCRS.getGeodeticDatum();
// convert from the source to target ellipsoid through the
// geocentric coordinate system.
if ( !isIdentity( sourceDatum.getWGS84Conversion() ) || !isIdentity( targetDatum.getWGS84Conversion() ) ) {
LOG.debug( "Creating helmert transformation: source(" + sourceCRS.getCode() + ")->target("
+ targetCRS.getCode() + ")." );
result = transformUsingPivot( sourceCRS, targetCRS, sourceDatum.getWGS84Conversion(),
targetDatum.getWGS84Conversion() );
}
}
if ( result == null ) {
// Swap axis order, and rotate the longitude coordinate if prime
// meridians are different.
final Matrix matrix = swapAxis( sourceCRS, targetCRS );
result = createMatrixTransform( sourceCRS, targetCRS, matrix );
if ( LOG.isDebugEnabled() ) {
StringBuilder sb = new StringBuilder(
"Resulting axis alignment between source geocentric and target geocentric is:" );
if ( result == null ) {
sb.append( " not necessary" );
} else {
sb.append( "\n" ).append( ( (MatrixTransform) result ).getMatrix() );
}
LOG.debug( sb.toString() );
}
}
}
return result;
}
private boolean isEllipsoidTransformNeeded( ICRS sourceCRS, ICRS targetCRS ) {
final IGeodeticDatum sourceDatum = sourceCRS.getGeodeticDatum();
final IGeodeticDatum targetDatum = targetCRS.getGeodeticDatum();
if ( !sourceDatum.equals( targetDatum ) ) {
final IEllipsoid sourceEllipsoid = sourceDatum.getEllipsoid();
final IEllipsoid targetEllipsoid = targetDatum.getEllipsoid();
// If the two coordinate systems use different ellipsoid, a
// transformation needs to take place.
return sourceEllipsoid != null && !sourceEllipsoid.equals( targetEllipsoid );
}
return false;
}
private Transformation transformUsingPivot( IGeocentricCRS sourceCRS, IGeocentricCRS targetCRS,
Helmert sourceHelmert, Helmert targetHelmert )
throws TransformationException {
// Transform between different ellipsoids using Bursa Wolf parameters.
Matrix tmp = swapAxis( sourceCRS, GeocentricCRS.WGS84 );
Matrix4d forwardAxisAlign = null;
if ( tmp != null ) {
forwardAxisAlign = new Matrix4d();
tmp.get( forwardAxisAlign );
}
final Matrix4d forwardToWGS = getWGS84Parameters( sourceHelmert );
final Matrix4d inverseToWGS = getWGS84Parameters( targetHelmert );
tmp = swapAxis( GeocentricCRS.WGS84, targetCRS );
Matrix4d resultMatrix = null;
if ( tmp != null ) {
resultMatrix = new Matrix4d();
tmp.get( resultMatrix );
}
if ( forwardAxisAlign == null && forwardToWGS == null && inverseToWGS == null && resultMatrix == null ) {
LOG.debug( "The given geocentric crs's do not need a helmert transformation (but they are not equal), returning identity" );
resultMatrix = new Matrix4d();
resultMatrix.setIdentity();
} else {
LOG.debug( "step1 matrix: \n " + forwardAxisAlign );
LOG.debug( "step2 matrix: \n " + forwardToWGS );
LOG.debug( "step3 matrix: \n " + inverseToWGS );
LOG.debug( "step4 matrix: \n " + resultMatrix );
if ( inverseToWGS != null ) {
inverseToWGS.invert(); // Invert in place.
LOG.debug( "inverseToWGS inverted matrix: \n " + inverseToWGS );
}
if ( resultMatrix != null ) {
if ( inverseToWGS != null ) {
resultMatrix.mul( inverseToWGS ); // step4 = step4*step3
LOG.debug( "resultMatrix (after mul with inverseToWGS): \n " + resultMatrix );
}
if ( forwardToWGS != null ) {
resultMatrix.mul( forwardToWGS ); // step4 = step4*step3*step2
LOG.debug( "resultMatrix (after mul with forwardToWGS2): \n " + resultMatrix );
}
if ( forwardAxisAlign != null ) {
resultMatrix.mul( forwardAxisAlign ); // step4 =
// step4*step3*step2*step1
}
} else if ( inverseToWGS != null ) {
resultMatrix = inverseToWGS;
if ( forwardToWGS != null ) {
resultMatrix.mul( forwardToWGS ); // step4 = step3*step2*step1
LOG.debug( "resultMatrix (after mul with forwardToWGS2): \n " + resultMatrix );
}
if ( forwardAxisAlign != null ) {
resultMatrix.mul( forwardAxisAlign ); // step4 =
// step3*step2*step1
}
} else if ( forwardToWGS != null ) {
resultMatrix = forwardToWGS;
if ( forwardAxisAlign != null ) {
resultMatrix.mul( forwardAxisAlign ); // step4 = step2*step1
}
} else {
resultMatrix = forwardAxisAlign;
}
}
LOG.debug( "The resulting helmert transformation matrix: from( " + sourceCRS.getCode() + ") to("
+ targetCRS.getCode() + ")\n " + resultMatrix );
return new MatrixTransform( sourceCRS, targetCRS, resultMatrix, "Helmert-Transformation" );
}
/**
* True if the transformation is null || it's an identity ( {@link Transformation#isIdentity()}.
*
* @param transformation
* to check for.
* @return true if the given transformation is null or an identity.
*/
public final static boolean isIdentity( Transformation transformation ) {
return transformation == null || transformation.isIdentity();
}
/**
* @return the WGS84 parameters as an affine transform, or <code>null</code> if not available.
*/
private Matrix4d getWGS84Parameters( final Helmert transformation ) {
if ( !isIdentity( transformation ) ) {
return transformation.getAsAffineTransform();
}
return null;
}
private ICRS resolve( ICRS crs ) {
if ( crs instanceof CRSRef ) {
return ( (CRSRef) crs ).getReferencedObject();
}
return crs;
}
}
| false | true | private Transformation createTransformation( ICompoundCRS sourceCRS, ICompoundCRS targetCRS )
throws TransformationException {
if ( sourceCRS.getUnderlyingCRS().equals( targetCRS.getUnderlyingCRS() ) ) {
return null;
}
sourceCRS = ( (CompoundCRS) resolve( sourceCRS ) );
targetCRS = ( (CompoundCRS) resolve( targetCRS ) );
LOG.debug( "Creating compound( " + sourceCRS.getUnderlyingCRS().getCode() + ") ->compound transformation( "
+ targetCRS.getUnderlyingCRS().getCode() + "): from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() );
final CRSType sourceType = sourceCRS.getUnderlyingCRS().getType();
final CRSType targetType = targetCRS.getUnderlyingCRS().getType();
Transformation result = null;
// basic check for simple (invert) projections
if ( sourceType == PROJECTED && targetType == GEOGRAPHIC ) {
if ( ( ( (IProjectedCRS) resolve( sourceCRS.getUnderlyingCRS() ) ).getGeographicCRS() ).equals( targetCRS.getUnderlyingCRS() ) ) {
result = new ProjectionTransform( (IProjectedCRS) sourceCRS.getUnderlyingCRS() );
result.inverse();
}
}
if ( sourceType == GEOGRAPHIC && targetType == PROJECTED ) {
if ( ( ( (IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) ).getGeographicCRS() ).equals( sourceCRS.getUnderlyingCRS() ) ) {
result = new ProjectionTransform( (IProjectedCRS) targetCRS.getUnderlyingCRS() );
}
}
if ( result == null ) {
IGeocentricCRS sourceGeocentric = null;
if ( sourceType == GEOCENTRIC ) {
sourceGeocentric = (IGeocentricCRS) resolve( sourceCRS.getUnderlyingCRS() );
} else {
sourceGeocentric = new GeocentricCRS(
sourceCRS.getGeodeticDatum(),
CRSCodeType.valueOf( "tmp_" + sourceCRS.getCode() + "_geocentric" ),
sourceCRS.getName() + "_Geocentric" );
}
IGeocentricCRS targetGeocentric = null;
if ( targetType == GEOCENTRIC ) {
targetGeocentric = (IGeocentricCRS) resolve( targetCRS.getUnderlyingCRS() );
} else {
targetGeocentric = new GeocentricCRS(
targetCRS.getGeodeticDatum(),
CRSCodeType.valueOf( "tmp_" + targetCRS.getCode() + "_geocentric" ),
targetCRS.getName() + "_Geocentric" );
}
// Transformation helmertTransformation = createTransformation(
// sourceGeocentric, targetGeocentric );
Transformation sourceTransformationChain = null;
Transformation targetTransformationChain = null;
Transformation sourceT = null;
Transformation targetT = null;
IGeographicCRS sourceGeographic = null;
IGeographicCRS targetGeographic = null;
switch ( sourceType ) {
case GEOCENTRIC:
break;
case PROJECTED:
ICRS underlying = resolve( sourceCRS.getUnderlyingCRS() );
sourceTransformationChain = new ProjectionTransform( (ProjectedCRS) underlying );
sourceTransformationChain.inverse();
sourceGeographic = ( (IProjectedCRS) underlying ).getGeographicCRS();
case GEOGRAPHIC:
underlying = sourceCRS.getUnderlyingCRS();
if ( sourceGeographic == null ) {
sourceGeographic = (IGeographicCRS) resolve( underlying );
}
sourceT = getToWGSTransformation( sourceGeographic );
/*
* Only create a geocentric transform if the helmert transformation != null, e.g. the datums and
* ellipsoids are not equal.
*/
// if ( helmertTransformation != null ) {
// create a 2d->3d mapping.
final Transformation axisAligned = createMatrixTransform( sourceGeographic,
sourceGeocentric,
swapAxis( sourceGeographic,
GeographicCRS.WGS84 ) );
if ( LOG.isDebugEnabled() ) {
StringBuilder sb = new StringBuilder(
"Resulting axis alignment between source geographic and source geocentric is:" );
if ( axisAligned == null ) {
sb.append( " not necessary" );
} else {
sb.append( "\n" ).append( ( (MatrixTransform) axisAligned ).getMatrix() );
}
LOG.debug( sb.toString() );
}
final Transformation geoCentricTransform = new GeocentricTransform( sourceCRS, sourceGeocentric );
// concatenate the possible projection with the axis alignment
// and the geocentric transform.
sourceTransformationChain = concatenate( sourceTransformationChain, axisAligned, geoCentricTransform );
// }
break;
case COMPOUND:
// cannot happen.
break;
case VERTICAL:
LOG.warn( "Vertical crs is currently not supported for the Compound crs." );
break;
}
switch ( targetType ) {
case GEOCENTRIC:
break;
case PROJECTED:
targetTransformationChain = new ProjectionTransform(
(IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) );
targetGeographic = ( (IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) ).getGeographicCRS();
case GEOGRAPHIC:
if ( targetGeographic == null ) {
targetGeographic = (IGeographicCRS) resolve( targetCRS.getUnderlyingCRS() );
}
targetT = getToWGSTransformation( targetGeographic );
/*
* Only create a geocentric transform if the helmert transformation != null, e.g. the datums and
* ellipsoids are not equal.
*/
// if ( helmertTransformation != null ) {
// create a 2d->3d mapping.
final Transformation axisAligned = createMatrixTransform( targetGeocentric,
targetGeographic,
swapAxis( GeographicCRS.WGS84,
targetGeographic ) );
final Transformation geoCentricTransform = new GeocentricTransform( targetCRS, targetGeocentric );
geoCentricTransform.inverse();
// concatenate the possible projection with the axis alignment
// and the geocentric transform.
targetTransformationChain = concatenate( geoCentricTransform, axisAligned, targetTransformationChain );
// }
break;
case COMPOUND:
// cannot happen.
break;
case VERTICAL:
LOG.warn( "Vertical crs is currently not supported for the Compound crs." );
break;
}
Transformation helmertTransformation = null;
if ( !isIdentity( sourceT ) || !isIdentity( targetT ) ) {
helmertTransformation = transformUsingPivot( sourceGeocentric, targetGeocentric, (Helmert) sourceT,
(Helmert) targetT );
}
result = concatenate( sourceTransformationChain, helmertTransformation, targetTransformationChain );
}
return result;
}
| private Transformation createTransformation( ICompoundCRS sourceCRS, ICompoundCRS targetCRS )
throws TransformationException {
if ( sourceCRS.getUnderlyingCRS().equals( targetCRS.getUnderlyingCRS() ) ) {
return null;
}
sourceCRS = ( (CompoundCRS) resolve( sourceCRS ) );
targetCRS = ( (CompoundCRS) resolve( targetCRS ) );
LOG.debug( "Creating compound( " + sourceCRS.getUnderlyingCRS().getCode() + ") ->compound transformation( "
+ targetCRS.getUnderlyingCRS().getCode() + "): from (source): " + sourceCRS.getCode()
+ " to(target): " + targetCRS.getCode() );
final CRSType sourceType = sourceCRS.getUnderlyingCRS().getType();
final CRSType targetType = targetCRS.getUnderlyingCRS().getType();
Transformation result = null;
// basic check for simple (invert) projections
if ( sourceType == PROJECTED && targetType == GEOGRAPHIC ) {
if ( ( ( (IProjectedCRS) resolve( sourceCRS.getUnderlyingCRS() ) ).getGeographicCRS() ).equals( targetCRS.getUnderlyingCRS() ) ) {
result = new ProjectionTransform( (IProjectedCRS) resolve( sourceCRS.getUnderlyingCRS() ) );
result.inverse();
}
}
if ( sourceType == GEOGRAPHIC && targetType == PROJECTED ) {
if ( ( ( (IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) ).getGeographicCRS() ).equals( sourceCRS.getUnderlyingCRS() ) ) {
result = new ProjectionTransform( (IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) );
}
}
if ( result == null ) {
IGeocentricCRS sourceGeocentric = null;
if ( sourceType == GEOCENTRIC ) {
sourceGeocentric = (IGeocentricCRS) resolve( sourceCRS.getUnderlyingCRS() );
} else {
sourceGeocentric = new GeocentricCRS(
sourceCRS.getGeodeticDatum(),
CRSCodeType.valueOf( "tmp_" + sourceCRS.getCode() + "_geocentric" ),
sourceCRS.getName() + "_Geocentric" );
}
IGeocentricCRS targetGeocentric = null;
if ( targetType == GEOCENTRIC ) {
targetGeocentric = (IGeocentricCRS) resolve( targetCRS.getUnderlyingCRS() );
} else {
targetGeocentric = new GeocentricCRS(
targetCRS.getGeodeticDatum(),
CRSCodeType.valueOf( "tmp_" + targetCRS.getCode() + "_geocentric" ),
targetCRS.getName() + "_Geocentric" );
}
// Transformation helmertTransformation = createTransformation(
// sourceGeocentric, targetGeocentric );
Transformation sourceTransformationChain = null;
Transformation targetTransformationChain = null;
Transformation sourceT = null;
Transformation targetT = null;
IGeographicCRS sourceGeographic = null;
IGeographicCRS targetGeographic = null;
switch ( sourceType ) {
case GEOCENTRIC:
break;
case PROJECTED:
ICRS underlying = resolve( sourceCRS.getUnderlyingCRS() );
sourceTransformationChain = new ProjectionTransform( (ProjectedCRS) underlying );
sourceTransformationChain.inverse();
sourceGeographic = ( (IProjectedCRS) underlying ).getGeographicCRS();
case GEOGRAPHIC:
underlying = sourceCRS.getUnderlyingCRS();
if ( sourceGeographic == null ) {
sourceGeographic = (IGeographicCRS) resolve( underlying );
}
sourceT = getToWGSTransformation( sourceGeographic );
/*
* Only create a geocentric transform if the helmert transformation != null, e.g. the datums and
* ellipsoids are not equal.
*/
// if ( helmertTransformation != null ) {
// create a 2d->3d mapping.
final Transformation axisAligned = createMatrixTransform( sourceGeographic,
sourceGeocentric,
swapAxis( sourceGeographic,
GeographicCRS.WGS84 ) );
if ( LOG.isDebugEnabled() ) {
StringBuilder sb = new StringBuilder(
"Resulting axis alignment between source geographic and source geocentric is:" );
if ( axisAligned == null ) {
sb.append( " not necessary" );
} else {
sb.append( "\n" ).append( ( (MatrixTransform) axisAligned ).getMatrix() );
}
LOG.debug( sb.toString() );
}
final Transformation geoCentricTransform = new GeocentricTransform( sourceCRS, sourceGeocentric );
// concatenate the possible projection with the axis alignment
// and the geocentric transform.
sourceTransformationChain = concatenate( sourceTransformationChain, axisAligned, geoCentricTransform );
// }
break;
case COMPOUND:
// cannot happen.
break;
case VERTICAL:
LOG.warn( "Vertical crs is currently not supported for the Compound crs." );
break;
}
switch ( targetType ) {
case GEOCENTRIC:
break;
case PROJECTED:
targetTransformationChain = new ProjectionTransform(
(IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) );
targetGeographic = ( (IProjectedCRS) resolve( targetCRS.getUnderlyingCRS() ) ).getGeographicCRS();
case GEOGRAPHIC:
if ( targetGeographic == null ) {
targetGeographic = (IGeographicCRS) resolve( targetCRS.getUnderlyingCRS() );
}
targetT = getToWGSTransformation( targetGeographic );
/*
* Only create a geocentric transform if the helmert transformation != null, e.g. the datums and
* ellipsoids are not equal.
*/
// if ( helmertTransformation != null ) {
// create a 2d->3d mapping.
final Transformation axisAligned = createMatrixTransform( targetGeocentric,
targetGeographic,
swapAxis( GeographicCRS.WGS84,
targetGeographic ) );
final Transformation geoCentricTransform = new GeocentricTransform( targetCRS, targetGeocentric );
geoCentricTransform.inverse();
// concatenate the possible projection with the axis alignment
// and the geocentric transform.
targetTransformationChain = concatenate( geoCentricTransform, axisAligned, targetTransformationChain );
// }
break;
case COMPOUND:
// cannot happen.
break;
case VERTICAL:
LOG.warn( "Vertical crs is currently not supported for the Compound crs." );
break;
}
Transformation helmertTransformation = null;
if ( !isIdentity( sourceT ) || !isIdentity( targetT ) ) {
helmertTransformation = transformUsingPivot( sourceGeocentric, targetGeocentric, (Helmert) sourceT,
(Helmert) targetT );
}
result = concatenate( sourceTransformationChain, helmertTransformation, targetTransformationChain );
}
return result;
}
|
diff --git a/core/src/visad/trunk/data/mcidas/McIDASGridReader.java b/core/src/visad/trunk/data/mcidas/McIDASGridReader.java
index 2216044b0..bf8dff578 100644
--- a/core/src/visad/trunk/data/mcidas/McIDASGridReader.java
+++ b/core/src/visad/trunk/data/mcidas/McIDASGridReader.java
@@ -1,138 +1,138 @@
//
// McIDASGridDirectory.java
//
/*
The software in this file is Copyright(C) 1998 by Tom Whittaker.
It is designed to be used with the VisAD system for interactive
analysis and visualization of numerical data.
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 1, 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 in file NOTICE 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package visad.data.mcidas;
import java.io.*;
import java.util.*;
import visad.*;
import visad.data.mcidas.*;
import edu.wisc.ssec.mcidas.adde.*;
import edu.wisc.ssec.mcidas.*;
/** Read grid(s) from a McIDAS grid file
*/
public class McIDASGridReader {
ArrayList gridH, gridD;
int[] entry;
RandomAccessFile fn;
public McIDASGridReader() {
gridD = null;
gridH = null;
}
/** read the first grid from the named file
*
* @return first grid
*/
public ArrayList getGridData(String filename ) {
// open file and get pointer block
try {
fn = new RandomAccessFile(filename,"r");
fn.seek(0);
// read the fileheader
int[] fileHeader = new int[10];
for (int i=0; i<10; i++) {
fileHeader[i] = fn.readInt();
System.out.println("head="+fileHeader[i]);
}
int numEntries = Math.abs( fn.readInt() );
System.out.println("number entries="+numEntries);
entry = new int[numEntries];
for (int i=0; i<numEntries; i++) {
entry[i] = fn.readInt();
}
readEntry(0);
} catch (Exception e) {System.out.println("exp="+e);}
return gridD;
}
// internal method to fetch the 'ent'-th grid
private void readEntry(int ent) {
try {
int te = entry[ent] * 4;
System.out.println("Entry 0 = "+te);
byte[] gridHeader = new byte[256];
fn.seek(te);
fn.readFully(gridHeader);
//gridHeader[32]='m'; // we had to make the units m instead of M
McIDASGridDirectory mgd = new McIDASGridDirectory(gridHeader);
System.out.println("grid header ="+mgd.toString());
CoordinateSystem c = mgd.getCoordinateSystem();
int rows = mgd.getRows();
int cols = mgd.getColumns();
System.out.println("# rows & cols = "+rows+" "+cols);
double scale = mgd.getParamScale();
- System.out.println("param scale = "+scale+" gridType="+mgd.getGridType());
+ //System.out.println("param scale = "+scale+" gridType="+mgd.getGridType());
double[] data = new double[rows*cols];
int n = 0;
// store such that 0,0 is in lower left corner...
for (int nc=0; nc<cols; nc++) {
for (int nr=0; nr<rows; nr++) {
int temp = fn.readInt(); // check for missing value
data[(rows-nr-1)*cols + nc] =
(temp == McIDASUtil.MCMISSING)
? Double.NaN
: ( (double) temp) / scale ;
}
}
gridH = new ArrayList();
gridD = new ArrayList();
gridH.add(mgd);
gridD.add(data);
} catch (Exception esc) {System.out.println(esc);}
}
/** to get some grid, by index value, other than the first one
*
* @return ArrayList of the single grid
*/
public ArrayList getGrid(int index) {
readEntry(index);
return gridD;
}
/** to get the grid header corresponding to the last grid read
*
* @return McIDASGridDirectory of the last grid read
*/
public ArrayList getGridHeaders() {
return gridH;
}
/** for testing purposes
*/
public static void main(String[] a) {
McIDASGridReader mg = new McIDASGridReader();
mg.getGridData("/src/visad/data/mcidas/GRID1715");
}
}
| true | true | private void readEntry(int ent) {
try {
int te = entry[ent] * 4;
System.out.println("Entry 0 = "+te);
byte[] gridHeader = new byte[256];
fn.seek(te);
fn.readFully(gridHeader);
//gridHeader[32]='m'; // we had to make the units m instead of M
McIDASGridDirectory mgd = new McIDASGridDirectory(gridHeader);
System.out.println("grid header ="+mgd.toString());
CoordinateSystem c = mgd.getCoordinateSystem();
int rows = mgd.getRows();
int cols = mgd.getColumns();
System.out.println("# rows & cols = "+rows+" "+cols);
double scale = mgd.getParamScale();
System.out.println("param scale = "+scale+" gridType="+mgd.getGridType());
double[] data = new double[rows*cols];
int n = 0;
// store such that 0,0 is in lower left corner...
for (int nc=0; nc<cols; nc++) {
for (int nr=0; nr<rows; nr++) {
int temp = fn.readInt(); // check for missing value
data[(rows-nr-1)*cols + nc] =
(temp == McIDASUtil.MCMISSING)
? Double.NaN
: ( (double) temp) / scale ;
}
}
gridH = new ArrayList();
gridD = new ArrayList();
gridH.add(mgd);
gridD.add(data);
} catch (Exception esc) {System.out.println(esc);}
}
| private void readEntry(int ent) {
try {
int te = entry[ent] * 4;
System.out.println("Entry 0 = "+te);
byte[] gridHeader = new byte[256];
fn.seek(te);
fn.readFully(gridHeader);
//gridHeader[32]='m'; // we had to make the units m instead of M
McIDASGridDirectory mgd = new McIDASGridDirectory(gridHeader);
System.out.println("grid header ="+mgd.toString());
CoordinateSystem c = mgd.getCoordinateSystem();
int rows = mgd.getRows();
int cols = mgd.getColumns();
System.out.println("# rows & cols = "+rows+" "+cols);
double scale = mgd.getParamScale();
//System.out.println("param scale = "+scale+" gridType="+mgd.getGridType());
double[] data = new double[rows*cols];
int n = 0;
// store such that 0,0 is in lower left corner...
for (int nc=0; nc<cols; nc++) {
for (int nr=0; nr<rows; nr++) {
int temp = fn.readInt(); // check for missing value
data[(rows-nr-1)*cols + nc] =
(temp == McIDASUtil.MCMISSING)
? Double.NaN
: ( (double) temp) / scale ;
}
}
gridH = new ArrayList();
gridD = new ArrayList();
gridH.add(mgd);
gridD.add(data);
} catch (Exception esc) {System.out.println(esc);}
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/FindFileCommand.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/FindFileCommand.java
index a3dab8f1..6c34db22 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/FindFileCommand.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/FindFileCommand.java
@@ -1,23 +1,23 @@
package net.sourceforge.vrapper.vim.commands;
import net.sourceforge.vrapper.vim.EditorAdaptor;
import net.sourceforge.vrapper.vim.Options;
public class FindFileCommand extends CountIgnoringNonRepeatableCommand {
private String filename;
public FindFileCommand(String filename) {
this.filename = filename;
}
public void execute(EditorAdaptor editorAdaptor)
throws CommandExecutionException {
String[] paths = editorAdaptor.getConfiguration().get(Options.PATH).split(",");
boolean success = editorAdaptor.getFileService().findAndOpenFile(filename, paths);
if(! success) {
- editorAdaptor.getUserInterfaceService().setErrorMessage("Could not find file: " + filename);
+ editorAdaptor.getUserInterfaceService().setErrorMessage("Can't find file \"" + filename + "\" in path");
}
}
}
| true | true | public void execute(EditorAdaptor editorAdaptor)
throws CommandExecutionException {
String[] paths = editorAdaptor.getConfiguration().get(Options.PATH).split(",");
boolean success = editorAdaptor.getFileService().findAndOpenFile(filename, paths);
if(! success) {
editorAdaptor.getUserInterfaceService().setErrorMessage("Could not find file: " + filename);
}
}
| public void execute(EditorAdaptor editorAdaptor)
throws CommandExecutionException {
String[] paths = editorAdaptor.getConfiguration().get(Options.PATH).split(",");
boolean success = editorAdaptor.getFileService().findAndOpenFile(filename, paths);
if(! success) {
editorAdaptor.getUserInterfaceService().setErrorMessage("Can't find file \"" + filename + "\" in path");
}
}
|
diff --git a/apptests/GattServerApp/src/com/android/bluetooth/test/GattServerAppReceiver.java b/apptests/GattServerApp/src/com/android/bluetooth/test/GattServerAppReceiver.java
index 67e3f2a..90feb23 100644
--- a/apptests/GattServerApp/src/com/android/bluetooth/test/GattServerAppReceiver.java
+++ b/apptests/GattServerApp/src/com/android/bluetooth/test/GattServerAppReceiver.java
@@ -1,111 +1,115 @@
/*
* Copyright (c) 2012, Code Aurora Forum. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Code Aurora Forum, Inc. 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.android.bluetooth.test;
import java.util.ArrayList;
import java.util.Arrays;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.app.Activity;
import android.bluetooth.BluetoothDevicePicker;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
/**
* This class is the broadcast receiver class for the Gatt Server application.
* This receiver handles the intents and starts the Gatt Server service when the
* phone boots up and when Bluetooth is turned on
*/
public class GattServerAppReceiver extends BroadcastReceiver{
private final static String TAG = "GattServerAppReceiver";
private static final int REQUEST_ENABLE_BT = 1;
private static Handler handler = null;
GattServerAppService gattService = new GattServerAppService();
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(action != null && action.equalsIgnoreCase(BluetoothAdapter.ACTION_STATE_CHANGED)) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) ==
BluetoothAdapter.STATE_ON) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.android.bluetooth.test.GattServerAppService");
Log.d(TAG, "Going to start service from BT Server app Broadcast Receiver::");
context.startService(serviceIntent);
}
else if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) ==
BluetoothAdapter.STATE_OFF) {
Log.d(TAG, "Bluetooth is off");
if(GattServerAppService.gattProfile != null &&
GattServerAppService.serverConfiguration != null) {
if(GattServerAppService.connectedDevicesList != null &&
GattServerAppService.connectedDevicesList.size() > 0) {
if(GattServerAppService.connectedDevicesList != null &&
GattServerAppService.connectedDevicesList.size() > 0) {
for(int i=0; i < GattServerAppService.connectedDevicesList.size(); i++) {
BluetoothDevice remoteDevice = GattServerAppService.connectedDevicesList.get(i);
gattService.disconnectLEDevice(remoteDevice);
}
}
}
GattServerAppService.gattProfile.
unregisterServerConfiguration(GattServerAppService.serverConfiguration);
Log.d(TAG, "Unregistered server app configuration");
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.android.bluetooth.test.GattServerAppService");
Log.d(TAG, "Going to stop service from BT Server app Broadcast Receiver::");
context.stopService(serviceIntent);
}
}
}
else if (action.equals(BluetoothDevicePicker.ACTION_DEVICE_SELECTED)) {
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "Received BT device selected intent, BT device: " + remoteDevice.getAddress());
String deviceName = remoteDevice.getName();
Message msg = new Message();
msg.what = GattServerAppService.DEVICE_SELECTED;
Bundle b = new Bundle();
b.putParcelable(GattServerAppService.REMOTE_DEVICE, remoteDevice);
msg.setData(b);
handler.sendMessage(msg);
}
+ else if (action.equals(BluetoothDevice.ACTION_LE_CONN_PARAMS)) {
+ int connInterval = intent.getIntExtra(BluetoothDevice.EXTRA_CONN_INTERVAL, 0);
+ Log.d(TAG, "LE Connection interval is: " + connInterval);
+ }
}
public static void registerHandler(Handler handle) {
Log.d(TAG, "Registered Handler");
handler = handle;
}
}
| true | true | public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(action != null && action.equalsIgnoreCase(BluetoothAdapter.ACTION_STATE_CHANGED)) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) ==
BluetoothAdapter.STATE_ON) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.android.bluetooth.test.GattServerAppService");
Log.d(TAG, "Going to start service from BT Server app Broadcast Receiver::");
context.startService(serviceIntent);
}
else if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) ==
BluetoothAdapter.STATE_OFF) {
Log.d(TAG, "Bluetooth is off");
if(GattServerAppService.gattProfile != null &&
GattServerAppService.serverConfiguration != null) {
if(GattServerAppService.connectedDevicesList != null &&
GattServerAppService.connectedDevicesList.size() > 0) {
if(GattServerAppService.connectedDevicesList != null &&
GattServerAppService.connectedDevicesList.size() > 0) {
for(int i=0; i < GattServerAppService.connectedDevicesList.size(); i++) {
BluetoothDevice remoteDevice = GattServerAppService.connectedDevicesList.get(i);
gattService.disconnectLEDevice(remoteDevice);
}
}
}
GattServerAppService.gattProfile.
unregisterServerConfiguration(GattServerAppService.serverConfiguration);
Log.d(TAG, "Unregistered server app configuration");
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.android.bluetooth.test.GattServerAppService");
Log.d(TAG, "Going to stop service from BT Server app Broadcast Receiver::");
context.stopService(serviceIntent);
}
}
}
else if (action.equals(BluetoothDevicePicker.ACTION_DEVICE_SELECTED)) {
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "Received BT device selected intent, BT device: " + remoteDevice.getAddress());
String deviceName = remoteDevice.getName();
Message msg = new Message();
msg.what = GattServerAppService.DEVICE_SELECTED;
Bundle b = new Bundle();
b.putParcelable(GattServerAppService.REMOTE_DEVICE, remoteDevice);
msg.setData(b);
handler.sendMessage(msg);
}
}
| public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(action != null && action.equalsIgnoreCase(BluetoothAdapter.ACTION_STATE_CHANGED)) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) ==
BluetoothAdapter.STATE_ON) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.android.bluetooth.test.GattServerAppService");
Log.d(TAG, "Going to start service from BT Server app Broadcast Receiver::");
context.startService(serviceIntent);
}
else if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) ==
BluetoothAdapter.STATE_OFF) {
Log.d(TAG, "Bluetooth is off");
if(GattServerAppService.gattProfile != null &&
GattServerAppService.serverConfiguration != null) {
if(GattServerAppService.connectedDevicesList != null &&
GattServerAppService.connectedDevicesList.size() > 0) {
if(GattServerAppService.connectedDevicesList != null &&
GattServerAppService.connectedDevicesList.size() > 0) {
for(int i=0; i < GattServerAppService.connectedDevicesList.size(); i++) {
BluetoothDevice remoteDevice = GattServerAppService.connectedDevicesList.get(i);
gattService.disconnectLEDevice(remoteDevice);
}
}
}
GattServerAppService.gattProfile.
unregisterServerConfiguration(GattServerAppService.serverConfiguration);
Log.d(TAG, "Unregistered server app configuration");
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.android.bluetooth.test.GattServerAppService");
Log.d(TAG, "Going to stop service from BT Server app Broadcast Receiver::");
context.stopService(serviceIntent);
}
}
}
else if (action.equals(BluetoothDevicePicker.ACTION_DEVICE_SELECTED)) {
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "Received BT device selected intent, BT device: " + remoteDevice.getAddress());
String deviceName = remoteDevice.getName();
Message msg = new Message();
msg.what = GattServerAppService.DEVICE_SELECTED;
Bundle b = new Bundle();
b.putParcelable(GattServerAppService.REMOTE_DEVICE, remoteDevice);
msg.setData(b);
handler.sendMessage(msg);
}
else if (action.equals(BluetoothDevice.ACTION_LE_CONN_PARAMS)) {
int connInterval = intent.getIntExtra(BluetoothDevice.EXTRA_CONN_INTERVAL, 0);
Log.d(TAG, "LE Connection interval is: " + connInterval);
}
}
|
diff --git a/src/main/java/org/apache/maven/plugin/nar/NarSystemGenerate.java b/src/main/java/org/apache/maven/plugin/nar/NarSystemGenerate.java
index e3c81617..d33df60f 100644
--- a/src/main/java/org/apache/maven/plugin/nar/NarSystemGenerate.java
+++ b/src/main/java/org/apache/maven/plugin/nar/NarSystemGenerate.java
@@ -1,109 +1,121 @@
package org.apache.maven.plugin.nar;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Generates a NarSystem class with static methods to use inside the java part of the library.
*
* @goal nar-system-generate
* @phase generate-sources
* @requiresProject
* @author Mark Donszelmann
*/
public class NarSystemGenerate
extends AbstractCompileMojo
{
public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( shouldSkip() )
return;
// get packageName if specified for JNI.
String packageName = null;
String narSystemName = null;
String narSystemDirectory = null;
boolean jniFound = false;
for ( Iterator i = getLibraries().iterator(); !jniFound && i.hasNext(); )
{
Library library = (Library) i.next();
if ( library.getType().equals( Library.JNI ) )
{
packageName = library.getNarSystemPackage();
narSystemName = library.getNarSystemName();
narSystemDirectory = library.getNarSystemDirectory();
jniFound = true;
}
}
if ( !jniFound || packageName == null)
return;
File narSystemTarget = new File(getMavenProject().getBasedir(), narSystemDirectory);
// make sure destination is there
narSystemTarget.mkdirs();
getMavenProject().addCompileSourceRoot( narSystemTarget.getPath() );
File fullDir = new File( narSystemTarget, packageName.replace( '.', '/' ) );
fullDir.mkdirs();
File narSystem = new File( fullDir, narSystemName + ".java" );
getLog().info("Generating "+narSystem);
try
{
+ String artifactId = getMavenProject().getArtifactId();
+ String version = getMavenProject().getVersion();
FileOutputStream fos = new FileOutputStream( narSystem );
PrintWriter p = new PrintWriter( fos );
p.println( "// DO NOT EDIT: Generated by NarSystemGenerate." );
p.println( "package " + packageName + ";" );
p.println( "" );
+ p.println( "/**" );
+ p.println( " * Generated class to load the correct version of the jni library" );
+ p.println( " *" );
+ p.println( " * @author maven-nar-plugin" );
+ p.println( " */" );
p.println( "public class NarSystem" );
p.println( "{" );
p.println( "" );
p.println( " private NarSystem() " );
p.println( " {" );
p.println( " }" );
p.println( "" );
+ p.println( " /**" );
+ p.println( " * Load jni library: "+artifactId+"-"+version );
+ p.println( " *" );
+ p.println( " * @author maven-nar-plugin" );
+ p.println( " */" );
p.println( " public static void loadLibrary()" );
p.println( " {" );
- p.println( " System.loadLibrary(\"" + getMavenProject().getArtifactId() + "-"
- + getMavenProject().getVersion() + "\");" );
+ p.println( " System.loadLibrary(\"" + artifactId + "-"
+ + version + "\");" );
p.println( " }" );
p.println( "}" );
p.close();
fos.close();
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not write '" + narSystemName + "'", e );
}
}
}
| false | true | public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( shouldSkip() )
return;
// get packageName if specified for JNI.
String packageName = null;
String narSystemName = null;
String narSystemDirectory = null;
boolean jniFound = false;
for ( Iterator i = getLibraries().iterator(); !jniFound && i.hasNext(); )
{
Library library = (Library) i.next();
if ( library.getType().equals( Library.JNI ) )
{
packageName = library.getNarSystemPackage();
narSystemName = library.getNarSystemName();
narSystemDirectory = library.getNarSystemDirectory();
jniFound = true;
}
}
if ( !jniFound || packageName == null)
return;
File narSystemTarget = new File(getMavenProject().getBasedir(), narSystemDirectory);
// make sure destination is there
narSystemTarget.mkdirs();
getMavenProject().addCompileSourceRoot( narSystemTarget.getPath() );
File fullDir = new File( narSystemTarget, packageName.replace( '.', '/' ) );
fullDir.mkdirs();
File narSystem = new File( fullDir, narSystemName + ".java" );
getLog().info("Generating "+narSystem);
try
{
FileOutputStream fos = new FileOutputStream( narSystem );
PrintWriter p = new PrintWriter( fos );
p.println( "// DO NOT EDIT: Generated by NarSystemGenerate." );
p.println( "package " + packageName + ";" );
p.println( "" );
p.println( "public class NarSystem" );
p.println( "{" );
p.println( "" );
p.println( " private NarSystem() " );
p.println( " {" );
p.println( " }" );
p.println( "" );
p.println( " public static void loadLibrary()" );
p.println( " {" );
p.println( " System.loadLibrary(\"" + getMavenProject().getArtifactId() + "-"
+ getMavenProject().getVersion() + "\");" );
p.println( " }" );
p.println( "}" );
p.close();
fos.close();
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not write '" + narSystemName + "'", e );
}
}
| public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( shouldSkip() )
return;
// get packageName if specified for JNI.
String packageName = null;
String narSystemName = null;
String narSystemDirectory = null;
boolean jniFound = false;
for ( Iterator i = getLibraries().iterator(); !jniFound && i.hasNext(); )
{
Library library = (Library) i.next();
if ( library.getType().equals( Library.JNI ) )
{
packageName = library.getNarSystemPackage();
narSystemName = library.getNarSystemName();
narSystemDirectory = library.getNarSystemDirectory();
jniFound = true;
}
}
if ( !jniFound || packageName == null)
return;
File narSystemTarget = new File(getMavenProject().getBasedir(), narSystemDirectory);
// make sure destination is there
narSystemTarget.mkdirs();
getMavenProject().addCompileSourceRoot( narSystemTarget.getPath() );
File fullDir = new File( narSystemTarget, packageName.replace( '.', '/' ) );
fullDir.mkdirs();
File narSystem = new File( fullDir, narSystemName + ".java" );
getLog().info("Generating "+narSystem);
try
{
String artifactId = getMavenProject().getArtifactId();
String version = getMavenProject().getVersion();
FileOutputStream fos = new FileOutputStream( narSystem );
PrintWriter p = new PrintWriter( fos );
p.println( "// DO NOT EDIT: Generated by NarSystemGenerate." );
p.println( "package " + packageName + ";" );
p.println( "" );
p.println( "/**" );
p.println( " * Generated class to load the correct version of the jni library" );
p.println( " *" );
p.println( " * @author maven-nar-plugin" );
p.println( " */" );
p.println( "public class NarSystem" );
p.println( "{" );
p.println( "" );
p.println( " private NarSystem() " );
p.println( " {" );
p.println( " }" );
p.println( "" );
p.println( " /**" );
p.println( " * Load jni library: "+artifactId+"-"+version );
p.println( " *" );
p.println( " * @author maven-nar-plugin" );
p.println( " */" );
p.println( " public static void loadLibrary()" );
p.println( " {" );
p.println( " System.loadLibrary(\"" + artifactId + "-"
+ version + "\");" );
p.println( " }" );
p.println( "}" );
p.close();
fos.close();
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not write '" + narSystemName + "'", e );
}
}
|
diff --git a/test/test/RunXmlTest.java b/test/test/RunXmlTest.java
index 3ee13c3..c8ad1d8 100644
--- a/test/test/RunXmlTest.java
+++ b/test/test/RunXmlTest.java
@@ -1,53 +1,51 @@
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test;
import com.google.caliper.MeasurementSet;
import com.google.caliper.Run;
import com.google.caliper.Scenario;
import com.google.caliper.Xml;
import com.google.common.collect.ImmutableMap;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import junit.framework.TestCase;
public class RunXmlTest extends TestCase {
public void testXmlRoundtrip() {
Scenario a15dalvik = new Scenario(ImmutableMap.of(
"foo", "A", "bar", "15", "vm", "dalvikvm"));
Scenario b15dalvik = new Scenario(ImmutableMap.of(
"foo", "B", "bar", "15", "vm", "dalvikvm"));
Run toEncode = new Run(ImmutableMap.of(a15dalvik, new MeasurementSet(1200.1, 1198.8),
- b15dalvik, new MeasurementSet(1100.2, 1110.0)),
- "examples.FooBenchmark", "A0:1F:CAFE:BABE", new Date());
+ b15dalvik, new MeasurementSet(1100.2, 1110.0)), "examples.FooBenchmark", new Date());
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
Xml.runToXml(toEncode, bytesOut);
// we don't validate the XML directly because it's a hassle to cope with arbitrary orderings of
// an element's attributes
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesOut.toByteArray());
Run decoded = Xml.runFromXml(bytesIn);
assertEquals(toEncode.getBenchmarkName(), decoded.getBenchmarkName());
- assertEquals(toEncode.getApiKey(), decoded.getApiKey());
- assertEquals(toEncode.getMeasurements().keySet(), decoded.getMeasurements().keySet());
+ assertEquals(toEncode.getMeasurements().keySet(), decoded.getMeasurements().keySet());
}
}
| false | true | public void testXmlRoundtrip() {
Scenario a15dalvik = new Scenario(ImmutableMap.of(
"foo", "A", "bar", "15", "vm", "dalvikvm"));
Scenario b15dalvik = new Scenario(ImmutableMap.of(
"foo", "B", "bar", "15", "vm", "dalvikvm"));
Run toEncode = new Run(ImmutableMap.of(a15dalvik, new MeasurementSet(1200.1, 1198.8),
b15dalvik, new MeasurementSet(1100.2, 1110.0)),
"examples.FooBenchmark", "A0:1F:CAFE:BABE", new Date());
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
Xml.runToXml(toEncode, bytesOut);
// we don't validate the XML directly because it's a hassle to cope with arbitrary orderings of
// an element's attributes
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesOut.toByteArray());
Run decoded = Xml.runFromXml(bytesIn);
assertEquals(toEncode.getBenchmarkName(), decoded.getBenchmarkName());
assertEquals(toEncode.getApiKey(), decoded.getApiKey());
assertEquals(toEncode.getMeasurements().keySet(), decoded.getMeasurements().keySet());
}
| public void testXmlRoundtrip() {
Scenario a15dalvik = new Scenario(ImmutableMap.of(
"foo", "A", "bar", "15", "vm", "dalvikvm"));
Scenario b15dalvik = new Scenario(ImmutableMap.of(
"foo", "B", "bar", "15", "vm", "dalvikvm"));
Run toEncode = new Run(ImmutableMap.of(a15dalvik, new MeasurementSet(1200.1, 1198.8),
b15dalvik, new MeasurementSet(1100.2, 1110.0)), "examples.FooBenchmark", new Date());
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
Xml.runToXml(toEncode, bytesOut);
// we don't validate the XML directly because it's a hassle to cope with arbitrary orderings of
// an element's attributes
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesOut.toByteArray());
Run decoded = Xml.runFromXml(bytesIn);
assertEquals(toEncode.getBenchmarkName(), decoded.getBenchmarkName());
assertEquals(toEncode.getMeasurements().keySet(), decoded.getMeasurements().keySet());
}
|
diff --git a/android/src/org/shokai/goldfish/API.java b/android/src/org/shokai/goldfish/API.java
index fbb4475..821c42c 100644
--- a/android/src/org/shokai/goldfish/API.java
+++ b/android/src/org/shokai/goldfish/API.java
@@ -1,46 +1,46 @@
package org.shokai.goldfish;
import java.util.*;
import java.io.*;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class API {
public class Action{
public final static String COPY = "copy";
public final static String PASTE = "paste";
}
private String api_url;
public String getApiUrl(){
return this.api_url;
}
public API(String api_url){
this.api_url = api_url;
}
public String post(String tag, String action) throws Exception{
HttpClient client = new DefaultHttpClient();
- HttpPost httppost = new HttpPost(this.api_url);
+ HttpPost httppost = new HttpPost(this.api_url+"/android");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", tag));
params.add(new BasicNameValuePair("action", action));
try{
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse res = client.execute(httppost);
ByteArrayOutputStream os = new ByteArrayOutputStream();
res.getEntity().writeTo(os);
return os.toString();
}
catch(Exception e){
throw e;
}
}
}
| true | true | public String post(String tag, String action) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.api_url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", tag));
params.add(new BasicNameValuePair("action", action));
try{
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse res = client.execute(httppost);
ByteArrayOutputStream os = new ByteArrayOutputStream();
res.getEntity().writeTo(os);
return os.toString();
}
catch(Exception e){
throw e;
}
}
| public String post(String tag, String action) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.api_url+"/android");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", tag));
params.add(new BasicNameValuePair("action", action));
try{
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse res = client.execute(httppost);
ByteArrayOutputStream os = new ByteArrayOutputStream();
res.getEntity().writeTo(os);
return os.toString();
}
catch(Exception e){
throw e;
}
}
|
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/AbstractBackend.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/AbstractBackend.java
index 922f0e7f3..999f67bf9 100644
--- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/AbstractBackend.java
+++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/AbstractBackend.java
@@ -1,1016 +1,1016 @@
/*
* Copyright (c) 2009-2011, IETR/INSA of Rennes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the IETR/INSA of Rennes nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.orcc.backends;
import static net.sf.orcc.OrccActivator.getDefault;
import static net.sf.orcc.OrccLaunchConstants.CLASSIFY;
import static net.sf.orcc.OrccLaunchConstants.COMPILE_XDF;
import static net.sf.orcc.OrccLaunchConstants.DEBUG_MODE;
import static net.sf.orcc.OrccLaunchConstants.DEFAULT_FIFO_SIZE;
import static net.sf.orcc.OrccLaunchConstants.FIFO_SIZE;
import static net.sf.orcc.OrccLaunchConstants.MAPPING;
import static net.sf.orcc.OrccLaunchConstants.MERGE_ACTIONS;
import static net.sf.orcc.OrccLaunchConstants.MERGE_ACTORS;
import static net.sf.orcc.OrccLaunchConstants.OUTPUT_FOLDER;
import static net.sf.orcc.OrccLaunchConstants.PROJECT;
import static net.sf.orcc.OrccLaunchConstants.XDF_FILE;
import static net.sf.orcc.preferences.PreferenceConstants.P_SOLVER;
import static net.sf.orcc.preferences.PreferenceConstants.P_SOLVER_OPTIONS;
import static net.sf.orcc.util.OrccUtil.getFile;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import net.sf.orcc.OrccException;
import net.sf.orcc.OrccRuntimeException;
import net.sf.orcc.df.Actor;
import net.sf.orcc.df.Instance;
import net.sf.orcc.df.Network;
import net.sf.orcc.df.util.DfSwitch;
import net.sf.orcc.df.util.NetworkValidator;
import net.sf.orcc.graph.Vertex;
import net.sf.orcc.util.OrccLogger;
import net.sf.orcc.util.OrccUtil;
import net.sf.orcc.util.util.EcoreHelper;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
/**
* This class is an abstract implementation of {@link Backend}. The two entry
* points of this class are the public methods {@link #compileVTL()} and
* {@link #compileXDF()} which should NOT be called by back-ends themselves.
*
* <p>
* The following methods are abstract and must be implemented by back-ends:
* <ul>
* <li>{@link #doInitializeOptions()} is called by {@link #setOptions(Map)} to
* initialize the options of the back-end.</li>
* <li>{@link #doTransformActor(Actor)} is called by
* {@link #transformActors(List)} to transform a list of actors.</li>
* <li>{@link #doVtlCodeGeneration(List)} is called to compile a list of actors.
* </li>
* <li>{@link #doXdfCodeGeneration(Network)} is called to compile a network.</li>
* </ul>
* </p>
*
* The following methods may be extended by back-ends, if they print actors or
* instances respectively, or if a library must be exported with source file
* produced.
* <ul>
* <li>{@link #printActor(Actor)} is called by {@link #printActors(List)}.</li>
* <li>{@link #printInstance(Instance)} is called by
* {@link #printInstances(Network)}.</li>
* <li>{@link #exportRuntimeLibrary()} is called by {@link #start}.</li>
* </ul>
*
* The other methods declared <code>final</code> may be called by back-ends.
*
* @author Matthieu Wipliez
*
*/
public abstract class AbstractBackend implements Backend, IApplication {
protected boolean debug;
/**
* Fifo size used in backend.
*/
protected int fifoSize;
private IFile inputFile;
protected Map<String, String> mapping;
/**
* List of transformations to apply on each network
*/
protected List<DfSwitch<?>> networkTransfos;
/**
* List of transformations to apply on each actor
*/
protected List<DfSwitch<?>> actorTransfos;
protected boolean classify;
protected boolean mergeActions;
protected boolean mergeActors;
protected boolean convertMulti2Mono;
/**
* the progress monitor
*/
private IProgressMonitor monitor;
/**
* Options of backend execution. Its content can be manipulated with
* {@link #getAttribute} and {@link #setAttribute}
*/
private Map<String, Object> options;
/**
* Path where output files will be written.
*/
protected String path;
/**
* Represents the project where call application to build is located
*/
protected IProject project;
/**
* Path of the folder that contains VTL under IR form.
*/
private List<IFolder> vtlFolders;
/**
* Initialize some members
*/
public AbstractBackend() {
actorTransfos = new ArrayList<DfSwitch<?>>();
networkTransfos = new ArrayList<DfSwitch<?>>();
}
@Override
public void compile() {
compileVTL();
if ((Boolean) options.get(COMPILE_XDF)) {
compileXDF();
}
}
final private void compileVTL() {
// lists actors
OrccLogger.traceln("Lists actors...");
List<IFile> vtlFiles = OrccUtil.getAllFiles("ir", vtlFolders);
doVtlCodeGeneration(vtlFiles);
}
final private void compileXDF() {
// set FIFO size
ResourceSet set = new ResourceSetImpl();
// parses top network
Network network = EcoreHelper.getEObject(set, inputFile);
if (isCanceled()) {
return;
}
new NetworkValidator().doSwitch(network);
// because the UnitImporter will load additional resources, we filter
// only actors
List<Actor> actors = new ArrayList<Actor>();
for (Resource resource : set.getResources()) {
EObject eObject = resource.getContents().get(0);
if (eObject instanceof Actor) {
actors.add((Actor) eObject);
}
}
if (isCanceled()) {
return;
}
doXdfCodeGeneration(network);
}
/**
* Copy <i>source</i> file at <i>destination</i> path. If <i>destination</i>
* parents folder does not exists, they will be created
*
* @param source
* Resource file path starting with '/'. Must be an existing path
* relative to classpath (JAR file root or project classpath)
* @param destination
* Path of the target file
* @return <code>true</code> if the file has been successfully copied
*/
protected boolean copyFileToFilesystem(final String source,
final String dest) {
int bufferSize = 512;
assert source != null;
assert dest != null;
assert source.startsWith("/");
File fileOut = new File(dest);
if (!fileOut.exists()) {
try {
File parentDir = fileOut.getParentFile();
if (parentDir != null) {
parentDir.mkdirs();
}
fileOut.createNewFile();
} catch (IOException e) {
OrccLogger.warnln("Unable to write " + dest + " file");
return false;
}
}
if (!fileOut.isFile()) {
OrccLogger.warnln(dest + " is not a file path");
fileOut.delete();
return false;
}
InputStream is = this.getClass().getResourceAsStream(source);
if (is == null) {
OrccLogger.warnln("Unable to find " + source);
return false;
}
DataInputStream dis;
dis = new DataInputStream(is);
FileOutputStream out;
try {
out = new FileOutputStream(fileOut);
} catch (FileNotFoundException e1) {
OrccLogger.warnln("File " + dest + " not found !");
return false;
}
try {
byte[] b = new byte[bufferSize];
int i = is.read(b);
while (i != -1) {
out.write(b, 0, i);
i = is.read(b);
}
dis.close();
out.close();
} catch (IOException e) {
OrccLogger.warnln("IOError : " + e.getMessage());
return false;
}
return true;
}
/**
* Copy <i>source</i> folder and all its content under <i>destination</i>.
* Final '/' is not required for both parameters. If <i>destination</i> does
* not exists, it will be created
*
* @param source
* Resource folder path starting with '/'. Must be an existing
* path relative to classpath (JAR file root or project
* classpath)
* @param destination
* Filesystem folder path
* @return <code>true</code> if the folder has been successfully copied
*/
protected boolean copyFolderToFileSystem(final String source,
final String destination) {
assert source != null;
assert destination != null;
assert source.startsWith("/");
File outputDir = new File(destination);
if (!outputDir.exists()) {
if (!outputDir.mkdirs()) {
OrccLogger.warnln("Unable to create " + outputDir + " folder");
return false;
}
}
if (!outputDir.isDirectory()) {
OrccLogger.warnln(outputDir
+ " does not exists or is not a directory.");
return false;
}
String inputDir;
// Remove last '/' character (if needed)
if (source.charAt(source.length() - 1) == '/') {
inputDir = source.substring(0, source.length() - 1);
} else {
inputDir = source;
}
try {
URL toto = this.getClass().getResource(inputDir);
URL inputURL = FileLocator.resolve(toto);
String inputPath = inputURL.toString();
boolean result = true;
if (inputPath.startsWith("jar:file:")) {
// Backend running from jar file
inputPath = inputPath.substring(9, inputPath.indexOf('!'));
JarFile jar = new JarFile(inputPath);
try {
Enumeration<JarEntry> jarEntries = jar.entries();
if (jarEntries == null) {
OrccLogger.warnln("Unable to list content from "
+ jar.getName() + " file.");
return false;
}
// "source" value without starting '/' char
String sourceMinusSlash = source.substring(1);
JarEntry elt;
while (jarEntries.hasMoreElements()) {
elt = jarEntries.nextElement();
// Only deal with sub-files of 'source' path
if (elt.isDirectory()
|| !elt.getName().startsWith(sourceMinusSlash)) {
continue;
}
String newInPath = "/" + elt.getName();
String newOutPath = outputDir
+ File.separator
+ elt.getName().substring(
sourceMinusSlash.length());
result &= copyFileToFilesystem(newInPath, newOutPath);
}
return result;
} finally {
jar.close();
}
} else {
// Backend running from filesystem
File[] listDir = new File(inputPath.substring(5)).listFiles();
for (File elt : listDir) {
String newInPath = inputDir + File.separator
+ elt.getName();
String newOutPath = outputDir + File.separator
+ elt.getName();
if (elt.isDirectory()) {
result &= copyFolderToFileSystem(newInPath, newOutPath);
} else {
result &= copyFileToFilesystem(newInPath, newOutPath);
}
}
return result;
}
} catch (IOException e) {
OrccLogger.warnln("IOError" + e.getMessage());
return false;
}
}
/**
* Called when options are initialized.
*/
abstract protected void doInitializeOptions();
/**
* Transforms the given actor.
*
* @param actor
* the actor
*/
abstract protected void doTransformActor(Actor actor);
/**
* This method must be implemented by subclasses to do the actual code
* generation for VTL.
*
* @param files
* a list of IR files
*/
abstract protected void doVtlCodeGeneration(List<IFile> files);
/**
* This method must be implemented by subclasses to do the actual code
* generation for the network or its instances or both.
*
* @param network
* a network
*/
abstract protected void doXdfCodeGeneration(Network network);
/**
* Executes the given list of tasks using a thread pool with one thread per
* processor available.
*
* @param tasks
* a list of tasks
*/
private int executeTasks(List<Callable<Boolean>> tasks) {
// creates the pool
int nThreads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(nThreads);
try {
// invokes all tasks and wait for them to complete
List<Future<Boolean>> completeTasks = pool.invokeAll(tasks);
// counts number of cached actors and checks exceptions
int numCached = 0;
for (Future<Boolean> completeTask : completeTasks) {
try {
if (completeTask.get()) {
numCached++;
}
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof OrccRuntimeException) {
throw (OrccRuntimeException) e.getCause();
} else {
String msg = "";
if (e.getCause().getMessage() != null) {
msg = "(" + e.getCause().getMessage() + ")";
}
throw new OrccRuntimeException(
"One actor could not be printed " + msg,
e.getCause());
}
}
}
// shutdowns the pool
// no need to wait because tasks are completed after invokeAll
pool.shutdown();
return numCached;
} catch (InterruptedException e) {
throw new OrccRuntimeException("actors could not be printed", e);
}
}
/**
* Export runtime library used by source produced. Should be overridden by
* back-ends that produce code source which need third party libraries at
* runtime.
*
* @return <code>true</code> if the libraries were correctly exported
*/
@Override
public boolean exportRuntimeLibrary() {
return false;
}
/**
* Returns the boolean-valued attribute with the given name. Returns the
* given default value if the attribute is undefined.
*
* @param attributeName
* the name of the attribute
* @param defaultValue
* the value to use if no value is found
* @return the value or the default value if no value was found.
*/
final public boolean getAttribute(String attributeName, boolean defaultValue) {
Object obj = options.get(attributeName);
if (obj instanceof Boolean) {
return (Boolean) obj;
} else {
return defaultValue;
}
}
/**
* Returns the integer-valued attribute with the given name. Returns the
* given default value if the attribute is undefined.
*
* @param attributeName
* the name of the attribute
* @param defaultValue
* the value to use if no value is found
* @return the value or the default value if no value was found.
*/
final public int getAttribute(String attributeName, int defaultValue) {
Object obj = options.get(attributeName);
if (obj instanceof Integer) {
return (Integer) obj;
} else {
return defaultValue;
}
}
/**
* Returns the map-valued attribute with the given name. Returns the given
* default value if the attribute is undefined.
*
* @param attributeName
* the name of the attribute
* @param defaultValue
* the value to use if no value is found
* @return the value or the default value if no value was found.
*/
@SuppressWarnings("unchecked")
final public Map<String, String> getAttribute(String attributeName,
Map<String, String> defaultValue) {
Object obj = options.get(attributeName);
if (obj instanceof Map<?, ?>) {
return (Map<String, String>) obj;
} else {
return defaultValue;
}
}
/**
* Returns the string-valued attribute with the given name. Returns the
* given default value if the attribute is undefined.
*
* @param attributeName
* the name of the attribute
* @param defaultValue
* the value to use if no value is found
* @return the value or the default value if no value was found.
*/
final public String getAttribute(String attributeName, String defaultValue) {
Object obj = options.get(attributeName);
if (obj instanceof String) {
return (String) obj;
} else {
return defaultValue;
}
}
/**
* Returns a map containing the backend attributes in this launch
* configuration. Returns an empty map if the backend configuration has no
* attributes.
*
* @return a map of attribute keys and values.
*/
final public Map<String, Object> getAttributes() {
return options;
}
/**
* Returns true if this process has been canceled.
*
* @return true if this process has been canceled
*/
protected boolean isCanceled() {
if (monitor == null) {
return false;
} else {
return monitor.isCanceled();
}
}
/**
* Parses the given file list and returns a list of actors.
*
* @param files
* a list of JSON files
* @return a list of actors
*/
final public List<Actor> parseActors(List<IFile> files) {
// NOTE: the actors are parsed but are NOT put in the actor pool because
// they may be transformed and not have the same properties (in
// particular concerning types), and instantiation then complains.
OrccLogger.traceln("Parsing " + files.size() + " actors...");
ResourceSet set = new ResourceSetImpl();
List<Actor> actors = new ArrayList<Actor>();
for (IFile file : files) {
Resource resource = set.getResource(URI.createPlatformResourceURI(
file.getFullPath().toString(), true), true);
EObject eObject = resource.getContents().get(0);
if (eObject instanceof Actor) {
// do not add units
actors.add((Actor) eObject);
}
if (isCanceled()) {
break;
}
}
return actors;
}
/**
* Prints the given actor. Should be overridden by back-ends that wish to
* print the given actor.
*
* @param actor
* the actor
* @return <code>true</code> if the actor was cached
*/
protected boolean printActor(Actor actor) {
return false;
}
/**
* Print instances of the given network.
*
* @param actors
* a list of actors
*/
final public void printActors(List<Actor> actors) {
OrccLogger.traceln("Printing actors...");
long t0 = System.currentTimeMillis();
// creates a list of tasks: each task will print an actor when called
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
for (final Actor actor : actors) {
tasks.add(new Callable<Boolean>() {
@Override
public Boolean call() {
if (isCanceled()) {
return false;
}
return printActor(actor);
}
});
}
// executes the tasks
int numCached = executeTasks(tasks);
long t1 = System.currentTimeMillis();
OrccLogger.traceln("Done in " + ((float) (t1 - t0) / (float) 1000)
+ "s");
if (numCached > 0) {
OrccLogger
.traceln("*******************************************************************************");
OrccLogger.traceln("* NOTE: " + numCached
+ " actors were not regenerated "
+ "because they were already up-to-date. *");
OrccLogger
.traceln("*******************************************************************************");
}
}
/**
* Print entities of the given network.
*
* @param entities
* a list of entities
*/
final public void printEntities(Network network) {
OrccLogger.traceln("Printing entities...");
long t0 = System.currentTimeMillis();
// creates a list of tasks: each task will print an actor when called
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
for (final Vertex vertex : network.getChildren()) {
tasks.add(new Callable<Boolean>() {
@Override
public Boolean call() {
if (isCanceled()) {
return false;
}
return printEntity(vertex);
}
});
}
// executes the tasks
int numCached = executeTasks(tasks);
long t1 = System.currentTimeMillis();
OrccLogger.traceln("Done in " + ((float) (t1 - t0) / (float) 1000)
+ "s");
if (numCached > 0) {
OrccLogger
.traceln("*******************************************************************************");
OrccLogger.traceln("* NOTE: " + numCached
+ " entities were not regenerated "
+ "because they were already up-to-date. *");
OrccLogger
.traceln("*******************************************************************************");
}
}
/**
* Prints the given entity. Should be overridden by back-ends that wish to
* print the given entity.
*
* @param entity
* the entity
* @return <code>true</code> if the actor was cached
*/
protected boolean printEntity(Vertex entity) {
return false;
}
/**
* Prints the given instance. Should be overridden by back-ends that wish to
* print the given instance.
*
* @param instance
* the instance
* @return <code>true</code> if the actor was cached
*/
protected boolean printInstance(Instance instance) {
return false;
}
/**
* Print instances of the given network.
*
* @param network
* a network
* @throws OrccException
*/
final public void printInstances(Network network) {
OrccLogger.traceln("Printing instances...");
long t0 = System.currentTimeMillis();
// creates a list of tasks: each task will print an instance when called
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
for (Vertex vertex : network.getChildren()) {
final Instance instance = vertex.getAdapter(Instance.class);
if (instance != null) {
tasks.add(new Callable<Boolean>() {
@Override
public Boolean call() {
return printInstance(instance);
}
});
}
}
// executes the tasks
int numCached = executeTasks(tasks);
long t1 = System.currentTimeMillis();
OrccLogger.traceln("Done in " + ((float) (t1 - t0) / (float) 1000)
+ "s");
if (numCached > 0) {
OrccLogger
.traceln("*******************************************************************************");
OrccLogger.traceln("* NOTE: " + numCached
+ " instances were not regenerated "
+ "because they were already up-to-date. *");
OrccLogger
.traceln("*******************************************************************************");
}
}
private void printUsage(IApplicationContext context, Options options,
String parserMsg) {
String footer = "";
if (parserMsg != null && !parserMsg.isEmpty()) {
footer = "\nMessage of the command line parser :\n" + parserMsg;
}
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.setWidth(80);
helpFormatter.printHelp(getClass().getSimpleName()
+ " [options] <network.qualified.name>", "Valid options are :",
options, footer);
}
@Override
public void setOptions(Map<String, Object> options) {
this.options = options;
String name = getAttribute(PROJECT, "");
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
project = root.getProject(name);
vtlFolders = OrccUtil.getOutputFolders(project);
inputFile = getFile(project, getAttribute(XDF_FILE, ""), "xdf");
fifoSize = getAttribute(FIFO_SIZE, DEFAULT_FIFO_SIZE);
debug = getAttribute(DEBUG_MODE, true);
mapping = getAttribute(MAPPING, new HashMap<String, String>());
classify = getAttribute(CLASSIFY, false);
// Merging transformations need the results of classification
mergeActions = classify && getAttribute(MERGE_ACTIONS, false);
mergeActors = classify && getAttribute(MERGE_ACTORS, false);
convertMulti2Mono = getAttribute("net.sf.orcc.backends.multi2mono",
false);
String outputFolder;
Object obj = options.get(OUTPUT_FOLDER);
if (obj instanceof String) {
outputFolder = (String) obj;
if (outputFolder.startsWith("~")) {
outputFolder = outputFolder.replace("~",
System.getProperty("user.home"));
}
} else {
outputFolder = "";
}
if (outputFolder.isEmpty()) {
String tmpdir = System.getProperty("java.io.tmpdir");
File output = new File(tmpdir, "orcc");
output.mkdir();
outputFolder = output.getAbsolutePath();
}
// set output path
path = new File(outputFolder).getAbsolutePath();
doInitializeOptions();
}
@Override
public void setProgressMonitor(IProgressMonitor monitor) {
this.monitor = monitor;
}
@Override
public Object start(IApplicationContext context) throws Exception {
Options options = new Options();
Option opt;
// Required command line arguments
opt = new Option("p", "project", true, "Project name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("o", "output", true, "Output folder");
opt.setRequired(true);
options.addOption(opt);
// Optional command line arguments
options.addOption("d", "debug", false, "Enable debug mode");
options.addOption("c", "classify", false, "Classify the given network");
options.addOption("smt", "smt-solver", true,
"Set path to the binary of the SMT solver (Z3 v4.12+)");
- options.addOption("m", "merge", false, "Merge (1) static actions "
+ options.addOption("m", "merge", true, "Merge (1) static actions "
+ "(2) static actors (3) both");
options.addOption("s", "advanced-scheduler", false, "(C) Use the "
+ "data-driven/demand-driven strategy for the actor-scheduler");
options.addOption("m2m", "multi2mono", false,
"Transform high-level actors with multi-tokens actions"
+ " in low-level actors with mono-token actions");
// FIXME: choose independently the transformation to apply
options.addOption("t", "transfo_add", false,
"Execute additional transformations before generate code");
try {
CommandLineParser parser = new PosixParser();
// parse the command line arguments
CommandLine line = parser.parse(options, (String[]) context
.getArguments().get(IApplicationContext.APPLICATION_ARGS));
if (line.getArgs().length != 1) {
throw new ParseException(
"Expected network name as last argument");
}
String networkName = line.getArgs()[0];
Map<String, Object> optionMap = new HashMap<String, Object>();
optionMap.put(COMPILE_XDF, true);
optionMap.put(PROJECT, line.getOptionValue('p'));
optionMap.put(XDF_FILE, networkName);
optionMap.put(OUTPUT_FOLDER, line.getOptionValue('o'));
optionMap.put(DEBUG_MODE, line.hasOption('d'));
optionMap.put(CLASSIFY, line.hasOption('c'));
if (line.hasOption("smt")) {
String smt_path = line.getOptionValue("smt");
String smt_option = new String();
if (smt_path.contains("z3")) {
if (Platform.OS_WIN32.equals(Platform.getOS())) {
smt_option = "/smt2";
} else {
smt_option = "-smt2";
}
getDefault().setPreference(P_SOLVER, smt_path);
getDefault().setPreference(P_SOLVER_OPTIONS, smt_option);
} else {
OrccLogger.warnln("Unknown SMT solver.");
}
}
if (line.hasOption('m')) {
String type = line.getOptionValue('m');
optionMap.put(MERGE_ACTIONS,
type.equals("1") || type.equals("3"));
optionMap.put(MERGE_ACTORS,
type.equals("2") || type.equals("3"));
}
optionMap.put("net.sf.orcc.backends.newScheduler",
line.hasOption('s'));
optionMap.put("net.sf.orcc.backends.multi2mono",
line.hasOption("m2m"));
optionMap.put("net.sf.orcc.backends.additionalTransfos",
line.hasOption('t'));
try {
setOptions(optionMap);
exportRuntimeLibrary();
compile();
return IApplication.EXIT_OK;
} catch (OrccRuntimeException e) {
OrccLogger.severeln(e.getMessage());
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
} catch (Exception e) {
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
e.printStackTrace();
}
return IApplication.EXIT_RELAUNCH;
} catch (UnrecognizedOptionException uoe) {
printUsage(context, options, uoe.getLocalizedMessage());
} catch (ParseException exp) {
printUsage(context, options, exp.getLocalizedMessage());
}
return IApplication.EXIT_RELAUNCH;
}
@Override
public void stop() {
}
/**
* Transforms instances of the given network.
*
* @param actors
* a list of actors
* @throws OrccException
*/
final public void transformActors(List<Actor> actors) {
OrccLogger.traceln("Transforming actors...");
for (Actor actor : actors) {
doTransformActor(actor);
}
}
}
| true | true | public Object start(IApplicationContext context) throws Exception {
Options options = new Options();
Option opt;
// Required command line arguments
opt = new Option("p", "project", true, "Project name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("o", "output", true, "Output folder");
opt.setRequired(true);
options.addOption(opt);
// Optional command line arguments
options.addOption("d", "debug", false, "Enable debug mode");
options.addOption("c", "classify", false, "Classify the given network");
options.addOption("smt", "smt-solver", true,
"Set path to the binary of the SMT solver (Z3 v4.12+)");
options.addOption("m", "merge", false, "Merge (1) static actions "
+ "(2) static actors (3) both");
options.addOption("s", "advanced-scheduler", false, "(C) Use the "
+ "data-driven/demand-driven strategy for the actor-scheduler");
options.addOption("m2m", "multi2mono", false,
"Transform high-level actors with multi-tokens actions"
+ " in low-level actors with mono-token actions");
// FIXME: choose independently the transformation to apply
options.addOption("t", "transfo_add", false,
"Execute additional transformations before generate code");
try {
CommandLineParser parser = new PosixParser();
// parse the command line arguments
CommandLine line = parser.parse(options, (String[]) context
.getArguments().get(IApplicationContext.APPLICATION_ARGS));
if (line.getArgs().length != 1) {
throw new ParseException(
"Expected network name as last argument");
}
String networkName = line.getArgs()[0];
Map<String, Object> optionMap = new HashMap<String, Object>();
optionMap.put(COMPILE_XDF, true);
optionMap.put(PROJECT, line.getOptionValue('p'));
optionMap.put(XDF_FILE, networkName);
optionMap.put(OUTPUT_FOLDER, line.getOptionValue('o'));
optionMap.put(DEBUG_MODE, line.hasOption('d'));
optionMap.put(CLASSIFY, line.hasOption('c'));
if (line.hasOption("smt")) {
String smt_path = line.getOptionValue("smt");
String smt_option = new String();
if (smt_path.contains("z3")) {
if (Platform.OS_WIN32.equals(Platform.getOS())) {
smt_option = "/smt2";
} else {
smt_option = "-smt2";
}
getDefault().setPreference(P_SOLVER, smt_path);
getDefault().setPreference(P_SOLVER_OPTIONS, smt_option);
} else {
OrccLogger.warnln("Unknown SMT solver.");
}
}
if (line.hasOption('m')) {
String type = line.getOptionValue('m');
optionMap.put(MERGE_ACTIONS,
type.equals("1") || type.equals("3"));
optionMap.put(MERGE_ACTORS,
type.equals("2") || type.equals("3"));
}
optionMap.put("net.sf.orcc.backends.newScheduler",
line.hasOption('s'));
optionMap.put("net.sf.orcc.backends.multi2mono",
line.hasOption("m2m"));
optionMap.put("net.sf.orcc.backends.additionalTransfos",
line.hasOption('t'));
try {
setOptions(optionMap);
exportRuntimeLibrary();
compile();
return IApplication.EXIT_OK;
} catch (OrccRuntimeException e) {
OrccLogger.severeln(e.getMessage());
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
} catch (Exception e) {
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
e.printStackTrace();
}
return IApplication.EXIT_RELAUNCH;
} catch (UnrecognizedOptionException uoe) {
printUsage(context, options, uoe.getLocalizedMessage());
} catch (ParseException exp) {
printUsage(context, options, exp.getLocalizedMessage());
}
return IApplication.EXIT_RELAUNCH;
}
| public Object start(IApplicationContext context) throws Exception {
Options options = new Options();
Option opt;
// Required command line arguments
opt = new Option("p", "project", true, "Project name");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("o", "output", true, "Output folder");
opt.setRequired(true);
options.addOption(opt);
// Optional command line arguments
options.addOption("d", "debug", false, "Enable debug mode");
options.addOption("c", "classify", false, "Classify the given network");
options.addOption("smt", "smt-solver", true,
"Set path to the binary of the SMT solver (Z3 v4.12+)");
options.addOption("m", "merge", true, "Merge (1) static actions "
+ "(2) static actors (3) both");
options.addOption("s", "advanced-scheduler", false, "(C) Use the "
+ "data-driven/demand-driven strategy for the actor-scheduler");
options.addOption("m2m", "multi2mono", false,
"Transform high-level actors with multi-tokens actions"
+ " in low-level actors with mono-token actions");
// FIXME: choose independently the transformation to apply
options.addOption("t", "transfo_add", false,
"Execute additional transformations before generate code");
try {
CommandLineParser parser = new PosixParser();
// parse the command line arguments
CommandLine line = parser.parse(options, (String[]) context
.getArguments().get(IApplicationContext.APPLICATION_ARGS));
if (line.getArgs().length != 1) {
throw new ParseException(
"Expected network name as last argument");
}
String networkName = line.getArgs()[0];
Map<String, Object> optionMap = new HashMap<String, Object>();
optionMap.put(COMPILE_XDF, true);
optionMap.put(PROJECT, line.getOptionValue('p'));
optionMap.put(XDF_FILE, networkName);
optionMap.put(OUTPUT_FOLDER, line.getOptionValue('o'));
optionMap.put(DEBUG_MODE, line.hasOption('d'));
optionMap.put(CLASSIFY, line.hasOption('c'));
if (line.hasOption("smt")) {
String smt_path = line.getOptionValue("smt");
String smt_option = new String();
if (smt_path.contains("z3")) {
if (Platform.OS_WIN32.equals(Platform.getOS())) {
smt_option = "/smt2";
} else {
smt_option = "-smt2";
}
getDefault().setPreference(P_SOLVER, smt_path);
getDefault().setPreference(P_SOLVER_OPTIONS, smt_option);
} else {
OrccLogger.warnln("Unknown SMT solver.");
}
}
if (line.hasOption('m')) {
String type = line.getOptionValue('m');
optionMap.put(MERGE_ACTIONS,
type.equals("1") || type.equals("3"));
optionMap.put(MERGE_ACTORS,
type.equals("2") || type.equals("3"));
}
optionMap.put("net.sf.orcc.backends.newScheduler",
line.hasOption('s'));
optionMap.put("net.sf.orcc.backends.multi2mono",
line.hasOption("m2m"));
optionMap.put("net.sf.orcc.backends.additionalTransfos",
line.hasOption('t'));
try {
setOptions(optionMap);
exportRuntimeLibrary();
compile();
return IApplication.EXIT_OK;
} catch (OrccRuntimeException e) {
OrccLogger.severeln(e.getMessage());
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
} catch (Exception e) {
OrccLogger.severeln("Could not run the back-end with \""
+ networkName + "\" :");
OrccLogger.severeln(e.getLocalizedMessage());
e.printStackTrace();
}
return IApplication.EXIT_RELAUNCH;
} catch (UnrecognizedOptionException uoe) {
printUsage(context, options, uoe.getLocalizedMessage());
} catch (ParseException exp) {
printUsage(context, options, exp.getLocalizedMessage());
}
return IApplication.EXIT_RELAUNCH;
}
|
diff --git a/axis2/src/main/java/org/apache/ode/axis2/ExternalService.java b/axis2/src/main/java/org/apache/ode/axis2/ExternalService.java
index c8c29aa7..8a7bd642 100644
--- a/axis2/src/main/java/org/apache/ode/axis2/ExternalService.java
+++ b/axis2/src/main/java/org/apache/ode/axis2/ExternalService.java
@@ -1,176 +1,182 @@
/*
* 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.ode.axis2;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.axis2.util.OMUtils;
import org.apache.ode.axis2.util.SOAPUtils;
import org.apache.ode.bpel.epr.EndpointFactory;
import org.apache.ode.bpel.epr.MutableEndpoint;
import org.apache.ode.bpel.epr.WSAEndpoint;
import org.apache.ode.bpel.iapi.Message;
import org.apache.ode.bpel.iapi.MessageExchange;
import org.apache.ode.bpel.iapi.PartnerRoleChannel;
import org.apache.ode.bpel.iapi.PartnerRoleMessageExchange;
import org.apache.ode.utils.DOMUtils;
import org.w3c.dom.Element;
import javax.wsdl.Definition;
import javax.xml.namespace.QName;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
/**
* Acts as a service not provided by ODE. Used mainly for invocation as a way to
* maintain the WSDL decription of used services.
*/
public class ExternalService implements PartnerRoleChannel {
private static final Log __log = LogFactory.getLog(ExternalService.class);
private ExecutorService _executorService;
private Definition _definition;
private QName _serviceName;
private String _portName;
private AxisConfiguration _axisConfig;
public ExternalService(Definition definition, QName serviceName,
String portName, ExecutorService executorService, AxisConfiguration axisConfig) {
_definition = definition;
_serviceName = serviceName;
_portName = portName;
_executorService = executorService;
_axisConfig = axisConfig;
}
public void invoke(final PartnerRoleMessageExchange odeMex) {
boolean isTwoWay = odeMex.getMessageExchangePattern() ==
org.apache.ode.bpel.iapi.MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
try {
Element msgContent = SOAPUtils.wrap(odeMex.getRequest().getMessage(), _definition, _serviceName,
odeMex.getOperation(), odeMex.getOperation().getInput().getMessage());
final OMElement payload = OMUtils.toOM(msgContent);
Options options = new Options();
EndpointReference axisEPR = new EndpointReference(((MutableEndpoint)odeMex.getEndpointReference()).getUrl());
__log.debug("Axis2 sending message to " + axisEPR.getAddress() + " using MEX " + odeMex);
__log.debug("Message: " + payload);
options.setTo(axisEPR);
ConfigurationContext ctx = new ConfigurationContext(_axisConfig);
final ServiceClient serviceClient = new ServiceClient(ctx, null);
serviceClient.setOptions(options);
// Override options are passed to the axis MessageContext so we can
// retrieve them in our session out handler.
Options mexOptions = new Options();
writeHeader(mexOptions, odeMex);
serviceClient.setOverrideOptions(mexOptions);
if (isTwoWay) {
// Invoking in a separate thread even though we're supposed to wait for a synchronous reply
// to force clear transaction separation.
Future<OMElement> freply = _executorService.submit(new Callable<OMElement>() {
public OMElement call() throws Exception {
return serviceClient.sendReceive(payload);
}
});
- OMElement reply = null;
+ OMElement reply;
try {
reply = freply.get();
- final Message response = odeMex.createMessage(odeMex.getOperation().getOutput().getMessage().getQName());
- Element responseElmt = OMUtils.toDOM(reply);
- responseElmt = SOAPUtils.unwrap(responseElmt, _definition,
- odeMex.getOperation().getOutput().getMessage(), _serviceName);
- __log.debug("Received synchronous response for MEX " + odeMex);
- __log.debug("Message: " + DOMUtils.domToString(responseElmt));
- response.setMessage(responseElmt);
- odeMex.reply(response);
+ if (reply == null) {
+ String errmsg = "Received empty (null) reply for ODE mex " + odeMex;
+ __log.error(errmsg);
+ odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
+ } else {
+ Message response = odeMex.createMessage(odeMex.getOperation().getOutput().getMessage().getQName());
+ Element responseElmt = OMUtils.toDOM(reply);
+ responseElmt = SOAPUtils.unwrap(responseElmt, _definition,
+ odeMex.getOperation().getOutput().getMessage(), _serviceName);
+ __log.debug("Received synchronous response for MEX " + odeMex);
+ __log.debug("Message: " + DOMUtils.domToString(responseElmt));
+ response.setMessage(responseElmt);
+ odeMex.reply(response);
+ }
} catch (Exception e) {
- __log.error("We've been interrupted while waiting for reply to MEX " + odeMex + "!!!");
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
- } else
+ } else /** one-way case **/ {
serviceClient.fireAndForget(payload);
+ }
} catch (AxisFault axisFault) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, axisFault);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
}
/**
* Extracts endpoint information from ODE message exchange to stuff them into
* Axis MessageContext.
*/
private void writeHeader(Options options, PartnerRoleMessageExchange odeMex) {
WSAEndpoint targetEPR = EndpointFactory.convertToWSA((MutableEndpoint) odeMex.getEndpointReference());
WSAEndpoint myRoleEPR = EndpointFactory.convertToWSA((MutableEndpoint) odeMex.getMyRoleEndpointReference());
String partnerSessionId = odeMex.getProperty(MessageExchange.PROPERTY_SEP_PARTNERROLE_SESSIONID);
String myRoleSessionId = odeMex.getProperty(MessageExchange.PROPERTY_SEP_MYROLE_SESSIONID);
if (partnerSessionId != null) {
__log.debug("Partner session identifier found for WSA endpoint: " + partnerSessionId);
targetEPR.setSessionId(partnerSessionId);
}
options.setProperty("targetSessionEndpoint", targetEPR);
String soapAction = SOAPUtils.getSoapAction(_definition, _serviceName, _portName,
odeMex.getOperationName());
options.setProperty("soapAction", soapAction);
if (myRoleEPR != null) {
if (myRoleSessionId != null) {
__log.debug("MyRole session identifier found for myrole (callback) WSA endpoint: " + myRoleSessionId);
myRoleEPR.setSessionId(myRoleSessionId);
}
options.setProperty("callbackSessionEndpoint", odeMex.getMyRoleEndpointReference());
} else {
__log.debug("My-Role EPR not specified, SEP will not be used.");
}
}
public org.apache.ode.bpel.iapi.EndpointReference getInitialEndpointReference() {
Element eprElmt = ODEService.genEPRfromWSDL(_definition, _serviceName, _portName);
if (eprElmt == null)
throw new IllegalArgumentException("Service " + _serviceName + " and port " + _portName +
"couldn't be found in provided WSDL document!");
return EndpointFactory.convertToWSA(ODEService.createServiceRef(eprElmt));
}
public void close() {
// TODO Auto-generated method stub
}
}
| false | true | public void invoke(final PartnerRoleMessageExchange odeMex) {
boolean isTwoWay = odeMex.getMessageExchangePattern() ==
org.apache.ode.bpel.iapi.MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
try {
Element msgContent = SOAPUtils.wrap(odeMex.getRequest().getMessage(), _definition, _serviceName,
odeMex.getOperation(), odeMex.getOperation().getInput().getMessage());
final OMElement payload = OMUtils.toOM(msgContent);
Options options = new Options();
EndpointReference axisEPR = new EndpointReference(((MutableEndpoint)odeMex.getEndpointReference()).getUrl());
__log.debug("Axis2 sending message to " + axisEPR.getAddress() + " using MEX " + odeMex);
__log.debug("Message: " + payload);
options.setTo(axisEPR);
ConfigurationContext ctx = new ConfigurationContext(_axisConfig);
final ServiceClient serviceClient = new ServiceClient(ctx, null);
serviceClient.setOptions(options);
// Override options are passed to the axis MessageContext so we can
// retrieve them in our session out handler.
Options mexOptions = new Options();
writeHeader(mexOptions, odeMex);
serviceClient.setOverrideOptions(mexOptions);
if (isTwoWay) {
// Invoking in a separate thread even though we're supposed to wait for a synchronous reply
// to force clear transaction separation.
Future<OMElement> freply = _executorService.submit(new Callable<OMElement>() {
public OMElement call() throws Exception {
return serviceClient.sendReceive(payload);
}
});
OMElement reply = null;
try {
reply = freply.get();
final Message response = odeMex.createMessage(odeMex.getOperation().getOutput().getMessage().getQName());
Element responseElmt = OMUtils.toDOM(reply);
responseElmt = SOAPUtils.unwrap(responseElmt, _definition,
odeMex.getOperation().getOutput().getMessage(), _serviceName);
__log.debug("Received synchronous response for MEX " + odeMex);
__log.debug("Message: " + DOMUtils.domToString(responseElmt));
response.setMessage(responseElmt);
odeMex.reply(response);
} catch (Exception e) {
__log.error("We've been interrupted while waiting for reply to MEX " + odeMex + "!!!");
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
} else
serviceClient.fireAndForget(payload);
} catch (AxisFault axisFault) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, axisFault);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
}
| public void invoke(final PartnerRoleMessageExchange odeMex) {
boolean isTwoWay = odeMex.getMessageExchangePattern() ==
org.apache.ode.bpel.iapi.MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
try {
Element msgContent = SOAPUtils.wrap(odeMex.getRequest().getMessage(), _definition, _serviceName,
odeMex.getOperation(), odeMex.getOperation().getInput().getMessage());
final OMElement payload = OMUtils.toOM(msgContent);
Options options = new Options();
EndpointReference axisEPR = new EndpointReference(((MutableEndpoint)odeMex.getEndpointReference()).getUrl());
__log.debug("Axis2 sending message to " + axisEPR.getAddress() + " using MEX " + odeMex);
__log.debug("Message: " + payload);
options.setTo(axisEPR);
ConfigurationContext ctx = new ConfigurationContext(_axisConfig);
final ServiceClient serviceClient = new ServiceClient(ctx, null);
serviceClient.setOptions(options);
// Override options are passed to the axis MessageContext so we can
// retrieve them in our session out handler.
Options mexOptions = new Options();
writeHeader(mexOptions, odeMex);
serviceClient.setOverrideOptions(mexOptions);
if (isTwoWay) {
// Invoking in a separate thread even though we're supposed to wait for a synchronous reply
// to force clear transaction separation.
Future<OMElement> freply = _executorService.submit(new Callable<OMElement>() {
public OMElement call() throws Exception {
return serviceClient.sendReceive(payload);
}
});
OMElement reply;
try {
reply = freply.get();
if (reply == null) {
String errmsg = "Received empty (null) reply for ODE mex " + odeMex;
__log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
} else {
Message response = odeMex.createMessage(odeMex.getOperation().getOutput().getMessage().getQName());
Element responseElmt = OMUtils.toDOM(reply);
responseElmt = SOAPUtils.unwrap(responseElmt, _definition,
odeMex.getOperation().getOutput().getMessage(), _serviceName);
__log.debug("Received synchronous response for MEX " + odeMex);
__log.debug("Message: " + DOMUtils.domToString(responseElmt));
response.setMessage(responseElmt);
odeMex.reply(response);
}
} catch (Exception e) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
} else /** one-way case **/ {
serviceClient.fireAndForget(payload);
}
} catch (AxisFault axisFault) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, axisFault);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
}
|
diff --git a/src/com/android/deskclock/timer/CountingTimerView.java b/src/com/android/deskclock/timer/CountingTimerView.java
index 58b89675..54b11552 100644
--- a/src/com/android/deskclock/timer/CountingTimerView.java
+++ b/src/com/android/deskclock/timer/CountingTimerView.java
@@ -1,315 +1,307 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.deskclock.timer;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import com.android.deskclock.R;
public class CountingTimerView extends View {
private static final String TWO_DIGITS = "%02d";
private static final String ONE_DIGIT = "%01d";
private static final String NEG_TWO_DIGITS = "-%02d";
private static final String NEG_ONE_DIGIT = "-%01d";
private static final float TEXT_SIZE_TO_WIDTH_RATIO = 0.75f;
// This is the ratio of the font typeface we need to offset the font by vertically to align it
// vertically center.
private static final float FONT_VERTICAL_OFFSET = 0.14f;
private String mHours, mMinutes, mSeconds, mHunderdths;
private final String mHoursLabel, mMinutesLabel, mSecondsLabel;
private float mHoursWidth, mMinutesWidth, mSecondsWidth, mHundredthsWidth;
private float mHoursLabelWidth, mMinutesLabelWidth, mSecondsLabelWidth, mHundredthsSepWidth;
private boolean mShowTimeStr = true;
private final Typeface mRobotoThin, mRobotoBold, mRobotoLabel;
private final Paint mPaintBig = new Paint();
private final Paint mPaintBigThin = new Paint();
private final Paint mPaintMed = new Paint();
private final Paint mPaintLabel = new Paint();
private float mTextHeight = 0;
private float mTotalTextWidth;
private static final String HUNDREDTH_SEPERATOR = ".";
private boolean mRemeasureText = true;
Runnable mBlinkThread = new Runnable() {
@Override
public void run() {
mShowTimeStr = !mShowTimeStr;
CountingTimerView.this.setVisibility(mShowTimeStr ? View.VISIBLE : View.INVISIBLE);
CountingTimerView.this.invalidate();
mRemeasureText = true;
postDelayed(mBlinkThread, 500);
}
};
public CountingTimerView(Context context) {
this(context, null);
}
public CountingTimerView(Context context, AttributeSet attrs) {
super(context, attrs);
mRobotoThin = Typeface.createFromAsset(context.getAssets(),"fonts/Roboto-Thin.ttf");
mRobotoBold = Typeface.create("sans-serif", Typeface.BOLD);
mRobotoLabel= Typeface.create("sans-serif-condensed", Typeface.BOLD);
Resources r = context.getResources();
mHoursLabel = r.getString(R.string.hours_label).toUpperCase();
mMinutesLabel = r.getString(R.string.minutes_label).toUpperCase();
mSecondsLabel = r.getString(R.string.seconds_label).toUpperCase();
mPaintBig.setAntiAlias(true);
mPaintBig.setStyle(Paint.Style.STROKE);
mPaintBig.setColor(r.getColor(R.color.clock_white));
mPaintBig.setTextAlign(Paint.Align.LEFT);
mPaintBig.setTypeface(mRobotoBold);
float bigFontSize = r.getDimension(R.dimen.big_font_size);
mPaintBig.setTextSize(bigFontSize);
mTextHeight = bigFontSize;
mPaintBigThin.setAntiAlias(true);
mPaintBigThin.setStyle(Paint.Style.STROKE);
mPaintBigThin.setColor(r.getColor(R.color.clock_white));
mPaintBigThin.setTextAlign(Paint.Align.LEFT);
mPaintBigThin.setTypeface(mRobotoThin);
mPaintBigThin.setTextSize(r.getDimension(R.dimen.big_font_size));
mPaintMed.setAntiAlias(true);
mPaintMed.setStyle(Paint.Style.STROKE);
mPaintMed.setColor(r.getColor(R.color.clock_white));
mPaintMed.setTextAlign(Paint.Align.LEFT);
mPaintMed.setTypeface(mRobotoThin);
mPaintMed.setTextSize(r.getDimension(R.dimen.small_font_size));
mPaintLabel.setAntiAlias(true);
mPaintLabel.setStyle(Paint.Style.STROKE);
mPaintLabel.setColor(r.getColor(R.color.clock_white));
mPaintLabel.setTextAlign(Paint.Align.LEFT);
mPaintLabel.setTypeface(mRobotoLabel);
mPaintLabel.setTextSize(r.getDimension(R.dimen.label_font_size));
}
public void setTime(long time, boolean showHundredths, boolean update) {
boolean neg = false, showNeg = false;
String format = null;
if (time < 0) {
time = -time;
neg = showNeg = true;
}
long hundreds, seconds, minutes, hours;
seconds = time / 1000;
hundreds = (time - seconds * 1000) / 10;
minutes = seconds / 60;
seconds = seconds - minutes * 60;
hours = minutes / 60;
minutes = minutes - hours * 60;
if (hours > 99) {
hours = 0;
}
// time may less than a second below zero, since we do not show fractions of seconds
// when counting down, do not show the minus sign.
if (hours ==0 && minutes == 0 && seconds == 0) {
showNeg = false;
}
// TODO: must build to account for localization
if (!showHundredths) {
if (!neg && hundreds != 0) {
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
}
}
}
if (hundreds < 10 || hundreds > 90) {
update = true;
}
}
if (hours >= 10) {
format = showNeg ? NEG_TWO_DIGITS : TWO_DIGITS;
mHours = String.format(format, hours);
} else if (hours > 0) {
format = showNeg ? NEG_ONE_DIGIT : ONE_DIGIT;
mHours = String.format(format, hours);
} else {
mHours = null;
}
if (minutes >= 10 || hours > 0) {
format = (showNeg && hours == 0) ? NEG_TWO_DIGITS : TWO_DIGITS;
mMinutes = String.format(format, minutes);
} else {
format = (showNeg && hours == 0) ? NEG_ONE_DIGIT : ONE_DIGIT;
mMinutes = String.format(format, minutes);
}
- if (!showHundredths) {
- if (!neg && hundreds != 0) {
- seconds++;
- }
- if (hundreds < 10 || hundreds > 90) {
- update = true;
- }
- }
mSeconds = String.format(TWO_DIGITS, seconds);
if (showHundredths) {
mHunderdths = String.format(TWO_DIGITS, hundreds);
} else {
mHunderdths = null;
}
mRemeasureText = true;
if (update) {
invalidate();
}
}
private void setTotalTextWidth() {
mTotalTextWidth = 0;
if (mHours != null) {
mHoursWidth = mPaintBig.measureText(mHours);
mTotalTextWidth += mHoursWidth;
mHoursLabelWidth = mPaintLabel.measureText(mHoursLabel);
mTotalTextWidth += mHoursLabelWidth;
}
if (mMinutes != null) {
mMinutesWidth = mPaintBig.measureText(mMinutes);
mTotalTextWidth += mMinutesWidth;
mMinutesLabelWidth = mPaintLabel.measureText(mMinutesLabel);
mTotalTextWidth += mMinutesLabelWidth;
}
if (mSeconds != null) {
mSecondsWidth = mPaintBigThin.measureText(mSeconds);
mTotalTextWidth += mSecondsWidth;
mSecondsLabelWidth = mPaintLabel.measureText(mSecondsLabel);
mTotalTextWidth += mSecondsLabelWidth;
}
if (mHunderdths != null) {
mHundredthsWidth = mPaintMed.measureText(mHunderdths);
mTotalTextWidth += mHundredthsWidth;
mHundredthsSepWidth = mPaintLabel.measureText(HUNDREDTH_SEPERATOR);
mTotalTextWidth += mHundredthsSepWidth;
}
// This is a hack: if the text is too wide, reduce all the paint text sizes
// To determine the maximum width, we find the minimum of the height and width (since the
// circle we are trying to fit the text into has its radius sized to the smaller of the
// two.
int width = Math.min(getWidth(), getHeight());
if (width != 0) {
float ratio = mTotalTextWidth / width;
if (ratio > TEXT_SIZE_TO_WIDTH_RATIO) {
float sizeRatio = (TEXT_SIZE_TO_WIDTH_RATIO / ratio);
mPaintBig.setTextSize( mPaintBig.getTextSize() * sizeRatio);
mPaintBigThin.setTextSize( mPaintBigThin.getTextSize() * sizeRatio);
mPaintMed.setTextSize( mPaintMed.getTextSize() * sizeRatio);
mTotalTextWidth *= sizeRatio;
mMinutesWidth *= sizeRatio;
mHoursWidth *= sizeRatio;
mSecondsWidth *= sizeRatio;
mHundredthsWidth *= sizeRatio;
mHundredthsSepWidth *= sizeRatio;
//recalculate the new total text width and half text height
mTotalTextWidth = mHoursWidth + mMinutesWidth + mSecondsWidth +
mHundredthsWidth + mHundredthsSepWidth + mHoursLabelWidth +
mMinutesLabelWidth + mSecondsLabelWidth;
mTextHeight = mPaintBig.getTextSize();
}
}
}
public void setTime(String hours, String minutes, String seconds, String hundreds) {
mHours = hours;
mMinutes = minutes;
mSeconds = seconds;
mHunderdths = hundreds;
mRemeasureText = true;
invalidate();
}
public void blinkTimeStr(boolean blink) {
if (blink) {
removeCallbacks(mBlinkThread);
postDelayed(mBlinkThread, 1000);
} else {
removeCallbacks(mBlinkThread);
mShowTimeStr = true;
this.setVisibility(View.VISIBLE);
}
}
public String getTimeString() {
if (mHours == null) {
return String.format("%s:%s.%s",mMinutes, mSeconds, mHunderdths);
}
return String.format("%s:%s:%s.%s",mHours, mMinutes, mSeconds, mHunderdths);
}
@Override
public void onDraw(Canvas canvas) {
int width = getWidth();
if (mRemeasureText && width != 0) {
setTotalTextWidth();
width = getWidth();
mRemeasureText = false;
}
int xCenter = width / 2;
int yCenter = getHeight() / 2;
float textXstart = xCenter - mTotalTextWidth / 2;
float textYstart = yCenter + mTextHeight/2 - (mTextHeight * FONT_VERTICAL_OFFSET);
// align the labels vertically to the top of the rest of the text
float labelYStart = textYstart - (mTextHeight * (1 - 2 * FONT_VERTICAL_OFFSET))
+ (1 - 2 * FONT_VERTICAL_OFFSET) * mPaintLabel.getTextSize();
if (mHours != null) {
canvas.drawText(mHours, textXstart, textYstart, mPaintBig);
textXstart += mHoursWidth;
canvas.drawText(mHoursLabel, textXstart, labelYStart, mPaintLabel);
textXstart += mHoursLabelWidth;
}
if (mMinutes != null) {
canvas.drawText(mMinutes, textXstart, textYstart, mPaintBig);
textXstart += mMinutesWidth;
canvas.drawText(mMinutesLabel, textXstart, labelYStart, mPaintLabel);
textXstart += mMinutesLabelWidth;
}
if (mSeconds != null) {
canvas.drawText(mSeconds, textXstart, textYstart, mPaintBigThin);
textXstart += mSecondsWidth;
canvas.drawText(mSecondsLabel, textXstart, labelYStart, mPaintLabel);
textXstart += mSecondsLabelWidth;
}
if (mHunderdths != null) {
canvas.drawText(HUNDREDTH_SEPERATOR, textXstart, textYstart, mPaintLabel);
textXstart += mHundredthsSepWidth;
canvas.drawText(mHunderdths, textXstart, textYstart, mPaintMed);
}
}
}
| true | true | public void setTime(long time, boolean showHundredths, boolean update) {
boolean neg = false, showNeg = false;
String format = null;
if (time < 0) {
time = -time;
neg = showNeg = true;
}
long hundreds, seconds, minutes, hours;
seconds = time / 1000;
hundreds = (time - seconds * 1000) / 10;
minutes = seconds / 60;
seconds = seconds - minutes * 60;
hours = minutes / 60;
minutes = minutes - hours * 60;
if (hours > 99) {
hours = 0;
}
// time may less than a second below zero, since we do not show fractions of seconds
// when counting down, do not show the minus sign.
if (hours ==0 && minutes == 0 && seconds == 0) {
showNeg = false;
}
// TODO: must build to account for localization
if (!showHundredths) {
if (!neg && hundreds != 0) {
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
}
}
}
if (hundreds < 10 || hundreds > 90) {
update = true;
}
}
if (hours >= 10) {
format = showNeg ? NEG_TWO_DIGITS : TWO_DIGITS;
mHours = String.format(format, hours);
} else if (hours > 0) {
format = showNeg ? NEG_ONE_DIGIT : ONE_DIGIT;
mHours = String.format(format, hours);
} else {
mHours = null;
}
if (minutes >= 10 || hours > 0) {
format = (showNeg && hours == 0) ? NEG_TWO_DIGITS : TWO_DIGITS;
mMinutes = String.format(format, minutes);
} else {
format = (showNeg && hours == 0) ? NEG_ONE_DIGIT : ONE_DIGIT;
mMinutes = String.format(format, minutes);
}
if (!showHundredths) {
if (!neg && hundreds != 0) {
seconds++;
}
if (hundreds < 10 || hundreds > 90) {
update = true;
}
}
mSeconds = String.format(TWO_DIGITS, seconds);
if (showHundredths) {
mHunderdths = String.format(TWO_DIGITS, hundreds);
} else {
mHunderdths = null;
}
mRemeasureText = true;
if (update) {
invalidate();
}
}
| public void setTime(long time, boolean showHundredths, boolean update) {
boolean neg = false, showNeg = false;
String format = null;
if (time < 0) {
time = -time;
neg = showNeg = true;
}
long hundreds, seconds, minutes, hours;
seconds = time / 1000;
hundreds = (time - seconds * 1000) / 10;
minutes = seconds / 60;
seconds = seconds - minutes * 60;
hours = minutes / 60;
minutes = minutes - hours * 60;
if (hours > 99) {
hours = 0;
}
// time may less than a second below zero, since we do not show fractions of seconds
// when counting down, do not show the minus sign.
if (hours ==0 && minutes == 0 && seconds == 0) {
showNeg = false;
}
// TODO: must build to account for localization
if (!showHundredths) {
if (!neg && hundreds != 0) {
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
}
}
}
if (hundreds < 10 || hundreds > 90) {
update = true;
}
}
if (hours >= 10) {
format = showNeg ? NEG_TWO_DIGITS : TWO_DIGITS;
mHours = String.format(format, hours);
} else if (hours > 0) {
format = showNeg ? NEG_ONE_DIGIT : ONE_DIGIT;
mHours = String.format(format, hours);
} else {
mHours = null;
}
if (minutes >= 10 || hours > 0) {
format = (showNeg && hours == 0) ? NEG_TWO_DIGITS : TWO_DIGITS;
mMinutes = String.format(format, minutes);
} else {
format = (showNeg && hours == 0) ? NEG_ONE_DIGIT : ONE_DIGIT;
mMinutes = String.format(format, minutes);
}
mSeconds = String.format(TWO_DIGITS, seconds);
if (showHundredths) {
mHunderdths = String.format(TWO_DIGITS, hundreds);
} else {
mHunderdths = null;
}
mRemeasureText = true;
if (update) {
invalidate();
}
}
|
diff --git a/src/com/android/browser/Controller.java b/src/com/android/browser/Controller.java
index 0ffb4be7..fcbe3878 100644
--- a/src/com/android/browser/Controller.java
+++ b/src/com/android/browser/Controller.java
@@ -1,2834 +1,2835 @@
/*
* 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.browser;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.SearchManager;
import android.content.ClipboardManager;
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceActivity;
import android.provider.Browser;
import android.provider.BrowserContract;
import android.provider.BrowserContract.Images;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Intents.Insert;
import android.speech.RecognizerIntent;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.MimeTypeMap;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebIconDatabase;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClassic;
import android.widget.Toast;
import com.android.browser.IntentHandler.UrlData;
import com.android.browser.UI.ComboViews;
import com.android.browser.provider.BrowserProvider;
import com.android.browser.provider.BrowserProvider2.Thumbnails;
import com.android.browser.provider.SnapshotProvider.Snapshots;
import com.android.browser.search.SearchEngine;
import com.android.common.Search;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Controller for browser
*/
public class Controller
implements WebViewController, UiController {
private static final String LOGTAG = "Controller";
private static final String SEND_APP_ID_EXTRA =
"android.speech.extras.SEND_APPLICATION_ID_EXTRA";
private static final String INCOGNITO_URI = "browser:incognito";
// public message ids
public final static int LOAD_URL = 1001;
public final static int STOP_LOAD = 1002;
// Message Ids
private static final int FOCUS_NODE_HREF = 102;
private static final int RELEASE_WAKELOCK = 107;
static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
private static final int OPEN_BOOKMARKS = 201;
private static final int EMPTY_MENU = -1;
// activity requestCode
final static int COMBO_VIEW = 1;
final static int PREFERENCES_PAGE = 3;
final static int FILE_SELECTED = 4;
final static int AUTOFILL_SETUP = 5;
private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
// As the ids are dynamically created, we can't guarantee that they will
// be in sequence, so this static array maps ids to a window number.
final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
{ R.id.window_one_menu_id, R.id.window_two_menu_id,
R.id.window_three_menu_id, R.id.window_four_menu_id,
R.id.window_five_menu_id, R.id.window_six_menu_id,
R.id.window_seven_menu_id, R.id.window_eight_menu_id };
// "source" parameter for Google search through search key
final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
// "source" parameter for Google search through simplily type
final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
// "no-crash-recovery" parameter in intent to suppress crash recovery
final static String NO_CRASH_RECOVERY = "no-crash-recovery";
// A bitmap that is re-used in createScreenshot as scratch space
private static Bitmap sThumbnailBitmap;
private Activity mActivity;
private UI mUi;
private TabControl mTabControl;
private BrowserSettings mSettings;
private WebViewFactory mFactory;
private WakeLock mWakeLock;
private UrlHandler mUrlHandler;
private UploadHandler mUploadHandler;
private IntentHandler mIntentHandler;
private PageDialogsHandler mPageDialogsHandler;
private NetworkStateHandler mNetworkHandler;
private Message mAutoFillSetupMessage;
private boolean mShouldShowErrorConsole;
private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
// FIXME, temp address onPrepareMenu performance problem.
// When we move everything out of view, we should rewrite this.
private int mCurrentMenuState = 0;
private int mMenuState = R.id.MAIN_MENU;
private int mOldMenuState = EMPTY_MENU;
private Menu mCachedMenu;
private boolean mMenuIsDown;
// For select and find, we keep track of the ActionMode so that
// finish() can be called as desired.
private ActionMode mActionMode;
/**
* Only meaningful when mOptionsMenuOpen is true. This variable keeps track
* of whether the configuration has changed. The first onMenuOpened call
* after a configuration change is simply a reopening of the same menu
* (i.e. mIconView did not change).
*/
private boolean mConfigChanged;
/**
* Keeps track of whether the options menu is open. This is important in
* determining whether to show or hide the title bar overlay
*/
private boolean mOptionsMenuOpen;
/**
* Whether or not the options menu is in its bigger, popup menu form. When
* true, we want the title bar overlay to be gone. When false, we do not.
* Only meaningful if mOptionsMenuOpen is true.
*/
private boolean mExtendedMenuOpen;
private boolean mActivityPaused = true;
private boolean mLoadStopped;
private Handler mHandler;
// Checks to see when the bookmarks database has changed, and updates the
// Tabs' notion of whether they represent bookmarked sites.
private ContentObserver mBookmarksObserver;
private CrashRecoveryHandler mCrashRecoveryHandler;
private boolean mBlockEvents;
public Controller(Activity browser) {
mActivity = browser;
mSettings = BrowserSettings.getInstance();
mTabControl = new TabControl(this);
mSettings.setController(this);
mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
mCrashRecoveryHandler.preloadCrashState();
mFactory = new BrowserWebViewFactory(browser);
mUrlHandler = new UrlHandler(this);
mIntentHandler = new IntentHandler(mActivity, this);
mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
startHandler();
mBookmarksObserver = new ContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange) {
int size = mTabControl.getTabCount();
for (int i = 0; i < size; i++) {
mTabControl.getTab(i).updateBookmarkedStatus();
}
}
};
browser.getContentResolver().registerContentObserver(
BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
mNetworkHandler = new NetworkStateHandler(mActivity, this);
// Start watching the default geolocation permissions
mSystemAllowGeolocationOrigins =
new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
mSystemAllowGeolocationOrigins.start();
openIconDatabase();
}
void start(final Intent intent) {
// mCrashRecoverHandler has any previously saved state.
mCrashRecoveryHandler.startRecovery(intent);
}
void doStart(final Bundle icicle, final Intent intent) {
// Unless the last browser usage was within 24 hours, destroy any
// remaining incognito tabs.
Calendar lastActiveDate = icicle != null ?
(Calendar) icicle.getSerializable("lastActiveDate") : null;
Calendar today = Calendar.getInstance();
Calendar yesterday = Calendar.getInstance();
yesterday.add(Calendar.DATE, -1);
final boolean restoreIncognitoTabs = !(lastActiveDate == null
|| lastActiveDate.before(yesterday)
|| lastActiveDate.after(today));
// Find out if we will restore any state and remember the tab.
final long currentTabId =
mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
if (currentTabId == -1) {
// Not able to restore so we go ahead and clear session cookies. We
// must do this before trying to login the user as we don't want to
// clear any session cookies set during login.
CookieManager.getInstance().removeSessionCookie();
}
GoogleAccountLogin.startLoginIfNeeded(mActivity,
new Runnable() {
@Override public void run() {
onPreloginFinished(icicle, intent, currentTabId,
restoreIncognitoTabs);
}
});
}
private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
boolean restoreIncognitoTabs) {
if (currentTabId == -1) {
BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
if (intent == null) {
// This won't happen under common scenarios. The icicle is
// not null, but there aren't any tabs to restore.
openTabToHomePage();
} else {
final Bundle extra = intent.getExtras();
// Create an initial tab.
// If the intent is ACTION_VIEW and data is not null, the Browser is
// invoked to view the content by another application. In this case,
// the tab will be close when exit.
UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Tab t = null;
if (urlData.isEmpty()) {
t = openTabToHomePage();
} else {
t = openTab(urlData);
}
if (t != null) {
t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
}
WebView webView = t.getWebView();
if (extra != null) {
int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
if (scale > 0 && scale <= 1000) {
webView.setInitialScale(scale);
}
}
}
mUi.updateTabs(mTabControl.getTabs());
} else {
mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
mUi.needsRestoreAllTabs());
List<Tab> tabs = mTabControl.getTabs();
ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
for (Tab t : tabs) {
restoredTabs.add(t.getId());
}
BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
if (tabs.size() == 0) {
openTabToHomePage();
}
mUi.updateTabs(tabs);
// TabControl.restoreState() will create a new tab even if
// restoring the state fails.
setActiveTab(mTabControl.getCurrentTab());
// Intent is non-null when framework thinks the browser should be
// launching with a new intent (icicle is null).
if (intent != null) {
mIntentHandler.onNewIntent(intent);
}
}
// Read JavaScript flags if it exists.
String jsFlags = getSettings().getJsEngineFlags();
if (jsFlags.trim().length() != 0) {
WebViewClassic.fromWebView(getCurrentWebView()).setJsFlags(jsFlags);
}
if (intent != null
&& BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
}
}
private static class PruneThumbnails implements Runnable {
private Context mContext;
private List<Long> mIds;
PruneThumbnails(Context context, List<Long> preserveIds) {
mContext = context.getApplicationContext();
mIds = preserveIds;
}
@Override
public void run() {
ContentResolver cr = mContext.getContentResolver();
if (mIds == null || mIds.size() == 0) {
cr.delete(Thumbnails.CONTENT_URI, null, null);
} else {
int length = mIds.size();
StringBuilder where = new StringBuilder();
where.append(Thumbnails._ID);
where.append(" not in (");
for (int i = 0; i < length; i++) {
where.append(mIds.get(i));
if (i < (length - 1)) {
where.append(",");
}
}
where.append(")");
cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
}
}
}
@Override
public WebViewFactory getWebViewFactory() {
return mFactory;
}
@Override
public void onSetWebView(Tab tab, WebView view) {
mUi.onSetWebView(tab, view);
}
@Override
public void createSubWindow(Tab tab) {
endActionMode();
WebView mainView = tab.getWebView();
WebView subView = mFactory.createWebView((mainView == null)
? false
: mainView.isPrivateBrowsingEnabled());
mUi.createSubWindow(tab, subView);
}
@Override
public Context getContext() {
return mActivity;
}
@Override
public Activity getActivity() {
return mActivity;
}
void setUi(UI ui) {
mUi = ui;
}
BrowserSettings getSettings() {
return mSettings;
}
IntentHandler getIntentHandler() {
return mIntentHandler;
}
@Override
public UI getUi() {
return mUi;
}
int getMaxTabs() {
return mActivity.getResources().getInteger(R.integer.max_tabs);
}
@Override
public TabControl getTabControl() {
return mTabControl;
}
@Override
public List<Tab> getTabs() {
return mTabControl.getTabs();
}
// Open the icon database.
private void openIconDatabase() {
// We have to call getInstance on the UI thread
final WebIconDatabase instance = WebIconDatabase.getInstance();
BackgroundHandler.execute(new Runnable() {
@Override
public void run() {
instance.open(mActivity.getDir("icons", 0).getPath());
}
});
}
private void startHandler() {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case OPEN_BOOKMARKS:
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
break;
case FOCUS_NODE_HREF:
{
String url = (String) msg.getData().get("url");
String title = (String) msg.getData().get("title");
String src = (String) msg.getData().get("src");
if (url == "") url = src; // use image if no anchor
if (TextUtils.isEmpty(url)) {
break;
}
HashMap focusNodeMap = (HashMap) msg.obj;
WebView view = (WebView) focusNodeMap.get("webview");
// Only apply the action if the top window did not change.
if (getCurrentTopWebView() != view) {
break;
}
switch (msg.arg1) {
case R.id.open_context_menu_id:
loadUrlFromContext(url);
break;
case R.id.view_image_context_menu_id:
loadUrlFromContext(src);
break;
case R.id.open_newtab_context_menu_id:
final Tab parent = mTabControl.getCurrentTab();
openTab(url, parent,
!mSettings.openInBackground(), true);
break;
case R.id.copy_link_context_menu_id:
copy(url);
break;
case R.id.save_link_context_menu_id:
case R.id.download_context_menu_id:
DownloadHandler.onDownloadStartNoStream(
mActivity, url, null, null, null,
view.isPrivateBrowsingEnabled());
break;
}
break;
}
case LOAD_URL:
loadUrlFromContext((String) msg.obj);
break;
case STOP_LOAD:
stopLoading();
break;
case RELEASE_WAKELOCK:
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
// if we reach here, Browser should be still in the
// background loading after WAKELOCK_TIMEOUT (5-min).
// To avoid burning the battery, stop loading.
mTabControl.stopAllLoading();
}
break;
case UPDATE_BOOKMARK_THUMBNAIL:
Tab tab = (Tab) msg.obj;
if (tab != null) {
updateScreenshot(tab);
}
break;
}
}
};
}
@Override
public Tab getCurrentTab() {
return mTabControl.getCurrentTab();
}
@Override
public void shareCurrentPage() {
shareCurrentPage(mTabControl.getCurrentTab());
}
private void shareCurrentPage(Tab tab) {
if (tab != null) {
sharePage(mActivity, tab.getTitle(),
tab.getUrl(), tab.getFavicon(),
createScreenshot(tab.getWebView(),
getDesiredThumbnailWidth(mActivity),
getDesiredThumbnailHeight(mActivity)));
}
}
/**
* Share a page, providing the title, url, favicon, and a screenshot. Uses
* an {@link Intent} to launch the Activity chooser.
* @param c Context used to launch a new Activity.
* @param title Title of the page. Stored in the Intent with
* {@link Intent#EXTRA_SUBJECT}
* @param url URL of the page. Stored in the Intent with
* {@link Intent#EXTRA_TEXT}
* @param favicon Bitmap of the favicon for the page. Stored in the Intent
* with {@link Browser#EXTRA_SHARE_FAVICON}
* @param screenshot Bitmap of a screenshot of the page. Stored in the
* Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
*/
static final void sharePage(Context c, String title, String url,
Bitmap favicon, Bitmap screenshot) {
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("text/plain");
send.putExtra(Intent.EXTRA_TEXT, url);
send.putExtra(Intent.EXTRA_SUBJECT, title);
send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
try {
c.startActivity(Intent.createChooser(send, c.getString(
R.string.choosertitle_sharevia)));
} catch(android.content.ActivityNotFoundException ex) {
// if no app handles it, do nothing
}
}
private void copy(CharSequence text) {
ClipboardManager cm = (ClipboardManager) mActivity
.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(text);
}
// lifecycle
protected void onConfgurationChanged(Configuration config) {
mConfigChanged = true;
// update the menu in case of a locale change
mActivity.invalidateOptionsMenu();
if (mPageDialogsHandler != null) {
mPageDialogsHandler.onConfigurationChanged(config);
}
mUi.onConfigurationChanged(config);
}
@Override
public void handleNewIntent(Intent intent) {
if (!mUi.isWebShowing()) {
mUi.showWeb(false);
}
mIntentHandler.onNewIntent(intent);
}
protected void onPause() {
if (mUi.isCustomViewShowing()) {
hideCustomView();
}
if (mActivityPaused) {
Log.e(LOGTAG, "BrowserActivity is already paused.");
return;
}
mActivityPaused = true;
Tab tab = mTabControl.getCurrentTab();
if (tab != null) {
tab.pause();
if (!pauseWebViewTimers(tab)) {
if (mWakeLock == null) {
PowerManager pm = (PowerManager) mActivity
.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
}
mWakeLock.acquire();
mHandler.sendMessageDelayed(mHandler
.obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
}
}
mUi.onPause();
mNetworkHandler.onPause();
WebView.disablePlatformNotifications();
NfcHandler.unregister(mActivity);
if (sThumbnailBitmap != null) {
sThumbnailBitmap.recycle();
sThumbnailBitmap = null;
}
}
void onSaveInstanceState(Bundle outState) {
// Save all the tabs
Bundle saveState = createSaveState();
// crash recovery manages all save & restore state
mCrashRecoveryHandler.writeState(saveState);
mSettings.setLastRunPaused(true);
}
/**
* Save the current state to outState. Does not write the state to
* disk.
* @return Bundle containing the current state of all tabs.
*/
/* package */ Bundle createSaveState() {
Bundle saveState = new Bundle();
mTabControl.saveState(saveState);
if (!saveState.isEmpty()) {
// Save time so that we know how old incognito tabs (if any) are.
saveState.putSerializable("lastActiveDate", Calendar.getInstance());
}
return saveState;
}
void onResume() {
if (!mActivityPaused) {
Log.e(LOGTAG, "BrowserActivity is already resumed.");
return;
}
mSettings.setLastRunPaused(false);
mActivityPaused = false;
Tab current = mTabControl.getCurrentTab();
if (current != null) {
current.resume();
resumeWebViewTimers(current);
}
releaseWakeLock();
mUi.onResume();
mNetworkHandler.onResume();
WebView.enablePlatformNotifications();
NfcHandler.register(mActivity, this);
}
private void releaseWakeLock() {
if (mWakeLock != null && mWakeLock.isHeld()) {
mHandler.removeMessages(RELEASE_WAKELOCK);
mWakeLock.release();
}
}
/**
* resume all WebView timers using the WebView instance of the given tab
* @param tab guaranteed non-null
*/
private void resumeWebViewTimers(Tab tab) {
boolean inLoad = tab.inPageLoad();
if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
CookieSyncManager.getInstance().startSync();
WebView w = tab.getWebView();
WebViewTimersControl.getInstance().onBrowserActivityResume(w);
}
}
/**
* Pause all WebView timers using the WebView of the given tab
* @param tab
* @return true if the timers are paused or tab is null
*/
private boolean pauseWebViewTimers(Tab tab) {
if (tab == null) {
return true;
} else if (!tab.inPageLoad()) {
CookieSyncManager.getInstance().stopSync();
WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
return true;
}
return false;
}
void onDestroy() {
if (mUploadHandler != null && !mUploadHandler.handled()) {
mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
mUploadHandler = null;
}
if (mTabControl == null) return;
mUi.onDestroy();
// Remove the current tab and sub window
Tab t = mTabControl.getCurrentTab();
if (t != null) {
dismissSubWindow(t);
removeTab(t);
}
mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
// Destroy all the tabs
mTabControl.destroy();
WebIconDatabase.getInstance().close();
// Stop watching the default geolocation permissions
mSystemAllowGeolocationOrigins.stop();
mSystemAllowGeolocationOrigins = null;
}
protected boolean isActivityPaused() {
return mActivityPaused;
}
protected void onLowMemory() {
mTabControl.freeMemory();
}
@Override
public boolean shouldShowErrorConsole() {
return mShouldShowErrorConsole;
}
protected void setShouldShowErrorConsole(boolean show) {
if (show == mShouldShowErrorConsole) {
// Nothing to do.
return;
}
mShouldShowErrorConsole = show;
Tab t = mTabControl.getCurrentTab();
if (t == null) {
// There is no current tab so we cannot toggle the error console
return;
}
mUi.setShouldShowErrorConsole(t, show);
}
@Override
public void stopLoading() {
mLoadStopped = true;
Tab tab = mTabControl.getCurrentTab();
WebView w = getCurrentTopWebView();
if (w != null) {
w.stopLoading();
mUi.onPageStopped(tab);
}
}
boolean didUserStopLoading() {
return mLoadStopped;
}
// WebViewController
@Override
public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
// We've started to load a new page. If there was a pending message
// to save a screenshot then we will now take the new page and save
// an incorrect screenshot. Therefore, remove any pending thumbnail
// messages from the queue.
mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
tab);
// reset sync timer to avoid sync starts during loading a page
CookieSyncManager.getInstance().resetSync();
if (!mNetworkHandler.isNetworkUp()) {
view.setNetworkAvailable(false);
}
// when BrowserActivity just starts, onPageStarted may be called before
// onResume as it is triggered from onCreate. Call resumeWebViewTimers
// to start the timer. As we won't switch tabs while an activity is in
// pause state, we can ensure calling resume and pause in pair.
if (mActivityPaused) {
resumeWebViewTimers(tab);
}
mLoadStopped = false;
endActionMode();
mUi.onTabDataChanged(tab);
String url = tab.getUrl();
// update the bookmark database for favicon
maybeUpdateFavicon(tab, null, url, favicon);
Performance.tracePageStart(url);
// Performance probe
if (false) {
Performance.onPageStarted();
}
}
@Override
public void onPageFinished(Tab tab) {
mUi.onTabDataChanged(tab);
// pause the WebView timer and release the wake lock if it is finished
// while BrowserActivity is in pause state.
if (mActivityPaused && pauseWebViewTimers(tab)) {
releaseWakeLock();
}
// Performance probe
if (false) {
Performance.onPageFinished(tab.getUrl());
}
Performance.tracePageFinished();
}
@Override
public void onProgressChanged(Tab tab) {
mCrashRecoveryHandler.backupState();
int newProgress = tab.getLoadProgress();
if (newProgress == 100) {
CookieSyncManager.getInstance().sync();
// onProgressChanged() may continue to be called after the main
// frame has finished loading, as any remaining sub frames continue
// to load. We'll only get called once though with newProgress as
// 100 when everything is loaded. (onPageFinished is called once
// when the main frame completes loading regardless of the state of
// any sub frames so calls to onProgressChanges may continue after
// onPageFinished has executed)
if (tab.inPageLoad()) {
updateInLoadMenuItems(mCachedMenu, tab);
}
if (!tab.isPrivateBrowsingEnabled()
&& !TextUtils.isEmpty(tab.getUrl())
&& !tab.isSnapshot()) {
// Only update the bookmark screenshot if the user did not
// cancel the load early and there is not already
// a pending update for the tab.
if (tab.inForeground() && !didUserStopLoading()
|| !tab.inForeground()) {
if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
mHandler.sendMessageDelayed(mHandler.obtainMessage(
UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
500);
}
}
}
} else {
if (!tab.inPageLoad()) {
// onPageFinished may have already been called but a subframe is
// still loading
// updating the progress and
// update the menu items.
updateInLoadMenuItems(mCachedMenu, tab);
}
}
mUi.onProgressChanged(tab);
}
@Override
public void onUpdatedSecurityState(Tab tab) {
mUi.onTabDataChanged(tab);
}
@Override
public void onReceivedTitle(Tab tab, final String title) {
mUi.onTabDataChanged(tab);
final String pageUrl = tab.getOriginalUrl();
if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
>= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
return;
}
// Update the title in the history database if not in private browsing mode
if (!tab.isPrivateBrowsingEnabled()) {
DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
}
}
@Override
public void onFavicon(Tab tab, WebView view, Bitmap icon) {
mUi.onTabDataChanged(tab);
maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
}
@Override
public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
}
@Override
public boolean shouldOverrideKeyEvent(KeyEvent event) {
if (mMenuIsDown) {
// only check shortcut key when MENU is held
return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
event);
} else {
return false;
}
}
@Override
public void onUnhandledKeyEvent(KeyEvent event) {
if (!isActivityPaused()) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
mActivity.onKeyDown(event.getKeyCode(), event);
} else {
mActivity.onKeyUp(event.getKeyCode(), event);
}
}
}
@Override
public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
// Don't save anything in private browsing mode
if (tab.isPrivateBrowsingEnabled()) return;
String url = tab.getOriginalUrl();
if (TextUtils.isEmpty(url)
|| url.regionMatches(true, 0, "about:", 0, 6)) {
return;
}
DataController.getInstance(mActivity).updateVisitedHistory(url);
mCrashRecoveryHandler.backupState();
}
@Override
public void getVisitedHistory(final ValueCallback<String[]> callback) {
AsyncTask<Void, Void, String[]> task =
new AsyncTask<Void, Void, String[]>() {
@Override
public String[] doInBackground(Void... unused) {
return Browser.getVisitedHistory(mActivity.getContentResolver());
}
@Override
public void onPostExecute(String[] result) {
callback.onReceiveValue(result);
}
};
task.execute();
}
@Override
public void onReceivedHttpAuthRequest(Tab tab, WebView view,
final HttpAuthHandler handler, final String host,
final String realm) {
String username = null;
String password = null;
boolean reuseHttpAuthUsernamePassword
= handler.useHttpAuthUsernamePassword();
if (reuseHttpAuthUsernamePassword && view != null) {
String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
if (credentials != null && credentials.length == 2) {
username = credentials[0];
password = credentials[1];
}
}
if (username != null && password != null) {
handler.proceed(username, password);
} else {
if (tab.inForeground() && !handler.suppressDialog()) {
mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
} else {
handler.cancel();
}
}
}
@Override
public void onDownloadStart(Tab tab, String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
WebView w = tab.getWebView();
DownloadHandler.onDownloadStart(mActivity, url, userAgent,
contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
if (w.copyBackForwardList().getSize() == 0) {
// This Tab was opened for the sole purpose of downloading a
// file. Remove it.
if (tab == mTabControl.getCurrentTab()) {
// In this case, the Tab is still on top.
goBackOnePageOrQuit();
} else {
// In this case, it is not.
closeTab(tab);
}
}
}
@Override
public Bitmap getDefaultVideoPoster() {
return mUi.getDefaultVideoPoster();
}
@Override
public View getVideoLoadingProgressView() {
return mUi.getVideoLoadingProgressView();
}
@Override
public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
SslError error) {
mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
}
@Override
public void showAutoLogin(Tab tab) {
assert tab.inForeground();
// Update the title bar to show the auto-login request.
mUi.showAutoLogin(tab);
}
@Override
public void hideAutoLogin(Tab tab) {
assert tab.inForeground();
mUi.hideAutoLogin(tab);
}
// helper method
/*
* Update the favorites icon if the private browsing isn't enabled and the
* icon is valid.
*/
private void maybeUpdateFavicon(Tab tab, final String originalUrl,
final String url, Bitmap favicon) {
if (favicon == null) {
return;
}
if (!tab.isPrivateBrowsingEnabled()) {
Bookmarks.updateFavicon(mActivity
.getContentResolver(), originalUrl, url, favicon);
}
}
@Override
public void bookmarkedStatusHasChanged(Tab tab) {
// TODO: Switch to using onTabDataChanged after b/3262950 is fixed
mUi.bookmarkedStatusHasChanged(tab);
}
// end WebViewController
protected void pageUp() {
getCurrentTopWebView().pageUp(false);
}
protected void pageDown() {
getCurrentTopWebView().pageDown(false);
}
// callback from phone title bar
public void editUrl() {
if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
mUi.editUrl(false);
}
public void startVoiceSearch() {
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
mActivity.getComponentName().flattenToString());
intent.putExtra(SEND_APP_ID_EXTRA, false);
intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
mActivity.startActivity(intent);
}
@Override
public void activateVoiceSearchMode(String title, List<String> results) {
mUi.showVoiceTitleBar(title, results);
}
public void revertVoiceSearchMode(Tab tab) {
mUi.revertVoiceTitleBar(tab);
}
public boolean supportsVoiceSearch() {
SearchEngine searchEngine = getSettings().getSearchEngine();
return (searchEngine != null && searchEngine.supportsVoiceSearch());
}
public void showCustomView(Tab tab, View view, int requestedOrientation,
WebChromeClient.CustomViewCallback callback) {
if (tab.inForeground()) {
if (mUi.isCustomViewShowing()) {
callback.onCustomViewHidden();
return;
}
mUi.showCustomView(view, requestedOrientation, callback);
// Save the menu state and set it to empty while the custom
// view is showing.
mOldMenuState = mMenuState;
mMenuState = EMPTY_MENU;
mActivity.invalidateOptionsMenu();
}
}
@Override
public void hideCustomView() {
if (mUi.isCustomViewShowing()) {
mUi.onHideCustomView();
// Reset the old menu state.
mMenuState = mOldMenuState;
mOldMenuState = EMPTY_MENU;
mActivity.invalidateOptionsMenu();
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (getCurrentTopWebView() == null) return;
switch (requestCode) {
case PREFERENCES_PAGE:
if (resultCode == Activity.RESULT_OK && intent != null) {
String action = intent.getStringExtra(Intent.EXTRA_TEXT);
if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
mTabControl.removeParentChildRelationShips();
}
}
break;
case FILE_SELECTED:
// Chose a file from the file picker.
if (null == mUploadHandler) break;
mUploadHandler.onResult(resultCode, intent);
break;
case AUTOFILL_SETUP:
// Determine whether a profile was actually set up or not
// and if so, send the message back to the WebTextView to
// fill the form with the new profile.
if (getSettings().getAutoFillProfile() != null) {
mAutoFillSetupMessage.sendToTarget();
mAutoFillSetupMessage = null;
}
break;
case COMBO_VIEW:
if (intent == null || resultCode != Activity.RESULT_OK) {
break;
}
mUi.showWeb(false);
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Tab t = getCurrentTab();
Uri uri = intent.getData();
loadUrl(t, uri.toString());
} else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
String[] urls = intent.getStringArrayExtra(
ComboViewActivity.EXTRA_OPEN_ALL);
Tab parent = getCurrentTab();
for (String url : urls) {
parent = openTab(url, parent,
!mSettings.openInBackground(), true);
}
} else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
long id = intent.getLongExtra(
ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
if (id >= 0) {
createNewSnapshotTab(id, true);
}
}
break;
default:
break;
}
getCurrentTopWebView().requestFocus();
}
/**
* Open the Go page.
* @param startWithHistory If true, open starting on the history tab.
* Otherwise, start with the bookmarks tab.
*/
@Override
public void bookmarksOrHistoryPicker(ComboViews startView) {
if (mTabControl.getCurrentWebView() == null) {
return;
}
// clear action mode
if (isInCustomActionMode()) {
endActionMode();
}
Bundle extras = new Bundle();
// Disable opening in a new window if we have maxed out the windows
extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
!mTabControl.canCreateNewTab());
mUi.showComboView(startView, extras);
}
// combo view callbacks
// key handling
protected void onBackKey() {
if (!mUi.onBackKey()) {
WebView subwindow = mTabControl.getCurrentSubWindow();
if (subwindow != null) {
if (subwindow.canGoBack()) {
subwindow.goBack();
} else {
dismissSubWindow(mTabControl.getCurrentTab());
}
} else {
goBackOnePageOrQuit();
}
}
}
protected boolean onMenuKey() {
return mUi.onMenuKey();
}
// menu handling and state
// TODO: maybe put into separate handler
protected boolean onCreateOptionsMenu(Menu menu) {
if (mMenuState == EMPTY_MENU) {
return false;
}
MenuInflater inflater = mActivity.getMenuInflater();
inflater.inflate(R.menu.browser, menu);
return true;
}
protected void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v instanceof TitleBar) {
return;
}
if (!(v instanceof WebView)) {
return;
}
final WebView webview = (WebView) v;
WebView.HitTestResult result = webview.getHitTestResult();
if (result == null) {
return;
}
int type = result.getType();
if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
Log.w(LOGTAG,
"We should not show context menu when nothing is touched");
return;
}
if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
// let TextView handles context menu
return;
}
// Note, http://b/issue?id=1106666 is requesting that
// an inflated menu can be used again. This is not available
// yet, so inflate each time (yuk!)
MenuInflater inflater = mActivity.getMenuInflater();
inflater.inflate(R.menu.browsercontext, menu);
// Show the correct menu group
final String extra = result.getExtra();
if (extra == null) return;
menu.setGroupVisible(R.id.PHONE_MENU,
type == WebView.HitTestResult.PHONE_TYPE);
menu.setGroupVisible(R.id.EMAIL_MENU,
type == WebView.HitTestResult.EMAIL_TYPE);
menu.setGroupVisible(R.id.GEO_MENU,
type == WebView.HitTestResult.GEO_TYPE);
menu.setGroupVisible(R.id.IMAGE_MENU,
type == WebView.HitTestResult.IMAGE_TYPE
|| type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
menu.setGroupVisible(R.id.ANCHOR_MENU,
type == WebView.HitTestResult.SRC_ANCHOR_TYPE
|| type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
|| type == WebView.HitTestResult.PHONE_TYPE
|| type == WebView.HitTestResult.EMAIL_TYPE
|| type == WebView.HitTestResult.GEO_TYPE;
menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
if (hitText) {
menu.findItem(R.id.select_text_menu_id)
.setOnMenuItemClickListener(new SelectText(webview));
}
// Setup custom handling depending on the type
switch (type) {
case WebView.HitTestResult.PHONE_TYPE:
menu.setHeaderTitle(Uri.decode(extra));
menu.findItem(R.id.dial_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri
.parse(WebView.SCHEME_TEL + extra)));
Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
menu.findItem(R.id.add_contact_context_menu_id).setIntent(
addIntent);
menu.findItem(R.id.copy_phone_context_menu_id)
.setOnMenuItemClickListener(
new Copy(extra));
break;
case WebView.HitTestResult.EMAIL_TYPE:
menu.setHeaderTitle(extra);
menu.findItem(R.id.email_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri
.parse(WebView.SCHEME_MAILTO + extra)));
menu.findItem(R.id.copy_mail_context_menu_id)
.setOnMenuItemClickListener(
new Copy(extra));
break;
case WebView.HitTestResult.GEO_TYPE:
menu.setHeaderTitle(extra);
menu.findItem(R.id.map_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri
.parse(WebView.SCHEME_GEO
+ URLEncoder.encode(extra))));
menu.findItem(R.id.copy_geo_context_menu_id)
.setOnMenuItemClickListener(
new Copy(extra));
break;
case WebView.HitTestResult.SRC_ANCHOR_TYPE:
case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
menu.setHeaderTitle(extra);
// decide whether to show the open link in new tab option
boolean showNewTab = mTabControl.canCreateNewTab();
MenuItem newTabItem
= menu.findItem(R.id.open_newtab_context_menu_id);
newTabItem.setTitle(getSettings().openInBackground()
? R.string.contextmenu_openlink_newwindow_background
: R.string.contextmenu_openlink_newwindow);
newTabItem.setVisible(showNewTab);
if (showNewTab) {
if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
newTabItem.setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
final HashMap<String, WebView> hrefMap =
new HashMap<String, WebView>();
hrefMap.put("webview", webview);
final Message msg = mHandler.obtainMessage(
FOCUS_NODE_HREF,
R.id.open_newtab_context_menu_id,
0, hrefMap);
webview.requestFocusNodeHref(msg);
return true;
}
});
} else {
newTabItem.setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
final Tab parent = mTabControl.getCurrentTab();
openTab(extra, parent,
!mSettings.openInBackground(),
true);
return true;
}
});
}
}
if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
break;
}
// otherwise fall through to handle image part
case WebView.HitTestResult.IMAGE_TYPE:
MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
if (type == WebView.HitTestResult.IMAGE_TYPE) {
menu.setHeaderTitle(extra);
shareItem.setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
sharePage(mActivity, null, extra, null,
null);
return true;
}
}
);
}
menu.findItem(R.id.view_image_context_menu_id)
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
openTab(extra, mTabControl.getCurrentTab(), true, true);
return false;
}
});
menu.findItem(R.id.download_context_menu_id).
setOnMenuItemClickListener(
new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
menu.findItem(R.id.set_wallpaper_context_menu_id).
setOnMenuItemClickListener(new WallpaperHandler(mActivity,
extra));
break;
default:
Log.w(LOGTAG, "We should not get here.");
break;
}
//update the ui
mUi.onContextMenuCreated(menu);
}
/**
* As the menu can be open when loading state changes
* we must manually update the state of the stop/reload menu
* item
*/
private void updateInLoadMenuItems(Menu menu, Tab tab) {
if (menu == null) {
return;
}
MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
MenuItem src = ((tab != null) && tab.inPageLoad()) ?
menu.findItem(R.id.stop_menu_id):
menu.findItem(R.id.reload_menu_id);
if (src != null) {
dest.setIcon(src.getIcon());
dest.setTitle(src.getTitle());
}
}
boolean onPrepareOptionsMenu(Menu menu) {
updateInLoadMenuItems(menu, getCurrentTab());
// hold on to the menu reference here; it is used by the page callbacks
// to update the menu based on loading state
mCachedMenu = menu;
// Note: setVisible will decide whether an item is visible; while
// setEnabled() will decide whether an item is enabled, which also means
// whether the matching shortcut key will function.
switch (mMenuState) {
case EMPTY_MENU:
if (mCurrentMenuState != mMenuState) {
menu.setGroupVisible(R.id.MAIN_MENU, false);
menu.setGroupEnabled(R.id.MAIN_MENU, false);
menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
}
break;
default:
if (mCurrentMenuState != mMenuState) {
menu.setGroupVisible(R.id.MAIN_MENU, true);
menu.setGroupEnabled(R.id.MAIN_MENU, true);
menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
}
updateMenuState(getCurrentTab(), menu);
break;
}
mCurrentMenuState = mMenuState;
return mUi.onPrepareOptionsMenu(menu);
}
@Override
public void updateMenuState(Tab tab, Menu menu) {
boolean canGoBack = false;
boolean canGoForward = false;
boolean isHome = false;
boolean isDesktopUa = false;
boolean isLive = false;
if (tab != null) {
canGoBack = tab.canGoBack();
canGoForward = tab.canGoForward();
isHome = mSettings.getHomePage().equals(tab.getUrl());
isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
isLive = !tab.isSnapshot();
}
final MenuItem back = menu.findItem(R.id.back_menu_id);
back.setEnabled(canGoBack);
final MenuItem home = menu.findItem(R.id.homepage_menu_id);
home.setEnabled(!isHome);
final MenuItem forward = menu.findItem(R.id.forward_menu_id);
forward.setEnabled(canGoForward);
final MenuItem source = menu.findItem(isInLoad() ? R.id.stop_menu_id
: R.id.reload_menu_id);
final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
if (source != null && dest != null) {
dest.setTitle(source.getTitle());
dest.setIcon(source.getIcon());
}
menu.setGroupVisible(R.id.NAV_MENU, isLive);
// decide whether to show the share link option
PackageManager pm = mActivity.getPackageManager();
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("text/plain");
ResolveInfo ri = pm.resolveActivity(send,
PackageManager.MATCH_DEFAULT_ONLY);
menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
boolean isNavDump = mSettings.enableNavDump();
final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
nav.setVisible(isNavDump);
nav.setEnabled(isNavDump);
boolean showDebugSettings = mSettings.isDebugEnabled();
final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
uaSwitcher.setChecked(isDesktopUa);
menu.setGroupVisible(R.id.LIVE_MENU, isLive);
menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
menu.setGroupVisible(R.id.COMBO_MENU, false);
mUi.updateMenuState(tab, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (null == getCurrentTopWebView()) {
return false;
}
if (mMenuIsDown) {
// The shortcut action consumes the MENU. Even if it is still down,
// it won't trigger the next shortcut action. In the case of the
// shortcut action triggering a new activity, like Bookmarks, we
// won't get onKeyUp for MENU. So it is important to reset it here.
mMenuIsDown = false;
}
if (mUi.onOptionsItemSelected(item)) {
// ui callback handled it
return true;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.incognito_menu_id:
openIncognitoTab();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
break;
case R.id.history_menu_id:
bookmarksOrHistoryPicker(ComboViews.History);
break;
case R.id.snapshots_menu_id:
bookmarksOrHistoryPicker(ComboViews.Snapshots);
break;
case R.id.add_bookmark_menu_id:
bookmarkCurrentPage();
break;
case R.id.stop_reload_menu_id:
if (isInLoad()) {
stopLoading();
} else {
getCurrentTopWebView().reload();
}
break;
case R.id.back_menu_id:
getCurrentTab().goBack();
break;
case R.id.forward_menu_id:
getCurrentTab().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentTab();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
loadUrl(current, mSettings.getHomePage());
break;
case R.id.preferences_menu_id:
openPreferences();
break;
case R.id.find_menu_id:
+ findOnPage();
break;
case R.id.save_snapshot_menu_id:
final Tab source = getTabControl().getCurrentTab();
if (source == null) break;
final ContentResolver cr = mActivity.getContentResolver();
final ContentValues values = source.createSnapshotValues();
if (values != null) {
new AsyncTask<Tab, Void, Long>() {
@Override
protected Long doInBackground(Tab... params) {
Uri result = cr.insert(Snapshots.CONTENT_URI, values);
if (result == null) {
return null;
}
long id = ContentUris.parseId(result);
return id;
}
@Override
protected void onPostExecute(Long id) {
if (id == null) {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
return;
}
Bundle b = new Bundle();
b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
mUi.showComboView(ComboViews.Snapshots, b);
};
}.execute(source);
} else {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
}
break;
case R.id.page_info_menu_id:
showPageInfo();
break;
case R.id.snapshot_go_live:
goLive();
return true;
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
return false;
}
shareCurrentPage(currentTab);
break;
case R.id.dump_nav_menu_id:
getCurrentTopWebView().debugDump();
break;
case R.id.zoom_in_menu_id:
getCurrentTopWebView().zoomIn();
break;
case R.id.zoom_out_menu_id:
getCurrentTopWebView().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads();
break;
case R.id.ua_desktop_menu_id:
toggleUserAgent();
break;
case R.id.window_one_menu_id:
case R.id.window_two_menu_id:
case R.id.window_three_menu_id:
case R.id.window_four_menu_id:
case R.id.window_five_menu_id:
case R.id.window_six_menu_id:
case R.id.window_seven_menu_id:
case R.id.window_eight_menu_id:
{
int menuid = item.getItemId();
for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Tab desiredTab = mTabControl.getTab(id);
if (desiredTab != null &&
desiredTab != mTabControl.getCurrentTab()) {
switchToTab(desiredTab);
}
break;
}
}
}
break;
default:
return false;
}
return true;
}
@Override
public void toggleUserAgent() {
WebView web = getCurrentWebView();
mSettings.toggleDesktopUseragent(web);
web.loadUrl(web.getOriginalUrl());
}
@Override
public void findOnPage() {
getCurrentTopWebView().showFindDialog(null, true);
}
@Override
public void openPreferences() {
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
getCurrentTopWebView().getUrl());
mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
}
@Override
public void bookmarkCurrentPage() {
Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
if (bookmarkIntent != null) {
mActivity.startActivity(bookmarkIntent);
}
}
private void goLive() {
Tab t = getCurrentTab();
t.loadUrl(t.getUrl(), null);
}
@Override
public void showPageInfo() {
mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
}
public boolean onContextItemSelected(MenuItem item) {
// Let the History and Bookmark fragments handle menus they created.
if (item.getGroupId() == R.id.CONTEXT_MENU) {
return false;
}
int id = item.getItemId();
boolean result = true;
switch (id) {
// -- Browser context menu
case R.id.open_context_menu_id:
case R.id.save_link_context_menu_id:
case R.id.copy_link_context_menu_id:
final WebView webView = getCurrentTopWebView();
if (null == webView) {
result = false;
break;
}
final HashMap<String, WebView> hrefMap =
new HashMap<String, WebView>();
hrefMap.put("webview", webView);
final Message msg = mHandler.obtainMessage(
FOCUS_NODE_HREF, id, 0, hrefMap);
webView.requestFocusNodeHref(msg);
break;
default:
// For other context menus
result = onOptionsItemSelected(item);
}
return result;
}
/**
* support programmatically opening the context menu
*/
public void openContextMenu(View view) {
mActivity.openContextMenu(view);
}
/**
* programmatically open the options menu
*/
public void openOptionsMenu() {
mActivity.openOptionsMenu();
}
public boolean onMenuOpened(int featureId, Menu menu) {
if (mOptionsMenuOpen) {
if (mConfigChanged) {
// We do not need to make any changes to the state of the
// title bar, since the only thing that happened was a
// change in orientation
mConfigChanged = false;
} else {
if (!mExtendedMenuOpen) {
mExtendedMenuOpen = true;
mUi.onExtendedMenuOpened();
} else {
// Switching the menu back to icon view, so show the
// title bar once again.
mExtendedMenuOpen = false;
mUi.onExtendedMenuClosed(isInLoad());
}
}
} else {
// The options menu is closed, so open it, and show the title
mOptionsMenuOpen = true;
mConfigChanged = false;
mExtendedMenuOpen = false;
mUi.onOptionsMenuOpened();
}
return true;
}
public void onOptionsMenuClosed(Menu menu) {
mOptionsMenuOpen = false;
mUi.onOptionsMenuClosed(isInLoad());
}
public void onContextMenuClosed(Menu menu) {
mUi.onContextMenuClosed(menu, isInLoad());
}
// Helper method for getting the top window.
@Override
public WebView getCurrentTopWebView() {
return mTabControl.getCurrentTopWebView();
}
@Override
public WebView getCurrentWebView() {
return mTabControl.getCurrentWebView();
}
/*
* This method is called as a result of the user selecting the options
* menu to see the download window. It shows the download window on top of
* the current window.
*/
void viewDownloads() {
Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
mActivity.startActivity(intent);
}
int getActionModeHeight() {
TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
new int[] { android.R.attr.actionBarSize });
int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
actionBarSizeTypedArray.recycle();
return size;
}
// action mode
void onActionModeStarted(ActionMode mode) {
mUi.onActionModeStarted(mode);
mActionMode = mode;
}
/*
* True if a custom ActionMode (i.e. find or select) is in use.
*/
@Override
public boolean isInCustomActionMode() {
return mActionMode != null;
}
/*
* End the current ActionMode.
*/
@Override
public void endActionMode() {
if (mActionMode != null) {
mActionMode.finish();
}
}
/*
* Called by find and select when they are finished. Replace title bars
* as necessary.
*/
public void onActionModeFinished(ActionMode mode) {
if (!isInCustomActionMode()) return;
mUi.onActionModeFinished(isInLoad());
mActionMode = null;
}
boolean isInLoad() {
final Tab tab = getCurrentTab();
return (tab != null) && tab.inPageLoad();
}
// bookmark handling
/**
* add the current page as a bookmark to the given folder id
* @param folderId use -1 for the default folder
* @param editExisting If true, check to see whether the site is already
* bookmarked, and if it is, edit that bookmark. If false, and
* the site is already bookmarked, do not attempt to edit the
* existing bookmark.
*/
@Override
public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
WebView w = getCurrentTopWebView();
if (w == null) {
return null;
}
Intent i = new Intent(mActivity,
AddBookmarkPage.class);
i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
String touchIconUrl = w.getTouchIconUrl();
if (touchIconUrl != null) {
i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
WebSettings settings = w.getSettings();
if (settings != null) {
i.putExtra(AddBookmarkPage.USER_AGENT,
settings.getUserAgentString());
}
}
i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
createScreenshot(w, getDesiredThumbnailWidth(mActivity),
getDesiredThumbnailHeight(mActivity)));
i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
if (editExisting) {
i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
}
// Put the dialog at the upper right of the screen, covering the
// star on the title bar.
i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
return i;
}
// file chooser
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadHandler = new UploadHandler(this);
mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
}
// thumbnails
/**
* Return the desired width for thumbnail screenshots, which are stored in
* the database, and used on the bookmarks screen.
* @param context Context for finding out the density of the screen.
* @return desired width for thumbnail screenshot.
*/
static int getDesiredThumbnailWidth(Context context) {
return context.getResources().getDimensionPixelOffset(
R.dimen.bookmarkThumbnailWidth);
}
/**
* Return the desired height for thumbnail screenshots, which are stored in
* the database, and used on the bookmarks screen.
* @param context Context for finding out the density of the screen.
* @return desired height for thumbnail screenshot.
*/
static int getDesiredThumbnailHeight(Context context) {
return context.getResources().getDimensionPixelOffset(
R.dimen.bookmarkThumbnailHeight);
}
static Bitmap createScreenshot(WebView view, int width, int height) {
if (view == null || view.getContentHeight() == 0
|| view.getContentWidth() == 0) {
return null;
}
// We render to a bitmap 2x the desired size so that we can then
// re-scale it with filtering since canvas.scale doesn't filter
// This helps reduce aliasing at the cost of being slightly blurry
final int filter_scale = 2;
int scaledWidth = width * filter_scale;
int scaledHeight = height * filter_scale;
if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
|| sThumbnailBitmap.getHeight() != scaledHeight) {
if (sThumbnailBitmap != null) {
sThumbnailBitmap.recycle();
sThumbnailBitmap = null;
}
sThumbnailBitmap =
Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(sThumbnailBitmap);
int contentWidth = view.getContentWidth();
float overviewScale = scaledWidth / (view.getScale() * contentWidth);
if (view instanceof BrowserWebView) {
int dy = -((BrowserWebView)view).getTitleHeight();
canvas.translate(0, dy * overviewScale);
}
canvas.scale(overviewScale, overviewScale);
if (view instanceof BrowserWebView) {
((BrowserWebView)view).drawContent(canvas);
} else {
view.draw(canvas);
}
Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
width, height, true);
canvas.setBitmap(null);
return ret;
}
private void updateScreenshot(Tab tab) {
// If this is a bookmarked site, add a screenshot to the database.
// FIXME: Would like to make sure there is actually something to
// draw, but the API for that (WebViewCore.pictureReady()) is not
// currently accessible here.
WebView view = tab.getWebView();
if (view == null) {
// Tab was destroyed
return;
}
final String url = tab.getUrl();
final String originalUrl = view.getOriginalUrl();
if (TextUtils.isEmpty(url)) {
return;
}
// Only update thumbnails for web urls (http(s)://), not for
// about:, javascript:, data:, etc...
// Unless it is a bookmarked site, then always update
if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
return;
}
final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
getDesiredThumbnailHeight(mActivity));
if (bm == null) {
return;
}
final ContentResolver cr = mActivity.getContentResolver();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... unused) {
Cursor cursor = null;
try {
// TODO: Clean this up
cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
if (cursor != null && cursor.moveToFirst()) {
final ByteArrayOutputStream os =
new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, os);
ContentValues values = new ContentValues();
values.put(Images.THUMBNAIL, os.toByteArray());
do {
values.put(Images.URL, cursor.getString(0));
cr.update(Images.CONTENT_URI, values, null, null);
} while (cursor.moveToNext());
}
} catch (IllegalStateException e) {
// Ignore
} finally {
if (cursor != null) cursor.close();
}
return null;
}
}.execute();
}
private class Copy implements OnMenuItemClickListener {
private CharSequence mText;
public boolean onMenuItemClick(MenuItem item) {
copy(mText);
return true;
}
public Copy(CharSequence toCopy) {
mText = toCopy;
}
}
private static class Download implements OnMenuItemClickListener {
private Activity mActivity;
private String mText;
private boolean mPrivateBrowsing;
private static final String FALLBACK_EXTENSION = "dat";
private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
public boolean onMenuItemClick(MenuItem item) {
if (DataUri.isDataUri(mText)) {
saveDataUri();
} else {
DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
null, null, mPrivateBrowsing);
}
return true;
}
public Download(Activity activity, String toDownload, boolean privateBrowsing) {
mActivity = activity;
mText = toDownload;
mPrivateBrowsing = privateBrowsing;
}
/**
* Treats mText as a data URI and writes its contents to a file
* based on the current time.
*/
private void saveDataUri() {
FileOutputStream outputStream = null;
try {
DataUri uri = new DataUri(mText);
File target = getTarget(uri);
outputStream = new FileOutputStream(target);
outputStream.write(uri.getData());
final DownloadManager manager =
(DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
manager.addCompletedDownload(target.getName(),
mActivity.getTitle().toString(), false,
uri.getMimeType(), target.getAbsolutePath(),
(long)uri.getData().length, true);
} catch (IOException e) {
Log.e(LOGTAG, "Could not save data URL");
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
// ignore close errors
}
}
}
}
/**
* Creates a File based on the current time stamp and uses
* the mime type of the DataUri to get the extension.
*/
private File getTarget(DataUri uri) throws IOException {
File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
String nameBase = format.format(new Date());
String mimeType = uri.getMimeType();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
if (extension == null) {
Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
extension = FALLBACK_EXTENSION;
}
extension = "." + extension; // createTempFile needs the '.'
File targetFile = File.createTempFile(nameBase, extension, dir);
return targetFile;
}
}
private static class SelectText implements OnMenuItemClickListener {
private WebViewClassic mWebView;
public boolean onMenuItemClick(MenuItem item) {
if (mWebView != null) {
return mWebView.selectText();
}
return false;
}
public SelectText(WebView webView) {
mWebView = WebViewClassic.fromWebView(webView);
}
}
/********************** TODO: UI stuff *****************************/
// these methods have been copied, they still need to be cleaned up
/****************** tabs ***************************************************/
// basic tab interactions:
// it is assumed that tabcontrol already knows about the tab
protected void addTab(Tab tab) {
mUi.addTab(tab);
}
protected void removeTab(Tab tab) {
mUi.removeTab(tab);
mTabControl.removeTab(tab);
mCrashRecoveryHandler.backupState();
}
@Override
public void setActiveTab(Tab tab) {
// monkey protection against delayed start
if (tab != null) {
mTabControl.setCurrentTab(tab);
// the tab is guaranteed to have a webview after setCurrentTab
mUi.setActiveTab(tab);
}
}
protected void closeEmptyTab() {
Tab current = mTabControl.getCurrentTab();
if (current != null
&& current.getWebView().copyBackForwardList().getSize() == 0) {
closeCurrentTab();
}
}
protected void reuseTab(Tab appTab, UrlData urlData) {
// Dismiss the subwindow if applicable.
dismissSubWindow(appTab);
// Since we might kill the WebView, remove it from the
// content view first.
mUi.detachTab(appTab);
// Recreate the main WebView after destroying the old one.
mTabControl.recreateWebView(appTab);
// TODO: analyze why the remove and add are necessary
mUi.attachTab(appTab);
if (mTabControl.getCurrentTab() != appTab) {
switchToTab(appTab);
loadUrlDataIn(appTab, urlData);
} else {
// If the tab was the current tab, we have to attach
// it to the view system again.
setActiveTab(appTab);
loadUrlDataIn(appTab, urlData);
}
}
// Remove the sub window if it exists. Also called by TabControl when the
// user clicks the 'X' to dismiss a sub window.
public void dismissSubWindow(Tab tab) {
removeSubWindow(tab);
// dismiss the subwindow. This will destroy the WebView.
tab.dismissSubWindow();
WebView wv = getCurrentTopWebView();
if (wv != null) {
wv.requestFocus();
}
}
@Override
public void removeSubWindow(Tab t) {
if (t.getSubWebView() != null) {
mUi.removeSubWindow(t.getSubViewContainer());
}
}
@Override
public void attachSubWindow(Tab tab) {
if (tab.getSubWebView() != null) {
mUi.attachSubWindow(tab.getSubViewContainer());
getCurrentTopWebView().requestFocus();
}
}
private Tab showPreloadedTab(final UrlData urlData) {
if (!urlData.isPreloaded()) {
return null;
}
final PreloadedTabControl tabControl = urlData.getPreloadedTab();
final String sbQuery = urlData.getSearchBoxQueryToSubmit();
if (sbQuery != null) {
if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
// Could not submit query. Fallback to regular tab creation
tabControl.destroy();
return null;
}
}
// check tab count and make room for new tab
if (!mTabControl.canCreateNewTab()) {
Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
if (leastUsed != null) {
closeTab(leastUsed);
}
}
Tab t = tabControl.getTab();
t.refreshIdAfterPreload();
mTabControl.addPreloadedTab(t);
addTab(t);
setActiveTab(t);
return t;
}
// open a non inconito tab with the given url data
// and set as active tab
public Tab openTab(UrlData urlData) {
Tab tab = showPreloadedTab(urlData);
if (tab == null) {
tab = createNewTab(false, true, true);
if ((tab != null) && !urlData.isEmpty()) {
loadUrlDataIn(tab, urlData);
}
}
return tab;
}
@Override
public Tab openTabToHomePage() {
return openTab(mSettings.getHomePage(), false, true, false);
}
@Override
public Tab openIncognitoTab() {
return openTab(INCOGNITO_URI, true, true, false);
}
@Override
public Tab openTab(String url, boolean incognito, boolean setActive,
boolean useCurrent) {
return openTab(url, incognito, setActive, useCurrent, null);
}
@Override
public Tab openTab(String url, Tab parent, boolean setActive,
boolean useCurrent) {
return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
setActive, useCurrent, parent);
}
public Tab openTab(String url, boolean incognito, boolean setActive,
boolean useCurrent, Tab parent) {
Tab tab = createNewTab(incognito, setActive, useCurrent);
if (tab != null) {
if (parent != null && parent != tab) {
parent.addChildTab(tab);
}
if (url != null) {
loadUrl(tab, url);
}
}
return tab;
}
// this method will attempt to create a new tab
// incognito: private browsing tab
// setActive: ste tab as current tab
// useCurrent: if no new tab can be created, return current tab
private Tab createNewTab(boolean incognito, boolean setActive,
boolean useCurrent) {
Tab tab = null;
if (mTabControl.canCreateNewTab()) {
tab = mTabControl.createNewTab(incognito);
addTab(tab);
if (setActive) {
setActiveTab(tab);
}
} else {
if (useCurrent) {
tab = mTabControl.getCurrentTab();
reuseTab(tab, null);
} else {
mUi.showMaxTabsWarning();
}
}
return tab;
}
@Override
public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
SnapshotTab tab = null;
if (mTabControl.canCreateNewTab()) {
tab = mTabControl.createSnapshotTab(snapshotId);
addTab(tab);
if (setActive) {
setActiveTab(tab);
}
} else {
mUi.showMaxTabsWarning();
}
return tab;
}
/**
* @param tab the tab to switch to
* @return boolean True if we successfully switched to a different tab. If
* the indexth tab is null, or if that tab is the same as
* the current one, return false.
*/
@Override
public boolean switchToTab(Tab tab) {
Tab currentTab = mTabControl.getCurrentTab();
if (tab == null || tab == currentTab) {
return false;
}
setActiveTab(tab);
return true;
}
@Override
public void closeCurrentTab() {
closeCurrentTab(false);
}
protected void closeCurrentTab(boolean andQuit) {
if (mTabControl.getTabCount() == 1) {
mCrashRecoveryHandler.clearState();
mTabControl.removeTab(getCurrentTab());
mActivity.finish();
return;
}
final Tab current = mTabControl.getCurrentTab();
final int pos = mTabControl.getCurrentPosition();
Tab newTab = current.getParent();
if (newTab == null) {
newTab = mTabControl.getTab(pos + 1);
if (newTab == null) {
newTab = mTabControl.getTab(pos - 1);
}
}
if (andQuit) {
mTabControl.setCurrentTab(newTab);
closeTab(current);
} else if (switchToTab(newTab)) {
// Close window
closeTab(current);
}
}
/**
* Close the tab, remove its associated title bar, and adjust mTabControl's
* current tab to a valid value.
*/
@Override
public void closeTab(Tab tab) {
if (tab == mTabControl.getCurrentTab()) {
closeCurrentTab();
} else {
removeTab(tab);
}
}
// Called when loading from context menu or LOAD_URL message
protected void loadUrlFromContext(String url) {
Tab tab = getCurrentTab();
WebView view = tab != null ? tab.getWebView() : null;
// In case the user enters nothing.
if (url != null && url.length() != 0 && tab != null && view != null) {
url = UrlUtils.smartUrlFilter(url);
if (!WebViewClassic.fromWebView(view).getWebViewClient().
shouldOverrideUrlLoading(view, url)) {
loadUrl(tab, url);
}
}
}
/**
* Load the URL into the given WebView and update the title bar
* to reflect the new load. Call this instead of WebView.loadUrl
* directly.
* @param view The WebView used to load url.
* @param url The URL to load.
*/
@Override
public void loadUrl(Tab tab, String url) {
loadUrl(tab, url, null);
}
protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
if (tab != null) {
dismissSubWindow(tab);
tab.loadUrl(url, headers);
mUi.onProgressChanged(tab);
}
}
/**
* Load UrlData into a Tab and update the title bar to reflect the new
* load. Call this instead of UrlData.loadIn directly.
* @param t The Tab used to load.
* @param data The UrlData being loaded.
*/
protected void loadUrlDataIn(Tab t, UrlData data) {
if (data != null) {
if (data.mVoiceIntent != null) {
t.activateVoiceSearchMode(data.mVoiceIntent);
} else if (data.isPreloaded()) {
// this isn't called for preloaded tabs
} else {
loadUrl(t, data.mUrl, data.mHeaders);
}
}
}
@Override
public void onUserCanceledSsl(Tab tab) {
// TODO: Figure out the "right" behavior
if (tab.canGoBack()) {
tab.goBack();
} else {
tab.loadUrl(mSettings.getHomePage(), null);
}
}
void goBackOnePageOrQuit() {
Tab current = mTabControl.getCurrentTab();
if (current == null) {
/*
* Instead of finishing the activity, simply push this to the back
* of the stack and let ActivityManager to choose the foreground
* activity. As BrowserActivity is singleTask, it will be always the
* root of the task. So we can use either true or false for
* moveTaskToBack().
*/
mActivity.moveTaskToBack(true);
return;
}
if (current.canGoBack()) {
current.goBack();
} else {
// Check to see if we are closing a window that was created by
// another window. If so, we switch back to that window.
Tab parent = current.getParent();
if (parent != null) {
switchToTab(parent);
// Now we close the other tab
closeTab(current);
} else {
if ((current.getAppId() != null) || current.closeOnBack()) {
closeCurrentTab(true);
}
/*
* Instead of finishing the activity, simply push this to the back
* of the stack and let ActivityManager to choose the foreground
* activity. As BrowserActivity is singleTask, it will be always the
* root of the task. So we can use either true or false for
* moveTaskToBack().
*/
mActivity.moveTaskToBack(true);
}
}
}
/**
* Feed the previously stored results strings to the BrowserProvider so that
* the SearchDialog will show them instead of the standard searches.
* @param result String to show on the editable line of the SearchDialog.
*/
@Override
public void showVoiceSearchResults(String result) {
ContentProviderClient client = mActivity.getContentResolver()
.acquireContentProviderClient(Browser.BOOKMARKS_URI);
ContentProvider prov = client.getLocalContentProvider();
BrowserProvider bp = (BrowserProvider) prov;
bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
client.release();
Bundle bundle = createGoogleSearchSourceBundle(
GOOGLE_SEARCH_SOURCE_SEARCHKEY);
bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
startSearch(result, false, bundle, false);
}
private void startSearch(String initialQuery, boolean selectInitialQuery,
Bundle appSearchData, boolean globalSearch) {
if (appSearchData == null) {
appSearchData = createGoogleSearchSourceBundle(
GOOGLE_SEARCH_SOURCE_TYPE);
}
SearchEngine searchEngine = mSettings.getSearchEngine();
if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
}
mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
globalSearch);
}
private Bundle createGoogleSearchSourceBundle(String source) {
Bundle bundle = new Bundle();
bundle.putString(Search.SOURCE, source);
return bundle;
}
/**
* helper method for key handler
* returns the current tab if it can't advance
*/
private Tab getNextTab() {
int pos = mTabControl.getCurrentPosition() + 1;
if (pos >= mTabControl.getTabCount()) {
pos = 0;
}
return mTabControl.getTab(pos);
}
/**
* helper method for key handler
* returns the current tab if it can't advance
*/
private Tab getPrevTab() {
int pos = mTabControl.getCurrentPosition() - 1;
if ( pos < 0) {
pos = mTabControl.getTabCount() - 1;
}
return mTabControl.getTab(pos);
}
boolean isMenuOrCtrlKey(int keyCode) {
return (KeyEvent.KEYCODE_MENU == keyCode)
|| (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
|| (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
}
/**
* handle key events in browser
*
* @param keyCode
* @param event
* @return true if handled, false to pass to super
*/
boolean onKeyDown(int keyCode, KeyEvent event) {
boolean noModifiers = event.hasNoModifiers();
// Even if MENU is already held down, we need to call to super to open
// the IME on long press.
if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
mMenuIsDown = true;
return false;
}
WebView webView = getCurrentTopWebView();
Tab tab = getCurrentTab();
if (webView == null || tab == null) return false;
boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
switch(keyCode) {
case KeyEvent.KEYCODE_TAB:
if (event.isCtrlPressed()) {
if (event.isShiftPressed()) {
// prev tab
switchToTab(getPrevTab());
} else {
// next tab
switchToTab(getNextTab());
}
return true;
}
break;
case KeyEvent.KEYCODE_SPACE:
// WebView/WebTextView handle the keys in the KeyDown. As
// the Activity's shortcut keys are only handled when WebView
// doesn't, have to do it in onKeyDown instead of onKeyUp.
if (shift) {
pageUp();
} else if (noModifiers) {
pageDown();
}
return true;
case KeyEvent.KEYCODE_BACK:
if (!noModifiers) break;
event.startTracking();
return true;
case KeyEvent.KEYCODE_FORWARD:
if (!noModifiers) break;
tab.goForward();
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (ctrl) {
tab.goBack();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (ctrl) {
tab.goForward();
return true;
}
break;
case KeyEvent.KEYCODE_A:
if (ctrl) {
WebViewClassic.fromWebView(webView).selectAll();
return true;
}
break;
// case KeyEvent.KEYCODE_B: // menu
case KeyEvent.KEYCODE_C:
if (ctrl) {
WebViewClassic.fromWebView(webView).copySelection();
return true;
}
break;
// case KeyEvent.KEYCODE_D: // menu
// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
// case KeyEvent.KEYCODE_F: // menu
// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
// case KeyEvent.KEYCODE_H: // menu
// case KeyEvent.KEYCODE_I: // unused
// case KeyEvent.KEYCODE_J: // menu
// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
// case KeyEvent.KEYCODE_L: // menu
// case KeyEvent.KEYCODE_M: // unused
// case KeyEvent.KEYCODE_N: // in Chrome: new window
// case KeyEvent.KEYCODE_O: // in Chrome: open file
// case KeyEvent.KEYCODE_P: // in Chrome: print page
// case KeyEvent.KEYCODE_Q: // unused
// case KeyEvent.KEYCODE_R:
// case KeyEvent.KEYCODE_S: // in Chrome: saves page
case KeyEvent.KEYCODE_T:
// we can't use the ctrl/shift flags, they check for
// exclusive use of a modifier
if (event.isCtrlPressed()) {
if (event.isShiftPressed()) {
openIncognitoTab();
} else {
openTabToHomePage();
}
return true;
}
break;
// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
// case KeyEvent.KEYCODE_V: // text view intercepts to paste
// case KeyEvent.KEYCODE_W: // menu
// case KeyEvent.KEYCODE_X: // text view intercepts to cut
// case KeyEvent.KEYCODE_Y: // unused
// case KeyEvent.KEYCODE_Z: // unused
}
// it is a regular key and webview is not null
return mUi.dispatchKey(keyCode, event);
}
boolean onKeyLongPress(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mUi.isWebShowing()) {
bookmarksOrHistoryPicker(ComboViews.History);
return true;
}
break;
}
return false;
}
boolean onKeyUp(int keyCode, KeyEvent event) {
if (isMenuOrCtrlKey(keyCode)) {
mMenuIsDown = false;
if (KeyEvent.KEYCODE_MENU == keyCode
&& event.isTracking() && !event.isCanceled()) {
return onMenuKey();
}
}
if (!event.hasNoModifiers()) return false;
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.isTracking() && !event.isCanceled()) {
onBackKey();
return true;
}
break;
}
return false;
}
public boolean isMenuDown() {
return mMenuIsDown;
}
public void setupAutoFill(Message message) {
// Open the settings activity at the AutoFill profile fragment so that
// the user can create a new profile. When they return, we will dispatch
// the message so that we can autofill the form using their new profile.
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
AutoFillSettingsFragment.class.getName());
mAutoFillSetupMessage = message;
mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
}
public boolean onSearchRequested() {
mUi.editUrl(false);
return true;
}
@Override
public boolean shouldCaptureThumbnails() {
return mUi.shouldCaptureThumbnails();
}
@Override
public void setBlockEvents(boolean block) {
mBlockEvents = block;
}
public boolean dispatchKeyEvent(KeyEvent event) {
return mBlockEvents;
}
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
return mBlockEvents;
}
public boolean dispatchTouchEvent(MotionEvent ev) {
return mBlockEvents;
}
public boolean dispatchTrackballEvent(MotionEvent ev) {
return mBlockEvents;
}
public boolean dispatchGenericMotionEvent(MotionEvent ev) {
return mBlockEvents;
}
}
| true | true | public boolean onOptionsItemSelected(MenuItem item) {
if (null == getCurrentTopWebView()) {
return false;
}
if (mMenuIsDown) {
// The shortcut action consumes the MENU. Even if it is still down,
// it won't trigger the next shortcut action. In the case of the
// shortcut action triggering a new activity, like Bookmarks, we
// won't get onKeyUp for MENU. So it is important to reset it here.
mMenuIsDown = false;
}
if (mUi.onOptionsItemSelected(item)) {
// ui callback handled it
return true;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.incognito_menu_id:
openIncognitoTab();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
break;
case R.id.history_menu_id:
bookmarksOrHistoryPicker(ComboViews.History);
break;
case R.id.snapshots_menu_id:
bookmarksOrHistoryPicker(ComboViews.Snapshots);
break;
case R.id.add_bookmark_menu_id:
bookmarkCurrentPage();
break;
case R.id.stop_reload_menu_id:
if (isInLoad()) {
stopLoading();
} else {
getCurrentTopWebView().reload();
}
break;
case R.id.back_menu_id:
getCurrentTab().goBack();
break;
case R.id.forward_menu_id:
getCurrentTab().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentTab();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
loadUrl(current, mSettings.getHomePage());
break;
case R.id.preferences_menu_id:
openPreferences();
break;
case R.id.find_menu_id:
break;
case R.id.save_snapshot_menu_id:
final Tab source = getTabControl().getCurrentTab();
if (source == null) break;
final ContentResolver cr = mActivity.getContentResolver();
final ContentValues values = source.createSnapshotValues();
if (values != null) {
new AsyncTask<Tab, Void, Long>() {
@Override
protected Long doInBackground(Tab... params) {
Uri result = cr.insert(Snapshots.CONTENT_URI, values);
if (result == null) {
return null;
}
long id = ContentUris.parseId(result);
return id;
}
@Override
protected void onPostExecute(Long id) {
if (id == null) {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
return;
}
Bundle b = new Bundle();
b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
mUi.showComboView(ComboViews.Snapshots, b);
};
}.execute(source);
} else {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
}
break;
case R.id.page_info_menu_id:
showPageInfo();
break;
case R.id.snapshot_go_live:
goLive();
return true;
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
return false;
}
shareCurrentPage(currentTab);
break;
case R.id.dump_nav_menu_id:
getCurrentTopWebView().debugDump();
break;
case R.id.zoom_in_menu_id:
getCurrentTopWebView().zoomIn();
break;
case R.id.zoom_out_menu_id:
getCurrentTopWebView().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads();
break;
case R.id.ua_desktop_menu_id:
toggleUserAgent();
break;
case R.id.window_one_menu_id:
case R.id.window_two_menu_id:
case R.id.window_three_menu_id:
case R.id.window_four_menu_id:
case R.id.window_five_menu_id:
case R.id.window_six_menu_id:
case R.id.window_seven_menu_id:
case R.id.window_eight_menu_id:
{
int menuid = item.getItemId();
for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Tab desiredTab = mTabControl.getTab(id);
if (desiredTab != null &&
desiredTab != mTabControl.getCurrentTab()) {
switchToTab(desiredTab);
}
break;
}
}
}
break;
default:
return false;
}
return true;
}
| public boolean onOptionsItemSelected(MenuItem item) {
if (null == getCurrentTopWebView()) {
return false;
}
if (mMenuIsDown) {
// The shortcut action consumes the MENU. Even if it is still down,
// it won't trigger the next shortcut action. In the case of the
// shortcut action triggering a new activity, like Bookmarks, we
// won't get onKeyUp for MENU. So it is important to reset it here.
mMenuIsDown = false;
}
if (mUi.onOptionsItemSelected(item)) {
// ui callback handled it
return true;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.incognito_menu_id:
openIncognitoTab();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
break;
case R.id.history_menu_id:
bookmarksOrHistoryPicker(ComboViews.History);
break;
case R.id.snapshots_menu_id:
bookmarksOrHistoryPicker(ComboViews.Snapshots);
break;
case R.id.add_bookmark_menu_id:
bookmarkCurrentPage();
break;
case R.id.stop_reload_menu_id:
if (isInLoad()) {
stopLoading();
} else {
getCurrentTopWebView().reload();
}
break;
case R.id.back_menu_id:
getCurrentTab().goBack();
break;
case R.id.forward_menu_id:
getCurrentTab().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentTab();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
loadUrl(current, mSettings.getHomePage());
break;
case R.id.preferences_menu_id:
openPreferences();
break;
case R.id.find_menu_id:
findOnPage();
break;
case R.id.save_snapshot_menu_id:
final Tab source = getTabControl().getCurrentTab();
if (source == null) break;
final ContentResolver cr = mActivity.getContentResolver();
final ContentValues values = source.createSnapshotValues();
if (values != null) {
new AsyncTask<Tab, Void, Long>() {
@Override
protected Long doInBackground(Tab... params) {
Uri result = cr.insert(Snapshots.CONTENT_URI, values);
if (result == null) {
return null;
}
long id = ContentUris.parseId(result);
return id;
}
@Override
protected void onPostExecute(Long id) {
if (id == null) {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
return;
}
Bundle b = new Bundle();
b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
mUi.showComboView(ComboViews.Snapshots, b);
};
}.execute(source);
} else {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
}
break;
case R.id.page_info_menu_id:
showPageInfo();
break;
case R.id.snapshot_go_live:
goLive();
return true;
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
return false;
}
shareCurrentPage(currentTab);
break;
case R.id.dump_nav_menu_id:
getCurrentTopWebView().debugDump();
break;
case R.id.zoom_in_menu_id:
getCurrentTopWebView().zoomIn();
break;
case R.id.zoom_out_menu_id:
getCurrentTopWebView().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads();
break;
case R.id.ua_desktop_menu_id:
toggleUserAgent();
break;
case R.id.window_one_menu_id:
case R.id.window_two_menu_id:
case R.id.window_three_menu_id:
case R.id.window_four_menu_id:
case R.id.window_five_menu_id:
case R.id.window_six_menu_id:
case R.id.window_seven_menu_id:
case R.id.window_eight_menu_id:
{
int menuid = item.getItemId();
for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Tab desiredTab = mTabControl.getTab(id);
if (desiredTab != null &&
desiredTab != mTabControl.getCurrentTab()) {
switchToTab(desiredTab);
}
break;
}
}
}
break;
default:
return false;
}
return true;
}
|
diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/TLDValidator.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/TLDValidator.java
index 4f9388385..b9f4e87db 100644
--- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/TLDValidator.java
+++ b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/TLDValidator.java
@@ -1,289 +1,291 @@
/*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jst.jsp.core.internal.validation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.content.IContentTypeSettings;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jst.jsp.core.internal.Assert;
import org.eclipse.jst.jsp.core.internal.JSPCoreMessages;
import org.eclipse.jst.jsp.core.internal.JSPCorePlugin;
import org.eclipse.jst.jsp.core.internal.Logger;
import org.eclipse.jst.jsp.core.internal.contentmodel.tld.provisional.JSP11TLDNames;
import org.eclipse.jst.jsp.core.internal.contentmodel.tld.provisional.JSP12TLDNames;
import org.eclipse.jst.jsp.core.internal.preferences.JSPCorePreferenceNames;
import org.eclipse.osgi.util.NLS;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.validate.ValidationMessage;
import org.eclipse.wst.validation.AbstractValidator;
import org.eclipse.wst.validation.ValidationResult;
import org.eclipse.wst.validation.ValidationState;
import org.eclipse.wst.validation.ValidatorMessage;
import org.eclipse.wst.validation.internal.provisional.core.IMessage;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
import org.eclipse.wst.xml.core.internal.validation.MarkupValidator;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* A miniature validator for .tld files. Checks for valid class names.
*/
public class TLDValidator extends AbstractValidator {
private static final String MARKER_TYPE = "org.eclipse.jst.jsp.core.validationMarker"; //$NON-NLS-1$
private static final String PREFERENCE_NODE_QUALIFIER = JSPCorePlugin.getDefault().getBundle().getSymbolicName();
private IPreferencesService fPreferencesService = Platform.getPreferencesService();
private static final String[] classElementNames = new String[]{JSP11TLDNames.TAGCLASS, JSP12TLDNames.TAG_CLASS, JSP11TLDNames.TEICLASS, JSP12TLDNames.TEI_CLASS, JSP12TLDNames.VALIDATOR_CLASS, JSP12TLDNames.VARIABLE_CLASS, JSP12TLDNames.LISTENER_CLASS};
private static final String[] missingClassMessages = new String[]{JSPCoreMessages.TaglibHelper_3, JSPCoreMessages.TaglibHelper_3, JSPCoreMessages.TaglibHelper_0, JSPCoreMessages.TaglibHelper_0, JSPCoreMessages.TLDValidator_MissingValidator, JSPCoreMessages.TLDValidator_MissingVariable, JSPCoreMessages.TLDValidator_MissingListener};
private static final String[] missingClassSeverityPreferenceKeys = new String[]{JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TEI_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TEI_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND};
private static final String TAGX_CONTENT_TYPE_ID = "org.eclipse.jst.jsp.core.tagxsource"; //$NON-NLS-1$
private List fTagXexts = null;
private List fTagXnames = null;
public TLDValidator() {
super();
Assert.isTrue(classElementNames.length == missingClassMessages.length, "mismanaged arrays"); //$NON-NLS-1$
Assert.isTrue(classElementNames.length == missingClassSeverityPreferenceKeys.length, "mismanaged arrays"); //$NON-NLS-1$
Assert.isTrue(missingClassMessages.length == missingClassSeverityPreferenceKeys.length, "mismanaged arrays"); //$NON-NLS-1$
initContentTypes();
}
private void initContentTypes() {
fTagXexts = new ArrayList(Arrays.asList(Platform.getContentTypeManager().getContentType(TAGX_CONTENT_TYPE_ID).getFileSpecs(IContentTypeSettings.FILE_EXTENSION_SPEC)));
fTagXnames = new ArrayList(Arrays.asList(Platform.getContentTypeManager().getContentType(TAGX_CONTENT_TYPE_ID).getFileSpecs(IContentTypeSettings.FILE_NAME_SPEC)));
}
private Map checkClass(IJavaProject javaProject, Node classSpecifier, IScopeContext[] preferenceScopes, String preferenceKey, String errorMessage) {
String className = getTextContents(classSpecifier);
if (className != null && className.length() > 2) {
IType type = null;
try {
type = javaProject.findType(className);
}
catch (JavaModelException e) {
return null;
}
if (type == null || !type.exists()) {
Object severity = getMessageSeverity(preferenceScopes, preferenceKey);
if (severity == null)
return null;
IDOMNode classElement = (IDOMNode) classSpecifier;
Map markerValues = new HashMap();
markerValues.put(IMarker.SEVERITY, severity);
int start = classElement.getStartOffset();
if (classElement.getStartStructuredDocumentRegion() != null && classElement.getEndStructuredDocumentRegion() != null)
start = classElement.getStartStructuredDocumentRegion().getEndOffset();
markerValues.put(IMarker.CHAR_START, new Integer(start));
int end = classElement.getEndOffset();
if (classElement.getStartStructuredDocumentRegion() != null && classElement.getEndStructuredDocumentRegion() != null)
end = classElement.getEndStructuredDocumentRegion().getStartOffset();
markerValues.put(IMarker.CHAR_END, new Integer(end));
int line = classElement.getStructuredDocument().getLineOfOffset(start);
markerValues.put(IMarker.LINE_NUMBER, new Integer(line + 1));
markerValues.put(IMarker.MESSAGE, NLS.bind(errorMessage, (errorMessage.indexOf("{1}") >= 0) ? new String[]{getTagName(classSpecifier), className} : new String[]{className})); //$NON-NLS-1$
return markerValues;
}
}
return null;
}
private Map[] detectProblems(IJavaProject javaProject, IFile tld, IScopeContext[] preferenceScopes) throws CoreException {
List problems = new ArrayList();
IStructuredModel m = null;
try {
m = StructuredModelManager.getModelManager().getModelForRead(tld);
if (m != null && m instanceof IDOMModel) {
IDOMDocument document = ((IDOMModel) m).getDocument();
for (int i = 0; i < classElementNames.length; i++) {
NodeList classes = document.getElementsByTagName(classElementNames[i]);
for (int j = 0; j < classes.getLength(); j++) {
Map problem = checkClass(javaProject, classes.item(j), preferenceScopes, missingClassSeverityPreferenceKeys[i], missingClassMessages[i]);
if (problem != null)
problems.add(problem);
}
}
}
}
catch (IOException e) {
Logger.logException(e);
}
finally {
if (m != null)
m.releaseFromRead();
}
return (Map[]) problems.toArray(new Map[problems.size()]);
}
Integer getMessageSeverity(IScopeContext[] preferenceScopes, String key) {
int sev = fPreferencesService.getInt(PREFERENCE_NODE_QUALIFIER, key, IMessage.NORMAL_SEVERITY, preferenceScopes);
switch (sev) {
case ValidationMessage.ERROR :
return new Integer(IMarker.SEVERITY_ERROR);
case ValidationMessage.WARNING :
return new Integer(IMarker.SEVERITY_WARNING);
case ValidationMessage.INFORMATION :
return new Integer(IMarker.SEVERITY_INFO);
case ValidationMessage.IGNORE :
return null;
}
return new Integer(IMarker.SEVERITY_WARNING);
}
private String getTagName(Node classSpecifier) {
Node tagElement = classSpecifier.getParentNode();
Node child = tagElement.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
String name = child.getNodeName();
if (JSP11TLDNames.NAME.equals(name))
return getTextContents(child);
}
child = child.getNextSibling();
}
return "";
}
private String getTextContents(Node parent) {
NodeList children = parent.getChildNodes();
if (children.getLength() == 1) {
return children.item(0).getNodeValue().trim();
}
StringBuffer s = new StringBuffer();
Node child = parent.getFirstChild();
while (child != null) {
s.append(child.getNodeValue().trim());
child = child.getNextSibling();
}
return s.toString().trim();
}
public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor) {
if (resource.getType() != IResource.FILE)
return null;
ValidationResult result = new ValidationResult();
IFile file = (IFile) resource;
if (file.isAccessible()) {
// TAGX
if (fTagXexts.contains(file.getFileExtension()) || fTagXnames.contains(file.getName())) {
monitor.beginTask("", 3);
org.eclipse.wst.xml.core.internal.validation.eclipse.Validator xmlValidator = new org.eclipse.wst.xml.core.internal.validation.eclipse.Validator();
ValidationResult result3 = new MarkupValidator().validate(resource, kind, state, new SubProgressMonitor(monitor, 1));
+ if(monitor.isCanceled()) return result;
ValidationResult result2 = xmlValidator.validate(resource, kind, state, new SubProgressMonitor(monitor, 1));
+ if(monitor.isCanceled()) return result;
ValidationResult result1 = new JSPActionValidator().validate(resource, kind, state, new SubProgressMonitor(monitor, 1));
List messages = new ArrayList(result1.getReporter(new NullProgressMonitor()).getMessages());
messages.addAll(result2.getReporter(new NullProgressMonitor()).getMessages());
messages.addAll(result3.getReporter(new NullProgressMonitor()).getMessages());
for (int i = 0; i < messages.size(); i++) {
IMessage message = (IMessage) messages.get(i);
if (message.getText() != null && message.getText().length() > 0) {
ValidatorMessage vmessage = ValidatorMessage.create(message.getText(), resource);
if (message.getAttributes() != null) {
Map attrs = message.getAttributes();
Iterator it = attrs.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Boolean)) {
it.remove();
}
}
vmessage.setAttributes(attrs);
}
vmessage.setAttribute(IMarker.LINE_NUMBER, message.getLineNumber());
vmessage.setAttribute(IMarker.MESSAGE, message.getText());
if (message.getOffset() > -1) {
vmessage.setAttribute(IMarker.CHAR_START, message.getOffset());
vmessage.setAttribute(IMarker.CHAR_END, message.getOffset() + message.getLength());
}
int severity = 0;
switch (message.getSeverity()) {
case IMessage.HIGH_SEVERITY :
severity = IMarker.SEVERITY_ERROR;
break;
case IMessage.NORMAL_SEVERITY :
severity = IMarker.SEVERITY_WARNING;
break;
case IMessage.LOW_SEVERITY :
severity = IMarker.SEVERITY_INFO;
break;
}
vmessage.setAttribute(IMarker.SEVERITY, severity);
vmessage.setType(MARKER_TYPE);
result.add(vmessage);
}
}
monitor.done();
}
// TLD
else {
try {
final IJavaProject javaProject = JavaCore.create(file.getProject());
if (javaProject.exists()) {
IScopeContext[] scopes = new IScopeContext[]{new InstanceScope(), new DefaultScope()};
ProjectScope projectScope = new ProjectScope(file.getProject());
if (projectScope.getNode(PREFERENCE_NODE_QUALIFIER).getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false)) {
scopes = new IScopeContext[]{projectScope, new InstanceScope(), new DefaultScope()};
}
Map[] problems = detectProblems(javaProject, file, scopes);
for (int i = 0; i < problems.length; i++) {
ValidatorMessage message = ValidatorMessage.create(problems[i].get(IMarker.MESSAGE).toString(), resource);
message.setType(MARKER_TYPE);
message.setAttributes(problems[i]);
result.add(message);
}
}
}
catch (Exception e) {
Logger.logException(e);
}
}
}
return result;
}
}
| false | true | public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor) {
if (resource.getType() != IResource.FILE)
return null;
ValidationResult result = new ValidationResult();
IFile file = (IFile) resource;
if (file.isAccessible()) {
// TAGX
if (fTagXexts.contains(file.getFileExtension()) || fTagXnames.contains(file.getName())) {
monitor.beginTask("", 3);
org.eclipse.wst.xml.core.internal.validation.eclipse.Validator xmlValidator = new org.eclipse.wst.xml.core.internal.validation.eclipse.Validator();
ValidationResult result3 = new MarkupValidator().validate(resource, kind, state, new SubProgressMonitor(monitor, 1));
ValidationResult result2 = xmlValidator.validate(resource, kind, state, new SubProgressMonitor(monitor, 1));
ValidationResult result1 = new JSPActionValidator().validate(resource, kind, state, new SubProgressMonitor(monitor, 1));
List messages = new ArrayList(result1.getReporter(new NullProgressMonitor()).getMessages());
messages.addAll(result2.getReporter(new NullProgressMonitor()).getMessages());
messages.addAll(result3.getReporter(new NullProgressMonitor()).getMessages());
for (int i = 0; i < messages.size(); i++) {
IMessage message = (IMessage) messages.get(i);
if (message.getText() != null && message.getText().length() > 0) {
ValidatorMessage vmessage = ValidatorMessage.create(message.getText(), resource);
if (message.getAttributes() != null) {
Map attrs = message.getAttributes();
Iterator it = attrs.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Boolean)) {
it.remove();
}
}
vmessage.setAttributes(attrs);
}
vmessage.setAttribute(IMarker.LINE_NUMBER, message.getLineNumber());
vmessage.setAttribute(IMarker.MESSAGE, message.getText());
if (message.getOffset() > -1) {
vmessage.setAttribute(IMarker.CHAR_START, message.getOffset());
vmessage.setAttribute(IMarker.CHAR_END, message.getOffset() + message.getLength());
}
int severity = 0;
switch (message.getSeverity()) {
case IMessage.HIGH_SEVERITY :
severity = IMarker.SEVERITY_ERROR;
break;
case IMessage.NORMAL_SEVERITY :
severity = IMarker.SEVERITY_WARNING;
break;
case IMessage.LOW_SEVERITY :
severity = IMarker.SEVERITY_INFO;
break;
}
vmessage.setAttribute(IMarker.SEVERITY, severity);
vmessage.setType(MARKER_TYPE);
result.add(vmessage);
}
}
monitor.done();
}
// TLD
else {
try {
final IJavaProject javaProject = JavaCore.create(file.getProject());
if (javaProject.exists()) {
IScopeContext[] scopes = new IScopeContext[]{new InstanceScope(), new DefaultScope()};
ProjectScope projectScope = new ProjectScope(file.getProject());
if (projectScope.getNode(PREFERENCE_NODE_QUALIFIER).getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false)) {
scopes = new IScopeContext[]{projectScope, new InstanceScope(), new DefaultScope()};
}
Map[] problems = detectProblems(javaProject, file, scopes);
for (int i = 0; i < problems.length; i++) {
ValidatorMessage message = ValidatorMessage.create(problems[i].get(IMarker.MESSAGE).toString(), resource);
message.setType(MARKER_TYPE);
message.setAttributes(problems[i]);
result.add(message);
}
}
}
catch (Exception e) {
Logger.logException(e);
}
}
}
return result;
}
| public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor) {
if (resource.getType() != IResource.FILE)
return null;
ValidationResult result = new ValidationResult();
IFile file = (IFile) resource;
if (file.isAccessible()) {
// TAGX
if (fTagXexts.contains(file.getFileExtension()) || fTagXnames.contains(file.getName())) {
monitor.beginTask("", 3);
org.eclipse.wst.xml.core.internal.validation.eclipse.Validator xmlValidator = new org.eclipse.wst.xml.core.internal.validation.eclipse.Validator();
ValidationResult result3 = new MarkupValidator().validate(resource, kind, state, new SubProgressMonitor(monitor, 1));
if(monitor.isCanceled()) return result;
ValidationResult result2 = xmlValidator.validate(resource, kind, state, new SubProgressMonitor(monitor, 1));
if(monitor.isCanceled()) return result;
ValidationResult result1 = new JSPActionValidator().validate(resource, kind, state, new SubProgressMonitor(monitor, 1));
List messages = new ArrayList(result1.getReporter(new NullProgressMonitor()).getMessages());
messages.addAll(result2.getReporter(new NullProgressMonitor()).getMessages());
messages.addAll(result3.getReporter(new NullProgressMonitor()).getMessages());
for (int i = 0; i < messages.size(); i++) {
IMessage message = (IMessage) messages.get(i);
if (message.getText() != null && message.getText().length() > 0) {
ValidatorMessage vmessage = ValidatorMessage.create(message.getText(), resource);
if (message.getAttributes() != null) {
Map attrs = message.getAttributes();
Iterator it = attrs.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Boolean)) {
it.remove();
}
}
vmessage.setAttributes(attrs);
}
vmessage.setAttribute(IMarker.LINE_NUMBER, message.getLineNumber());
vmessage.setAttribute(IMarker.MESSAGE, message.getText());
if (message.getOffset() > -1) {
vmessage.setAttribute(IMarker.CHAR_START, message.getOffset());
vmessage.setAttribute(IMarker.CHAR_END, message.getOffset() + message.getLength());
}
int severity = 0;
switch (message.getSeverity()) {
case IMessage.HIGH_SEVERITY :
severity = IMarker.SEVERITY_ERROR;
break;
case IMessage.NORMAL_SEVERITY :
severity = IMarker.SEVERITY_WARNING;
break;
case IMessage.LOW_SEVERITY :
severity = IMarker.SEVERITY_INFO;
break;
}
vmessage.setAttribute(IMarker.SEVERITY, severity);
vmessage.setType(MARKER_TYPE);
result.add(vmessage);
}
}
monitor.done();
}
// TLD
else {
try {
final IJavaProject javaProject = JavaCore.create(file.getProject());
if (javaProject.exists()) {
IScopeContext[] scopes = new IScopeContext[]{new InstanceScope(), new DefaultScope()};
ProjectScope projectScope = new ProjectScope(file.getProject());
if (projectScope.getNode(PREFERENCE_NODE_QUALIFIER).getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false)) {
scopes = new IScopeContext[]{projectScope, new InstanceScope(), new DefaultScope()};
}
Map[] problems = detectProblems(javaProject, file, scopes);
for (int i = 0; i < problems.length; i++) {
ValidatorMessage message = ValidatorMessage.create(problems[i].get(IMarker.MESSAGE).toString(), resource);
message.setType(MARKER_TYPE);
message.setAttributes(problems[i]);
result.add(message);
}
}
}
catch (Exception e) {
Logger.logException(e);
}
}
}
return result;
}
|
diff --git a/android/src/com/google/zxing/client/android/QRCodeEncoder.java b/android/src/com/google/zxing/client/android/QRCodeEncoder.java
index 49420436..76fd8495 100755
--- a/android/src/com/google/zxing/client/android/QRCodeEncoder.java
+++ b/android/src/com/google/zxing/client/android/QRCodeEncoder.java
@@ -1,194 +1,195 @@
/*
* Copyright (C) 2008 ZXing 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 com.google.zxing.client.android;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Contacts;
import android.util.Log;
import android.telephony.PhoneNumberUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.ByteMatrix;
public final class QRCodeEncoder {
private final Activity mActivity;
private String mContents;
private String mDisplayContents;
private String mTitle;
public QRCodeEncoder(Activity activity, Intent intent) {
mActivity = activity;
if (!encodeContents(intent)) {
throw new IllegalArgumentException("No valid data to encode.");
}
}
public void requestBarcode(Handler handler, int pixelResolution) {
Thread encodeThread = new EncodeThread(mContents, handler, pixelResolution);
encodeThread.start();
}
public String getContents() {
return mContents;
}
public String getDisplayContents() {
return mDisplayContents;
}
public String getTitle() {
return mTitle;
}
// TODO: The string encoding should live in the core ZXing library.
private boolean encodeContents(Intent intent) {
if (intent == null) {
return false;
}
String type = intent.getStringExtra(Intents.Encode.TYPE);
if (type == null || type.length() == 0) {
return false;
}
if (type.equals(Contents.Type.TEXT)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = data;
mDisplayContents = data;
mTitle = mActivity.getString(R.string.contents_text);
}
} else if (type.equals(Contents.Type.EMAIL)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = "mailto:" + data;
mDisplayContents = data;
mTitle = mActivity.getString(R.string.contents_email);
}
} else if (type.equals(Contents.Type.PHONE)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = "tel:" + data;
mDisplayContents = PhoneNumberUtils.formatNumber(data);
mTitle = mActivity.getString(R.string.contents_phone);
}
} else if (type.equals(Contents.Type.SMS)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = "sms:" + data;
mDisplayContents = PhoneNumberUtils.formatNumber(data);
mTitle = mActivity.getString(R.string.contents_sms);
}
} else if (type.equals(Contents.Type.CONTACT)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
String name = bundle.getString(Contacts.Intents.Insert.NAME);
if (name != null && name.length() > 0) {
mContents = "MECARD:N:" + name + ';';
mDisplayContents = name;
String address = bundle.getString(Contacts.Intents.Insert.POSTAL);
if (address != null && address.length() > 0) {
mContents += "ADR:" + address + ';';
mDisplayContents += '\n' + address;
}
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = bundle.getString(Contents.PHONE_KEYS[x]);
if (phone != null && phone.length() > 0) {
mContents += "TEL:" + phone + ';';
mDisplayContents += '\n' + PhoneNumberUtils.formatNumber(phone);
}
}
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = bundle.getString(Contents.EMAIL_KEYS[x]);
if (email != null && email.length() > 0) {
mContents += "EMAIL:" + email + ';';
mDisplayContents += '\n' + email;
}
}
mContents += ";";
mTitle = mActivity.getString(R.string.contents_contact);
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
- double latitude = bundle.getDouble("LAT", Double.NaN);
- double longitude = bundle.getDouble("LONG", Double.NaN);
- if (!Double.isNaN(latitude) && !Double.isNaN(longitude)) {
+ // These must use Bundle.getFloat(), not getDouble(), it's part of the API.
+ float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
+ float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
+ if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
mContents = "geo:" + latitude + ',' + longitude;
mDisplayContents = latitude + "," + longitude;
mTitle = mActivity.getString(R.string.contents_location);
}
}
}
return mContents != null && mContents.length() > 0;
}
private static final class EncodeThread extends Thread {
private static final String TAG = "EncodeThread";
private final String mContents;
private final Handler mHandler;
private final int mPixelResolution;
EncodeThread(String contents, Handler handler, int pixelResolution) {
mContents = contents;
mHandler = handler;
mPixelResolution = pixelResolution;
}
public void run() {
try {
ByteMatrix result = new MultiFormatWriter().encode(mContents, BarcodeFormat.QR_CODE,
mPixelResolution, mPixelResolution);
int width = result.width();
int height = result.height();
byte[][] array = result.getArray();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int grey = array[y][x] & 0xff;
//pixels[y * width + x] = (0xff << 24) | (grey << 16) | (grey << 8) | grey;
pixels[y * width + x] = 0xff000000 | (0x00010101 * grey);
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
Message message = Message.obtain(mHandler, R.id.encode_succeeded);
message.obj = bitmap;
message.sendToTarget();
} catch (WriterException e) {
Log.e(TAG, e.toString());
Message message = Message.obtain(mHandler, R.id.encode_failed);
message.sendToTarget();
} catch (IllegalArgumentException e) {
Log.e(TAG, e.toString());
Message message = Message.obtain(mHandler, R.id.encode_failed);
message.sendToTarget();
}
}
}
}
| true | true | private boolean encodeContents(Intent intent) {
if (intent == null) {
return false;
}
String type = intent.getStringExtra(Intents.Encode.TYPE);
if (type == null || type.length() == 0) {
return false;
}
if (type.equals(Contents.Type.TEXT)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = data;
mDisplayContents = data;
mTitle = mActivity.getString(R.string.contents_text);
}
} else if (type.equals(Contents.Type.EMAIL)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = "mailto:" + data;
mDisplayContents = data;
mTitle = mActivity.getString(R.string.contents_email);
}
} else if (type.equals(Contents.Type.PHONE)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = "tel:" + data;
mDisplayContents = PhoneNumberUtils.formatNumber(data);
mTitle = mActivity.getString(R.string.contents_phone);
}
} else if (type.equals(Contents.Type.SMS)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = "sms:" + data;
mDisplayContents = PhoneNumberUtils.formatNumber(data);
mTitle = mActivity.getString(R.string.contents_sms);
}
} else if (type.equals(Contents.Type.CONTACT)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
String name = bundle.getString(Contacts.Intents.Insert.NAME);
if (name != null && name.length() > 0) {
mContents = "MECARD:N:" + name + ';';
mDisplayContents = name;
String address = bundle.getString(Contacts.Intents.Insert.POSTAL);
if (address != null && address.length() > 0) {
mContents += "ADR:" + address + ';';
mDisplayContents += '\n' + address;
}
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = bundle.getString(Contents.PHONE_KEYS[x]);
if (phone != null && phone.length() > 0) {
mContents += "TEL:" + phone + ';';
mDisplayContents += '\n' + PhoneNumberUtils.formatNumber(phone);
}
}
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = bundle.getString(Contents.EMAIL_KEYS[x]);
if (email != null && email.length() > 0) {
mContents += "EMAIL:" + email + ';';
mDisplayContents += '\n' + email;
}
}
mContents += ";";
mTitle = mActivity.getString(R.string.contents_contact);
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
double latitude = bundle.getDouble("LAT", Double.NaN);
double longitude = bundle.getDouble("LONG", Double.NaN);
if (!Double.isNaN(latitude) && !Double.isNaN(longitude)) {
mContents = "geo:" + latitude + ',' + longitude;
mDisplayContents = latitude + "," + longitude;
mTitle = mActivity.getString(R.string.contents_location);
}
}
}
return mContents != null && mContents.length() > 0;
}
| private boolean encodeContents(Intent intent) {
if (intent == null) {
return false;
}
String type = intent.getStringExtra(Intents.Encode.TYPE);
if (type == null || type.length() == 0) {
return false;
}
if (type.equals(Contents.Type.TEXT)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = data;
mDisplayContents = data;
mTitle = mActivity.getString(R.string.contents_text);
}
} else if (type.equals(Contents.Type.EMAIL)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = "mailto:" + data;
mDisplayContents = data;
mTitle = mActivity.getString(R.string.contents_email);
}
} else if (type.equals(Contents.Type.PHONE)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = "tel:" + data;
mDisplayContents = PhoneNumberUtils.formatNumber(data);
mTitle = mActivity.getString(R.string.contents_phone);
}
} else if (type.equals(Contents.Type.SMS)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
mContents = "sms:" + data;
mDisplayContents = PhoneNumberUtils.formatNumber(data);
mTitle = mActivity.getString(R.string.contents_sms);
}
} else if (type.equals(Contents.Type.CONTACT)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
String name = bundle.getString(Contacts.Intents.Insert.NAME);
if (name != null && name.length() > 0) {
mContents = "MECARD:N:" + name + ';';
mDisplayContents = name;
String address = bundle.getString(Contacts.Intents.Insert.POSTAL);
if (address != null && address.length() > 0) {
mContents += "ADR:" + address + ';';
mDisplayContents += '\n' + address;
}
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = bundle.getString(Contents.PHONE_KEYS[x]);
if (phone != null && phone.length() > 0) {
mContents += "TEL:" + phone + ';';
mDisplayContents += '\n' + PhoneNumberUtils.formatNumber(phone);
}
}
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = bundle.getString(Contents.EMAIL_KEYS[x]);
if (email != null && email.length() > 0) {
mContents += "EMAIL:" + email + ';';
mDisplayContents += '\n' + email;
}
}
mContents += ";";
mTitle = mActivity.getString(R.string.contents_contact);
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
// These must use Bundle.getFloat(), not getDouble(), it's part of the API.
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
mContents = "geo:" + latitude + ',' + longitude;
mDisplayContents = latitude + "," + longitude;
mTitle = mActivity.getString(R.string.contents_location);
}
}
}
return mContents != null && mContents.length() > 0;
}
|
diff --git a/src/edu/csupomona/kyra/component/render/ai/AntiZombieRender.java b/src/edu/csupomona/kyra/component/render/ai/AntiZombieRender.java
index de18293..02ce672 100644
--- a/src/edu/csupomona/kyra/component/render/ai/AntiZombieRender.java
+++ b/src/edu/csupomona/kyra/component/render/ai/AntiZombieRender.java
@@ -1,30 +1,40 @@
package edu.csupomona.kyra.component.render.ai;
import org.newdawn.slick.Animation;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class AntiZombieRender extends AIRender {
public AntiZombieRender(String id) throws SlickException {
super(id);
- Image[] bERightmovement = {
+ int[] moveTween = {200, 200, 200, 200};
+ Image[] moveRight = {
new Image("img/anti-enemy-move-right_001.png"),
new Image("img/anti-enemy-move-right_002.png"),
new Image("img/anti-enemy-move-right_001.png"),
new Image("img/anti-enemy-move-right_003.png")
};
- Image[] bELeftmovement = {
+ Image[] moveLeft = {
new Image("img/anti-enemy-move-left_001.png"),
new Image("img/anti-enemy-move-left_002.png"),
new Image("img/anti-enemy-move-left_001.png"),
new Image("img/anti-enemy-move-left_003.png")
};
- int[] movementDuration = {200, 200, 200, 200};
+ setMoveRight(new Animation(moveRight, moveTween, false));
+ setMoveLeft(new Animation(moveLeft, moveTween, false));
- animations = new Animation[2];
- animations[0] = new Animation(bELeftmovement, movementDuration, false);
- animations[1] = new Animation(bERightmovement, movementDuration, false);
+ int[] deathTween = {500,175};
+ Image[] deathRight = {
+ new Image("img/anti-enemy-death-right-1.png"),
+ new Image("img/anti-enemy-death-right-2.png")
+ };
+ Image[] deathLeft = {
+ new Image("img/anti-enemy-death-left-1.png"),
+ new Image("img/amti-enemy-death-left-2.png")
+ };
+ setDeathRight(new Animation(deathRight, deathTween, false));
+ setDeathLeft(new Animation(deathLeft, deathTween, false));
- super.setAnimations(animations);
+ setSprite(super.moveLeft);
}
}
| false | true | public AntiZombieRender(String id) throws SlickException {
super(id);
Image[] bERightmovement = {
new Image("img/anti-enemy-move-right_001.png"),
new Image("img/anti-enemy-move-right_002.png"),
new Image("img/anti-enemy-move-right_001.png"),
new Image("img/anti-enemy-move-right_003.png")
};
Image[] bELeftmovement = {
new Image("img/anti-enemy-move-left_001.png"),
new Image("img/anti-enemy-move-left_002.png"),
new Image("img/anti-enemy-move-left_001.png"),
new Image("img/anti-enemy-move-left_003.png")
};
int[] movementDuration = {200, 200, 200, 200};
animations = new Animation[2];
animations[0] = new Animation(bELeftmovement, movementDuration, false);
animations[1] = new Animation(bERightmovement, movementDuration, false);
super.setAnimations(animations);
}
| public AntiZombieRender(String id) throws SlickException {
super(id);
int[] moveTween = {200, 200, 200, 200};
Image[] moveRight = {
new Image("img/anti-enemy-move-right_001.png"),
new Image("img/anti-enemy-move-right_002.png"),
new Image("img/anti-enemy-move-right_001.png"),
new Image("img/anti-enemy-move-right_003.png")
};
Image[] moveLeft = {
new Image("img/anti-enemy-move-left_001.png"),
new Image("img/anti-enemy-move-left_002.png"),
new Image("img/anti-enemy-move-left_001.png"),
new Image("img/anti-enemy-move-left_003.png")
};
setMoveRight(new Animation(moveRight, moveTween, false));
setMoveLeft(new Animation(moveLeft, moveTween, false));
int[] deathTween = {500,175};
Image[] deathRight = {
new Image("img/anti-enemy-death-right-1.png"),
new Image("img/anti-enemy-death-right-2.png")
};
Image[] deathLeft = {
new Image("img/anti-enemy-death-left-1.png"),
new Image("img/amti-enemy-death-left-2.png")
};
setDeathRight(new Animation(deathRight, deathTween, false));
setDeathLeft(new Animation(deathLeft, deathTween, false));
setSprite(super.moveLeft);
}
|
diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java
index d589a2e920..660ef818c4 100644
--- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java
+++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java
@@ -1,474 +1,474 @@
/*
* Copyright 2002-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.springframework.integration.aggregator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.MessageHeaders;
import org.springframework.integration.MessagingException;
import org.springframework.integration.channel.NullChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.core.MessagingTemplate;
import org.springframework.integration.handler.AbstractMessageHandler;
import org.springframework.integration.store.MessageGroup;
import org.springframework.integration.store.MessageGroupCallback;
import org.springframework.integration.store.MessageGroupStore;
import org.springframework.integration.store.MessageStore;
import org.springframework.integration.store.SimpleMessageGroup;
import org.springframework.integration.store.SimpleMessageStore;
import org.springframework.integration.util.DefaultLockRegistry;
import org.springframework.integration.util.LockRegistry;
import org.springframework.integration.util.UUIDConverter;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Abstract Message handler that holds a buffer of correlated messages in a
* {@link MessageStore}. This class takes care of correlated groups of messages
* that can be completed in batches. It is useful for custom implementation of MessageHandlers that require correlation
* and is used as a base class for Aggregator - {@link AggregatingMessageHandler} and
* Resequencer - {@link ResequencingMessageHandler},
* or custom implementations requiring correlation.
* <p/>
* To customize this handler inject {@link CorrelationStrategy},
* {@link ReleaseStrategy}, and {@link MessageGroupProcessor} implementations as
* you require.
* <p/>
* By default the {@link CorrelationStrategy} will be a
* {@link HeaderAttributeCorrelationStrategy} and the {@link ReleaseStrategy} will be a
* {@link SequenceSizeReleaseStrategy}.
*
* @author Iwein Fuld
* @author Dave Syer
* @author Oleg Zhurakousky
* @author Gary Russell
* @since 2.0
*/
public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageHandler implements MessageProducer {
private static final Log logger = LogFactory.getLog(AbstractCorrelatingMessageHandler.class);
public static final long DEFAULT_SEND_TIMEOUT = 1000L;
protected volatile MessageGroupStore messageStore;
private final MessageGroupProcessor outputProcessor;
private volatile CorrelationStrategy correlationStrategy;
private volatile ReleaseStrategy releaseStrategy;
private MessageChannel outputChannel;
private final MessagingTemplate messagingTemplate = new MessagingTemplate();
private volatile MessageChannel discardChannel = new NullChannel();
private boolean sendPartialResultOnExpiry = false;
private volatile boolean sequenceAware = false;
private volatile LockRegistry lockRegistry = new DefaultLockRegistry();
private boolean lockRegistrySet = false;
private volatile long minimumTimeoutForEmptyGroups;
public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store,
CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) {
Assert.notNull(processor);
Assert.notNull(store);
setMessageStore(store);
this.outputProcessor = processor;
this.correlationStrategy = correlationStrategy == null ?
new HeaderAttributeCorrelationStrategy(MessageHeaders.CORRELATION_ID) : correlationStrategy;
this.releaseStrategy = releaseStrategy == null ? new SequenceSizeReleaseStrategy() : releaseStrategy;
this.messagingTemplate.setSendTimeout(DEFAULT_SEND_TIMEOUT);
sequenceAware = this.releaseStrategy instanceof SequenceSizeReleaseStrategy;
}
public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store) {
this(processor, store, null, null);
}
public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor) {
this(processor, new SimpleMessageStore(0), null, null);
}
public void setLockRegistry(LockRegistry lockRegistry) {
Assert.isTrue(!lockRegistrySet, "'this.lockRegistry' can not be reset once its been set");
Assert.notNull("'lockRegistry' must not be null");
this.lockRegistry = lockRegistry;
this.lockRegistrySet = true;
}
public void setMessageStore(MessageGroupStore store) {
this.messageStore = store;
store.registerMessageGroupExpiryCallback(new MessageGroupCallback() {
public void execute(MessageGroupStore messageGroupStore, MessageGroup group) {
forceComplete(group);
}
});
}
public void setCorrelationStrategy(CorrelationStrategy correlationStrategy) {
Assert.notNull(correlationStrategy);
this.correlationStrategy = correlationStrategy;
}
public void setReleaseStrategy(ReleaseStrategy releaseStrategy) {
Assert.notNull(releaseStrategy);
this.releaseStrategy = releaseStrategy;
sequenceAware = this.releaseStrategy instanceof SequenceSizeReleaseStrategy;
}
public void setOutputChannel(MessageChannel outputChannel) {
Assert.notNull(outputChannel, "'outputChannel' must not be null");
this.outputChannel = outputChannel;
}
@Override
protected void onInit() throws Exception {
super.onInit();
BeanFactory beanFactory = this.getBeanFactory();
if (beanFactory != null) {
this.messagingTemplate.setBeanFactory(beanFactory);
}
/*
* Disallow any further changes to the lock registry
* (checked in the setter).
*/
this.lockRegistrySet = true;
}
public void setDiscardChannel(MessageChannel discardChannel) {
this.discardChannel = discardChannel;
}
public void setSendTimeout(long sendTimeout) {
this.messagingTemplate.setSendTimeout(sendTimeout);
}
public void setSendPartialResultOnExpiry(boolean sendPartialResultOnExpiry) {
this.sendPartialResultOnExpiry = sendPartialResultOnExpiry;
}
/**
* By default, when a MessageGroupStoreReaper is configured to expire partial
* groups, empty groups are also removed. Empty groups exist after a group
* is released normally. This is to enable the detection and discarding of
* late-arriving messages. If you wish to run empty group deletion on a longer
* schedule than expiring partial groups, set this property. Empty groups will
* then not be removed from the MessageStore until they have not been modified
* for at least this number of milliseconds.
*
* @param minimumTimeoutForEmptyGroups The minimum timeout.
*/
public void setMinimumTimeoutForEmptyGroups(long minimumTimeoutForEmptyGroups) {
this.minimumTimeoutForEmptyGroups = minimumTimeoutForEmptyGroups;
}
public void setReleasePartialSequences(boolean releasePartialSequences){
Assert.isInstanceOf(SequenceSizeReleaseStrategy.class, this.releaseStrategy,
"Release strategy of type [" + this.releaseStrategy.getClass().getSimpleName()
+ "] cannot release partial sequences. Use the default SequenceSizeReleaseStrategy instead.");
((SequenceSizeReleaseStrategy)this.releaseStrategy).setReleasePartialSequences(releasePartialSequences);
}
@Override
public String getComponentType() {
return "aggregator";
}
protected MessageGroupStore getMessageStore() {
return messageStore;
}
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
Object correlationKey = correlationStrategy.getCorrelationKey(message);
Assert.state(correlationKey!=null, "Null correlation not allowed. Maybe the CorrelationStrategy is failing?");
if (logger.isDebugEnabled()) {
logger.debug("Handling message with correlationKey [" + correlationKey + "]: " + message);
}
// TODO: INT-1117 - make the lock global?
Lock lock = this.lockRegistry.obtain(UUIDConverter.getUUID(correlationKey).toString());
lock.lockInterruptibly();
try {
MessageGroup messageGroup = messageStore.getMessageGroup(correlationKey);
if (this.sequenceAware){
messageGroup = new SequenceAwareMessageGroup(messageGroup);
}
if (!messageGroup.isComplete() && messageGroup.canAdd(message)) {
if (logger.isTraceEnabled()) {
logger.trace("Adding message to group [ " + messageGroup + "]");
}
messageGroup = this.store(correlationKey, message);
if (releaseStrategy.canRelease(messageGroup)) {
Collection<Message<?>> completedMessages = null;
try {
completedMessages = this.completeGroup(message, correlationKey, messageGroup);
}
finally {
// Always clean up even if there was an exception
// processing messages
this.afterRelease(messageGroup, completedMessages);
}
}
}
else {
discardChannel.send(message);
}
}
finally {
lock.unlock();
}
}
/**
* Allows you to provide additional logic that needs to be performed after the MessageGroup was released.
* @param group
* @param completedMessages
*/
protected abstract void afterRelease(MessageGroup group, Collection<Message<?>> completedMessages);
private void forceComplete(MessageGroup group) {
Object correlationKey = group.getGroupId();
// UUIDConverter is no-op if already converted
Lock lock = this.lockRegistry.obtain(UUIDConverter.getUUID(correlationKey).toString());
boolean removeGroup = true;
try {
lock.lockInterruptibly();
try {
/*
* Need to verify the group hasn't changed while we were waiting on
* its lock. We have to re-fetch the group for this. A possible
* future improvement would be to add MessageGroupStore.getLastModified(groupId).
*/
MessageGroup messageGroupNow = this.messageStore.getMessageGroup(
group.getGroupId());
long lastModifiedNow = messageGroupNow.getLastModified();
if (group.getLastModified() == lastModifiedNow) {
if (group.size() > 0) {
if (releaseStrategy.canRelease(group)) {
this.completeGroup(correlationKey, group);
}
else {
this.expireGroup(correlationKey, group);
}
}
else {
/*
* By default empty groups are removed on the same schedule as non-empty
* groups. A longer timeout for empty groups can be enabled by
* setting minimumTimeoutForEmptyGroups.
*/
- removeGroup = lastModifiedNow < (System.currentTimeMillis() - this.minimumTimeoutForEmptyGroups);
+ removeGroup = lastModifiedNow <= (System.currentTimeMillis() - this.minimumTimeoutForEmptyGroups);
if (removeGroup && logger.isDebugEnabled()) {
logger.debug("Removing empty group: " + group.getGroupId());
}
}
}
else {
removeGroup = false;
if (logger.isDebugEnabled()) {
logger.debug("Group expiry candidate (" + group.getGroupId() +
") has changed - it may be reconsidered for a future expiration");
}
}
}
finally {
if (removeGroup) {
this.remove(group);
}
lock.unlock();
}
}
catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new MessagingException("Thread was interrupted while trying to obtain lock");
}
}
void remove(MessageGroup group) {
Object correlationKey = group.getGroupId();
messageStore.removeMessageGroup(correlationKey);
}
protected int findLastReleasedSequenceNumber(Object groupId, Collection<Message<?>> partialSequence){
List<Message<?>> sorted = new ArrayList<Message<?>>(partialSequence);
Collections.sort(sorted, new SequenceNumberComparator());
Message<?> lastReleasedMessage = sorted.get(partialSequence.size()-1);
return lastReleasedMessage.getHeaders().getSequenceNumber();
}
private MessageGroup store(Object correlationKey, Message<?> message) {
return messageStore.addMessageToGroup(correlationKey, message);
}
private void expireGroup(Object correlationKey, MessageGroup group) {
if (logger.isInfoEnabled()) {
logger.info("Expiring MessageGroup with correlationKey[" + correlationKey + "]");
}
if (sendPartialResultOnExpiry) {
if (logger.isDebugEnabled()) {
logger.debug("Prematurely releasing partially complete group with key ["
+ correlationKey + "] to: " + outputChannel);
}
completeGroup(correlationKey, group);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Discarding messages of partially complete group with key ["
+ correlationKey + "] to: " + discardChannel);
}
for (Message<?> message : group.getMessages()) {
discardChannel.send(message);
}
}
}
private void completeGroup(Object correlationKey, MessageGroup group) {
Message<?> first = null;
if (group != null) {
first = group.getOne();
}
completeGroup(first, correlationKey, group);
}
@SuppressWarnings("unchecked")
private Collection<Message<?>> completeGroup(Message<?> message, Object correlationKey, MessageGroup group) {
if (logger.isDebugEnabled()) {
logger.debug("Completing group with correlationKey [" + correlationKey + "]");
}
Object result = outputProcessor.processMessageGroup(group);
Collection<Message<?>> partialSequence = null;
if (result instanceof Collection<?>) {
this.verifyResultCollectionConsistsOfMessages((Collection<?>) result);
partialSequence = (Collection<Message<?>>) result;
}
this.sendReplies(result, message);
return partialSequence;
}
private void verifyResultCollectionConsistsOfMessages(Collection<?> elements){
Class<?> commonElementType = CollectionUtils.findCommonElementType(elements);
Assert.isAssignable(Message.class, commonElementType, "The expected collection of Messages contains non-Message element: " + commonElementType);
}
@SuppressWarnings("rawtypes")
private void sendReplies(Object processorResult, Message message) {
Object replyChannelHeader = null;
if (message != null) {
replyChannelHeader = message.getHeaders().getReplyChannel();
}
Object replyChannel = this.outputChannel;
if (this.outputChannel == null) {
replyChannel = replyChannelHeader;
}
Assert.notNull(replyChannel, "no outputChannel or replyChannel header available");
if (processorResult instanceof Iterable<?> && shouldSendMultipleReplies((Iterable<?>) processorResult)) {
for (Object next : (Iterable<?>) processorResult) {
this.sendReplyMessage(next, replyChannel);
}
} else {
this.sendReplyMessage(processorResult, replyChannel);
}
}
private void sendReplyMessage(Object reply, Object replyChannel) {
if (replyChannel instanceof MessageChannel) {
if (reply instanceof Message<?>) {
this.messagingTemplate.send((MessageChannel) replyChannel, (Message<?>) reply);
} else {
this.messagingTemplate.convertAndSend((MessageChannel) replyChannel, reply);
}
} else if (replyChannel instanceof String) {
if (reply instanceof Message<?>) {
this.messagingTemplate.send((String) replyChannel, (Message<?>) reply);
} else {
this.messagingTemplate.convertAndSend((String) replyChannel, reply);
}
} else {
throw new MessagingException("replyChannel must be a MessageChannel or String");
}
}
private boolean shouldSendMultipleReplies(Iterable<?> iter) {
for (Object next : iter) {
if (next instanceof Message<?>) {
return true;
}
}
return false;
}
private static class SequenceAwareMessageGroup extends SimpleMessageGroup {
public SequenceAwareMessageGroup(MessageGroup messageGroup) {
super(messageGroup);
}
/**
* This method determines whether messages have been added to this group that supersede the given message based on
* its sequence id. This can be helpful to avoid ending up with sequences larger than their required sequence size
* or sequences that are missing certain sequence numbers.
*/
@Override
public boolean canAdd(Message<?> message) {
if (this.size() == 0) {
return true;
}
Integer messageSequenceNumber = message.getHeaders().getSequenceNumber();
if (messageSequenceNumber != null && messageSequenceNumber > 0) {
Integer messageSequenceSize = message.getHeaders().getSequenceSize();
if (!messageSequenceSize.equals(this.getSequenceSize())) {
return false;
}
else {
return !this.containsSequenceNumber(this.getMessages(), messageSequenceNumber);
}
}
return true;
}
private boolean containsSequenceNumber(Collection<Message<?>> messages, Integer messageSequenceNumber) {
for (Message<?> member : messages) {
Integer memberSequenceNumber = member.getHeaders().getSequenceNumber();
if (messageSequenceNumber.equals(memberSequenceNumber)) {
return true;
}
}
return false;
}
}
}
| true | true | private void forceComplete(MessageGroup group) {
Object correlationKey = group.getGroupId();
// UUIDConverter is no-op if already converted
Lock lock = this.lockRegistry.obtain(UUIDConverter.getUUID(correlationKey).toString());
boolean removeGroup = true;
try {
lock.lockInterruptibly();
try {
/*
* Need to verify the group hasn't changed while we were waiting on
* its lock. We have to re-fetch the group for this. A possible
* future improvement would be to add MessageGroupStore.getLastModified(groupId).
*/
MessageGroup messageGroupNow = this.messageStore.getMessageGroup(
group.getGroupId());
long lastModifiedNow = messageGroupNow.getLastModified();
if (group.getLastModified() == lastModifiedNow) {
if (group.size() > 0) {
if (releaseStrategy.canRelease(group)) {
this.completeGroup(correlationKey, group);
}
else {
this.expireGroup(correlationKey, group);
}
}
else {
/*
* By default empty groups are removed on the same schedule as non-empty
* groups. A longer timeout for empty groups can be enabled by
* setting minimumTimeoutForEmptyGroups.
*/
removeGroup = lastModifiedNow < (System.currentTimeMillis() - this.minimumTimeoutForEmptyGroups);
if (removeGroup && logger.isDebugEnabled()) {
logger.debug("Removing empty group: " + group.getGroupId());
}
}
}
else {
removeGroup = false;
if (logger.isDebugEnabled()) {
logger.debug("Group expiry candidate (" + group.getGroupId() +
") has changed - it may be reconsidered for a future expiration");
}
}
}
finally {
if (removeGroup) {
this.remove(group);
}
lock.unlock();
}
}
catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new MessagingException("Thread was interrupted while trying to obtain lock");
}
}
| private void forceComplete(MessageGroup group) {
Object correlationKey = group.getGroupId();
// UUIDConverter is no-op if already converted
Lock lock = this.lockRegistry.obtain(UUIDConverter.getUUID(correlationKey).toString());
boolean removeGroup = true;
try {
lock.lockInterruptibly();
try {
/*
* Need to verify the group hasn't changed while we were waiting on
* its lock. We have to re-fetch the group for this. A possible
* future improvement would be to add MessageGroupStore.getLastModified(groupId).
*/
MessageGroup messageGroupNow = this.messageStore.getMessageGroup(
group.getGroupId());
long lastModifiedNow = messageGroupNow.getLastModified();
if (group.getLastModified() == lastModifiedNow) {
if (group.size() > 0) {
if (releaseStrategy.canRelease(group)) {
this.completeGroup(correlationKey, group);
}
else {
this.expireGroup(correlationKey, group);
}
}
else {
/*
* By default empty groups are removed on the same schedule as non-empty
* groups. A longer timeout for empty groups can be enabled by
* setting minimumTimeoutForEmptyGroups.
*/
removeGroup = lastModifiedNow <= (System.currentTimeMillis() - this.minimumTimeoutForEmptyGroups);
if (removeGroup && logger.isDebugEnabled()) {
logger.debug("Removing empty group: " + group.getGroupId());
}
}
}
else {
removeGroup = false;
if (logger.isDebugEnabled()) {
logger.debug("Group expiry candidate (" + group.getGroupId() +
") has changed - it may be reconsidered for a future expiration");
}
}
}
finally {
if (removeGroup) {
this.remove(group);
}
lock.unlock();
}
}
catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new MessagingException("Thread was interrupted while trying to obtain lock");
}
}
|
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/ClasspathVariableTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/ClasspathVariableTests.java
index 8f15ffdb5..978866385 100644
--- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/ClasspathVariableTests.java
+++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/ClasspathVariableTests.java
@@ -1,152 +1,149 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 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.jdt.debug.tests.core;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.debug.testplugin.JavaProjectHelper;
import org.eclipse.jdt.debug.tests.AbstractDebugTest;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.LibraryLocation;
/**
* Tests for classpath variables
*/
public class ClasspathVariableTests extends AbstractDebugTest {
/**
* Constructor
* @param name the name of the test
*/
public ClasspathVariableTests(String name) {
super(name);
}
/**
* Tests that we do not fail on a null variable
* @throws CoreException
*/
public void testNullVariableResolution() throws CoreException {
String varName = "NULL_VARIABLE";
IRuntimeClasspathEntry entry = JavaRuntime.newVariableRuntimeClasspathEntry(new Path(varName));
IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveRuntimeClasspathEntry(entry, getJavaProject());
// since the variable cannot be resolved, the result should be the same before/after
assertEquals("Should be one resolved entry", 1, resolved.length);
assertEquals("Entries should be equal", entry, resolved[0]);
}
/**
* test JRE resolution
* @throws CoreException
*/
public void testJRELibResolution() throws CoreException {
String varName = JavaRuntime.JRELIB_VARIABLE;
IRuntimeClasspathEntry entry = JavaRuntime.newVariableRuntimeClasspathEntry(new Path(varName));
IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveRuntimeClasspathEntry(entry, getJavaProject());
assertTrue("Should be at least one resolved entry", resolved.length > 0);
IVMInstall vm = JavaRuntime.getDefaultVMInstall();
assertNotNull("no default JRE", vm);
LibraryLocation[] libs = JavaRuntime.getLibraryLocations(vm);
assertTrue("no default libs", libs.length > 0);
assertEquals("Should resolve to location of local JRE", libs[0].getSystemLibraryPath().toOSString().toLowerCase(), resolved[0].getPath().toOSString().toLowerCase());
}
/**
* Test that a variable set to the location of an archive via variable
* extension resolves properly, with a null source attachment.
* @throws Exception
*/
public void testVariableExtensionWithNullSourceAttachment() throws Exception {
IResource archive = getJavaProject().getProject().getFolder("src").getFile("A.jar");
IProject root = getJavaProject().getProject();
String varName = "RELATIVE_ARCHIVE";
JavaCore.setClasspathVariable(varName, root.getFullPath(), null);
IRuntimeClasspathEntry runtimeClasspathEntry = JavaRuntime.newVariableRuntimeClasspathEntry(new Path(varName).append(new Path("src")).append(new Path("A.jar")));
runtimeClasspathEntry.setSourceAttachmentPath(new Path("NULL_VARIABLE"));
IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveRuntimeClasspathEntry(runtimeClasspathEntry, getJavaProject());
assertEquals("Should be one resolved entry", 1, resolved.length);
assertEquals("Resolved path not correct", archive.getFullPath(), resolved[0].getPath());
assertEquals("Resolved path not correct", archive.getLocation(), new Path(resolved[0].getLocation()));
assertNull("Should be null source attachment", resolved[0].getSourceAttachmentPath());
}
/**
* Test that a variable set to the location of an archive via variable
* extension resolves properly, with a source attachment rooted with a null
* variable with an extension.
* @throws Exception
*/
public void testVariableExtensionWithNullSourceAttachmentWithExtension() throws Exception {
IResource archive = getJavaProject().getProject().getFolder("src").getFile("A.jar");
IProject root = getJavaProject().getProject();
String varName = "RELATIVE_ARCHIVE";
JavaCore.setClasspathVariable(varName, root.getFullPath(), null);
IRuntimeClasspathEntry runtimeClasspathEntry = JavaRuntime.newVariableRuntimeClasspathEntry(new Path(varName).append(new Path("src")).append(new Path("A.jar")));
runtimeClasspathEntry.setSourceAttachmentPath(new Path("NULL_VARIABLE").append("one").append("two"));
IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveRuntimeClasspathEntry(runtimeClasspathEntry, getJavaProject());
assertEquals("Should be one resolved entry", 1, resolved.length);
assertEquals("Resolved path not correct", archive.getFullPath(), resolved[0].getPath());
assertEquals("Resolved path not correct", archive.getLocation(), new Path(resolved[0].getLocation()));
assertNull("Should be null source attachment", resolved[0].getSourceAttachmentPath());
}
/**
* Test a class path entry with variable extensions for archive and source attachment.
*
* @throws Exception
*/
public void testVariableArchiveAndSourceAttachmentWithExtension() throws Exception {
IResource archive = getJavaProject().getProject().getFolder("src").getFile("A.jar");
IProject root = getJavaProject().getProject();
String varName = "RELATIVE_ARCHIVE";
JavaCore.setClasspathVariable(varName, root.getFullPath(), null);
IRuntimeClasspathEntry runtimeClasspathEntry = JavaRuntime.newVariableRuntimeClasspathEntry(new Path(varName).append(new Path("src")).append(new Path("A.jar")));
runtimeClasspathEntry.setSourceAttachmentPath(new Path(varName).append(new Path("src")).append(new Path("A.jar")));
IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveRuntimeClasspathEntry(runtimeClasspathEntry, getJavaProject());
assertEquals("Should be one resolved entry", 1, resolved.length);
assertEquals("Resolved path not correct", archive.getFullPath(), resolved[0].getPath());
assertEquals("Resolved path not correct", archive.getLocation(), new Path(resolved[0].getLocation()));
assertEquals("Resolved source attachment not correct", archive.getLocation(), new Path(resolved[0].getSourceAttachmentLocation()));
}
/**
* Test a class path entry with variable extensions for archive and source attachment.
*
* @throws Exception
*/
public void testProjectResolutionWithVariableArchiveAndSourceAttachmentWithExtension() throws Exception {
IJavaProject project = JavaProjectHelper.createJavaProject("VariableSource");
IResource archive = getJavaProject().getProject().getFolder("src").getFile("A.jar");
IProject root = getJavaProject().getProject();
String varName = "RELATIVE_ARCHIVE";
JavaCore.setClasspathVariable(varName, root.getFullPath(), null);
JavaProjectHelper.addVariableEntry(project, new Path(varName).append(new Path("src")).append(new Path("A.jar")), new Path(varName).append(new Path("src")).append(new Path("A.jar")), Path.EMPTY);
IRuntimeClasspathEntry entry = JavaRuntime.newDefaultProjectClasspathEntry(project);
IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveRuntimeClasspathEntry(entry, project);
- for (int i = 0; i < resolved.length; i++) {
- System.out.println(resolved[i]);
- }
-// assertEquals("Should be one resolved entry", 1, resolved.length);
-// assertEquals("Resolved path not correct", archive.getFullPath(), resolved[0].getPath());
-// assertEquals("Resolved path not correct", archive.getLocation(), new Path(resolved[0].getLocation()));
-// assertEquals("Resolved source attachment not correct", archive.getLocation(), new Path(resolved[0].getSourceAttachmentLocation()));
+ assertEquals("Should be one resolved entry", 1, resolved.length);
+ assertEquals("Resolved path not correct", archive.getFullPath(), resolved[0].getPath());
+ assertEquals("Resolved path not correct", archive.getLocation(), new Path(resolved[0].getLocation()));
+ assertEquals("Resolved source attachment not correct", archive.getLocation(), new Path(resolved[0].getSourceAttachmentLocation()));
}
}
| true | true | public void testProjectResolutionWithVariableArchiveAndSourceAttachmentWithExtension() throws Exception {
IJavaProject project = JavaProjectHelper.createJavaProject("VariableSource");
IResource archive = getJavaProject().getProject().getFolder("src").getFile("A.jar");
IProject root = getJavaProject().getProject();
String varName = "RELATIVE_ARCHIVE";
JavaCore.setClasspathVariable(varName, root.getFullPath(), null);
JavaProjectHelper.addVariableEntry(project, new Path(varName).append(new Path("src")).append(new Path("A.jar")), new Path(varName).append(new Path("src")).append(new Path("A.jar")), Path.EMPTY);
IRuntimeClasspathEntry entry = JavaRuntime.newDefaultProjectClasspathEntry(project);
IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveRuntimeClasspathEntry(entry, project);
for (int i = 0; i < resolved.length; i++) {
System.out.println(resolved[i]);
}
// assertEquals("Should be one resolved entry", 1, resolved.length);
// assertEquals("Resolved path not correct", archive.getFullPath(), resolved[0].getPath());
// assertEquals("Resolved path not correct", archive.getLocation(), new Path(resolved[0].getLocation()));
// assertEquals("Resolved source attachment not correct", archive.getLocation(), new Path(resolved[0].getSourceAttachmentLocation()));
}
| public void testProjectResolutionWithVariableArchiveAndSourceAttachmentWithExtension() throws Exception {
IJavaProject project = JavaProjectHelper.createJavaProject("VariableSource");
IResource archive = getJavaProject().getProject().getFolder("src").getFile("A.jar");
IProject root = getJavaProject().getProject();
String varName = "RELATIVE_ARCHIVE";
JavaCore.setClasspathVariable(varName, root.getFullPath(), null);
JavaProjectHelper.addVariableEntry(project, new Path(varName).append(new Path("src")).append(new Path("A.jar")), new Path(varName).append(new Path("src")).append(new Path("A.jar")), Path.EMPTY);
IRuntimeClasspathEntry entry = JavaRuntime.newDefaultProjectClasspathEntry(project);
IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveRuntimeClasspathEntry(entry, project);
assertEquals("Should be one resolved entry", 1, resolved.length);
assertEquals("Resolved path not correct", archive.getFullPath(), resolved[0].getPath());
assertEquals("Resolved path not correct", archive.getLocation(), new Path(resolved[0].getLocation()));
assertEquals("Resolved source attachment not correct", archive.getLocation(), new Path(resolved[0].getSourceAttachmentLocation()));
}
|
diff --git a/org.neo4j.neoclipse/src/main/java/org/neo4j/neoclipse/editor/SqlEditorView.java b/org.neo4j.neoclipse/src/main/java/org/neo4j/neoclipse/editor/SqlEditorView.java
index 8db7e1e..79a5483 100644
--- a/org.neo4j.neoclipse/src/main/java/org/neo4j/neoclipse/editor/SqlEditorView.java
+++ b/org.neo4j.neoclipse/src/main/java/org/neo4j/neoclipse/editor/SqlEditorView.java
@@ -1,332 +1,332 @@
package org.neo4j.neoclipse.editor;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.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.part.ViewPart;
import org.json.JSONArray;
import org.neo4j.neoclipse.Activator;
import org.neo4j.neoclipse.Icons;
import org.neo4j.neoclipse.graphdb.GraphDbServiceManager;
import org.neo4j.neoclipse.util.ApplicationUtil;
import org.neo4j.neoclipse.util.DataExportUtils;
import org.neo4j.neoclipse.view.ErrorMessage;
import org.neo4j.neoclipse.view.UiHelper;
public class SqlEditorView extends ViewPart implements Listener
{
public static final String ID = "org.neo4j.neoclipse.editor.SqlEditorView"; //$NON-NLS-1$
private Text cypherQueryText;
private CTabFolder tabFolder;
private Label messageStatus;
private ToolItem tltmExecuteCypherSql;
private ToolItem exportCsv;
private ToolItem exportJson;
private ToolItem exportXml;
private String jsonString;
private static boolean altKeyPressed = false;
private static boolean enterKeyPressed = false;
public SqlEditorView()
{
}
/**
* Create contents of the view part.
*
* @param parent
*/
@Override
public void createPartControl( Composite parent )
{
parent.setLayout( new GridLayout( 1, false ) );
{
ToolBar toolBar = new ToolBar( parent, SWT.FLAT | SWT.RIGHT );
{
tltmExecuteCypherSql = new ToolItem( toolBar, SWT.PUSH );
tltmExecuteCypherSql.setEnabled( false );
- tltmExecuteCypherSql.setToolTipText( "Execute" );
+ tltmExecuteCypherSql.setToolTipText( "Execute (ALT+Enter)" );
tltmExecuteCypherSql.setImage( Icons.EXECUTE_SQL.image() );
tltmExecuteCypherSql.addListener( SWT.Selection, this );
}
}
cypherQueryText = new Text( parent, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI );
cypherQueryText.addKeyListener( new KeyListener()
{
@Override
public void keyReleased( KeyEvent keyEvent )
{
if ( !validate() )
{
return;
}
if ( altKeyPressed && keyEvent.keyCode == SWT.CR )
{
enterKeyPressed = true;
}
else
{
altKeyPressed = false;
}
if ( altKeyPressed && enterKeyPressed && validate() )
{
executeCypherQuery( cypherQueryText.getText() );
altKeyPressed = enterKeyPressed = false;
}
}
@Override
public void keyPressed( KeyEvent keyEvent )
{
if ( !validate() )
{
return;
}
if ( keyEvent.keyCode == SWT.ALT )
{
altKeyPressed = true;
}
}
} );
GridData gd_text = new GridData( SWT.FILL, SWT.CENTER, true, false, 1, 1 );
gd_text.heightHint = 172;
cypherQueryText.setLayoutData( gd_text );
{
new Label( parent, SWT.NONE );
}
{
ToolBar toolBar = new ToolBar( parent, SWT.FLAT | SWT.RIGHT );
{
exportCsv = new ToolItem( toolBar, SWT.PUSH );
exportCsv.setEnabled( false );
exportCsv.setToolTipText( "Export to CSV" );
exportCsv.setImage( Icons.CSV.image() );
exportCsv.addListener( SWT.Selection, this );
exportJson = new ToolItem( toolBar, SWT.PUSH );
exportJson.setEnabled( false );
exportJson.setToolTipText( "Export as Json" );
exportJson.setImage( Icons.JSON.image() );
exportJson.addListener( SWT.Selection, this );
exportXml = new ToolItem( toolBar, SWT.PUSH );
exportXml.setEnabled( false );
exportXml.setToolTipText( "Export as Xml" );
exportXml.setImage( Icons.XML.image() );
exportXml.addListener( SWT.Selection, this );
}
}
{
Label label = new Label( parent, SWT.SEPARATOR | SWT.HORIZONTAL );
label.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, false, false, 1, 1 ) );
}
{
tabFolder = new CTabFolder( parent, SWT.BORDER );
tabFolder.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 1, 1 ) );
tabFolder.setSelectionBackground( Display.getCurrent().getSystemColor(
SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT ) );
CTabItem resultsTabItem = new CTabItem( tabFolder, SWT.NONE );
resultsTabItem.setText( "Results" );
tabFolder.setSelection( resultsTabItem );
}
{
messageStatus = new Label( parent, SWT.NONE );
messageStatus.setTouchEnabled( true );
messageStatus.setLayoutData( new GridData( SWT.FILL, SWT.FILL, false, false, 1, 1 ) );
}
}
private void enableDisableToolBars( boolean flag )
{
exportCsv.setEnabled( flag );
exportJson.setEnabled( flag );
exportXml.setEnabled( flag );
}
private boolean validate()
{
boolean enableDisable = false;
if ( !cypherQueryText.getText().trim().isEmpty() )
{
enableDisable = true;
}
tltmExecuteCypherSql.setEnabled( enableDisable );
return enableDisable;
}
@Override
public void setFocus()
{
cypherQueryText.setFocus();
}
// This will create the columns for the table
private void createColumns( TableViewer tableViewer, Collection<String> titles )
{
TableViewerColumn col = null;
int columnCount = 0;
for ( final String column : titles )
{
col = createTableViewerColumn( tableViewer, column, columnCount++ );
col.setLabelProvider( new ColumnLabelProvider()
{
@Override
public String getText( Object element )
{
Map<String, Object> rs = (Map<String, Object>) element;
Object value = rs.get( column );
value = ApplicationUtil.getPropertyValue( value );
return value.toString().replace( "{", "" ).replace( "}", "" );
}
} );
}
}
private TableViewerColumn createTableViewerColumn( TableViewer tableViewer, String title, final int colNumber )
{
final TableViewerColumn viewerColumn = new TableViewerColumn( tableViewer, SWT.NONE, colNumber );
final TableColumn column = viewerColumn.getColumn();
column.setText( title );
column.setWidth( 150 );
column.setResizable( true );
column.setMoveable( true );
return viewerColumn;
}
@Override
public void handleEvent( Event event )
{
if ( event.widget == tltmExecuteCypherSql )
{
executeCypherQuery( cypherQueryText.getText() );
}
else if ( event.widget == exportCsv )
{
try
{
File file = DataExportUtils.exportToCsv( jsonString );
ErrorMessage.showDialog( "CSV Export", "CSV file is created at " + file );
}
catch ( Exception e )
{
ErrorMessage.showDialog( "CSV exporting problem", e );
}
}
else if ( event.widget == exportJson )
{
try
{
File file = DataExportUtils.exportToJson( jsonString );
ErrorMessage.showDialog( "Json Export", "Json file is created at " + file );
}
catch ( Exception e )
{
ErrorMessage.showDialog( "Json exporting problem", e );
}
}
else if ( event.widget == exportXml )
{
try
{
File file = DataExportUtils.exportToXml( jsonString );
ErrorMessage.showDialog( "XML Export", "XML file is created at " + file );
}
catch ( Exception e )
{
ErrorMessage.showDialog( "XML exporting problem", e );
}
}
}
private void executeCypherQuery( final String cypherSql )
{
UiHelper.asyncExec( new Runnable()
{
@Override
public void run()
{
final GraphDbServiceManager gsm = Activator.getDefault().getGraphDbServiceManager();
try
{
CypherResultSet cypherResultSet = gsm.executeCypher( cypherSql );
displayResultSet( cypherResultSet );
}
catch ( Exception e )
{
enableDisableToolBars( false );
ErrorMessage.showDialog( "execute cypher query", e );
}
}
} );
}
private void displayResultSet( CypherResultSet cypherResultSet )
{
List<Map<String, Object>> resultSetList = cypherResultSet.getIterator();
List<String> columns = cypherResultSet.getColumns();
JSONArray jsonArray = new JSONArray( resultSetList );
jsonString = jsonArray.toString();
messageStatus.setText( cypherResultSet.getMessage() );
TableViewer tableViewer = new TableViewer( tabFolder, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI
| SWT.VIRTUAL | SWT.FULL_SELECTION );
createColumns( tableViewer, columns );
tableViewer.setContentProvider( new ArrayContentProvider() );
Table table = tableViewer.getTable();
table.setHeaderVisible( true );
table.setLinesVisible( true );
tableViewer.setInput( resultSetList );
getSite().setSelectionProvider( tableViewer );
CTabItem resultsTabItem = tabFolder.getSelection();
if ( resultsTabItem == null )
{
resultsTabItem = new CTabItem( tabFolder, SWT.NONE );
resultsTabItem.setText( "Results" );
tabFolder.setSelection( resultsTabItem );
}
resultsTabItem.setControl( table );
enableDisableToolBars( true );
}
}
| true | true | public void createPartControl( Composite parent )
{
parent.setLayout( new GridLayout( 1, false ) );
{
ToolBar toolBar = new ToolBar( parent, SWT.FLAT | SWT.RIGHT );
{
tltmExecuteCypherSql = new ToolItem( toolBar, SWT.PUSH );
tltmExecuteCypherSql.setEnabled( false );
tltmExecuteCypherSql.setToolTipText( "Execute" );
tltmExecuteCypherSql.setImage( Icons.EXECUTE_SQL.image() );
tltmExecuteCypherSql.addListener( SWT.Selection, this );
}
}
cypherQueryText = new Text( parent, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI );
cypherQueryText.addKeyListener( new KeyListener()
{
@Override
public void keyReleased( KeyEvent keyEvent )
{
if ( !validate() )
{
return;
}
if ( altKeyPressed && keyEvent.keyCode == SWT.CR )
{
enterKeyPressed = true;
}
else
{
altKeyPressed = false;
}
if ( altKeyPressed && enterKeyPressed && validate() )
{
executeCypherQuery( cypherQueryText.getText() );
altKeyPressed = enterKeyPressed = false;
}
}
@Override
public void keyPressed( KeyEvent keyEvent )
{
if ( !validate() )
{
return;
}
if ( keyEvent.keyCode == SWT.ALT )
{
altKeyPressed = true;
}
}
} );
GridData gd_text = new GridData( SWT.FILL, SWT.CENTER, true, false, 1, 1 );
gd_text.heightHint = 172;
cypherQueryText.setLayoutData( gd_text );
{
new Label( parent, SWT.NONE );
}
{
ToolBar toolBar = new ToolBar( parent, SWT.FLAT | SWT.RIGHT );
{
exportCsv = new ToolItem( toolBar, SWT.PUSH );
exportCsv.setEnabled( false );
exportCsv.setToolTipText( "Export to CSV" );
exportCsv.setImage( Icons.CSV.image() );
exportCsv.addListener( SWT.Selection, this );
exportJson = new ToolItem( toolBar, SWT.PUSH );
exportJson.setEnabled( false );
exportJson.setToolTipText( "Export as Json" );
exportJson.setImage( Icons.JSON.image() );
exportJson.addListener( SWT.Selection, this );
exportXml = new ToolItem( toolBar, SWT.PUSH );
exportXml.setEnabled( false );
exportXml.setToolTipText( "Export as Xml" );
exportXml.setImage( Icons.XML.image() );
exportXml.addListener( SWT.Selection, this );
}
}
{
Label label = new Label( parent, SWT.SEPARATOR | SWT.HORIZONTAL );
label.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, false, false, 1, 1 ) );
}
{
tabFolder = new CTabFolder( parent, SWT.BORDER );
tabFolder.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 1, 1 ) );
tabFolder.setSelectionBackground( Display.getCurrent().getSystemColor(
SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT ) );
CTabItem resultsTabItem = new CTabItem( tabFolder, SWT.NONE );
resultsTabItem.setText( "Results" );
tabFolder.setSelection( resultsTabItem );
}
{
messageStatus = new Label( parent, SWT.NONE );
messageStatus.setTouchEnabled( true );
messageStatus.setLayoutData( new GridData( SWT.FILL, SWT.FILL, false, false, 1, 1 ) );
}
}
| public void createPartControl( Composite parent )
{
parent.setLayout( new GridLayout( 1, false ) );
{
ToolBar toolBar = new ToolBar( parent, SWT.FLAT | SWT.RIGHT );
{
tltmExecuteCypherSql = new ToolItem( toolBar, SWT.PUSH );
tltmExecuteCypherSql.setEnabled( false );
tltmExecuteCypherSql.setToolTipText( "Execute (ALT+Enter)" );
tltmExecuteCypherSql.setImage( Icons.EXECUTE_SQL.image() );
tltmExecuteCypherSql.addListener( SWT.Selection, this );
}
}
cypherQueryText = new Text( parent, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI );
cypherQueryText.addKeyListener( new KeyListener()
{
@Override
public void keyReleased( KeyEvent keyEvent )
{
if ( !validate() )
{
return;
}
if ( altKeyPressed && keyEvent.keyCode == SWT.CR )
{
enterKeyPressed = true;
}
else
{
altKeyPressed = false;
}
if ( altKeyPressed && enterKeyPressed && validate() )
{
executeCypherQuery( cypherQueryText.getText() );
altKeyPressed = enterKeyPressed = false;
}
}
@Override
public void keyPressed( KeyEvent keyEvent )
{
if ( !validate() )
{
return;
}
if ( keyEvent.keyCode == SWT.ALT )
{
altKeyPressed = true;
}
}
} );
GridData gd_text = new GridData( SWT.FILL, SWT.CENTER, true, false, 1, 1 );
gd_text.heightHint = 172;
cypherQueryText.setLayoutData( gd_text );
{
new Label( parent, SWT.NONE );
}
{
ToolBar toolBar = new ToolBar( parent, SWT.FLAT | SWT.RIGHT );
{
exportCsv = new ToolItem( toolBar, SWT.PUSH );
exportCsv.setEnabled( false );
exportCsv.setToolTipText( "Export to CSV" );
exportCsv.setImage( Icons.CSV.image() );
exportCsv.addListener( SWT.Selection, this );
exportJson = new ToolItem( toolBar, SWT.PUSH );
exportJson.setEnabled( false );
exportJson.setToolTipText( "Export as Json" );
exportJson.setImage( Icons.JSON.image() );
exportJson.addListener( SWT.Selection, this );
exportXml = new ToolItem( toolBar, SWT.PUSH );
exportXml.setEnabled( false );
exportXml.setToolTipText( "Export as Xml" );
exportXml.setImage( Icons.XML.image() );
exportXml.addListener( SWT.Selection, this );
}
}
{
Label label = new Label( parent, SWT.SEPARATOR | SWT.HORIZONTAL );
label.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, false, false, 1, 1 ) );
}
{
tabFolder = new CTabFolder( parent, SWT.BORDER );
tabFolder.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 1, 1 ) );
tabFolder.setSelectionBackground( Display.getCurrent().getSystemColor(
SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT ) );
CTabItem resultsTabItem = new CTabItem( tabFolder, SWT.NONE );
resultsTabItem.setText( "Results" );
tabFolder.setSelection( resultsTabItem );
}
{
messageStatus = new Label( parent, SWT.NONE );
messageStatus.setTouchEnabled( true );
messageStatus.setLayoutData( new GridData( SWT.FILL, SWT.FILL, false, false, 1, 1 ) );
}
}
|
diff --git a/src/model/undo/AddItems.java b/src/model/undo/AddItems.java
index a5bc47a..1b9c36a 100644
--- a/src/model/undo/AddItems.java
+++ b/src/model/undo/AddItems.java
@@ -1,128 +1,129 @@
package model.undo;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;
import model.BarcodePrinter;
import model.Item;
import model.ItemManager;
import model.Product;
import model.ProductContainer;
import model.ProductManager;
/**
* Encapsulates the reversible action of adding a new Item (and perhaps a new Product) to the
* system.
*
* @author clayton
*/
public class AddItems implements Command {
private final ProductContainer container;
private final Date entryDate;
private final int count;
private final ProductManager productManager;
private Product product;
private final ItemManager itemManager;
private final Set<Item> addedItems;
private final AddProduct addProduct;
/**
* Constructs an AddItem command with the given dependencies.
*
* @param productBarcode
* Barcode of the to-be-created Item's Product
* @param entryDate
* Entry date of the to-be-created Item
* @param count
* Number of Items to be created
* @param productManager
* Manager to notify if a new Product is created
* @param itemManager
* Manager to notify of the new Item
*
* @pre productBarcode != null
* @pre entryDate != null
* @pre count > 0
* @pre productManager != null
* @pre itemManager != null
* @post getAddedItem() == null
*/
public AddItems(ProductContainer container, AddProduct addProduct, Product product,
Date entryDate, int count, ProductManager productManager, ItemManager itemManager) {
this.container = container;
this.addProduct = addProduct;
this.product = product;
addedItems = new TreeSet<Item>();
this.entryDate = entryDate;
this.count = count;
this.productManager = productManager;
this.itemManager = itemManager;
}
/**
* Adds Items to the model based on the data provided on construction.
*
* @pre true
* @post !(getAddedItems().isEmpty())
*/
@Override
public void execute() {
if (addProduct != null) {
addProduct.execute();
product = addProduct.getProduct();
}
if (!addedItems.isEmpty()) {
for (Item item : addedItems) {
container.add(item);
itemManager.manage(item);
+ product.addItem(item);
BarcodePrinter.getInstance().addItemToBatch(item);
}
} else {
for (int i = 0; i < count; i++) {
Item item = new Item(product, container, entryDate, itemManager);
addedItems.add(item);
BarcodePrinter.getInstance().addItemToBatch(item);
}
}
}
/**
* Returns a set of Items added by the execute method of this Command.
*
* @return the Items added by the execute method of this Command.
*
* @pre true
* @post true
*/
public final Set<Item> getAddedItems() {
return addedItems;
}
public final AddProduct getAddProductCommand() {
return addProduct;
}
public int getItemCount() {
return count;
}
/**
* Remove an Item previously added by the execute method.
*
* @pre getAddedItem() != null
* @post getAddedItem() == null
*/
@Override
public void undo() {
for (Item item : addedItems) {
container.remove(item, itemManager, false);
BarcodePrinter.getInstance().removeItemFromBatch(item);
}
// addedItems.clear();
if (addProduct != null)
addProduct.undo();
product = null;
}
}
| true | true | public void execute() {
if (addProduct != null) {
addProduct.execute();
product = addProduct.getProduct();
}
if (!addedItems.isEmpty()) {
for (Item item : addedItems) {
container.add(item);
itemManager.manage(item);
BarcodePrinter.getInstance().addItemToBatch(item);
}
} else {
for (int i = 0; i < count; i++) {
Item item = new Item(product, container, entryDate, itemManager);
addedItems.add(item);
BarcodePrinter.getInstance().addItemToBatch(item);
}
}
}
| public void execute() {
if (addProduct != null) {
addProduct.execute();
product = addProduct.getProduct();
}
if (!addedItems.isEmpty()) {
for (Item item : addedItems) {
container.add(item);
itemManager.manage(item);
product.addItem(item);
BarcodePrinter.getInstance().addItemToBatch(item);
}
} else {
for (int i = 0; i < count; i++) {
Item item = new Item(product, container, entryDate, itemManager);
addedItems.add(item);
BarcodePrinter.getInstance().addItemToBatch(item);
}
}
}
|
diff --git a/core/src/com/google/zxing/qrcode/QRCodeReader.java b/core/src/com/google/zxing/qrcode/QRCodeReader.java
index 3a9be4e8..c272d030 100644
--- a/core/src/com/google/zxing/qrcode/QRCodeReader.java
+++ b/core/src/com/google/zxing/qrcode/QRCodeReader.java
@@ -1,181 +1,181 @@
/*
* Copyright 2007 ZXing 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 com.google.zxing.qrcode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.ResultMetadataType;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.DecoderResult;
import com.google.zxing.common.DetectorResult;
import com.google.zxing.qrcode.decoder.Decoder;
import com.google.zxing.qrcode.detector.Detector;
import java.util.List;
import java.util.Map;
/**
* This implementation can detect and decode QR Codes in an image.
*
* @author Sean Owen
*/
public class QRCodeReader implements Reader {
private static final ResultPoint[] NO_POINTS = new ResultPoint[0];
private final Decoder decoder = new Decoder();
protected Decoder getDecoder() {
return decoder;
}
/**
* Locates and decodes a QR code in an image.
*
* @return a String representing the content encoded by the QR code
* @throws NotFoundException if a QR code cannot be found
* @throws FormatException if a QR code cannot be decoded
* @throws ChecksumException if error correction fails
*/
@Override
public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException {
return decode(image, null);
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
ResultPoint[] points;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits, hints);
points = NO_POINTS;
} else {
DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints);
decoderResult = decoder.decode(detectorResult.getBits(), hints);
points = detectorResult.getPoints();
}
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE);
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
return result;
}
@Override
public void reset() {
// do nothing
}
/**
* This method detects a code in a "pure" image -- that is, pure monochrome image
* which contains only an unrotated, unskewed, image of a code, with some white border
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*
* @see com.google.zxing.pdf417.PDF417Reader#extractPureBits(BitMatrix)
* @see com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix)
*/
private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {
int[] leftTopBlack = image.getTopLeftOnBit();
int[] rightBottomBlack = image.getBottomRightOnBit();
if (leftTopBlack == null || rightBottomBlack == null) {
throw NotFoundException.getNotFoundInstance();
}
float moduleSize = moduleSize(leftTopBlack, image);
int top = leftTopBlack[1];
int bottom = rightBottomBlack[1];
int left = leftTopBlack[0];
int right = rightBottomBlack[0];
if (bottom - top != right - left) {
// Special case, where bottom-right module wasn't black so we found something else in the last row
// Assume it's a square, so use height as the width
right = left + (bottom - top);
}
int matrixWidth = Math.round((right - left + 1) / moduleSize);
int matrixHeight = Math.round((bottom - top + 1) / moduleSize);
if (matrixWidth <= 0 || matrixHeight <= 0) {
throw NotFoundException.getNotFoundInstance();
}
if (matrixHeight != matrixWidth) {
// Only possibly decode square regions
throw NotFoundException.getNotFoundInstance();
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
- int nudge = Math.round(moduleSize / 2.0f);
+ int nudge = (int) (moduleSize / 2.0f);
top += nudge;
left += nudge;
// Now just read off the bits
BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);
for (int y = 0; y < matrixHeight; y++) {
int iOffset = top + (int) (y * moduleSize);
for (int x = 0; x < matrixWidth; x++) {
if (image.get(left + (int) (x * moduleSize), iOffset)) {
bits.set(x, y);
}
}
}
return bits;
}
private static float moduleSize(int[] leftTopBlack, BitMatrix image) throws NotFoundException {
int height = image.getHeight();
int width = image.getWidth();
int x = leftTopBlack[0];
int y = leftTopBlack[1];
boolean inBlack = true;
int transitions = 0;
while (x < width && y < height) {
if (inBlack != image.get(x, y)) {
if (++transitions == 5) {
break;
}
inBlack = !inBlack;
}
x++;
y++;
}
if (x == width || y == height) {
throw NotFoundException.getNotFoundInstance();
}
return (x - leftTopBlack[0]) / 7.0f;
}
}
| true | true | private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {
int[] leftTopBlack = image.getTopLeftOnBit();
int[] rightBottomBlack = image.getBottomRightOnBit();
if (leftTopBlack == null || rightBottomBlack == null) {
throw NotFoundException.getNotFoundInstance();
}
float moduleSize = moduleSize(leftTopBlack, image);
int top = leftTopBlack[1];
int bottom = rightBottomBlack[1];
int left = leftTopBlack[0];
int right = rightBottomBlack[0];
if (bottom - top != right - left) {
// Special case, where bottom-right module wasn't black so we found something else in the last row
// Assume it's a square, so use height as the width
right = left + (bottom - top);
}
int matrixWidth = Math.round((right - left + 1) / moduleSize);
int matrixHeight = Math.round((bottom - top + 1) / moduleSize);
if (matrixWidth <= 0 || matrixHeight <= 0) {
throw NotFoundException.getNotFoundInstance();
}
if (matrixHeight != matrixWidth) {
// Only possibly decode square regions
throw NotFoundException.getNotFoundInstance();
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
int nudge = Math.round(moduleSize / 2.0f);
top += nudge;
left += nudge;
// Now just read off the bits
BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);
for (int y = 0; y < matrixHeight; y++) {
int iOffset = top + (int) (y * moduleSize);
for (int x = 0; x < matrixWidth; x++) {
if (image.get(left + (int) (x * moduleSize), iOffset)) {
bits.set(x, y);
}
}
}
return bits;
}
| private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {
int[] leftTopBlack = image.getTopLeftOnBit();
int[] rightBottomBlack = image.getBottomRightOnBit();
if (leftTopBlack == null || rightBottomBlack == null) {
throw NotFoundException.getNotFoundInstance();
}
float moduleSize = moduleSize(leftTopBlack, image);
int top = leftTopBlack[1];
int bottom = rightBottomBlack[1];
int left = leftTopBlack[0];
int right = rightBottomBlack[0];
if (bottom - top != right - left) {
// Special case, where bottom-right module wasn't black so we found something else in the last row
// Assume it's a square, so use height as the width
right = left + (bottom - top);
}
int matrixWidth = Math.round((right - left + 1) / moduleSize);
int matrixHeight = Math.round((bottom - top + 1) / moduleSize);
if (matrixWidth <= 0 || matrixHeight <= 0) {
throw NotFoundException.getNotFoundInstance();
}
if (matrixHeight != matrixWidth) {
// Only possibly decode square regions
throw NotFoundException.getNotFoundInstance();
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
int nudge = (int) (moduleSize / 2.0f);
top += nudge;
left += nudge;
// Now just read off the bits
BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);
for (int y = 0; y < matrixHeight; y++) {
int iOffset = top + (int) (y * moduleSize);
for (int x = 0; x < matrixWidth; x++) {
if (image.get(left + (int) (x * moduleSize), iOffset)) {
bits.set(x, y);
}
}
}
return bits;
}
|
diff --git a/src/lib/com/izforge/izpack/compiler/Packager.java b/src/lib/com/izforge/izpack/compiler/Packager.java
index e59aca68..3a1b1ae9 100644
--- a/src/lib/com/izforge/izpack/compiler/Packager.java
+++ b/src/lib/com/izforge/izpack/compiler/Packager.java
@@ -1,289 +1,289 @@
/*
* $Id$
* IzPack
* Copyright (C) 2001-2003 Julien Ponge
*
* File : Packager.java
* Description : The abstract class for the packagers.
* Author's email : [email protected]
* Author's Website : http://www.izforge.com
*
* Portions are Copyright (c) 2001 Johannes Lehtinen
* [email protected]
* http://www.iki.fi/jle/
*
* 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 any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.izforge.izpack.compiler;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import com.izforge.izpack.GUIPrefs;
import com.izforge.izpack.Info;
import com.izforge.izpack.Pack;
/**
* The packager class. A packager is used by the compiler to actually do the
* packaging job.
*
* @author Julien Ponge
* @created October 26, 2002
*/
public abstract class Packager
{
/** The path to the skeleton installer. */
public final static String SKELETON_SUBPATH = "lib" +
File.separator + "installer.jar";
/** The packs informations. */
protected ArrayList packs;
/** The langpacks ISO3 names. */
protected ArrayList langpacks;
/** The listeners. */
protected PackagerListener listener;
/**
* Adds a listener.
*
* @param listener The listener.
*/
public void setPackagerListener(PackagerListener listener)
{
this.listener = listener;
}
/**
* Dispatches a message to the listeners.
*
* @param job The job description.
*/
protected void sendMsg(String job)
{
listener.packagerMsg(job);
}
/** Dispatches a start event to the listeners. */
protected void sendStart()
{
listener.packagerStart();
}
/** Dispatches a stop event to the listeners. */
protected void sendStop()
{
listener.packagerStop();
}
/**
* Write the skeleton installer to the output JAR.
*/
public void writeSkeletonInstaller (JarOutputStream out)
throws Exception
{
InputStream is = getClass().getResourceAsStream("lib/installer.jar");
ZipInputStream skeleton_is = null;
if (is != null)
{
skeleton_is = new ZipInputStream (is);
}
if (skeleton_is == null)
{
- skeleton_is = new JarInputStream (new FileInputStream (
+ skeleton_is = new ZipInputStream (new FileInputStream (
Compiler.IZPACK_HOME + "lib" + File.separator + "installer.jar"));
}
ZipEntry zentry;
while ((zentry = skeleton_is.getNextEntry()) != null)
{
// Puts a new entry
out.putNextEntry(new ZipEntry(zentry.getName()));
// Copy the data
copyStream(skeleton_is, out);
out.closeEntry();
skeleton_is.closeEntry();
}
}
/**
* Adds a pack (the compiler sends the merged data).
*
* @param packNumber The pack number.
* @param name The pack name.
* @param required Is the pack required ?
* @param osConstraints The target operation system(s) of this pack.
* @param description The pack description.
* @return Description of the Return Value
* @exception Exception Description of the Exception
*/
public abstract ZipOutputStream addPack(int packNumber, String name, List osConstraints,
boolean required, String description, boolean preselected)
throws Exception;
/**
* Adds a panel.
*
* @param classFilename The class filename.
* @param input The stream to get the file data from.
* @exception Exception Description of the Exception
*/
public abstract void addPanelClass(String classFilename, InputStream input)
throws Exception;
/**
* Sets the GUI preferences.
*
* @param prefs The new gUIPrefs value
* @exception Exception Description of the Exception
*/
public abstract void setGUIPrefs(GUIPrefs prefs) throws Exception;
/**
* Sets the panels order.
*
* @param order The ordered list of the panels.
* @exception Exception Description of the Exception
*/
public abstract void setPanelsOrder(ArrayList order) throws Exception;
/**
* Sets the informations related to this installation.
*
* @param info The info section.
* @exception Exception Description of the Exception
*/
public abstract void setInfo(Info info) throws Exception;
/**
* Adds Variable Declaration.
*
* @param varDef The variables definitions.
* @exception Exception Description of the Exception
*/
public abstract void setVariables(Properties varDef) throws Exception;
/**
* Adds a resource.
*
* @param resId The resource Id.
* @param input The stream to get the data from.
* @exception Exception Description of the Exception
*/
public abstract void addResource(String resId, InputStream input) throws Exception;
/**
* Adds a language pack.
*
* @param iso3 The ISO3 code.
* @param input The stream to get the data from.
* @exception Exception Description of the Exception
*/
public abstract void addLangPack(String iso3, InputStream input) throws Exception;
/**
* Adds a native library.
*
* @param name The native library name.
* @param input The stream to get the data from.
* @exception Exception Description of the Exception
*/
public abstract void addNativeLibrary(String name, InputStream input) throws Exception;
/**
* Adds a jar file content to the installer.
*
* @param file The jar filename.
* @exception Exception Description of the Exception
*/
public abstract void addJarContent(String file) throws Exception;
/**
* Tells the packager to finish the job (misc writings, cleanups, closings ,
* ...).
*
* @exception Exception Description of the Exception
*/
public abstract void finish() throws Exception;
/**
* Copies all the data from the specified input stream to the specified
* output stream. This is an utility method which may be used by the
* subclasses. by Johannes Lehtinen
*
* @param in the input stream to read
* @param out the output stream to write
* @return the total number of bytes copied
* @exception IOException if an I/O error occurs
*/
protected long copyStream(InputStream in, OutputStream out)
throws IOException
{
byte[] buffer = new byte[5120];
long bytesCopied = 0;
int bytesInBuffer;
while ((bytesInBuffer = in.read(buffer)) != -1)
{
out.write(buffer, 0, bytesInBuffer);
bytesCopied += bytesInBuffer;
}
return bytesCopied;
}
/**
* Called by the Compiler when the pack content adding is done. (JP)
*
* @param number the pack number
* @param nbytes the number of bytes written
*/
protected void packAdded(int number, long nbytes)
{
((Pack) packs.get(number)).nbytes = nbytes;
}
}
| true | true | public void writeSkeletonInstaller (JarOutputStream out)
throws Exception
{
InputStream is = getClass().getResourceAsStream("lib/installer.jar");
ZipInputStream skeleton_is = null;
if (is != null)
{
skeleton_is = new ZipInputStream (is);
}
if (skeleton_is == null)
{
skeleton_is = new JarInputStream (new FileInputStream (
Compiler.IZPACK_HOME + "lib" + File.separator + "installer.jar"));
}
ZipEntry zentry;
while ((zentry = skeleton_is.getNextEntry()) != null)
{
// Puts a new entry
out.putNextEntry(new ZipEntry(zentry.getName()));
// Copy the data
copyStream(skeleton_is, out);
out.closeEntry();
skeleton_is.closeEntry();
}
}
| public void writeSkeletonInstaller (JarOutputStream out)
throws Exception
{
InputStream is = getClass().getResourceAsStream("lib/installer.jar");
ZipInputStream skeleton_is = null;
if (is != null)
{
skeleton_is = new ZipInputStream (is);
}
if (skeleton_is == null)
{
skeleton_is = new ZipInputStream (new FileInputStream (
Compiler.IZPACK_HOME + "lib" + File.separator + "installer.jar"));
}
ZipEntry zentry;
while ((zentry = skeleton_is.getNextEntry()) != null)
{
// Puts a new entry
out.putNextEntry(new ZipEntry(zentry.getName()));
// Copy the data
copyStream(skeleton_is, out);
out.closeEntry();
skeleton_is.closeEntry();
}
}
|
diff --git a/src/org/ohmage/feedback/visualization/FeedbackTimeChart.java b/src/org/ohmage/feedback/visualization/FeedbackTimeChart.java
index 8606b7b..bec4507 100644
--- a/src/org/ohmage/feedback/visualization/FeedbackTimeChart.java
+++ b/src/org/ohmage/feedback/visualization/FeedbackTimeChart.java
@@ -1,239 +1,240 @@
/**
* Copyright (C) 2009, 2010 SC 4ViewSoft SRL
*
* 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.ohmage.feedback.visualization;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.ohmage.Utilities.KVLTriplet;
import org.ohmage.feedback.FeedbackContract;
import org.ohmage.feedback.FeedbackContract.FeedbackPromptResponses;
import org.ohmage.feedback.FeedbackContract.FeedbackResponses;
import org.ohmage.prompt.AbstractPrompt;
import org.ohmage.prompt.Prompt;
import org.ohmage.prompt.number.NumberPrompt;
import org.ohmage.prompt.singlechoice.SingleChoicePrompt;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.net.Uri;
/**
* Project status demo chart.
*/
public class FeedbackTimeChart extends AbstractChart {
static final String TAG = "FeedbackTimeChartLog";
protected String mPromptID;
protected String mCampaignUrn;
protected String mSurveyID;
protected List<Prompt> mPrompts;
public FeedbackTimeChart(String title, String campaignUrn, String surveyID, String promptID, List<Prompt> prompts) {
super(title);
mCampaignUrn = campaignUrn;
mSurveyID = surveyID;
mPromptID = promptID;
mPrompts = prompts;
}
/**
* Returns the chart name.
*
* @return the chart name
*/
public String getName() {
return "FeedbackTimeChart";
}
/**
* Returns the chart description.
*
* @return the chart description
*/
public String getDesc() {
return "Feedback Time Chart Description";
}
/**
* Executes the chart demo.
*
* @param context
* the context
* @return the built intent
*/
public Intent execute(Context context) {
// titles for each of the series (in this case we have only one)
String[] titles = new String[] { "" };
// list of labels for each series (only one, since we only have one series)
List<Date[]> dates = new ArrayList<Date[]>();
// list of values for each series (only one, since we only have one series)
List<double[]> values = new ArrayList<double[]>();
// call up the contentprovider and feed it the campaign, survey, and prompt ID
// we should get a series of prompt values for the survey that we can plot
ContentResolver cr = context.getContentResolver();
// URI to match "<campaignUrn>/<surveyID>/responses/prompts/<promptID>"
Uri queryUri = FeedbackPromptResponses.getPromptsByCampaignAndSurvey(mCampaignUrn, mSurveyID, mPromptID);
// columns to return; in this case, we just need the date and the value at that date point
String[] projection = new String[] { FeedbackResponses.TIME, FeedbackPromptResponses.PROMPT_VALUE };
// nab that data! data is sorted by FeedbackResponses.TIME
Cursor cursor = cr.query(queryUri, projection, null, null, FeedbackResponses.TIME);
if(cursor.getCount() == 0){
+ cursor.close();
return null;
}
// now we iterate through the cursor and insert each column of each row
// into the appropriate list
ArrayList<Date> singleDates = new ArrayList<Date>();
ArrayList<Double> singleValues = new ArrayList<Double>();
double maxValue = 0;
while (cursor.moveToNext()) {
// extract date/value from each row and put it in our series
// 0: time field, as a long
// 1: prompt value, as text
singleDates.add(new Date(cursor.getLong(0)));
singleValues.add(cursor.getDouble(1));
if (cursor.getDouble(1) > maxValue)
maxValue = cursor.getDouble(1);
}
cursor.close();
// convert ArrayList<Double> to double[], because java is silly
double[] singleValuesArray = new double[singleValues.size()];
for (int i = 0; i < singleValues.size(); ++i)
singleValuesArray[i] = singleValues.get(i);
// and add our date/value series to the respective containers
dates.add(singleDates.toArray(new Date[singleDates.size()]));
values.add(singleValuesArray);
//Get startdate and enddate
long startDate = dates.get(0)[0].getTime() - (100 * 60 * 60 * 24 * 3);
long endDate = dates.get(0)[dates.get(0).length-1].getTime() + (100 * 60 * 60 * 24 * 3);
int[] colors = new int[] { Color.RED };
PointStyle[] styles = new PointStyle[] { PointStyle.X };
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
//Set Chart
setChartSettings(
renderer,
"",
"Date",
"",
startDate,
endDate,
0,
maxValue+1,
Color.GRAY,
Color.LTGRAY
);
renderer.setShowGrid(true);
//Set chart layout
int topMargin = 0;
int bottomMargin = 100;
int leftMargin = 10;
int rightMargin = 0;
int margins[] = {topMargin, leftMargin, bottomMargin, rightMargin};
renderer.setMargins(margins);
renderer.setAxisTitleTextSize(23);
renderer.setLabelsTextSize(20);
renderer.setXLabelsAlign(Align.LEFT);
renderer.setShowLegend(false);
renderer.setLegendTextSize(20);
renderer.setPointSize(10);
renderer.setXLabelsAngle(330);
renderer.setZoomButtonsVisible(true);
renderer.setShowAxes(true);
//Set pan limit from startData-3days to endDate+3days
renderer.setPanEnabled(true, true);
renderer.setPanLimits(new double[]{startDate, endDate, -1, maxValue+1});
//Set zoom
renderer.setZoomEnabled(true, false);
renderer.setZoomLimits(new double[]{startDate, endDate, -1, maxValue+1});
//Set Y Label
//TODO Need to organize all prompt types instead of handling this with NULL
renderer.setYLabelsAlign(Align.LEFT);
List<KVLTriplet> propertiesList = getPropertiesList(mPromptID);
if(propertiesList != null){
//Prompts that have properties (SingleChoice, MultiChoice, etc)
for(KVLTriplet i : propertiesList){
renderer.addYTextLabel(Double.valueOf(i.key).doubleValue(), i.label);
}
}
// disables interpolated values from being added between text labels
// i assume we want this if we're providing specific labels for enumerations
renderer.setYLabels(0);
int length = renderer.getSeriesRendererCount();
for (int i = 0; i < length; i++) {
SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
seriesRenderer.setDisplayChartValues(true);
}
return ChartFactory.getTimeChartIntent(
context,
buildDateDataset(titles, dates, values),
renderer,
"MM/dd hha",
mChartTitle
);
}
private List<KVLTriplet> getPropertiesList(String promptId){
Iterator<Prompt> ite = mPrompts.iterator();
while(ite.hasNext()){
AbstractPrompt allPromptList = (AbstractPrompt)ite.next();
if(promptId.equals(allPromptList.getId())){
if(allPromptList instanceof SingleChoicePrompt){
SingleChoicePrompt prompt = (SingleChoicePrompt)allPromptList;
List<KVLTriplet> choiceKVLTriplet = prompt.getChoices();
return choiceKVLTriplet;
}
else if(allPromptList instanceof NumberPrompt){
NumberPrompt prompt = (NumberPrompt)allPromptList;
List<KVLTriplet> choiceKVLTriplet = new ArrayList<KVLTriplet>();
for(int i=prompt.getMinimum(); i<=prompt.getMaximum(); i++){
choiceKVLTriplet.add(new KVLTriplet(String.valueOf(i), String.valueOf(i), String.valueOf(i)));
}
return choiceKVLTriplet;
}
}
}
return null;
}
}
| true | true | public Intent execute(Context context) {
// titles for each of the series (in this case we have only one)
String[] titles = new String[] { "" };
// list of labels for each series (only one, since we only have one series)
List<Date[]> dates = new ArrayList<Date[]>();
// list of values for each series (only one, since we only have one series)
List<double[]> values = new ArrayList<double[]>();
// call up the contentprovider and feed it the campaign, survey, and prompt ID
// we should get a series of prompt values for the survey that we can plot
ContentResolver cr = context.getContentResolver();
// URI to match "<campaignUrn>/<surveyID>/responses/prompts/<promptID>"
Uri queryUri = FeedbackPromptResponses.getPromptsByCampaignAndSurvey(mCampaignUrn, mSurveyID, mPromptID);
// columns to return; in this case, we just need the date and the value at that date point
String[] projection = new String[] { FeedbackResponses.TIME, FeedbackPromptResponses.PROMPT_VALUE };
// nab that data! data is sorted by FeedbackResponses.TIME
Cursor cursor = cr.query(queryUri, projection, null, null, FeedbackResponses.TIME);
if(cursor.getCount() == 0){
return null;
}
// now we iterate through the cursor and insert each column of each row
// into the appropriate list
ArrayList<Date> singleDates = new ArrayList<Date>();
ArrayList<Double> singleValues = new ArrayList<Double>();
double maxValue = 0;
while (cursor.moveToNext()) {
// extract date/value from each row and put it in our series
// 0: time field, as a long
// 1: prompt value, as text
singleDates.add(new Date(cursor.getLong(0)));
singleValues.add(cursor.getDouble(1));
if (cursor.getDouble(1) > maxValue)
maxValue = cursor.getDouble(1);
}
cursor.close();
// convert ArrayList<Double> to double[], because java is silly
double[] singleValuesArray = new double[singleValues.size()];
for (int i = 0; i < singleValues.size(); ++i)
singleValuesArray[i] = singleValues.get(i);
// and add our date/value series to the respective containers
dates.add(singleDates.toArray(new Date[singleDates.size()]));
values.add(singleValuesArray);
//Get startdate and enddate
long startDate = dates.get(0)[0].getTime() - (100 * 60 * 60 * 24 * 3);
long endDate = dates.get(0)[dates.get(0).length-1].getTime() + (100 * 60 * 60 * 24 * 3);
int[] colors = new int[] { Color.RED };
PointStyle[] styles = new PointStyle[] { PointStyle.X };
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
//Set Chart
setChartSettings(
renderer,
"",
"Date",
"",
startDate,
endDate,
0,
maxValue+1,
Color.GRAY,
Color.LTGRAY
);
renderer.setShowGrid(true);
//Set chart layout
int topMargin = 0;
int bottomMargin = 100;
int leftMargin = 10;
int rightMargin = 0;
int margins[] = {topMargin, leftMargin, bottomMargin, rightMargin};
renderer.setMargins(margins);
renderer.setAxisTitleTextSize(23);
renderer.setLabelsTextSize(20);
renderer.setXLabelsAlign(Align.LEFT);
renderer.setShowLegend(false);
renderer.setLegendTextSize(20);
renderer.setPointSize(10);
renderer.setXLabelsAngle(330);
renderer.setZoomButtonsVisible(true);
renderer.setShowAxes(true);
//Set pan limit from startData-3days to endDate+3days
renderer.setPanEnabled(true, true);
renderer.setPanLimits(new double[]{startDate, endDate, -1, maxValue+1});
//Set zoom
renderer.setZoomEnabled(true, false);
renderer.setZoomLimits(new double[]{startDate, endDate, -1, maxValue+1});
//Set Y Label
//TODO Need to organize all prompt types instead of handling this with NULL
renderer.setYLabelsAlign(Align.LEFT);
List<KVLTriplet> propertiesList = getPropertiesList(mPromptID);
if(propertiesList != null){
//Prompts that have properties (SingleChoice, MultiChoice, etc)
for(KVLTriplet i : propertiesList){
renderer.addYTextLabel(Double.valueOf(i.key).doubleValue(), i.label);
}
}
// disables interpolated values from being added between text labels
// i assume we want this if we're providing specific labels for enumerations
renderer.setYLabels(0);
int length = renderer.getSeriesRendererCount();
for (int i = 0; i < length; i++) {
SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
seriesRenderer.setDisplayChartValues(true);
}
return ChartFactory.getTimeChartIntent(
context,
buildDateDataset(titles, dates, values),
renderer,
"MM/dd hha",
mChartTitle
);
}
| public Intent execute(Context context) {
// titles for each of the series (in this case we have only one)
String[] titles = new String[] { "" };
// list of labels for each series (only one, since we only have one series)
List<Date[]> dates = new ArrayList<Date[]>();
// list of values for each series (only one, since we only have one series)
List<double[]> values = new ArrayList<double[]>();
// call up the contentprovider and feed it the campaign, survey, and prompt ID
// we should get a series of prompt values for the survey that we can plot
ContentResolver cr = context.getContentResolver();
// URI to match "<campaignUrn>/<surveyID>/responses/prompts/<promptID>"
Uri queryUri = FeedbackPromptResponses.getPromptsByCampaignAndSurvey(mCampaignUrn, mSurveyID, mPromptID);
// columns to return; in this case, we just need the date and the value at that date point
String[] projection = new String[] { FeedbackResponses.TIME, FeedbackPromptResponses.PROMPT_VALUE };
// nab that data! data is sorted by FeedbackResponses.TIME
Cursor cursor = cr.query(queryUri, projection, null, null, FeedbackResponses.TIME);
if(cursor.getCount() == 0){
cursor.close();
return null;
}
// now we iterate through the cursor and insert each column of each row
// into the appropriate list
ArrayList<Date> singleDates = new ArrayList<Date>();
ArrayList<Double> singleValues = new ArrayList<Double>();
double maxValue = 0;
while (cursor.moveToNext()) {
// extract date/value from each row and put it in our series
// 0: time field, as a long
// 1: prompt value, as text
singleDates.add(new Date(cursor.getLong(0)));
singleValues.add(cursor.getDouble(1));
if (cursor.getDouble(1) > maxValue)
maxValue = cursor.getDouble(1);
}
cursor.close();
// convert ArrayList<Double> to double[], because java is silly
double[] singleValuesArray = new double[singleValues.size()];
for (int i = 0; i < singleValues.size(); ++i)
singleValuesArray[i] = singleValues.get(i);
// and add our date/value series to the respective containers
dates.add(singleDates.toArray(new Date[singleDates.size()]));
values.add(singleValuesArray);
//Get startdate and enddate
long startDate = dates.get(0)[0].getTime() - (100 * 60 * 60 * 24 * 3);
long endDate = dates.get(0)[dates.get(0).length-1].getTime() + (100 * 60 * 60 * 24 * 3);
int[] colors = new int[] { Color.RED };
PointStyle[] styles = new PointStyle[] { PointStyle.X };
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
//Set Chart
setChartSettings(
renderer,
"",
"Date",
"",
startDate,
endDate,
0,
maxValue+1,
Color.GRAY,
Color.LTGRAY
);
renderer.setShowGrid(true);
//Set chart layout
int topMargin = 0;
int bottomMargin = 100;
int leftMargin = 10;
int rightMargin = 0;
int margins[] = {topMargin, leftMargin, bottomMargin, rightMargin};
renderer.setMargins(margins);
renderer.setAxisTitleTextSize(23);
renderer.setLabelsTextSize(20);
renderer.setXLabelsAlign(Align.LEFT);
renderer.setShowLegend(false);
renderer.setLegendTextSize(20);
renderer.setPointSize(10);
renderer.setXLabelsAngle(330);
renderer.setZoomButtonsVisible(true);
renderer.setShowAxes(true);
//Set pan limit from startData-3days to endDate+3days
renderer.setPanEnabled(true, true);
renderer.setPanLimits(new double[]{startDate, endDate, -1, maxValue+1});
//Set zoom
renderer.setZoomEnabled(true, false);
renderer.setZoomLimits(new double[]{startDate, endDate, -1, maxValue+1});
//Set Y Label
//TODO Need to organize all prompt types instead of handling this with NULL
renderer.setYLabelsAlign(Align.LEFT);
List<KVLTriplet> propertiesList = getPropertiesList(mPromptID);
if(propertiesList != null){
//Prompts that have properties (SingleChoice, MultiChoice, etc)
for(KVLTriplet i : propertiesList){
renderer.addYTextLabel(Double.valueOf(i.key).doubleValue(), i.label);
}
}
// disables interpolated values from being added between text labels
// i assume we want this if we're providing specific labels for enumerations
renderer.setYLabels(0);
int length = renderer.getSeriesRendererCount();
for (int i = 0; i < length; i++) {
SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
seriesRenderer.setDisplayChartValues(true);
}
return ChartFactory.getTimeChartIntent(
context,
buildDateDataset(titles, dates, values),
renderer,
"MM/dd hha",
mChartTitle
);
}
|
diff --git a/src/java/org/apache/cassandra/db/ColumnIndexer.java b/src/java/org/apache/cassandra/db/ColumnIndexer.java
index 8b2dc1c2e..538802e3b 100644
--- a/src/java/org/apache/cassandra/db/ColumnIndexer.java
+++ b/src/java/org/apache/cassandra/db/ColumnIndexer.java
@@ -1,147 +1,147 @@
/**
* 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.cassandra.db;
import java.io.DataOutput;
import java.io.IOError;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.sstable.IndexHelper;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.io.util.IIterableColumns;
import org.apache.cassandra.utils.BloomFilter;
/**
* Help to create an index for a column family based on size of columns
*/
public class ColumnIndexer
{
/**
* Given a column family this, function creates an in-memory structure that represents the
* column index for the column family, and subsequently writes it to disk.
* @param columns Column family to create index for
* @param dos data output stream
* @throws IOException
*/
public static void serialize(IIterableColumns columns, DataOutput dos)
{
try
{
serializeInternal(columns, dos);
}
catch (IOException e)
{
throw new IOError(e);
}
}
public static void serializeInternal(IIterableColumns columns, DataOutput dos) throws IOException
{
int columnCount = columns.getEstimatedColumnCount();
BloomFilter bf = BloomFilter.getFilter(columnCount, 4);
if (columnCount == 0)
{
writeEmptyHeader(dos, bf);
return;
}
// update bloom filter and create a list of IndexInfo objects marking the first and last column
// in each block of ColumnIndexSize
List<IndexHelper.IndexInfo> indexList = new ArrayList<IndexHelper.IndexInfo>();
- int endPosition = 0, startPosition = -1;
+ long endPosition = 0, startPosition = -1;
int indexSizeInBytes = 0;
IColumn lastColumn = null, firstColumn = null;
for (IColumn column : columns)
{
bf.add(column.name());
if (firstColumn == null)
{
firstColumn = column;
startPosition = endPosition;
}
endPosition += column.serializedSize();
/* if we hit the column index size that we have to index after, go ahead and index it. */
if (endPosition - startPosition >= DatabaseDescriptor.getColumnIndexSize())
{
IndexHelper.IndexInfo cIndexInfo = new IndexHelper.IndexInfo(firstColumn.name(), column.name(), startPosition, endPosition - startPosition);
indexList.add(cIndexInfo);
indexSizeInBytes += cIndexInfo.serializedSize();
firstColumn = null;
}
lastColumn = column;
}
// all columns were GC'd after all
if (lastColumn == null)
{
writeEmptyHeader(dos, bf);
return;
}
// the last column may have fallen on an index boundary already. if not, index it explicitly.
if (indexList.isEmpty() || columns.getComparator().compare(indexList.get(indexList.size() - 1).lastName, lastColumn.name()) != 0)
{
IndexHelper.IndexInfo cIndexInfo = new IndexHelper.IndexInfo(firstColumn.name(), lastColumn.name(), startPosition, endPosition - startPosition);
indexList.add(cIndexInfo);
indexSizeInBytes += cIndexInfo.serializedSize();
}
/* Write out the bloom filter. */
writeBloomFilter(dos, bf);
// write the index. we should always have at least one computed index block, but we only write it out if there is more than that.
assert indexSizeInBytes > 0;
if (indexList.size() > 1)
{
dos.writeInt(indexSizeInBytes);
for (IndexHelper.IndexInfo cIndexInfo : indexList)
{
cIndexInfo.serialize(dos);
}
}
else
{
dos.writeInt(0);
}
}
private static void writeEmptyHeader(DataOutput dos, BloomFilter bf)
throws IOException
{
writeBloomFilter(dos, bf);
dos.writeInt(0);
}
private static void writeBloomFilter(DataOutput dos, BloomFilter bf) throws IOException
{
DataOutputBuffer bufOut = new DataOutputBuffer();
BloomFilter.serializer().serialize(bf, bufOut);
dos.writeInt(bufOut.getLength());
dos.write(bufOut.getData(), 0, bufOut.getLength());
}
}
| true | true | public static void serializeInternal(IIterableColumns columns, DataOutput dos) throws IOException
{
int columnCount = columns.getEstimatedColumnCount();
BloomFilter bf = BloomFilter.getFilter(columnCount, 4);
if (columnCount == 0)
{
writeEmptyHeader(dos, bf);
return;
}
// update bloom filter and create a list of IndexInfo objects marking the first and last column
// in each block of ColumnIndexSize
List<IndexHelper.IndexInfo> indexList = new ArrayList<IndexHelper.IndexInfo>();
int endPosition = 0, startPosition = -1;
int indexSizeInBytes = 0;
IColumn lastColumn = null, firstColumn = null;
for (IColumn column : columns)
{
bf.add(column.name());
if (firstColumn == null)
{
firstColumn = column;
startPosition = endPosition;
}
endPosition += column.serializedSize();
/* if we hit the column index size that we have to index after, go ahead and index it. */
if (endPosition - startPosition >= DatabaseDescriptor.getColumnIndexSize())
{
IndexHelper.IndexInfo cIndexInfo = new IndexHelper.IndexInfo(firstColumn.name(), column.name(), startPosition, endPosition - startPosition);
indexList.add(cIndexInfo);
indexSizeInBytes += cIndexInfo.serializedSize();
firstColumn = null;
}
lastColumn = column;
}
// all columns were GC'd after all
if (lastColumn == null)
{
writeEmptyHeader(dos, bf);
return;
}
// the last column may have fallen on an index boundary already. if not, index it explicitly.
if (indexList.isEmpty() || columns.getComparator().compare(indexList.get(indexList.size() - 1).lastName, lastColumn.name()) != 0)
{
IndexHelper.IndexInfo cIndexInfo = new IndexHelper.IndexInfo(firstColumn.name(), lastColumn.name(), startPosition, endPosition - startPosition);
indexList.add(cIndexInfo);
indexSizeInBytes += cIndexInfo.serializedSize();
}
/* Write out the bloom filter. */
writeBloomFilter(dos, bf);
// write the index. we should always have at least one computed index block, but we only write it out if there is more than that.
assert indexSizeInBytes > 0;
if (indexList.size() > 1)
{
dos.writeInt(indexSizeInBytes);
for (IndexHelper.IndexInfo cIndexInfo : indexList)
{
cIndexInfo.serialize(dos);
}
}
else
{
dos.writeInt(0);
}
}
| public static void serializeInternal(IIterableColumns columns, DataOutput dos) throws IOException
{
int columnCount = columns.getEstimatedColumnCount();
BloomFilter bf = BloomFilter.getFilter(columnCount, 4);
if (columnCount == 0)
{
writeEmptyHeader(dos, bf);
return;
}
// update bloom filter and create a list of IndexInfo objects marking the first and last column
// in each block of ColumnIndexSize
List<IndexHelper.IndexInfo> indexList = new ArrayList<IndexHelper.IndexInfo>();
long endPosition = 0, startPosition = -1;
int indexSizeInBytes = 0;
IColumn lastColumn = null, firstColumn = null;
for (IColumn column : columns)
{
bf.add(column.name());
if (firstColumn == null)
{
firstColumn = column;
startPosition = endPosition;
}
endPosition += column.serializedSize();
/* if we hit the column index size that we have to index after, go ahead and index it. */
if (endPosition - startPosition >= DatabaseDescriptor.getColumnIndexSize())
{
IndexHelper.IndexInfo cIndexInfo = new IndexHelper.IndexInfo(firstColumn.name(), column.name(), startPosition, endPosition - startPosition);
indexList.add(cIndexInfo);
indexSizeInBytes += cIndexInfo.serializedSize();
firstColumn = null;
}
lastColumn = column;
}
// all columns were GC'd after all
if (lastColumn == null)
{
writeEmptyHeader(dos, bf);
return;
}
// the last column may have fallen on an index boundary already. if not, index it explicitly.
if (indexList.isEmpty() || columns.getComparator().compare(indexList.get(indexList.size() - 1).lastName, lastColumn.name()) != 0)
{
IndexHelper.IndexInfo cIndexInfo = new IndexHelper.IndexInfo(firstColumn.name(), lastColumn.name(), startPosition, endPosition - startPosition);
indexList.add(cIndexInfo);
indexSizeInBytes += cIndexInfo.serializedSize();
}
/* Write out the bloom filter. */
writeBloomFilter(dos, bf);
// write the index. we should always have at least one computed index block, but we only write it out if there is more than that.
assert indexSizeInBytes > 0;
if (indexList.size() > 1)
{
dos.writeInt(indexSizeInBytes);
for (IndexHelper.IndexInfo cIndexInfo : indexList)
{
cIndexInfo.serialize(dos);
}
}
else
{
dos.writeInt(0);
}
}
|
diff --git a/src/main/java/at/co/hohl/Announcer/AnnouncerThread.java b/src/main/java/at/co/hohl/Announcer/AnnouncerThread.java
index 643e740..712481e 100644
--- a/src/main/java/at/co/hohl/Announcer/AnnouncerThread.java
+++ b/src/main/java/at/co/hohl/Announcer/AnnouncerThread.java
@@ -1,68 +1,68 @@
/*
* Copyright (C) 2011-2012 Mi.Ho.
*
* 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 at.co.hohl.Announcer;
import java.util.Random;
/**
* Thread which handles the announcing.
*
* @author MiHo
*/
class AnnouncerThread extends Thread {
/**
* Tool used for generating random numbers.
*/
private final Random randomGenerator = new Random();
/**
* The plugin which holds this thread.
*/
private final AnnouncerPlugin plugin;
/**
* The last announcement index. (Only for sequential announcing.)
*/
private int lastAnnouncement = 0;
/**
* Allocates a new scheduled announcer thread.
*
* @param plugin the plugin which holds the thread.
*/
public AnnouncerThread(AnnouncerPlugin plugin) {
this.plugin = plugin;
}
/**
* The main method of the thread.
*/
@Override
public void run() {
if (plugin.isAnnouncerEnabled()) {
if (plugin.isRandom()) {
- lastAnnouncement = randomGenerator.nextInt() % plugin.numberOfAnnouncements();
+ lastAnnouncement = Math.abs(randomGenerator.nextInt() % plugin.numberOfAnnouncements());
} else {
if ((++lastAnnouncement) >= plugin.numberOfAnnouncements()) {
lastAnnouncement = 0;
}
}
if (lastAnnouncement < plugin.numberOfAnnouncements()) {
plugin.announce(lastAnnouncement + 1);
}
}
}
}
| true | true | public void run() {
if (plugin.isAnnouncerEnabled()) {
if (plugin.isRandom()) {
lastAnnouncement = randomGenerator.nextInt() % plugin.numberOfAnnouncements();
} else {
if ((++lastAnnouncement) >= plugin.numberOfAnnouncements()) {
lastAnnouncement = 0;
}
}
if (lastAnnouncement < plugin.numberOfAnnouncements()) {
plugin.announce(lastAnnouncement + 1);
}
}
}
| public void run() {
if (plugin.isAnnouncerEnabled()) {
if (plugin.isRandom()) {
lastAnnouncement = Math.abs(randomGenerator.nextInt() % plugin.numberOfAnnouncements());
} else {
if ((++lastAnnouncement) >= plugin.numberOfAnnouncements()) {
lastAnnouncement = 0;
}
}
if (lastAnnouncement < plugin.numberOfAnnouncements()) {
plugin.announce(lastAnnouncement + 1);
}
}
}
|
diff --git a/deegree-core/deegree-core-base/src/main/java/org/deegree/gml/feature/GMLFeatureWriter.java b/deegree-core/deegree-core-base/src/main/java/org/deegree/gml/feature/GMLFeatureWriter.java
index 3ab51fb48f..429a4a1153 100644
--- a/deegree-core/deegree-core-base/src/main/java/org/deegree/gml/feature/GMLFeatureWriter.java
+++ b/deegree-core/deegree-core-base/src/main/java/org/deegree/gml/feature/GMLFeatureWriter.java
@@ -1,726 +1,729 @@
//$HeadURL: svn+ssh://[email protected]/deegree/deegree3/commons/trunk/src/org/deegree/model/feature/Feature.java $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
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 information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.gml.feature;
import static org.deegree.commons.xml.CommonNamespaces.XLNNS;
import static org.deegree.commons.xml.CommonNamespaces.XSINS;
import static org.deegree.commons.xml.stax.StAXExportingHelper.writeAttribute;
import static org.deegree.feature.types.property.ValueRepresentation.REMOTE;
import static org.deegree.gml.GMLVersion.GML_2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import org.apache.xerces.xs.XSElementDeclaration;
import org.deegree.commons.tom.ElementNode;
import org.deegree.commons.tom.TypedObjectNode;
import org.deegree.commons.tom.array.TypedObjectNodeArray;
import org.deegree.commons.tom.genericxml.GenericXMLElement;
import org.deegree.commons.tom.gml.GMLObject;
import org.deegree.commons.tom.gml.property.Property;
import org.deegree.commons.tom.gml.property.PropertyType;
import org.deegree.commons.tom.ows.CodeType;
import org.deegree.commons.tom.ows.StringOrRef;
import org.deegree.commons.tom.primitive.BaseType;
import org.deegree.commons.tom.primitive.PrimitiveValue;
import org.deegree.commons.uom.Length;
import org.deegree.commons.uom.Measure;
import org.deegree.cs.exceptions.TransformationException;
import org.deegree.cs.exceptions.UnknownCRSException;
import org.deegree.feature.Feature;
import org.deegree.feature.FeatureCollection;
import org.deegree.feature.GenericFeatureCollection;
import org.deegree.feature.property.ExtraProps;
import org.deegree.feature.property.GenericProperty;
import org.deegree.feature.types.AppSchema;
import org.deegree.feature.types.property.ArrayPropertyType;
import org.deegree.feature.types.property.CodePropertyType;
import org.deegree.feature.types.property.CustomPropertyType;
import org.deegree.feature.types.property.EnvelopePropertyType;
import org.deegree.feature.types.property.FeaturePropertyType;
import org.deegree.feature.types.property.GeometryPropertyType;
import org.deegree.feature.types.property.LengthPropertyType;
import org.deegree.feature.types.property.MeasurePropertyType;
import org.deegree.feature.types.property.ObjectPropertyType;
import org.deegree.feature.types.property.SimplePropertyType;
import org.deegree.feature.types.property.StringOrRefPropertyType;
import org.deegree.feature.xpath.TypedObjectNodeXPathEvaluator;
import org.deegree.filter.Filter;
import org.deegree.filter.FilterEvaluationException;
import org.deegree.filter.projection.ProjectionClause;
import org.deegree.filter.projection.PropertyName;
import org.deegree.filter.projection.TimeSliceProjection;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.Geometry;
import org.deegree.gml.GMLStreamWriter;
import org.deegree.gml.commons.AbstractGMLObjectWriter;
import org.deegree.gml.reference.FeatureReference;
import org.deegree.gml.reference.GmlXlinkOptions;
import org.deegree.gml.schema.GMLSchemaInfoSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Stream-based GML writer for {@link Feature} (and {@link FeatureCollection}) instances.
*
* @author <a href="mailto:[email protected]">Markus Schneider</a>
* @author <a href="mailto:[email protected]">Andrei Ionita</a>
* @author last edited by: $Author:$
*
* @version $Revision:$, $Date:$
*/
public class GMLFeatureWriter extends AbstractGMLObjectWriter {
private static final Logger LOG = LoggerFactory.getLogger( GMLFeatureWriter.class );
private final QName fidAttr;
private final String gmlNull;
private final Map<QName, PropertyName> requestedPropertyNames = new HashMap<QName, PropertyName>();
private final List<Filter> timeSliceFilters = new ArrayList<Filter>();
private final boolean exportSf;
private final boolean outputGeometries;
private final boolean exportExtraProps;
private final boolean exportBoundedBy;
private final PropertyType boundedByPt;
private AppSchema schema;
private GMLSchemaInfoSet schemaInfoset;
private static final QName XSI_NIL = new QName( XSINS, "nil", "xsi" );
/**
* Creates a new {@link GMLFeatureWriter} instance.
*
* @param gmlStreamWriter
* GML stream writer, must not be <code>null</code>
*/
public GMLFeatureWriter( GMLStreamWriter gmlStreamWriter ) {
super( gmlStreamWriter );
if ( gmlStreamWriter.getProjections() != null ) {
for ( ProjectionClause projection : gmlStreamWriter.getProjections() ) {
if ( projection instanceof PropertyName ) {
PropertyName propName = (PropertyName) projection;
QName qName = propName.getPropertyName().getAsQName();
if ( qName != null ) {
requestedPropertyNames.put( qName, propName );
} else {
LOG.debug( "Only simple qualified element names are allowed for PropertyName projections. Ignoring '"
+ propName.getPropertyName() + "'" );
}
} else if ( projection instanceof TimeSliceProjection ) {
timeSliceFilters.add( ( (TimeSliceProjection) projection ).getTimeSliceFilter() );
}
}
}
if ( !version.equals( GML_2 ) ) {
fidAttr = new QName( gmlNs, "id" );
gmlNull = "Null";
} else {
fidAttr = new QName( "", "fid" );
gmlNull = "null";
}
this.outputGeometries = gmlStreamWriter.getOutputGeometries();
this.exportSf = false;
this.exportExtraProps = gmlStreamWriter.getExportExtraProps();
this.boundedByPt = new EnvelopePropertyType( new QName( gmlNs, "boundedBy" ), 0, 1, null, null );
this.exportBoundedBy = gmlStreamWriter.getGenerateBoundedByForFeatures();
}
/**
* Exports the given {@link Feature} (or {@link FeatureCollection}).
*
* @param feature
* feature to be exported, must not be <code>null</code>
* @throws XMLStreamException
* @throws UnknownCRSException
* @throws TransformationException
*/
public void export( Feature feature )
throws XMLStreamException, UnknownCRSException, TransformationException {
export( feature, referenceExportStrategy.getResolveOptions() );
}
/**
* Exports the given {@link Property}.
*
* @param prop
* property to be exported, must not be <code>null</code>
* @throws XMLStreamException
* @throws UnknownCRSException
* @throws TransformationException
*/
public void export( Property prop )
throws XMLStreamException, UnknownCRSException, TransformationException {
export( prop, referenceExportStrategy.getResolveOptions() );
}
public void export( TypedObjectNode node, GmlXlinkOptions resolveState )
throws XMLStreamException, UnknownCRSException, TransformationException {
if ( node instanceof GMLObject ) {
if ( node instanceof Feature ) {
export( (Feature) node, resolveState );
} else if ( node instanceof Geometry ) {
gmlStreamWriter.getGeometryWriter().export( (Geometry) node );
} else {
throw new UnsupportedOperationException();
}
} else if ( node instanceof PrimitiveValue ) {
writer.writeCharacters( ( (PrimitiveValue) node ).getAsText() );
} else if ( node instanceof Property ) {
export( (Property) node, resolveState );
} else if ( node instanceof ElementNode ) {
ElementNode xmlContent = (ElementNode) node;
exportGenericXmlElement( xmlContent, resolveState );
} else if ( node instanceof TypedObjectNodeArray<?> ) {
for ( TypedObjectNode elem : ( (TypedObjectNodeArray<?>) node ).getElements() ) {
export( elem, resolveState );
}
} else if ( node == null ) {
LOG.warn( "Null node encountered!?" );
} else {
throw new RuntimeException( "Unhandled node type '" + node.getClass() + "'" );
}
}
private void export( Property property, GmlXlinkOptions resolveState )
throws XMLStreamException, UnknownCRSException, TransformationException {
QName propName = property.getName();
PropertyType pt = property.getType();
if ( pt.getMinOccurs() == 0 ) {
LOG.debug( "Optional property '" + propName + "', checking if it is requested." );
if ( !isPropertyRequested( propName ) ) {
LOG.debug( "Skipping it." );
return;
}
// required for WMS:
if ( !outputGeometries && pt instanceof GeometryPropertyType ) {
LOG.debug( "Skipping it since geometries should not be output." );
return;
}
}
if ( resolveState.getCurrentLevel() == 0 ) {
resolveState = getResolveParams( property, resolveState );
}
TypedObjectNode value = property.getValue();
// if ( value instanceof GenericXMLElement ) {
// writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
// export( value, currentLevel, maxInlineLevels );
// writer.writeEndElement();
// return;
// }
// TODO check for GML 2 properties (gml:pointProperty, ...) and export
// as "app:gml2PointProperty" for GML 3
boolean nilled = false;
TypedObjectNode nil = property.getAttributes().get( XSI_NIL );
if ( nil instanceof PrimitiveValue ) {
nilled = Boolean.TRUE.equals( ( (PrimitiveValue) nil ).getValue() );
}
if ( pt instanceof FeaturePropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
exportFeatureProperty( (FeaturePropertyType) pt, (Feature) value, resolveState );
}
} else if ( pt instanceof SimplePropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
// must be a primitive value
PrimitiveValue pValue = (PrimitiveValue) value;
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( pValue != null ) {
// TODO
if ( pValue.getType().getBaseType() == BaseType.DECIMAL ) {
writer.writeCharacters( pValue.getValue().toString() );
} else {
writer.writeCharacters( pValue.getAsText() );
}
}
writer.writeEndElement();
}
} else if ( pt instanceof GeometryPropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
+ } else if ( value == null ) {
+ writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
+ endEmptyElement();
} else {
Geometry gValue = (Geometry) value;
if ( !exportSf && gValue.getId() != null && referenceExportStrategy.isObjectExported( gValue.getId() ) ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XLNNS, "href", "#" + gValue.getId() );
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( gValue.getId() != null ) {
// WFS CITE 1.1.0 test requirement (wfs:GetFeature.XLink-POST-XML-10)
writer.writeComment( "Inlined geometry '" + gValue.getId() + "'" );
}
gmlStreamWriter.getGeometryWriter().export( (Geometry) value );
writer.writeEndElement();
}
}
} else if ( pt instanceof CodePropertyType ) {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
CodeType codeType = (CodeType) value;
if ( codeType != null ) {
if ( codeType.getCodeSpace() != null && codeType.getCodeSpace().length() > 0 ) {
if ( GML_2 != version ) {
writer.writeAttribute( "codeSpace", codeType.getCodeSpace() );
}
}
writer.writeCharacters( codeType.getCode() );
}
writer.writeEndElement();
} else if ( pt instanceof EnvelopePropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( value != null ) {
gmlStreamWriter.getGeometryWriter().exportEnvelope( (Envelope) value );
} else {
writeStartElementWithNS( gmlNs, gmlNull );
writer.writeCharacters( "missing" );
writer.writeEndElement();
}
writer.writeEndElement();
}
} else if ( pt instanceof LengthPropertyType ) {
Length length = (Length) value;
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( GML_2 != version ) {
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
writer.writeAttribute( "uom", length.getUomUri() );
}
if ( !nilled ) {
writer.writeCharacters( String.valueOf( length.getValue() ) );
}
writer.writeEndElement();
} else if ( pt instanceof MeasurePropertyType ) {
Measure measure = (Measure) value;
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( GML_2 != version ) {
writer.writeAttribute( "uom", measure.getUomUri() );
}
writer.writeCharacters( String.valueOf( measure.getValue() ) );
writer.writeEndElement();
} else if ( pt instanceof StringOrRefPropertyType ) {
StringOrRef stringOrRef = (StringOrRef) value;
if ( stringOrRef.getString() == null || stringOrRef.getString().length() == 0 ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( stringOrRef.getRef() != null ) {
writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() );
}
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
if ( stringOrRef.getRef() != null ) {
writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() );
}
if ( !nilled && stringOrRef.getString() != null ) {
writer.writeCharacters( stringOrRef.getString() );
}
writer.writeEndElement();
}
} else if ( pt instanceof CustomPropertyType ) {
if ( !timeSliceFilters.isEmpty() ) {
if ( excludeByTimeSliceFilter( property ) ) {
return;
}
}
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( property.getAttributes() != null ) {
for ( Entry<QName, PrimitiveValue> attr : property.getAttributes().entrySet() ) {
writeAttribute( writer, attr.getKey(), attr.getValue().getAsText() );
}
}
if ( property.getChildren() != null ) {
for ( TypedObjectNode childNode : property.getChildren() ) {
export( childNode, resolveState );
}
}
writer.writeEndElement();
} else if ( pt instanceof ArrayPropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
export( (TypedObjectNode) property.getValue(), resolveState );
writer.writeEndElement();
}
} else {
throw new RuntimeException( "Internal error. Unhandled property type '" + pt.getClass() + "'" );
}
}
private boolean excludeByTimeSliceFilter( Property property ) {
XSElementDeclaration elDecl = property.getXSType();
if ( elDecl == null ) {
return false;
}
if ( schemaInfoset.getTimeSlicePropertySemantics( elDecl ) == null ) {
return false;
}
TypedObjectNode timeSlice = property.getValue();
// TODO will somebody *please* clean up getChildren() and getValue()!
if ( timeSlice instanceof GenericXMLElement ) {
GenericXMLElement el = (GenericXMLElement) timeSlice;
if ( !el.getChildren().isEmpty() ) {
timeSlice = el.getChildren().get( 0 );
}
}
for ( Filter timeSliceFilter : timeSliceFilters ) {
TypedObjectNodeXPathEvaluator evaluator = new TypedObjectNodeXPathEvaluator();
try {
if ( !timeSliceFilter.evaluate( timeSlice, evaluator ) ) {
return true;
}
} catch ( FilterEvaluationException e ) {
LOG.warn( "Unable to evaluate time slice projection filter: " + e.getMessage() );
}
}
return false;
}
private void exportBoundedBy( Envelope env, boolean indicateMissing )
throws XMLStreamException, UnknownCRSException, TransformationException {
if ( env != null || indicateMissing ) {
writer.writeStartElement( gmlNs, "boundedBy" );
if ( env != null ) {
gmlStreamWriter.getGeometryWriter().exportEnvelope( env );
} else {
writer.writeStartElement( gmlNs, gmlNull );
writer.writeCharacters( "missing" );
writer.writeEndElement();
}
writer.writeEndElement();
}
}
private void export( Feature feature, GmlXlinkOptions resolveState )
throws XMLStreamException, UnknownCRSException, TransformationException {
setSchema( feature );
if ( feature.getId() != null ) {
referenceExportStrategy.addExportedId( feature.getId() );
}
if ( feature instanceof GenericFeatureCollection ) {
LOG.debug( "Exporting generic feature collection." );
writeStartElementWithNS( gmlNs, "FeatureCollection" );
if ( feature.getId() != null ) {
if ( fidAttr.getNamespaceURI() == "" ) {
writer.writeAttribute( fidAttr.getLocalPart(), feature.getId() );
} else {
writeAttributeWithNS( fidAttr.getNamespaceURI(), fidAttr.getLocalPart(), feature.getId() );
}
}
exportBoundedBy( feature.getEnvelope(), false );
for ( Feature member : ( (FeatureCollection) feature ) ) {
String memberFid = member.getId();
writeStartElementWithNS( gmlNs, "featureMember" );
if ( memberFid != null && referenceExportStrategy.isObjectExported( memberFid ) ) {
writeAttributeWithNS( XLNNS, "href", "#" + memberFid );
} else {
export( member, getResolveStateForNextLevel( resolveState ) );
}
writer.writeEndElement();
}
writer.writeEndElement();
} else {
QName featureName = feature.getName();
LOG.debug( "Exporting Feature {} with ID {}", featureName, feature.getId() );
String namespaceURI = featureName.getNamespaceURI();
String localName = featureName.getLocalPart();
writeStartElementWithNS( namespaceURI, localName );
if ( feature.getId() != null ) {
if ( fidAttr.getNamespaceURI() == "" ) {
writer.writeAttribute( fidAttr.getLocalPart(), feature.getId() );
} else {
writeAttributeWithNS( fidAttr.getNamespaceURI(), fidAttr.getLocalPart(), feature.getId() );
}
}
List<Property> props = feature.getProperties();
if ( exportBoundedBy ) {
props = augmentBoundedBy( feature );
}
for ( Property prop : props ) {
export( prop, resolveState );
}
if ( exportExtraProps ) {
ExtraProps extraProps = feature.getExtraProperties();
if ( extraProps != null ) {
for ( Property prop : extraProps.getProperties() ) {
export( prop, resolveState );
}
}
}
writer.writeEndElement();
}
}
private void setSchema( Feature feature ) {
if ( schema == null ) {
schema = feature.getType().getSchema();
if ( schema != null ) {
schemaInfoset = schema.getGMLSchema();
}
}
}
private List<Property> augmentBoundedBy( Feature f ) {
LinkedList<Property> props = new LinkedList<Property>( f.getProperties() );
for ( int i = 0; i < props.size(); i++ ) {
QName name = props.get( i ).getName();
if ( !gmlNs.equals( name.getNamespaceURI() ) || name.getLocalPart().equals( "location" ) ) {
// not a GML property or gml:location -> gml:boundedBy must be included right before it
Property boundedBy = getBoundedBy( f );
if ( boundedBy != null ) {
props.add( i, boundedBy );
}
break;
} else if ( name.getLocalPart().equals( "boundedBy" ) ) {
// already present -> don't include it
break;
}
}
return props;
}
private Property getBoundedBy( Feature f ) {
Envelope env = f.getEnvelope();
if ( env == null ) {
env = f.calcEnvelope();
}
if ( env == null ) {
return null;
}
return new GenericProperty( boundedByPt, env );
}
private GmlXlinkOptions getResolveParams( Property prop, GmlXlinkOptions resolveState ) {
PropertyName projection = requestedPropertyNames.get( prop.getName() );
if ( projection != null && projection.getResolveParams() != null ) {
return new GmlXlinkOptions( projection.getResolveParams() );
}
return resolveState;
}
private void exportFeatureProperty( FeaturePropertyType pt, Feature subFeature, GmlXlinkOptions resolveState )
throws XMLStreamException, UnknownCRSException, TransformationException {
QName propName = pt.getName();
LOG.debug( "Exporting feature property '" + propName + "'" );
if ( subFeature == null ) {
exportEmptyFeatureProperty( propName );
} else if ( subFeature instanceof FeatureReference ) {
exportFeatureProperty( pt, (FeatureReference) subFeature, resolveState, propName );
} else {
// normal feature
String subFid = subFeature.getId();
if ( subFid == null ) {
// no feature id -> no other chance, but inlining it
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writer.writeComment( "Inlined feature '" + subFid + "'" );
export( subFeature, getResolveStateForNextLevel( resolveState ) );
writer.writeEndElement();
} else {
// has feature id
if ( referenceExportStrategy.isObjectExported( subFid ) ) {
exportAlreadyExportedFeaturePropertyByReference( subFeature, propName );
} else {
exportFeaturePropertyByValue( propName, subFeature, resolveState );
}
}
}
}
private void exportEmptyFeatureProperty( QName propName )
throws XMLStreamException {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
endEmptyElement();
}
private void exportFeatureProperty( FeaturePropertyType pt, FeatureReference ref, GmlXlinkOptions resolveState,
QName propName )
throws XMLStreamException, UnknownCRSException, TransformationException {
boolean includeNextLevelInOutput = includeNextLevelInOutput( resolveState );
if ( includeNextLevelInOutput ) {
if ( pt.getAllowedRepresentation() == REMOTE ) {
exportFeaturePropertyByReference( propName, ref, true, resolveState );
} else {
if ( referenceExportStrategy.isObjectExported( ref.getId() ) ) {
exportAlreadyExportedFeaturePropertyByReference( ref, propName );
} else {
exportFeaturePropertyByValue( propName, ref, resolveState );
}
}
} else {
exportFeaturePropertyByReference( propName, ref, false, resolveState );
}
}
private void exportAlreadyExportedFeaturePropertyByReference( Feature ref, QName propName )
throws XMLStreamException {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XLNNS, "href", "#" + ref.getId() );
endEmptyElement();
}
private boolean includeNextLevelInOutput( GmlXlinkOptions resolveState ) {
int maxInlineLevels = resolveState.getDepth();
int currentLevel = resolveState.getCurrentLevel();
return maxInlineLevels == -1 || ( maxInlineLevels > 0 && currentLevel < maxInlineLevels );
}
private void exportFeaturePropertyByReference( QName propName, FeatureReference ref,
boolean forceInclusionInDocument, GmlXlinkOptions resolveState )
throws XMLStreamException {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
String uri = null;
if ( forceInclusionInDocument ) {
resolveState = getResolveStateForNextLevel( resolveState );
uri = referenceExportStrategy.requireObject( ref, resolveState );
} else {
uri = referenceExportStrategy.handleReference( ref );
}
writeAttributeWithNS( XLNNS, "href", uri );
endEmptyElement();
}
private void exportFeaturePropertyByValue( QName propName, Feature subFeature, GmlXlinkOptions resolveState )
throws XMLStreamException, UnknownCRSException, TransformationException {
referenceExportStrategy.addExportedId( subFeature.getId() );
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writer.writeComment( "Inlined feature '" + subFeature.getId() + "'" );
export( subFeature, getResolveStateForNextLevel( resolveState ) );
writer.writeEndElement();
}
private void exportGenericXmlElement( ElementNode xmlContent, GmlXlinkOptions resolveState )
throws XMLStreamException, UnknownCRSException, TransformationException {
QName elName = xmlContent.getName();
LOG.debug( "Exporting " + elName );
XSElementDeclaration elDecl = xmlContent.getXSType();
if ( elDecl != null && schemaInfoset != null ) {
ObjectPropertyType gmlPropertyDecl = schemaInfoset.getGMLPropertyDecl( elDecl, elName, 0, 1, null );
if ( gmlPropertyDecl instanceof FeaturePropertyType ) {
List<TypedObjectNode> children = xmlContent.getChildren();
if ( children.size() == 1 && children.get( 0 ) instanceof Feature ) {
LOG.debug( "Exporting as nested feature property." );
exportFeatureProperty( (FeaturePropertyType) gmlPropertyDecl, (Feature) children.get( 0 ),
resolveState );
return;
}
}
}
writeStartElementWithNS( elName.getNamespaceURI(), elName.getLocalPart() );
if ( xmlContent.getAttributes() != null ) {
for ( Entry<QName, PrimitiveValue> attr : xmlContent.getAttributes().entrySet() ) {
writeAttributeWithNS( attr.getKey().getNamespaceURI(), attr.getKey().getLocalPart(),
attr.getValue().getAsText() );
}
}
if ( xmlContent.getChildren() != null ) {
for ( TypedObjectNode childNode : xmlContent.getChildren() ) {
export( childNode, resolveState );
}
}
writer.writeEndElement();
}
private boolean isPropertyRequested( QName propName ) {
return requestedPropertyNames.isEmpty() || requestedPropertyNames.containsKey( propName );
}
}
| true | true | private void export( Property property, GmlXlinkOptions resolveState )
throws XMLStreamException, UnknownCRSException, TransformationException {
QName propName = property.getName();
PropertyType pt = property.getType();
if ( pt.getMinOccurs() == 0 ) {
LOG.debug( "Optional property '" + propName + "', checking if it is requested." );
if ( !isPropertyRequested( propName ) ) {
LOG.debug( "Skipping it." );
return;
}
// required for WMS:
if ( !outputGeometries && pt instanceof GeometryPropertyType ) {
LOG.debug( "Skipping it since geometries should not be output." );
return;
}
}
if ( resolveState.getCurrentLevel() == 0 ) {
resolveState = getResolveParams( property, resolveState );
}
TypedObjectNode value = property.getValue();
// if ( value instanceof GenericXMLElement ) {
// writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
// export( value, currentLevel, maxInlineLevels );
// writer.writeEndElement();
// return;
// }
// TODO check for GML 2 properties (gml:pointProperty, ...) and export
// as "app:gml2PointProperty" for GML 3
boolean nilled = false;
TypedObjectNode nil = property.getAttributes().get( XSI_NIL );
if ( nil instanceof PrimitiveValue ) {
nilled = Boolean.TRUE.equals( ( (PrimitiveValue) nil ).getValue() );
}
if ( pt instanceof FeaturePropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
exportFeatureProperty( (FeaturePropertyType) pt, (Feature) value, resolveState );
}
} else if ( pt instanceof SimplePropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
// must be a primitive value
PrimitiveValue pValue = (PrimitiveValue) value;
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( pValue != null ) {
// TODO
if ( pValue.getType().getBaseType() == BaseType.DECIMAL ) {
writer.writeCharacters( pValue.getValue().toString() );
} else {
writer.writeCharacters( pValue.getAsText() );
}
}
writer.writeEndElement();
}
} else if ( pt instanceof GeometryPropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
Geometry gValue = (Geometry) value;
if ( !exportSf && gValue.getId() != null && referenceExportStrategy.isObjectExported( gValue.getId() ) ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XLNNS, "href", "#" + gValue.getId() );
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( gValue.getId() != null ) {
// WFS CITE 1.1.0 test requirement (wfs:GetFeature.XLink-POST-XML-10)
writer.writeComment( "Inlined geometry '" + gValue.getId() + "'" );
}
gmlStreamWriter.getGeometryWriter().export( (Geometry) value );
writer.writeEndElement();
}
}
} else if ( pt instanceof CodePropertyType ) {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
CodeType codeType = (CodeType) value;
if ( codeType != null ) {
if ( codeType.getCodeSpace() != null && codeType.getCodeSpace().length() > 0 ) {
if ( GML_2 != version ) {
writer.writeAttribute( "codeSpace", codeType.getCodeSpace() );
}
}
writer.writeCharacters( codeType.getCode() );
}
writer.writeEndElement();
} else if ( pt instanceof EnvelopePropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( value != null ) {
gmlStreamWriter.getGeometryWriter().exportEnvelope( (Envelope) value );
} else {
writeStartElementWithNS( gmlNs, gmlNull );
writer.writeCharacters( "missing" );
writer.writeEndElement();
}
writer.writeEndElement();
}
} else if ( pt instanceof LengthPropertyType ) {
Length length = (Length) value;
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( GML_2 != version ) {
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
writer.writeAttribute( "uom", length.getUomUri() );
}
if ( !nilled ) {
writer.writeCharacters( String.valueOf( length.getValue() ) );
}
writer.writeEndElement();
} else if ( pt instanceof MeasurePropertyType ) {
Measure measure = (Measure) value;
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( GML_2 != version ) {
writer.writeAttribute( "uom", measure.getUomUri() );
}
writer.writeCharacters( String.valueOf( measure.getValue() ) );
writer.writeEndElement();
} else if ( pt instanceof StringOrRefPropertyType ) {
StringOrRef stringOrRef = (StringOrRef) value;
if ( stringOrRef.getString() == null || stringOrRef.getString().length() == 0 ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( stringOrRef.getRef() != null ) {
writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() );
}
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
if ( stringOrRef.getRef() != null ) {
writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() );
}
if ( !nilled && stringOrRef.getString() != null ) {
writer.writeCharacters( stringOrRef.getString() );
}
writer.writeEndElement();
}
} else if ( pt instanceof CustomPropertyType ) {
if ( !timeSliceFilters.isEmpty() ) {
if ( excludeByTimeSliceFilter( property ) ) {
return;
}
}
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( property.getAttributes() != null ) {
for ( Entry<QName, PrimitiveValue> attr : property.getAttributes().entrySet() ) {
writeAttribute( writer, attr.getKey(), attr.getValue().getAsText() );
}
}
if ( property.getChildren() != null ) {
for ( TypedObjectNode childNode : property.getChildren() ) {
export( childNode, resolveState );
}
}
writer.writeEndElement();
} else if ( pt instanceof ArrayPropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
export( (TypedObjectNode) property.getValue(), resolveState );
writer.writeEndElement();
}
} else {
throw new RuntimeException( "Internal error. Unhandled property type '" + pt.getClass() + "'" );
}
}
| private void export( Property property, GmlXlinkOptions resolveState )
throws XMLStreamException, UnknownCRSException, TransformationException {
QName propName = property.getName();
PropertyType pt = property.getType();
if ( pt.getMinOccurs() == 0 ) {
LOG.debug( "Optional property '" + propName + "', checking if it is requested." );
if ( !isPropertyRequested( propName ) ) {
LOG.debug( "Skipping it." );
return;
}
// required for WMS:
if ( !outputGeometries && pt instanceof GeometryPropertyType ) {
LOG.debug( "Skipping it since geometries should not be output." );
return;
}
}
if ( resolveState.getCurrentLevel() == 0 ) {
resolveState = getResolveParams( property, resolveState );
}
TypedObjectNode value = property.getValue();
// if ( value instanceof GenericXMLElement ) {
// writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
// export( value, currentLevel, maxInlineLevels );
// writer.writeEndElement();
// return;
// }
// TODO check for GML 2 properties (gml:pointProperty, ...) and export
// as "app:gml2PointProperty" for GML 3
boolean nilled = false;
TypedObjectNode nil = property.getAttributes().get( XSI_NIL );
if ( nil instanceof PrimitiveValue ) {
nilled = Boolean.TRUE.equals( ( (PrimitiveValue) nil ).getValue() );
}
if ( pt instanceof FeaturePropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
exportFeatureProperty( (FeaturePropertyType) pt, (Feature) value, resolveState );
}
} else if ( pt instanceof SimplePropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
// must be a primitive value
PrimitiveValue pValue = (PrimitiveValue) value;
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( pValue != null ) {
// TODO
if ( pValue.getType().getBaseType() == BaseType.DECIMAL ) {
writer.writeCharacters( pValue.getValue().toString() );
} else {
writer.writeCharacters( pValue.getAsText() );
}
}
writer.writeEndElement();
}
} else if ( pt instanceof GeometryPropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else if ( value == null ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
endEmptyElement();
} else {
Geometry gValue = (Geometry) value;
if ( !exportSf && gValue.getId() != null && referenceExportStrategy.isObjectExported( gValue.getId() ) ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XLNNS, "href", "#" + gValue.getId() );
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( gValue.getId() != null ) {
// WFS CITE 1.1.0 test requirement (wfs:GetFeature.XLink-POST-XML-10)
writer.writeComment( "Inlined geometry '" + gValue.getId() + "'" );
}
gmlStreamWriter.getGeometryWriter().export( (Geometry) value );
writer.writeEndElement();
}
}
} else if ( pt instanceof CodePropertyType ) {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
CodeType codeType = (CodeType) value;
if ( codeType != null ) {
if ( codeType.getCodeSpace() != null && codeType.getCodeSpace().length() > 0 ) {
if ( GML_2 != version ) {
writer.writeAttribute( "codeSpace", codeType.getCodeSpace() );
}
}
writer.writeCharacters( codeType.getCode() );
}
writer.writeEndElement();
} else if ( pt instanceof EnvelopePropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( value != null ) {
gmlStreamWriter.getGeometryWriter().exportEnvelope( (Envelope) value );
} else {
writeStartElementWithNS( gmlNs, gmlNull );
writer.writeCharacters( "missing" );
writer.writeEndElement();
}
writer.writeEndElement();
}
} else if ( pt instanceof LengthPropertyType ) {
Length length = (Length) value;
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( GML_2 != version ) {
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
writer.writeAttribute( "uom", length.getUomUri() );
}
if ( !nilled ) {
writer.writeCharacters( String.valueOf( length.getValue() ) );
}
writer.writeEndElement();
} else if ( pt instanceof MeasurePropertyType ) {
Measure measure = (Measure) value;
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( GML_2 != version ) {
writer.writeAttribute( "uom", measure.getUomUri() );
}
writer.writeCharacters( String.valueOf( measure.getValue() ) );
writer.writeEndElement();
} else if ( pt instanceof StringOrRefPropertyType ) {
StringOrRef stringOrRef = (StringOrRef) value;
if ( stringOrRef.getString() == null || stringOrRef.getString().length() == 0 ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( stringOrRef.getRef() != null ) {
writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() );
}
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( nilled ) {
writeAttributeWithNS( XSINS, "nil", "true" );
}
if ( stringOrRef.getRef() != null ) {
writeAttributeWithNS( XLNNS, "href", stringOrRef.getRef() );
}
if ( !nilled && stringOrRef.getString() != null ) {
writer.writeCharacters( stringOrRef.getString() );
}
writer.writeEndElement();
}
} else if ( pt instanceof CustomPropertyType ) {
if ( !timeSliceFilters.isEmpty() ) {
if ( excludeByTimeSliceFilter( property ) ) {
return;
}
}
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
if ( property.getAttributes() != null ) {
for ( Entry<QName, PrimitiveValue> attr : property.getAttributes().entrySet() ) {
writeAttribute( writer, attr.getKey(), attr.getValue().getAsText() );
}
}
if ( property.getChildren() != null ) {
for ( TypedObjectNode childNode : property.getChildren() ) {
export( childNode, resolveState );
}
}
writer.writeEndElement();
} else if ( pt instanceof ArrayPropertyType ) {
if ( nilled ) {
writeEmptyElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
writeAttributeWithNS( XSINS, "nil", "true" );
endEmptyElement();
} else {
writeStartElementWithNS( propName.getNamespaceURI(), propName.getLocalPart() );
export( (TypedObjectNode) property.getValue(), resolveState );
writer.writeEndElement();
}
} else {
throw new RuntimeException( "Internal error. Unhandled property type '" + pt.getClass() + "'" );
}
}
|
diff --git a/seqware-queryengine-backend/src/test/java/com/github/seqware/queryengine/system/test/QueryVCFDumperBenchmarkTest.java b/seqware-queryengine-backend/src/test/java/com/github/seqware/queryengine/system/test/QueryVCFDumperBenchmarkTest.java
index aff6a809..899ae579 100644
--- a/seqware-queryengine-backend/src/test/java/com/github/seqware/queryengine/system/test/QueryVCFDumperBenchmarkTest.java
+++ b/seqware-queryengine-backend/src/test/java/com/github/seqware/queryengine/system/test/QueryVCFDumperBenchmarkTest.java
@@ -1,406 +1,406 @@
package com.github.seqware.queryengine.system.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.github.seqware.queryengine.Benchmarking;
import com.github.seqware.queryengine.Constants;
import com.github.seqware.queryengine.Constants.OVERLAP_STRATEGY;
import com.github.seqware.queryengine.factory.SWQEFactory;
import com.github.seqware.queryengine.model.Reference;
import com.github.seqware.queryengine.system.ReferenceCreator;
import com.github.seqware.queryengine.system.exporters.QueryVCFDumper;
import com.github.seqware.queryengine.system.importers.SOFeatureImporter;
import com.github.seqware.queryengine.util.SGID;
public class QueryVCFDumperBenchmarkTest implements Benchmarking{
private Configuration config;
private static String randomRef = null;
private static Reference reference = null;
private static SGID originalSet = null;
private static List<File> testingFiles = new ArrayList<File>();
private static final String DOWNLOAD_DIR = "/home/seqware/";
private static String FIRST_QUERY;
private static String SECOND_QUERY;
private static String THIRD_QUERY;
private static String FOURTH_QUERY;
private static long start, stop;
private static float diff;
private static List<Float> runQueryTimings = new ArrayList<Float>();
private static HashMap<String, List<Float>> allSingleScanRangeQueryTimings = new HashMap<String,List<Float>>();
private static HashMap<String, List<Float>> allMultiScanRangeQueryTimings = new HashMap<String,List<Float>>();
private static Float importTimingBinning;
private static Float importTimingNaiveOverlaps;
private static File outputFile;
/**Set this to true if you wish to use the smaller file (faster test) or larger file (longer test)**/
private static boolean QUICK_TEST = true;
@BeforeClass
public static void setUpTest(){
try{
if (QUICK_TEST == false){
/**This file contains 1,000,000 lines**/
String vcf = "https://dl.dropboxusercontent.com/u/3238966/ALL.wgs.VQSR_V2_GLs_polarized_biallelic.20101123.indels.sites1MillionLines.vcf.gz";
/**This file contains 2,000,000 lines**/
//String vcf = "https://dl.dropboxusercontent.com/u/3238966/ALL.wgs.VQSR_V2_GLs_polarized_biallelic.20101123.indels.sites.vcf.gz";
/**This file contains 4,000,000 lines**/
//String vcf = "http://ftp.1000genomes.ebi.ac.uk/vol1/ftp/phase1/analysis_results/consensus_call_sets/indels/ALL.wgs.VQSR_V2_GLs_polarized_biallelic.20101123.indels.sites.vcf.gz";
testingFiles = download(vcf);
FIRST_QUERY = "start>=61800882 && stop <=81800882";
SECOND_QUERY = "start>=61800882 && stop <=81800882 && (seqid==\"X\" || seqid==\"19\")";
THIRD_QUERY = "start>=61800882 && stop <=81800882 || start >= 6180882 && stop <= 9180082";
FOURTH_QUERY = "(start>=61800882 && stop <=81800882 || start >= 6180882 && stop <= 9180082) && (seqid==\"X\" || seqid==\"19\")";
} else if (QUICK_TEST == true){
testingFiles.add(new File("/home/seqware/gitroot/queryengine/seqware-queryengine-backend/src/test/resources/com/github/seqware/queryengine/system/FeatureImporter/consequences_annotated.vcf"));
FIRST_QUERY = "seqid==\"21\" ";
SECOND_QUERY = "seqid==\"21\" && start >= 20000000 && stop <= 30000000";
THIRD_QUERY = "seqid==\"21\" && start >= 20000000 && stop <= 30000000 || start >=40000000 && stop <=40200000";
FOURTH_QUERY = "seqid==\"21\" && (start >= 20000000 && stop <= 30000000 || start >=40000000 && stop <=40200000)";
}
outputFile = null;
try {
outputFile = File.createTempFile("output", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
} catch (Exception e){
e.printStackTrace();
}
}
@Test
public void testBinning(){
try{
setOverlapStrategy(Constants.OVERLAP_STRATEGY.BINNING);
System.out.println("Setting OVERLAP_STRATEGY => " + Constants.OVERLAP_STRATEGY.BINNING.toString() + "\n");
start = new Date().getTime();
importToBackend(testingFiles);
stop = new Date().getTime();
diff = ((stop - start) / 1000);
importTimingBinning = diff;
Constants.MULTIPLE_SCAN_RANGES = false;
System.out.println("Setting MULTIPLE_SCAN_RANGES => " + Constants.MULTIPLE_SCAN_RANGES + "\n");
runQueryTimings = runQueries();
allSingleScanRangeQueryTimings.put(Constants.OVERLAP_STRATEGY.BINNING.toString(), runQueryTimings);
Constants.MULTIPLE_SCAN_RANGES = true;
System.out.println("Setting MULTIPLE_SCAN_RANGES => " + Constants.MULTIPLE_SCAN_RANGES + "\n");
runQueryTimings = runQueries();
allMultiScanRangeQueryTimings.put(Constants.OVERLAP_STRATEGY.BINNING.toString(), runQueryTimings);
} catch (Exception e){
e.printStackTrace();
}
}
@Test
public void testNaiveOverlaps(){
try{
setOverlapStrategy(Constants.OVERLAP_STRATEGY.NAIVE_OVERLAPS);
System.out.println("Setting OVERLAP_STRATEGY => " + Constants.OVERLAP_STRATEGY.NAIVE_OVERLAPS.toString() + "\n");
start = new Date().getTime();
importToBackend(testingFiles);
stop = new Date().getTime();
diff = ((stop - start) / 1000);
importTimingNaiveOverlaps = diff;
Constants.MULTIPLE_SCAN_RANGES = false;
System.out.println("Setting MULTIPLE_SCAN_RANGES => " + Constants.MULTIPLE_SCAN_RANGES + "\n");
runQueryTimings = runQueries();
allSingleScanRangeQueryTimings.put(Constants.OVERLAP_STRATEGY.NAIVE_OVERLAPS.toString(), runQueryTimings);
Constants.MULTIPLE_SCAN_RANGES = true;
System.out.println("Setting MULTIPLE_SCAN_RANGES => " + Constants.MULTIPLE_SCAN_RANGES + "\n");
runQueryTimings = runQueries();
allMultiScanRangeQueryTimings.put(Constants.OVERLAP_STRATEGY.NAIVE_OVERLAPS.toString(), runQueryTimings);
} catch (Exception e){
e.printStackTrace();
}
}
@Test
public void testGenerateReport(){
try{
generateReport();
resetAllTables();
System.out.println("Done!");
} catch (Exception e){
e.printStackTrace();
}
}
public void setOverlapStrategy(OVERLAP_STRATEGY strategy){
Constants.OVERLAP_MODE = strategy;
}
public void generateReport(){
int i;
float singleTotal = 0;
float multiTotal= 0;
float total = 0;
System.out.println("\n");
System.out.println("Import timing for Binning: " + String.valueOf(importTimingBinning) + "\n");
System.out.println("Import timing for Naive Overlaps: " + String.valueOf(importTimingNaiveOverlaps) + "\n");
System.out.println("MULTIPLE SCAN RANGES = FALSE" );
for (Entry<String, List<Float>> e : allSingleScanRangeQueryTimings.entrySet()){
i=0;
System.out.println(" Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println(" Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "(" + f/60 + "min)");
- singleTotal =+ f;
+ singleTotal += f;
}
System.out.println(" Time to complete this set: " + singleTotal + "s" + "(" + singleTotal/60 + "min)");
System.out.println("\n");
}
System.out.println("MULTIPLE SCAN RANGES = TRUE");
for (Entry<String, List<Float>> e : allMultiScanRangeQueryTimings.entrySet()){
i=0;
System.out.println(" Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println(" Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "(" + f/60 + "min)");
- multiTotal =+ f;
+ multiTotal += f;
}
System.out.println(" Time to complete this set: " + multiTotal + "s" + "(" + multiTotal/60 + "min)");
System.out.println("\n");
}
total = singleTotal + multiTotal;
System.out.println(" **Time to complete all tests: " + total + "s" + "(" + total/60 + "min)");
}
public void resetAllTables(){
this.config = HBaseConfiguration.create();
try{
System.out.println("Closing tables....");
HBaseAdmin hba = new HBaseAdmin(config);
hba.disableTables("b.*");
hba.deleteTables("b.*");
hba.close();
} catch (Exception e){
e.printStackTrace();
}
}
private static void downloadFile(String file, File downloadDir, List<File> filesToReturnGZCompressed) throws IOException, MalformedURLException, URISyntaxException {
URL newURL = new URL(file);
String name = newURL.toString().substring(newURL.toString().lastIndexOf("/"));
File targetFile = new File(downloadDir, name);
if (!targetFile.exists()){
System.out.println("Downloading " + newURL.getFile() + " to " + targetFile.getAbsolutePath());
FileUtils.copyURLToFile(newURL, targetFile);
}
filesToReturnGZCompressed.add(targetFile);
}
private static List<File> download(String file) {
List<File> filesToReturnGZCompressed = new ArrayList<File>();
List<File> filesToReturnGZUnCompressed = new ArrayList<File>();
// always use the same directory so we do not re-download on repeated runs
File downloadDir = new File(DOWNLOAD_DIR);
try {
downloadFile(file, downloadDir, filesToReturnGZCompressed);
} catch (URISyntaxException ex) {
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
for (File thisGZCompressedFile : filesToReturnGZCompressed){
try{
File thisGZUncompressedFile = new File("");
thisGZUncompressedFile = gzDecompressor(thisGZCompressedFile);
Logger.getLogger(QueryVCFDumperBenchmarkTest.class).info("CompressedFile: " + thisGZCompressedFile.getAbsolutePath());
Logger.getLogger(QueryVCFDumperBenchmarkTest.class).info("DeCompressedFile: " + thisGZUncompressedFile.getAbsolutePath());
System.out.println("Done!\n");
filesToReturnGZUnCompressed.add(thisGZUncompressedFile);
} catch (Exception e){
e.printStackTrace();
}
}
return filesToReturnGZUnCompressed;
}
private static void importToBackend(List<File> file){
try{
//Use first file only for now
File f = file.get(0);
Assert.assertTrue("Cannot read VCF file for test", f.exists() && f.canRead());
List<String> argList = new ArrayList<String>();
randomRef = "Random_ref_" + new BigInteger(20, new SecureRandom()).toString(32);
SGID refID = ReferenceCreator.mainMethod(new String[]{randomRef});
reference = SWQEFactory.getQueryInterface().getAtomBySGID(Reference.class, refID);
argList.addAll(Arrays.asList(new String[]{"-w", "VCFVariantImportWorker",
"-i", f.getAbsolutePath(),
"-r", reference.getSGID().getRowKey()}));
System.out.println("Importing " + testingFiles.get(0).getName() + " to database.\n");
originalSet = SOFeatureImporter.runMain(argList.toArray(new String[argList.size()]));
Assert.assertTrue("Could not import VCF for test", originalSet != null);
} catch (Exception e){
e.printStackTrace();
}
}
private static File gzDecompressor(File filePathGZ) throws IOException{
String filename = filePathGZ
.getName()
.substring(0, filePathGZ.getName().lastIndexOf("."));
byte[] buf =
new byte[1024];
int len;
File thisGZUncompressedFile;
String outFilename = DOWNLOAD_DIR + filename;
FileInputStream instream =
new FileInputStream(filePathGZ);
GZIPInputStream ginstream =
new GZIPInputStream(instream);
FileOutputStream outstream =
new FileOutputStream(outFilename);
System.out.println("Decompressing... " + filePathGZ);
while ((len = ginstream.read(buf)) > 0)
{
outstream.write(buf, 0, len);
}
outstream.close();
ginstream.close();
thisGZUncompressedFile = new File(outFilename);
return thisGZUncompressedFile;
}
private void testFirstQuery(){
File keyValueFile = null;
try {
keyValueFile = File.createTempFile("keyValue", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
List<String> argList = new ArrayList<String>();
argList.addAll(Arrays.asList(new String[]{"-f", originalSet.getRowKey(),
"-k", keyValueFile.getAbsolutePath(), "-s", FIRST_QUERY,
"-o", outputFile.getAbsolutePath()}));
Stack<SGID> runMain = QueryVCFDumper.runMain(argList.toArray(new String[argList.size()]));
}
private void testSecondQuery(){
File keyValueFile = null;
try {
keyValueFile = File.createTempFile("keyValue", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
List<String> argList = new ArrayList<String>();
argList.addAll(Arrays.asList(new String[]{"-f", originalSet.getRowKey(),
"-k", keyValueFile.getAbsolutePath(), "-s", SECOND_QUERY,
"-o", outputFile.getAbsolutePath()}));
Stack<SGID> runMain = QueryVCFDumper.runMain(argList.toArray(new String[argList.size()]));
}
private void testThirdQuery(){
File keyValueFile = null;
try {
keyValueFile = File.createTempFile("keyValue", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
List<String> argList = new ArrayList<String>();
argList.addAll(Arrays.asList(new String[]{"-f", originalSet.getRowKey(),
"-k", keyValueFile.getAbsolutePath(), "-s", THIRD_QUERY,
"-o", outputFile.getAbsolutePath()}));
Stack<SGID> runMain = QueryVCFDumper.runMain(argList.toArray(new String[argList.size()]));
}
private void testFourthQuery(){
File keyValueFile = null;
try {
keyValueFile = File.createTempFile("keyValue", "txt");
} catch (IOException ex) {
Logger.getLogger(QueryVCFDumperTest.class.getName()).fatal(null, ex);
Assert.fail("Could not create output for test");
}
List<String> argList = new ArrayList<String>();
argList.addAll(Arrays.asList(new String[]{"-f", originalSet.getRowKey(),
"-k", keyValueFile.getAbsolutePath(), "-s", FOURTH_QUERY,
"-o", outputFile.getAbsolutePath()}));
Stack<SGID> runMain = QueryVCFDumper.runMain(argList.toArray(new String[argList.size()]));
}
private List<Float> runQueries(){
List<Float> runQueryTimings = new ArrayList<Float>();
System.out.println("Running first query....\n");
start = new Date().getTime();
testFirstQuery();
stop = new Date().getTime();
diff = ((stop - start) / 1000) ;
runQueryTimings.add(diff);
System.out.println("Running second query....\n");
start = new Date().getTime();
testSecondQuery();
stop = new Date().getTime();
diff = ((stop - start) / 1000) ;
runQueryTimings.add(diff);
System.out.println("Running third query....\n");
start = new Date().getTime();
testThirdQuery();
stop = new Date().getTime();
diff = ((stop - start) / 1000) ;
runQueryTimings.add(diff);
System.out.println("Running fourth query....\n");
start = new Date().getTime();
testFourthQuery();
stop = new Date().getTime();
diff = ((stop - start) / 1000) ;
runQueryTimings.add(diff);
return runQueryTimings;
}
}
| false | true | public void generateReport(){
int i;
float singleTotal = 0;
float multiTotal= 0;
float total = 0;
System.out.println("\n");
System.out.println("Import timing for Binning: " + String.valueOf(importTimingBinning) + "\n");
System.out.println("Import timing for Naive Overlaps: " + String.valueOf(importTimingNaiveOverlaps) + "\n");
System.out.println("MULTIPLE SCAN RANGES = FALSE" );
for (Entry<String, List<Float>> e : allSingleScanRangeQueryTimings.entrySet()){
i=0;
System.out.println(" Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println(" Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "(" + f/60 + "min)");
singleTotal =+ f;
}
System.out.println(" Time to complete this set: " + singleTotal + "s" + "(" + singleTotal/60 + "min)");
System.out.println("\n");
}
System.out.println("MULTIPLE SCAN RANGES = TRUE");
for (Entry<String, List<Float>> e : allMultiScanRangeQueryTimings.entrySet()){
i=0;
System.out.println(" Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println(" Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "(" + f/60 + "min)");
multiTotal =+ f;
}
System.out.println(" Time to complete this set: " + multiTotal + "s" + "(" + multiTotal/60 + "min)");
System.out.println("\n");
}
total = singleTotal + multiTotal;
System.out.println(" **Time to complete all tests: " + total + "s" + "(" + total/60 + "min)");
}
| public void generateReport(){
int i;
float singleTotal = 0;
float multiTotal= 0;
float total = 0;
System.out.println("\n");
System.out.println("Import timing for Binning: " + String.valueOf(importTimingBinning) + "\n");
System.out.println("Import timing for Naive Overlaps: " + String.valueOf(importTimingNaiveOverlaps) + "\n");
System.out.println("MULTIPLE SCAN RANGES = FALSE" );
for (Entry<String, List<Float>> e : allSingleScanRangeQueryTimings.entrySet()){
i=0;
System.out.println(" Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println(" Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "(" + f/60 + "min)");
singleTotal += f;
}
System.out.println(" Time to complete this set: " + singleTotal + "s" + "(" + singleTotal/60 + "min)");
System.out.println("\n");
}
System.out.println("MULTIPLE SCAN RANGES = TRUE");
for (Entry<String, List<Float>> e : allMultiScanRangeQueryTimings.entrySet()){
i=0;
System.out.println(" Using " + e.getKey() + ": ");
for (Float f : e.getValue()){
i++;
System.out.println(" Time to complete Test #" + String.valueOf(i) + ": " + f + "s" + "(" + f/60 + "min)");
multiTotal += f;
}
System.out.println(" Time to complete this set: " + multiTotal + "s" + "(" + multiTotal/60 + "min)");
System.out.println("\n");
}
total = singleTotal + multiTotal;
System.out.println(" **Time to complete all tests: " + total + "s" + "(" + total/60 + "min)");
}
|
diff --git a/android/voice-client-core/src/main/java/com/tuenti/voice/core/VoiceClient.java b/android/voice-client-core/src/main/java/com/tuenti/voice/core/VoiceClient.java
index feb7665..fb29c26 100644
--- a/android/voice-client-core/src/main/java/com/tuenti/voice/core/VoiceClient.java
+++ b/android/voice-client-core/src/main/java/com/tuenti/voice/core/VoiceClient.java
@@ -1,366 +1,368 @@
/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file in the root of the source tree. An additional
* intellectual property rights grant can be found in the file PATENTS. All
* contributing project authors may be found in the AUTHORS file in the root of
* the source tree.
*/
/*
* VoiceEngine Android test application. It starts either auto test or acts like
* a GUI test.
*/
package com.tuenti.voice.core;
import android.content.Context;
import android.util.Log;
import com.tuenti.voice.core.manager.BuddyManager;
import com.tuenti.voice.core.manager.CallManager;
import com.tuenti.voice.core.manager.ConnectionManager;
import com.tuenti.voice.core.manager.StatManager;
public class VoiceClient
{
// ------------------------------ FIELDS ------------------------------
//Event constants
/* Event Types */
public static final int CALL_STATE_EVENT = 0;
public static final int XMPP_STATE_EVENT = 1;
public static final int XMPP_ERROR_EVENT = 2;
public static final int BUDDY_LIST_EVENT = 3;
public static final int XMPP_SOCKET_CLOSE_EVENT = 4;
public static final int CALL_ERROR_EVENT = 5;
public static final int AUDIO_PLAYOUT_EVENT = 6;
public static final int STATS_UPDATE_EVENT = 7;
public static final int CALL_TRACKER_ID_EVENT = 8;
//End Event constants
private final static String TAG = "j-VoiceClient";
private static final Object mLock = new Object();
private boolean initialized;
private boolean voiceClientLoaded;
private BuddyManager mBuddyManager;
private CallManager mCallManager;
private ConnectionManager mConnectionManager;
private StatManager mStatManager;
// --------------------------- CONSTRUCTORS ---------------------------
public VoiceClient()
{
synchronized ( mLock )
{
Log.i( TAG, "loading native library voiceclient" );
try {
System.loadLibrary( "voiceclient" );
voiceClientLoaded = true;
} catch (UnsatisfiedLinkError e) {
// We need to do this, because Android will generate OOM error
// loading an so file on older phones when they don't have
// enough available memory at load time.
voiceClientLoaded = false;
}
}
}
// -------------------------- OTHER METHODS --------------------------
public boolean loaded() {
return voiceClientLoaded;
}
public void acceptCall( long call_id )
{
Log.i( TAG, "native accept call " + call_id );
if (loaded()) {
nativeAcceptCall( call_id );
}
}
public void call( String remoteUsername )
{
if (loaded()) {
nativeCall( remoteUsername );
}
}
public void callWithTrackerId( String remoteUsername, String callTrackerId )
{
if (loaded()) {
nativeCallWithTrackerId( remoteUsername, callTrackerId );
}
}
public void declineCall( long call_id, boolean busy )
{
if (loaded()) {
nativeDeclineCall( call_id, busy );
}
}
public void endCall( long call_id )
{
if (loaded()) {
nativeEndCall( call_id );
}
}
public void holdCall( long call_id, boolean hold )
{
if (loaded()) {
nativeHoldCall( call_id, hold );
}
}
public void init( Context context )
{
if ( loaded() && !initialized )
{
nativeInit( context );
initialized = true;
}
}
public void login( String username, String password, String stunServer, String turnServer, String turnUsername,
String turnPassword, String xmppServer, int xmppPort, boolean useSsl, int portAllocatorFilter )
{
if (loaded()) {
nativeLogin( username,
password,
stunServer,
turnServer,
turnUsername,
turnPassword,
xmppServer,
xmppPort,
useSsl,
portAllocatorFilter );
}
}
public void replaceTurn( String turnServer )
{
if (loaded()) {
nativeReplaceTurn( turnServer );
}
}
public void logout()
{
if (loaded()) {
nativeLogout();
}
}
public void muteCall( long call_id, boolean mute )
{
if (loaded()) {
nativeMuteCall( call_id, mute );
}
}
public void release()
{
if ( loaded() && initialized )
{
initialized = false;
nativeRelease();
}
}
public void setBuddyManager( BuddyManager buddyManager )
{
mBuddyManager = buddyManager;
}
public void setCallManager( CallManager callManager )
{
mCallManager = callManager;
}
public void setConnectionManager( ConnectionManager connectionManager )
{
mConnectionManager = connectionManager;
}
public void setStatManager( StatManager statManager )
{
mStatManager = statManager;
}
/**
* @see BuddyManager#handleBuddyListChanged(int, String)
*/
protected void handleBuddyListChanged( int state, String remoteJid )
{
if ( mBuddyManager != null )
{
synchronized ( mLock )
{
mBuddyManager.handleBuddyListChanged( state, remoteJid );
}
}
}
/**
* @see CallManager#handleCallError(int, long)
*/
protected void handleCallError( int error, long callId )
{
if ( mCallManager != null )
{
synchronized ( mLock )
{
mCallManager.handleCallError( error, callId );
}
}
}
/**
* @see CallManager#handleCallStateChanged(int, String, long)
*/
protected void handleCallStateChanged( int state, String remoteJid, long callId )
{
if ( mCallManager != null )
{
synchronized ( mLock )
{
mCallManager.handleCallStateChanged( state, remoteJid, callId );
}
}
}
/**
* @see ConnectionManager#handleXmppError(int)
*/
protected void handleXmppError( int error )
{
if ( mConnectionManager != null )
{
synchronized ( mLock )
{
mConnectionManager.handleXmppError( error );
}
}
}
/**
* @see ConnectionManager#handleXmppSocketClose(int)
*/
protected void handleXmppSocketClose( int state )
{
if ( mConnectionManager != null )
{
synchronized ( mLock )
{
mConnectionManager.handleXmppSocketClose( state );
}
}
}
/**
* @see ConnectionManager#handleXmppStateChanged(int)
*/
protected void handleXmppStateChanged( int state )
{
if ( mConnectionManager != null )
{
synchronized ( mLock )
{
mConnectionManager.handleXmppStateChanged( state );
}
}
}
/**
* @see StatManager#handleStatsUpdate(String)
*/
protected void handleStatsUpdate( String stats )
{
if ( mStatManager != null )
{
synchronized ( mLock )
{
mStatManager.handleStatsUpdate( stats );
}
}
}
/**
* @see CallManager#handleCallTrackerId(int, String)
*/
protected void handleCallTrackerId( long callId, String callTrackerId )
{
if ( mCallManager != null )
{
synchronized ( mLock )
{
mCallManager.handleCallTrackerId( callId, callTrackerId );
}
}
}
@SuppressWarnings("UnusedDeclaration")
//TODO: change the signature to be:
//dispatchNativeEvent( int what, int code, String data )
private void dispatchNativeEvent( int what, int code, String data, long callId )
{
switch ( what )
{
case CALL_STATE_EVENT:
// data contains remoteJid
handleCallStateChanged( code, data, callId );
break;
case CALL_ERROR_EVENT:
handleCallError( code, callId );
break;
case BUDDY_LIST_EVENT:
// data contains remoteJid
handleBuddyListChanged( code, data );
break;
case XMPP_STATE_EVENT:
handleXmppStateChanged( code );
break;
case XMPP_ERROR_EVENT:
handleXmppError( code );
break;
case XMPP_SOCKET_CLOSE_EVENT:
handleXmppSocketClose( code );
+ break;
case STATS_UPDATE_EVENT:
// data constains stats
handleStatsUpdate( data );
+ break;
case CALL_TRACKER_ID_EVENT:
// data contains call_tracking_id
handleCallTrackerId( callId, data );
break;
}
}
private native void nativeAcceptCall( long call_id );
private native void nativeCall( String remoteJid );
private native void nativeCallWithTrackerId( String remoteJid, String callTrackerId );
private native void nativeDeclineCall( long call_id, boolean busy );
private native void nativeEndCall( long call_id );
private native void nativeHoldCall( long call_id, boolean hold );
private native void nativeInit( Context context );
private native void nativeLogin( String user_name, String password, String stunServer, String turnServer,
String turnUsername, String turnPassword, String xmppServer, int xmppPort,
boolean UseSSL, int portAllocatorFilter );
private native void nativeReplaceTurn(String turn);
private native void nativeLogout();
private native void nativeMuteCall( long call_id, boolean mute );
private native void nativeRelease();
}
| false | true | private void dispatchNativeEvent( int what, int code, String data, long callId )
{
switch ( what )
{
case CALL_STATE_EVENT:
// data contains remoteJid
handleCallStateChanged( code, data, callId );
break;
case CALL_ERROR_EVENT:
handleCallError( code, callId );
break;
case BUDDY_LIST_EVENT:
// data contains remoteJid
handleBuddyListChanged( code, data );
break;
case XMPP_STATE_EVENT:
handleXmppStateChanged( code );
break;
case XMPP_ERROR_EVENT:
handleXmppError( code );
break;
case XMPP_SOCKET_CLOSE_EVENT:
handleXmppSocketClose( code );
case STATS_UPDATE_EVENT:
// data constains stats
handleStatsUpdate( data );
case CALL_TRACKER_ID_EVENT:
// data contains call_tracking_id
handleCallTrackerId( callId, data );
break;
}
}
| private void dispatchNativeEvent( int what, int code, String data, long callId )
{
switch ( what )
{
case CALL_STATE_EVENT:
// data contains remoteJid
handleCallStateChanged( code, data, callId );
break;
case CALL_ERROR_EVENT:
handleCallError( code, callId );
break;
case BUDDY_LIST_EVENT:
// data contains remoteJid
handleBuddyListChanged( code, data );
break;
case XMPP_STATE_EVENT:
handleXmppStateChanged( code );
break;
case XMPP_ERROR_EVENT:
handleXmppError( code );
break;
case XMPP_SOCKET_CLOSE_EVENT:
handleXmppSocketClose( code );
break;
case STATS_UPDATE_EVENT:
// data constains stats
handleStatsUpdate( data );
break;
case CALL_TRACKER_ID_EVENT:
// data contains call_tracking_id
handleCallTrackerId( callId, data );
break;
}
}
|
diff --git a/src/org/hackystat/dailyprojectdata/resource/filemetric/jaxb/TestFileMetricRestApi.java b/src/org/hackystat/dailyprojectdata/resource/filemetric/jaxb/TestFileMetricRestApi.java
index ec72212..baa159a 100644
--- a/src/org/hackystat/dailyprojectdata/resource/filemetric/jaxb/TestFileMetricRestApi.java
+++ b/src/org/hackystat/dailyprojectdata/resource/filemetric/jaxb/TestFileMetricRestApi.java
@@ -1,101 +1,102 @@
package org.hackystat.dailyprojectdata.resource.filemetric.jaxb;
import static org.junit.Assert.assertEquals;
import javax.xml.datatype.XMLGregorianCalendar;
import org.hackystat.dailyprojectdata.client.DailyProjectDataClient;
import org.hackystat.dailyprojectdata.test.DailyProjectDataTestHelper;
import org.hackystat.sensorbase.client.SensorBaseClient;
import org.hackystat.sensorbase.resource.sensordata.jaxb.Properties;
import org.hackystat.sensorbase.resource.sensordata.jaxb.Property;
import org.hackystat.sensorbase.resource.sensordata.jaxb.SensorData;
import org.hackystat.sensorbase.resource.sensordata.jaxb.SensorDatas;
import org.hackystat.utilities.tstamp.Tstamp;
import org.junit.Test;
public class TestFileMetricRestApi extends DailyProjectDataTestHelper {
/** The user for this test case. */
private String user = "[email protected]";
/**
* Test that GET {host}/filemetric/{user}/default/{starttime} works properly.
* First, it creates a test user and sends some sample FileMetric data to the
* SensorBase. Then, it invokes the GET request and checks to see that it
* obtains the right answer. Finally, it deletes the data and the user.
*
* @throws Exception If problems occur.
*/
@Test
public void getDefaultFileMetric() throws Exception {
// First, create a batch of DevEvent sensor data.
SensorDatas batchData = new SensorDatas();
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:00:00", "2007-04-30T02:00:00.001", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Property.java", "111"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:00:00", "2007-04-30T02:00:00.002", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Foo.java", "123"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:00:00", "2007-04-30T02:00:00.003", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Bar.java", "456"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:12:00", "2007-04-30T02:12:00.001", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Foo.java", "120"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:12:00", "2007-04-30T02:12:00.002", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Bar.java", "450"));
// Connect to the sensorbase and register the DailyProjectDataDevEvent user.
SensorBaseClient.registerUser(getSensorBaseHostName(), user);
SensorBaseClient client = new SensorBaseClient(getSensorBaseHostName(), user, user);
client.authenticate();
// Send the sensor data to the SensorBase.
client.putSensorDataBatch(batchData);
// Now connect to the DPD server.
DailyProjectDataClient dpdClient = new DailyProjectDataClient(getDailyProjectDataHostName(),
user, user);
dpdClient.authenticate();
FileMetricDailyProjectData fileMetric = dpdClient.getFileMetric(user, "Default",
Tstamp.makeTimestamp("2007-04-30"));
assertEquals("Checking default fileMetric", 570, fileMetric.getTotalSizeMetricValue().intValue());
assertEquals("Checking MemberData size", 2, fileMetric.getFileData().size());
fileMetric = dpdClient.getFileMetric(user, "Default", Tstamp.makeTimestamp("2007-05-01"));
// the value should be 0
assertEquals("Checking fileMetric day after data", 0, fileMetric.getTotalSizeMetricValue()
.intValue());
fileMetric = dpdClient.getFileMetric(user, "Default", Tstamp.makeTimestamp("2005-04-12"));
- assertEquals("Checking fileMetric before any data.", 0 , fileMetric.getTotalSizeMetricValue());
+ assertEquals("Checking fileMetric before any data.", 0 , fileMetric.getTotalSizeMetricValue()
+ .intValue());
}
/**
* Creates a sample SensorData DevEvent instance given a timestamp and a user.
*
* @param tstampString The timestamp as a string
* @param user The user.
* @return The new SensorData DevEvent instance.
* @throws Exception If problems occur.
*/
private SensorData makeFileMetric(String runTstampString, String tstampString, String user,
String file, String size) throws Exception {
XMLGregorianCalendar tstamp = Tstamp.makeTimestamp(tstampString);
XMLGregorianCalendar runStamp = Tstamp.makeTimestamp(runTstampString);
String sdt = "FileMetric";
SensorData data = new SensorData();
String tool = "SCLC";
data.setTool(tool);
data.setOwner(user);
data.setSensorDataType(sdt);
data.setTimestamp(tstamp);
data.setResource(file);
data.setRuntime(runStamp);
Property property = new Property();
property.setKey("TotalLines");
property.setValue(size);
Properties properties = new Properties();
properties.getProperty().add(property);
data.setProperties(properties);
return data;
}
}
| true | true | public void getDefaultFileMetric() throws Exception {
// First, create a batch of DevEvent sensor data.
SensorDatas batchData = new SensorDatas();
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:00:00", "2007-04-30T02:00:00.001", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Property.java", "111"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:00:00", "2007-04-30T02:00:00.002", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Foo.java", "123"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:00:00", "2007-04-30T02:00:00.003", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Bar.java", "456"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:12:00", "2007-04-30T02:12:00.001", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Foo.java", "120"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:12:00", "2007-04-30T02:12:00.002", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Bar.java", "450"));
// Connect to the sensorbase and register the DailyProjectDataDevEvent user.
SensorBaseClient.registerUser(getSensorBaseHostName(), user);
SensorBaseClient client = new SensorBaseClient(getSensorBaseHostName(), user, user);
client.authenticate();
// Send the sensor data to the SensorBase.
client.putSensorDataBatch(batchData);
// Now connect to the DPD server.
DailyProjectDataClient dpdClient = new DailyProjectDataClient(getDailyProjectDataHostName(),
user, user);
dpdClient.authenticate();
FileMetricDailyProjectData fileMetric = dpdClient.getFileMetric(user, "Default",
Tstamp.makeTimestamp("2007-04-30"));
assertEquals("Checking default fileMetric", 570, fileMetric.getTotalSizeMetricValue().intValue());
assertEquals("Checking MemberData size", 2, fileMetric.getFileData().size());
fileMetric = dpdClient.getFileMetric(user, "Default", Tstamp.makeTimestamp("2007-05-01"));
// the value should be 0
assertEquals("Checking fileMetric day after data", 0, fileMetric.getTotalSizeMetricValue()
.intValue());
fileMetric = dpdClient.getFileMetric(user, "Default", Tstamp.makeTimestamp("2005-04-12"));
assertEquals("Checking fileMetric before any data.", 0 , fileMetric.getTotalSizeMetricValue());
}
| public void getDefaultFileMetric() throws Exception {
// First, create a batch of DevEvent sensor data.
SensorDatas batchData = new SensorDatas();
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:00:00", "2007-04-30T02:00:00.001", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Property.java", "111"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:00:00", "2007-04-30T02:00:00.002", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Foo.java", "123"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:00:00", "2007-04-30T02:00:00.003", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Bar.java", "456"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:12:00", "2007-04-30T02:12:00.001", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Foo.java", "120"));
batchData.getSensorData().add(
makeFileMetric("2007-04-30T02:12:00", "2007-04-30T02:12:00.002", user,
"/home/hackystat-sensorbase-uh/src/org/hackystat/projects/Bar.java", "450"));
// Connect to the sensorbase and register the DailyProjectDataDevEvent user.
SensorBaseClient.registerUser(getSensorBaseHostName(), user);
SensorBaseClient client = new SensorBaseClient(getSensorBaseHostName(), user, user);
client.authenticate();
// Send the sensor data to the SensorBase.
client.putSensorDataBatch(batchData);
// Now connect to the DPD server.
DailyProjectDataClient dpdClient = new DailyProjectDataClient(getDailyProjectDataHostName(),
user, user);
dpdClient.authenticate();
FileMetricDailyProjectData fileMetric = dpdClient.getFileMetric(user, "Default",
Tstamp.makeTimestamp("2007-04-30"));
assertEquals("Checking default fileMetric", 570, fileMetric.getTotalSizeMetricValue().intValue());
assertEquals("Checking MemberData size", 2, fileMetric.getFileData().size());
fileMetric = dpdClient.getFileMetric(user, "Default", Tstamp.makeTimestamp("2007-05-01"));
// the value should be 0
assertEquals("Checking fileMetric day after data", 0, fileMetric.getTotalSizeMetricValue()
.intValue());
fileMetric = dpdClient.getFileMetric(user, "Default", Tstamp.makeTimestamp("2005-04-12"));
assertEquals("Checking fileMetric before any data.", 0 , fileMetric.getTotalSizeMetricValue()
.intValue());
}
|
diff --git a/src/ca/eandb/jmist/framework/lens/PanoramicLens.java b/src/ca/eandb/jmist/framework/lens/PanoramicLens.java
index 8d4c24e1..07c2a5a7 100644
--- a/src/ca/eandb/jmist/framework/lens/PanoramicLens.java
+++ b/src/ca/eandb/jmist/framework/lens/PanoramicLens.java
@@ -1,77 +1,77 @@
/**
*
*/
package ca.eandb.jmist.framework.lens;
import ca.eandb.jmist.math.Point2;
import ca.eandb.jmist.math.Point3;
import ca.eandb.jmist.math.Ray3;
import ca.eandb.jmist.math.Vector3;
/**
* A <code>Lens</code> that projects the scene onto a cylindrical virtual
* screen.
* @author Brad Kimmel
*/
public final class PanoramicLens extends TransformableLens {
/**
* Creates a new <code>PanoramicLens</code>.
*/
public PanoramicLens() {
this.hfov = DEFAULT_HORIZONTAL_FIELD_OF_VIEW;
this.vfov = DEFAULT_VERTICAL_FIELD_OF_VIEW;
}
/**
* Creates a new <code>PanoramicLens</code>.
* @param hfov The horizontal field of view (in radians).
*/
public PanoramicLens(double hfov) {
this.hfov = hfov;
this.vfov = DEFAULT_VERTICAL_FIELD_OF_VIEW;
}
/**
* Creates a new <code>PanoramicLens</code>.
* @param hfov The horizontal field of view (in radians).
* @param vfov The vertical field of view (in radians).
*/
public PanoramicLens(double hfov, double vfov) {
this.hfov = hfov;
this.vfov = vfov;
}
/** The default horizontal field of view (in radians). */
public static final double DEFAULT_HORIZONTAL_FIELD_OF_VIEW = Math.PI;
/** The default vertical field of view (in radians). */
public static final double DEFAULT_VERTICAL_FIELD_OF_VIEW = Math.PI / 2.0;
/* (non-Javadoc)
* @see ca.eandb.jmist.packages.TransformableLens#viewRayAt(ca.eandb.jmist.toolkit.Point2)
*/
@Override
protected Ray3 viewRayAt(Point2 p) {
- double theta = (p.x() - 0.05) * hfov;
+ double theta = (p.x() - 0.5) * hfov;
double height = 2.0 * Math.tan(vfov / 2.0);
return new Ray3(
Point3.ORIGIN,
new Vector3(
Math.sin(theta),
(0.5 - p.y()) * height,
-Math.cos(theta)
).unit()
);
}
/** Horizontal field of view (in radians). */
private final double hfov;
/** Vertical field of view (in radians). */
private final double vfov;
}
| true | true | protected Ray3 viewRayAt(Point2 p) {
double theta = (p.x() - 0.05) * hfov;
double height = 2.0 * Math.tan(vfov / 2.0);
return new Ray3(
Point3.ORIGIN,
new Vector3(
Math.sin(theta),
(0.5 - p.y()) * height,
-Math.cos(theta)
).unit()
);
}
| protected Ray3 viewRayAt(Point2 p) {
double theta = (p.x() - 0.5) * hfov;
double height = 2.0 * Math.tan(vfov / 2.0);
return new Ray3(
Point3.ORIGIN,
new Vector3(
Math.sin(theta),
(0.5 - p.y()) * height,
-Math.cos(theta)
).unit()
);
}
|
diff --git a/src/Gate.java b/src/Gate.java
index ec03589..213fdf7 100644
--- a/src/Gate.java
+++ b/src/Gate.java
@@ -1,355 +1,361 @@
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Level;
/**
* Gate.java - Plug-in for hey0's minecraft mod.
* @author Shaun (sturmeh)
* @author Dinnerbone
*/
public class Gate {
public static final int ANYTHING = -1;
public static final int ENTRANCE = -2;
public static final int CONTROL = -3;
private static HashMap<String, Gate> gates = new HashMap<String, Gate>();
private static HashMap<Integer, ArrayList<Gate>> controlBlocks = new HashMap<Integer, ArrayList<Gate>>();
private String filename;
private Integer[][] layout;
private HashMap<Character, Integer> types;
private RelativeBlockVector[] entrances = new RelativeBlockVector[0];
private RelativeBlockVector[] border = new RelativeBlockVector[0];
private RelativeBlockVector[] controls = new RelativeBlockVector[0];
private int portalBlockOpen = 90;
private int portalBlockClosed = 0;
private Gate(String filename, Integer[][] layout, HashMap<Character, Integer> types) {
this.filename = filename;
this.layout = layout;
this.types = types;
populateCoordinates();
}
private void populateCoordinates() {
ArrayList<RelativeBlockVector> entrances = new ArrayList<RelativeBlockVector>();
ArrayList<RelativeBlockVector> border = new ArrayList<RelativeBlockVector>();
ArrayList<RelativeBlockVector> controls = new ArrayList<RelativeBlockVector>();
for (int y = 0; y < layout.length; y++) {
for (int x = 0; x < layout[y].length; x++) {
Integer id = layout[y][x];
if (id == ENTRANCE) {
entrances.add(new RelativeBlockVector(x, y, 0));
} else if (id == CONTROL) {
controls.add(new RelativeBlockVector(x, y, 0));
} else if (id != ANYTHING) {
border.add(new RelativeBlockVector(x, y, 0));
}
}
}
this.entrances = entrances.toArray(this.entrances);
this.border = border.toArray(this.border);
this.controls = controls.toArray(this.controls);
}
public void save() {
HashMap<Integer, Character> reverse = new HashMap<Integer, Character>();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("stargates/" + filename));
bw.append("portal-open=" + portalBlockOpen);
bw.newLine();
bw.append("portal-closed=" + portalBlockClosed);
bw.newLine();
for (Character type : types.keySet()) {
Integer value = types.get(type);
if (!type.equals('-')) {
reverse.put(value, type);
}
bw.append(type);
bw.append('=');
bw.append(value.toString());
bw.newLine();
}
bw.newLine();
for (int y = 0; y < layout.length; y++) {
for (int x = 0; x < layout[y].length; x++) {
Integer id = layout[y][x];
Character symbol;
if (id == ENTRANCE) {
symbol = '.';
} else if (id == ANYTHING) {
symbol = ' ';
} else if (id == CONTROL) {
symbol = '-';
} else if (reverse.containsKey(id)) {
symbol = reverse.get(id);
} else {
symbol = '?';
}
bw.append(symbol);
}
bw.newLine();
}
bw.close();
} catch (IOException ex) {
Stargate.log(Level.SEVERE, "Could not load Gate " + filename + " - " + ex.getMessage());
}
}
public Integer[][] getLayout() {
return layout;
}
public RelativeBlockVector[] getEntrances() {
return entrances;
}
public RelativeBlockVector[] getBorder() {
return border;
}
public RelativeBlockVector[] getControls() {
return controls;
}
public int getControlBlock() {
return types.get('-');
}
public String getFilename() {
return filename;
}
public int getPortalBlockOpen() {
return portalBlockOpen;
}
public int getPortalBlockClosed() {
return portalBlockClosed;
}
public boolean matches(Block topleft, int modX, int modZ) {
return matches(new Blox(topleft), modX, modZ);
}
public boolean matches(Blox topleft, int modX, int modZ) {
for (int y = 0; y < layout.length; y++) {
for (int x = 0; x < layout[y].length; x++) {
int id = layout[y][x];
if (id == ENTRANCE) {
if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != 0) {
return false;
}
} else if (id == CONTROL) {
if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != getControlBlock()) {
return false;
}
} else if (id != ANYTHING) {
if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != id) {
return false;
}
}
}
}
return true;
}
private static void registerGate(Gate gate) {
gates.put(gate.getFilename(), gate);
RelativeBlockVector[] controls = gate.getControls();
for (RelativeBlockVector vector : controls) {
int id = gate.getControlBlock();
if (!controlBlocks.containsKey(id)) {
controlBlocks.put(id, new ArrayList<Gate>());
}
controlBlocks.get(id).add(gate);
}
}
private static Gate loadGate(File file) {
Scanner scanner = null;
boolean designing = false;
ArrayList<ArrayList<Integer>> design = new ArrayList<ArrayList<Integer>>();
HashMap<Character, Integer> types = new HashMap<Character, Integer>();
HashMap<String, String> config = new HashMap<String, String>();
int cols = 0;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (designing) {
ArrayList<Integer> row = new ArrayList<Integer>();
if (line.length() > cols) {
cols = line.length();
}
for (Character symbol : line.toCharArray()) {
Integer id = ANYTHING;
if (symbol.equals('.')) {
id = ENTRANCE;
} else if (symbol.equals(' ')) {
id = ANYTHING;
} else if (symbol.equals('-')) {
id = CONTROL;
} else if ((symbol.equals('?')) || (!types.containsKey(symbol))) {
Stargate.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Unknown symbol '" + symbol + "' in diagram");
return null;
} else {
id = types.get(symbol);
}
row.add(id);
}
design.add(row);
} else {
if ((line.isEmpty()) || (!line.contains("="))) {
designing = true;
} else {
String[] split = line.split("=");
String key = split[0].trim();
String value = split[1].trim();
if (key.length() == 1) {
Character symbol = key.charAt(0);
Integer id = Integer.parseInt(value);
types.put(symbol, id);
} else {
config.put(key, value);
}
}
}
}
} catch (Exception ex) {
Stargate.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Invalid block ID given");
return null;
} finally {
if (scanner != null) scanner.close();
}
Integer[][] layout = new Integer[design.size()][cols];
for (int y = 0; y < design.size(); y++) {
ArrayList<Integer> row = design.get(y);
Integer[] result = new Integer[cols];
for (int x = 0; x < cols; x++) {
if (x < row.size()) {
result[x] = row.get(x);
} else {
result[x] = ANYTHING;
}
}
layout[y] = result;
}
Gate gate = new Gate(file.getName(), layout, types);
if (config.containsKey("portal-open")) {
- gate.portalBlockOpen = Integer.getInteger(config.get("portal-open"));
+ try {
+ gate.portalBlockOpen = Integer.parseInt(config.get("portal-open"));
+ } catch (NumberFormatException ex) {
+ }
}
if (config.containsKey("portal-closed")) {
- gate.portalBlockClosed = Integer.getInteger(config.get("portal-closed"));
+ try {
+ gate.portalBlockClosed = Integer.parseInt(config.get("portal-closed"));
+ } catch (NumberFormatException ex) {
+ }
}
if (gate.getControls().length != 2) {
Stargate.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Gates must have exactly 2 control points.");
return null;
} else {
gate.save(); // Updates format for version changes
return gate;
}
}
public static void loadGates() {
File dir = new File("stargates");
File[] files;
if (dir.exists()) {
files = dir.listFiles(new StargateFilenameFilter());
} else {
files = new File[0];
}
if (files.length == 0) {
dir.mkdir();
populateDefaults(dir);
} else {
for (File file : files) {
Gate gate = loadGate(file);
if (gate != null) registerGate(gate);
}
}
}
public static void populateDefaults(File dir) {
Integer[][] layout = new Integer[][] {
{ANYTHING, Portal.OBSIDIAN, Portal.OBSIDIAN, ANYTHING},
{Portal.OBSIDIAN, ENTRANCE, ENTRANCE, Portal.OBSIDIAN},
{CONTROL, ENTRANCE, ENTRANCE, CONTROL},
{Portal.OBSIDIAN, ENTRANCE, ENTRANCE, Portal.OBSIDIAN},
{ANYTHING, Portal.OBSIDIAN, Portal.OBSIDIAN, ANYTHING},
};
HashMap<Character, Integer> types = new HashMap<Character, Integer>();
types.put('X', Portal.OBSIDIAN);
types.put('-', Portal.OBSIDIAN);
Gate gate = new Gate("nethergate.gate", layout, types);
gate.save();
registerGate(gate);
}
public static Gate[] getGatesByControlBlock(Block block) {
return getGatesByControlBlock(block.getType());
}
public static Gate[] getGatesByControlBlock(int type) {
Gate[] result = new Gate[0];
result = controlBlocks.get(type).toArray(result);
return result;
}
public static Gate getGateByName(String name) {
return gates.get(name);
}
static class StargateFilenameFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return name.endsWith(".gate");
}
}
}
| false | true | private static Gate loadGate(File file) {
Scanner scanner = null;
boolean designing = false;
ArrayList<ArrayList<Integer>> design = new ArrayList<ArrayList<Integer>>();
HashMap<Character, Integer> types = new HashMap<Character, Integer>();
HashMap<String, String> config = new HashMap<String, String>();
int cols = 0;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (designing) {
ArrayList<Integer> row = new ArrayList<Integer>();
if (line.length() > cols) {
cols = line.length();
}
for (Character symbol : line.toCharArray()) {
Integer id = ANYTHING;
if (symbol.equals('.')) {
id = ENTRANCE;
} else if (symbol.equals(' ')) {
id = ANYTHING;
} else if (symbol.equals('-')) {
id = CONTROL;
} else if ((symbol.equals('?')) || (!types.containsKey(symbol))) {
Stargate.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Unknown symbol '" + symbol + "' in diagram");
return null;
} else {
id = types.get(symbol);
}
row.add(id);
}
design.add(row);
} else {
if ((line.isEmpty()) || (!line.contains("="))) {
designing = true;
} else {
String[] split = line.split("=");
String key = split[0].trim();
String value = split[1].trim();
if (key.length() == 1) {
Character symbol = key.charAt(0);
Integer id = Integer.parseInt(value);
types.put(symbol, id);
} else {
config.put(key, value);
}
}
}
}
} catch (Exception ex) {
Stargate.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Invalid block ID given");
return null;
} finally {
if (scanner != null) scanner.close();
}
Integer[][] layout = new Integer[design.size()][cols];
for (int y = 0; y < design.size(); y++) {
ArrayList<Integer> row = design.get(y);
Integer[] result = new Integer[cols];
for (int x = 0; x < cols; x++) {
if (x < row.size()) {
result[x] = row.get(x);
} else {
result[x] = ANYTHING;
}
}
layout[y] = result;
}
Gate gate = new Gate(file.getName(), layout, types);
if (config.containsKey("portal-open")) {
gate.portalBlockOpen = Integer.getInteger(config.get("portal-open"));
}
if (config.containsKey("portal-closed")) {
gate.portalBlockClosed = Integer.getInteger(config.get("portal-closed"));
}
if (gate.getControls().length != 2) {
Stargate.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Gates must have exactly 2 control points.");
return null;
} else {
gate.save(); // Updates format for version changes
return gate;
}
}
| private static Gate loadGate(File file) {
Scanner scanner = null;
boolean designing = false;
ArrayList<ArrayList<Integer>> design = new ArrayList<ArrayList<Integer>>();
HashMap<Character, Integer> types = new HashMap<Character, Integer>();
HashMap<String, String> config = new HashMap<String, String>();
int cols = 0;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (designing) {
ArrayList<Integer> row = new ArrayList<Integer>();
if (line.length() > cols) {
cols = line.length();
}
for (Character symbol : line.toCharArray()) {
Integer id = ANYTHING;
if (symbol.equals('.')) {
id = ENTRANCE;
} else if (symbol.equals(' ')) {
id = ANYTHING;
} else if (symbol.equals('-')) {
id = CONTROL;
} else if ((symbol.equals('?')) || (!types.containsKey(symbol))) {
Stargate.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Unknown symbol '" + symbol + "' in diagram");
return null;
} else {
id = types.get(symbol);
}
row.add(id);
}
design.add(row);
} else {
if ((line.isEmpty()) || (!line.contains("="))) {
designing = true;
} else {
String[] split = line.split("=");
String key = split[0].trim();
String value = split[1].trim();
if (key.length() == 1) {
Character symbol = key.charAt(0);
Integer id = Integer.parseInt(value);
types.put(symbol, id);
} else {
config.put(key, value);
}
}
}
}
} catch (Exception ex) {
Stargate.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Invalid block ID given");
return null;
} finally {
if (scanner != null) scanner.close();
}
Integer[][] layout = new Integer[design.size()][cols];
for (int y = 0; y < design.size(); y++) {
ArrayList<Integer> row = design.get(y);
Integer[] result = new Integer[cols];
for (int x = 0; x < cols; x++) {
if (x < row.size()) {
result[x] = row.get(x);
} else {
result[x] = ANYTHING;
}
}
layout[y] = result;
}
Gate gate = new Gate(file.getName(), layout, types);
if (config.containsKey("portal-open")) {
try {
gate.portalBlockOpen = Integer.parseInt(config.get("portal-open"));
} catch (NumberFormatException ex) {
}
}
if (config.containsKey("portal-closed")) {
try {
gate.portalBlockClosed = Integer.parseInt(config.get("portal-closed"));
} catch (NumberFormatException ex) {
}
}
if (gate.getControls().length != 2) {
Stargate.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Gates must have exactly 2 control points.");
return null;
} else {
gate.save(); // Updates format for version changes
return gate;
}
}
|
diff --git a/src/org/jacorb/idl/ParseException.java b/src/org/jacorb/idl/ParseException.java
index 72c3ef748..5fce9d4ce 100644
--- a/src/org/jacorb/idl/ParseException.java
+++ b/src/org/jacorb/idl/ParseException.java
@@ -1,69 +1,70 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2003 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.jacorb.idl;
/**
* @author Gerald Brose
* @version $Id$
*
* Thrown by the IDL compiler when it encounters fatal errors
*/
public class ParseException
extends RuntimeException
{
/** remember the error position */
private PositionInfo position = null;
public ParseException()
{
}
public ParseException( String reason )
{
super( reason );
}
public ParseException( String reason, PositionInfo pos )
{
super( reason );
position = pos;
}
public String getMessage()
{
return
- ( position != null ? position.toString() : "" ) +
- ": " + "parse error: " + super.getMessage();
+ ( position != null ? (position.toString() + ": ") : "" ) +
+ "Parse error " +
+ ( super.getMessage() != null ? (": " + super.getMessage()) : "" ) ;
}
}
| true | true | public String getMessage()
{
return
( position != null ? position.toString() : "" ) +
": " + "parse error: " + super.getMessage();
}
| public String getMessage()
{
return
( position != null ? (position.toString() + ": ") : "" ) +
"Parse error " +
( super.getMessage() != null ? (": " + super.getMessage()) : "" ) ;
}
|
diff --git a/org.openscada.hd.client.net/src/org/openscada/hd/client/net/Activator.java b/org.openscada.hd.client.net/src/org/openscada/hd/client/net/Activator.java
index 354e89e2b..a1c62c98e 100644
--- a/org.openscada.hd.client.net/src/org/openscada/hd/client/net/Activator.java
+++ b/org.openscada.hd.client.net/src/org/openscada/hd/client/net/Activator.java
@@ -1,65 +1,65 @@
/*
* This file is part of the OpenSCADA project
* Copyright (C) 2006-2012 TH4 SYSTEMS GmbH (http://th4-systems.com)
*
* OpenSCADA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenSCADA 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenSCADA. If not, see
* <http://opensource.org/licenses/lgpl-3.0.html> for a copy of the LGPLv3 License.
*/
package org.openscada.hd.client.net;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
public class Activator implements BundleActivator
{
private DriverFactoryImpl factory;
private ServiceRegistration<org.openscada.core.client.DriverFactory> handle;
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
@Override
public void start ( final BundleContext context ) throws Exception
{
this.factory = new DriverFactoryImpl ();
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( org.openscada.core.client.DriverFactory.INTERFACE_NAME, "hd" );
properties.put ( org.openscada.core.client.DriverFactory.DRIVER_NAME, "net" );
- properties.put ( Constants.SERVICE_DESCRIPTION, "OpenSCADA HD NET Adapter" );
+ properties.put ( Constants.SERVICE_DESCRIPTION, "openSCADA HD NET Adapter" );
properties.put ( Constants.SERVICE_VENDOR, "TH4 SYSTEMS GmbH" );
this.handle = context.registerService ( org.openscada.core.client.DriverFactory.class, this.factory, properties );
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop ( final BundleContext context ) throws Exception
{
this.handle.unregister ();
this.handle = null;
this.factory = null;
}
}
| true | true | public void start ( final BundleContext context ) throws Exception
{
this.factory = new DriverFactoryImpl ();
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( org.openscada.core.client.DriverFactory.INTERFACE_NAME, "hd" );
properties.put ( org.openscada.core.client.DriverFactory.DRIVER_NAME, "net" );
properties.put ( Constants.SERVICE_DESCRIPTION, "OpenSCADA HD NET Adapter" );
properties.put ( Constants.SERVICE_VENDOR, "TH4 SYSTEMS GmbH" );
this.handle = context.registerService ( org.openscada.core.client.DriverFactory.class, this.factory, properties );
}
| public void start ( final BundleContext context ) throws Exception
{
this.factory = new DriverFactoryImpl ();
final Dictionary<String, String> properties = new Hashtable<String, String> ();
properties.put ( org.openscada.core.client.DriverFactory.INTERFACE_NAME, "hd" );
properties.put ( org.openscada.core.client.DriverFactory.DRIVER_NAME, "net" );
properties.put ( Constants.SERVICE_DESCRIPTION, "openSCADA HD NET Adapter" );
properties.put ( Constants.SERVICE_VENDOR, "TH4 SYSTEMS GmbH" );
this.handle = context.registerService ( org.openscada.core.client.DriverFactory.class, this.factory, properties );
}
|
diff --git a/Ingest/src/org/sleuthkit/autopsy/ingest/Installer.java b/Ingest/src/org/sleuthkit/autopsy/ingest/Installer.java
index 754069dd3..db57922ee 100644
--- a/Ingest/src/org/sleuthkit/autopsy/ingest/Installer.java
+++ b/Ingest/src/org/sleuthkit/autopsy/ingest/Installer.java
@@ -1,56 +1,56 @@
/*
* 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.ingest;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openide.modules.ModuleInstall;
import org.openide.windows.WindowManager;
/**
* Initializes ingest manager when the module is loaded
*/
public class Installer extends ModuleInstall {
@Override
public void restored() {
Logger logger = Logger.getLogger(Installer.class.getName());
logger.log(Level.INFO, "Initializing ingest manager");
final IngestManager manager = IngestManager.getDefault();
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
@Override
public void run() {
- manager.initUI();
+ //manager.initUI();
//force ingest inbox closed, even if previous state was open
//IngestMessageTopComponent.findInstance().close();
}
});
}
@Override
public boolean closing() {
//force ingest inbox closed on exit and save state as such
IngestMessageTopComponent.findInstance().close();
return true;
}
}
| true | true | public void restored() {
Logger logger = Logger.getLogger(Installer.class.getName());
logger.log(Level.INFO, "Initializing ingest manager");
final IngestManager manager = IngestManager.getDefault();
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
@Override
public void run() {
manager.initUI();
//force ingest inbox closed, even if previous state was open
//IngestMessageTopComponent.findInstance().close();
}
});
}
| public void restored() {
Logger logger = Logger.getLogger(Installer.class.getName());
logger.log(Level.INFO, "Initializing ingest manager");
final IngestManager manager = IngestManager.getDefault();
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
@Override
public void run() {
//manager.initUI();
//force ingest inbox closed, even if previous state was open
//IngestMessageTopComponent.findInstance().close();
}
});
}
|
diff --git a/Fanorona/src/team01/GUI.java b/Fanorona/src/team01/GUI.java
index 80bc9be..afdf9c9 100644
--- a/Fanorona/src/team01/GUI.java
+++ b/Fanorona/src/team01/GUI.java
@@ -1,322 +1,322 @@
package team01;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("serial")
public class GUI extends JFrame {
private List<Pair> gridLines = new ArrayList<Pair>();
private final Game game;
private int width;
private int height;
private int spacing;
private int radius;
private int diameter;
private int minX;
private int minY;
private int maxX;
private int maxY;
private int winWidth;
private int winHeight;
private boolean gameInProgress;
private DrawCanvas canvas;
public GUI(int width, int height, boolean aiPlayer, int player) {
//gameInProgress = false;
setBackground(new Color(47, 79, 79));
//create menu
JMenuBar b;
Menu menu = new Menu();
b = menu.get_bar();
setJMenuBar(b);
b.setVisible(true);
- width = menu.get_col_size();
- height = menu.get_row_size();
+// width = menu.get_col_size();
+// height = menu.get_row_size();
aiPlayer = menu.get_aiPlayer();
gameInProgress = menu.get_gameStart();
game = new Game(width, height, aiPlayer, player);
- // this.width = game.getBoard().getWidth();
- // this.height = game.getBoard().getHeight();
+ this.width = game.getBoard().getWidth();
+ this.height = game.getBoard().getHeight();
spacing = 80; // 80 px between board positions
radius = spacing / 2 - 8; // 8 px between game pieces
diameter = 2 * radius;
minX = spacing;
minY = spacing;
maxX = width * spacing;
maxY = height * spacing;
winWidth = maxX + spacing;
winHeight = maxY + spacing;
initializeGridLines();
canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(winWidth, winHeight));
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (game.isTie() || game.whiteWins() || game.blackWins())
{
game.reset();
setTitle("Fanorona");
repaint();
return;
}
int mouseX = e.getX();
int mouseY = e.getY();
int x = (mouseX + radius) / spacing;
int y = game.getBoard().getHeight() - ((mouseY + radius) / spacing) + 1;
Point point = new Point(x, y);
if (game.getBoard().isValidPoint(point))
{
if (! game.update(point))
{
System.out.println("!!! INVALID MOVE: " + point);
System.out.println();
}
}
if (game.isTie())
{
System.out.println("Tie");
setTitle("Tie");
}
else if (game.whiteWins())
{
System.out.println("White wins");
setTitle("White wins");
}
else if (game.blackWins())
{
System.out.println("Black wins");
setTitle("Black wins");
}
repaint();
}
});
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setTitle("Fanorona");
setVisible(true);
}
class DrawCanvas extends JPanel {
@Override
public void paintComponent(Graphics g) {
//if(gameInProgress) {
super.paintChildren(g);
drawGridLines(g);
drawGamePieces(g);
//} else {
// drawStartScreen(g);
//}
}
}
/*
class DrawStartScreen extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintChildren(g);
drawGridLines(g);
drawGamePieces(g);
}
}
*/
/*
private void changePanel(JPanel panel) {
getContentPane().removeAll();
getContentPane().add(panel, BorderLayout.CENTER);
getContentPane().doLayout();
update(getGraphics());
}
*/
private void drawStartScreen(Graphics g) {
String s1 = "Welcome to Fanorona";
String s2 = "Please use the dropdown menu above to select preferences, then start a new game.";
g.setColor(Color.white);
g.drawString(s1, 50, winHeight/2);
g.drawString(s2, 50, winHeight/2+50);
}
private void drawGamePieces(Graphics g)
{
Board board = game.getBoard();
Graphics2D g2d = (Graphics2D)g;
g2d.setStroke(new BasicStroke(2));
for (Point point : board)
{
int type = board.getPoint(point);
int x = point.getX() * spacing;
int y = winHeight - (point.getY() * spacing);
x -= radius;
y -= radius;
switch (type)
{
case Board.WHITE:
g2d.setColor(new Color(240, 255, 255));
g2d.fillOval(x, y, diameter, diameter);
break;
case Board.BLACK:
g2d.setColor(Color.BLACK);
g2d.fillOval(x, y, diameter, diameter);
break;
case Board.WHITE_GRAY:
case Board.BLACK_GRAY:
g2d.setColor(Color.GRAY);
g2d.fillOval(x, y, diameter, diameter);
break;
}
if (game.getClickable().contains(point))
{
g.setColor(Color.MAGENTA);
g.drawOval(x, y, diameter, diameter);
}
}
}
private void drawGridLines(Graphics g)
{
// g.setColor(new Color(221, 218, 236));
// g.fillRect(0, 0, winWidth, winHeight);
g.setColor(new Color(250, 158, 114));
for (Pair pair : gridLines)
{
Point src = pair.getSrc();
Point dest = pair.getDest();
g.drawLine(src.getX(), src.getY(), dest.getX(), dest.getY());
}
}
private void initializeGridLines()
{
// horizontal lines
for (int i = 1; i <= height; i++)
{
int y = i * spacing;
gridLines.add(new Pair(minX, y, maxX, y));
}
// vertical lines
for (int i = 1; i <= width; i++)
{
int x = i * spacing;
gridLines.add(new Pair(x, minY, x, maxY));
}
// diagonal lines (upper left to lower right)
for (int i = 1; i < width; i += 2)
{
int x1 = i * spacing;
int x2 = x1;
int y2 = minY;
while (x2 < maxX && y2 < maxY)
{
x2 += spacing;
y2 += spacing;
}
gridLines.add(new Pair(x1, minY, x2, y2));
}
for (int i = 3; i < height; i += 2)
{
int y1 = i * spacing;
int x2 = minX;
int y2 = y1;
while (x2 < maxX && y2 < maxY)
{
x2 += spacing;
y2 += spacing;
}
gridLines.add(new Pair(minX, y1, x2, y2));
}
// diagonal lines (upper right to lower left)
for (int i = 3; i < width; i += 2)
{
int x1 = i * spacing;
int x2 = x1;
int y2 = minY;
while (x2 > minX && y2 < maxY)
{
x2 -= spacing;
y2 += spacing;
}
gridLines.add(new Pair(x1, minY, x2, y2));
}
for (int i = 1; i < height; i += 2)
{
int y1 = i * spacing;
int x2 = maxX;
int y2 = y1;
while (x2 > minX && y2 < maxY)
{
x2 -= spacing;
y2 += spacing;
}
gridLines.add(new Pair(maxX, y1, x2, y2));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
int width = 9;
int height = 5;
boolean aiPlayer = true;
int player = Board.WHITE;
new GUI(width, height, aiPlayer, player);
}
});
}
}
| false | true | public GUI(int width, int height, boolean aiPlayer, int player) {
//gameInProgress = false;
setBackground(new Color(47, 79, 79));
//create menu
JMenuBar b;
Menu menu = new Menu();
b = menu.get_bar();
setJMenuBar(b);
b.setVisible(true);
width = menu.get_col_size();
height = menu.get_row_size();
aiPlayer = menu.get_aiPlayer();
gameInProgress = menu.get_gameStart();
game = new Game(width, height, aiPlayer, player);
// this.width = game.getBoard().getWidth();
// this.height = game.getBoard().getHeight();
spacing = 80; // 80 px between board positions
radius = spacing / 2 - 8; // 8 px between game pieces
diameter = 2 * radius;
minX = spacing;
minY = spacing;
maxX = width * spacing;
maxY = height * spacing;
winWidth = maxX + spacing;
winHeight = maxY + spacing;
initializeGridLines();
canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(winWidth, winHeight));
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (game.isTie() || game.whiteWins() || game.blackWins())
{
game.reset();
setTitle("Fanorona");
repaint();
return;
}
int mouseX = e.getX();
int mouseY = e.getY();
int x = (mouseX + radius) / spacing;
int y = game.getBoard().getHeight() - ((mouseY + radius) / spacing) + 1;
Point point = new Point(x, y);
if (game.getBoard().isValidPoint(point))
{
if (! game.update(point))
{
System.out.println("!!! INVALID MOVE: " + point);
System.out.println();
}
}
if (game.isTie())
{
System.out.println("Tie");
setTitle("Tie");
}
else if (game.whiteWins())
{
System.out.println("White wins");
setTitle("White wins");
}
else if (game.blackWins())
{
System.out.println("Black wins");
setTitle("Black wins");
}
repaint();
}
});
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setTitle("Fanorona");
setVisible(true);
}
| public GUI(int width, int height, boolean aiPlayer, int player) {
//gameInProgress = false;
setBackground(new Color(47, 79, 79));
//create menu
JMenuBar b;
Menu menu = new Menu();
b = menu.get_bar();
setJMenuBar(b);
b.setVisible(true);
// width = menu.get_col_size();
// height = menu.get_row_size();
aiPlayer = menu.get_aiPlayer();
gameInProgress = menu.get_gameStart();
game = new Game(width, height, aiPlayer, player);
this.width = game.getBoard().getWidth();
this.height = game.getBoard().getHeight();
spacing = 80; // 80 px between board positions
radius = spacing / 2 - 8; // 8 px between game pieces
diameter = 2 * radius;
minX = spacing;
minY = spacing;
maxX = width * spacing;
maxY = height * spacing;
winWidth = maxX + spacing;
winHeight = maxY + spacing;
initializeGridLines();
canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(winWidth, winHeight));
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (game.isTie() || game.whiteWins() || game.blackWins())
{
game.reset();
setTitle("Fanorona");
repaint();
return;
}
int mouseX = e.getX();
int mouseY = e.getY();
int x = (mouseX + radius) / spacing;
int y = game.getBoard().getHeight() - ((mouseY + radius) / spacing) + 1;
Point point = new Point(x, y);
if (game.getBoard().isValidPoint(point))
{
if (! game.update(point))
{
System.out.println("!!! INVALID MOVE: " + point);
System.out.println();
}
}
if (game.isTie())
{
System.out.println("Tie");
setTitle("Tie");
}
else if (game.whiteWins())
{
System.out.println("White wins");
setTitle("White wins");
}
else if (game.blackWins())
{
System.out.println("Black wins");
setTitle("Black wins");
}
repaint();
}
});
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setTitle("Fanorona");
setVisible(true);
}
|
diff --git a/webinos/common/android/app/src/org/webinos/app/anode/AnodeReceiver.java b/webinos/common/android/app/src/org/webinos/app/anode/AnodeReceiver.java
index 25bd04e3..50fc38fc 100644
--- a/webinos/common/android/app/src/org/webinos/app/anode/AnodeReceiver.java
+++ b/webinos/common/android/app/src/org/webinos/app/anode/AnodeReceiver.java
@@ -1,125 +1,127 @@
/*
* Copyright 2011-2012 Paddy Byers
*
* 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.webinos.app.anode;
import org.meshpoint.anode.Isolate;
import org.meshpoint.anode.Runtime;
import org.meshpoint.anode.Runtime.IllegalStateException;
import org.meshpoint.anode.Runtime.NodeException;
import org.webinos.app.wrt.ui.WidgetInstallActivity;
import org.webinos.app.wrt.ui.WidgetUninstallActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AnodeReceiver extends BroadcastReceiver {
private static String TAG = "anode::AnodeReceiver";
public static final String ACTION_START = "org.webinos.app.START";
public static final String ACTION_STOP = "org.webinos.app.STOP";
public static final String ACTION_STOPALL = "org.webinos.app.STOPALL";
public static final String ACTION_MODULE_INSTALL = "org.webinos.app.module.INSTALL";
public static final String ACTION_MODULE_UNINSTALL = "org.webinos.app.module.UNINSTALL";
public static final String ACTION_WGT_INSTALL = "org.webinos.app.wgt.INSTALL";
public static final String ACTION_WGT_UNINSTALL = "org.webinos.app.wgt.UNINSTALL";
public static final String CMD = "cmdline";
public static final String INST = "instance";
public static final String OPTS = "options";
public static final String MODULE = "module";
public static final String PATH = "path";
public AnodeReceiver() {
super();
}
@Override
public void onReceive(Context ctx, Intent intent) {
/* get the system options */
String action = intent.getAction();
if(ACTION_STOPALL.equals(action)) {
if(Runtime.isInitialised()) {
for(Isolate isolate : AnodeService.getAll())
stopInstance(isolate);
}
/* temporary ... kill the process */
System.exit(0);
return;
}
if(ACTION_STOP.equals(action)) {
if(Runtime.isInitialised()) {
String instance = intent.getStringExtra(INST);
if(instance == null) {
instance = AnodeService.soleInstance();
if(instance == null) {
Log.v(TAG, "AnodeReceiver.onReceive::stop: no instance specified");
return;
}
}
Isolate isolate = AnodeService.getInstance(instance);
if(isolate == null) {
Log.v(TAG, "AnodeReceiver.onReceive::stop: instance " + instance + " not found");
return;
}
stopInstance(isolate);
}
+ /* temporary ... Kill the process */
+ System.exit(0); // This was added for the review meeting to free up the ports
return;
}
if(ACTION_START.equals(action)) {
/* get the launch commandline */
String args = intent.getStringExtra(CMD);
/* if no cmdline was sent, then launch the activity for interactive behaviour */
if(args == null || args.isEmpty()) {
intent.setClassName(ctx, AnodeActivity.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
return;
}
}
if(ACTION_WGT_INSTALL.equals(action)) {
intent.setClassName(ctx, WidgetInstallActivity.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
return;
}
if(ACTION_WGT_UNINSTALL.equals(action)) {
intent.setClassName(ctx, WidgetUninstallActivity.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
return;
}
/* otherwise, start service */
intent.setClassName(ctx, AnodeService.class.getName());
ctx.startService(intent);
}
private void stopInstance(Isolate isolate) {
try {
isolate.stop();
} catch (IllegalStateException e) {
Log.v(TAG, "AnodeReceiver.onReceive::stop: exception: " + e + "; cause: " + e.getCause());
} catch (NodeException e) {
Log.v(TAG, "AnodeReceiver.onReceive::stop: exception: " + e + "; cause: " + e.getCause());
}
}
}
| true | true | public void onReceive(Context ctx, Intent intent) {
/* get the system options */
String action = intent.getAction();
if(ACTION_STOPALL.equals(action)) {
if(Runtime.isInitialised()) {
for(Isolate isolate : AnodeService.getAll())
stopInstance(isolate);
}
/* temporary ... kill the process */
System.exit(0);
return;
}
if(ACTION_STOP.equals(action)) {
if(Runtime.isInitialised()) {
String instance = intent.getStringExtra(INST);
if(instance == null) {
instance = AnodeService.soleInstance();
if(instance == null) {
Log.v(TAG, "AnodeReceiver.onReceive::stop: no instance specified");
return;
}
}
Isolate isolate = AnodeService.getInstance(instance);
if(isolate == null) {
Log.v(TAG, "AnodeReceiver.onReceive::stop: instance " + instance + " not found");
return;
}
stopInstance(isolate);
}
return;
}
if(ACTION_START.equals(action)) {
/* get the launch commandline */
String args = intent.getStringExtra(CMD);
/* if no cmdline was sent, then launch the activity for interactive behaviour */
if(args == null || args.isEmpty()) {
intent.setClassName(ctx, AnodeActivity.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
return;
}
}
if(ACTION_WGT_INSTALL.equals(action)) {
intent.setClassName(ctx, WidgetInstallActivity.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
return;
}
if(ACTION_WGT_UNINSTALL.equals(action)) {
intent.setClassName(ctx, WidgetUninstallActivity.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
return;
}
/* otherwise, start service */
intent.setClassName(ctx, AnodeService.class.getName());
ctx.startService(intent);
}
| public void onReceive(Context ctx, Intent intent) {
/* get the system options */
String action = intent.getAction();
if(ACTION_STOPALL.equals(action)) {
if(Runtime.isInitialised()) {
for(Isolate isolate : AnodeService.getAll())
stopInstance(isolate);
}
/* temporary ... kill the process */
System.exit(0);
return;
}
if(ACTION_STOP.equals(action)) {
if(Runtime.isInitialised()) {
String instance = intent.getStringExtra(INST);
if(instance == null) {
instance = AnodeService.soleInstance();
if(instance == null) {
Log.v(TAG, "AnodeReceiver.onReceive::stop: no instance specified");
return;
}
}
Isolate isolate = AnodeService.getInstance(instance);
if(isolate == null) {
Log.v(TAG, "AnodeReceiver.onReceive::stop: instance " + instance + " not found");
return;
}
stopInstance(isolate);
}
/* temporary ... Kill the process */
System.exit(0); // This was added for the review meeting to free up the ports
return;
}
if(ACTION_START.equals(action)) {
/* get the launch commandline */
String args = intent.getStringExtra(CMD);
/* if no cmdline was sent, then launch the activity for interactive behaviour */
if(args == null || args.isEmpty()) {
intent.setClassName(ctx, AnodeActivity.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
return;
}
}
if(ACTION_WGT_INSTALL.equals(action)) {
intent.setClassName(ctx, WidgetInstallActivity.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
return;
}
if(ACTION_WGT_UNINSTALL.equals(action)) {
intent.setClassName(ctx, WidgetUninstallActivity.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
return;
}
/* otherwise, start service */
intent.setClassName(ctx, AnodeService.class.getName());
ctx.startService(intent);
}
|
diff --git a/src/java/org/infoglue/deliver/taglib/common/RSSFeedTag.java b/src/java/org/infoglue/deliver/taglib/common/RSSFeedTag.java
index 672862c26..293f3dca1 100755
--- a/src/java/org/infoglue/deliver/taglib/common/RSSFeedTag.java
+++ b/src/java/org/infoglue/deliver/taglib/common/RSSFeedTag.java
@@ -1,132 +1,136 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including 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 org.infoglue.deliver.taglib.common;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.servlet.jsp.JspException;
import org.apache.log4j.Logger;
import org.infoglue.deliver.taglib.AbstractTag;
import org.infoglue.deliver.taglib.TemplateControllerTag;
import org.infoglue.deliver.util.rss.RssHelper;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
/**
* This tag will get a cookie value
*/
public class RSSFeedTag extends TemplateControllerTag
{
private final static Logger logger = Logger.getLogger(RSSFeedTag.class.getName());
/**
* The universal version identifier.
*/
private static final long serialVersionUID = 8603406098980150888L;
private String feedType = null;
private String title = null;
private String link = null;
private String description = null;
private List entries = new ArrayList();
/**
* Default constructor.
*/
public RSSFeedTag()
{
super();
}
/**
* Initializes the parameters to make it accessible for the children tags (if any).
*
* @return indication of whether to evaluate the body or not.
* @throws JspException if an error occurred while processing this tag.
*/
public int doStartTag() throws JspException
{
return EVAL_BODY_INCLUDE;
}
/**
* Process the end tag. Sets a cookie.
*
* @return indication of whether to continue evaluating the JSP page.
* @throws JspException if an error occurred while processing this tag.
*/
public int doEndTag() throws JspException
{
try
{
RssHelper rssHelper = new RssHelper();
SyndFeed feed = rssHelper.getFeed(this.feedType, this.title, this.link, this.description);
feed.setEntries(entries);
String rss = rssHelper.render(feed);
setResultAttribute(rss);
}
catch(Exception e)
{
logger.error("An error occurred when generating RSS-feed:" + e.getMessage(), e);
}
+ finally
+ {
+ entries = new ArrayList();
+ }
return EVAL_PAGE;
}
public void setFeedType(String feedType) throws JspException
{
this.feedType = evaluateString("RssFeed", "feedType", feedType);;
}
public void setDescription(String description) throws JspException
{
this.description = evaluateString("RssFeed", "description", description);
}
public void setLink(String link) throws JspException
{
this.link = evaluateString("RssFeed", "link", link);
}
public void setTitle(String title) throws JspException
{
this.title = evaluateString("RssFeed", "title", title);
}
/**
* Add syndentry to the list of entries that are to be rendered.
*/
public void addFeedEntry(final SyndEntry entry)
{
this.entries.add(entry);
}
}
| true | true | public int doEndTag() throws JspException
{
try
{
RssHelper rssHelper = new RssHelper();
SyndFeed feed = rssHelper.getFeed(this.feedType, this.title, this.link, this.description);
feed.setEntries(entries);
String rss = rssHelper.render(feed);
setResultAttribute(rss);
}
catch(Exception e)
{
logger.error("An error occurred when generating RSS-feed:" + e.getMessage(), e);
}
return EVAL_PAGE;
}
| public int doEndTag() throws JspException
{
try
{
RssHelper rssHelper = new RssHelper();
SyndFeed feed = rssHelper.getFeed(this.feedType, this.title, this.link, this.description);
feed.setEntries(entries);
String rss = rssHelper.render(feed);
setResultAttribute(rss);
}
catch(Exception e)
{
logger.error("An error occurred when generating RSS-feed:" + e.getMessage(), e);
}
finally
{
entries = new ArrayList();
}
return EVAL_PAGE;
}
|
diff --git a/src/main/java/org/castor/transactionmanager/JOTMTransactionManagerFactory.java b/src/main/java/org/castor/transactionmanager/JOTMTransactionManagerFactory.java
index fd5db3c7..d651a043 100644
--- a/src/main/java/org/castor/transactionmanager/JOTMTransactionManagerFactory.java
+++ b/src/main/java/org/castor/transactionmanager/JOTMTransactionManagerFactory.java
@@ -1,110 +1,110 @@
/*
* Copyright 2005 Werner Guttmann
*
* 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.castor.transactionmanager;
import java.lang.reflect.Method;
import java.util.Properties;
import javax.transaction.TransactionManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Transaction manager factory instance to be used with J2EE containers
* where the transaction manager used is JOTM.
*
* Implements {link org.castor.jdo.transaction.TransactionManagerFactory}.
*
* @author <a href=" mailto:werner DOT guttmann AT gmx DOT net">Werner Guttmann</a>
* @version $Revision$ $Date: 2006-04-13 10:49:49 -0600 (Thu, 13 Apr 2006) $
* @since 1.0
*/
public final class JOTMTransactionManagerFactory implements TransactionManagerFactory {
//--------------------------------------------------------------------------
/** The <a href="http://jakarta.apache.org/commons/logging/">Jakarta
* Commons Logging</a> instance used for all logging. */
private static final Log LOG = LogFactory.getLog(
JOTMTransactionManagerFactory.class);
/** Name of the JOTM specific transaction manager factory class. */
public static final String FACTORY_CLASS_NAME = "org.objectweb.jotm.Jotm";
/** The name of the factory. */
public static final String NAME = "jotm";
//--------------------------------------------------------------------------
/**
* {@inheritDoc}
* @see org.castor.transactionmanager.TransactionManagerFactory#getName()
*/
public String getName() { return NAME; }
/**
* {@inheritDoc}
* @see org.castor.transactionmanager.TransactionManagerFactory
* #getTransactionManager(java.util.Properties)
*/
public TransactionManager getTransactionManager(final Properties properties)
throws TransactionManagerAcquireException {
return getTransactionManager(FACTORY_CLASS_NAME, properties);
}
/**
* Acquires a <tt>javax.transaction.TransactionManager</tt> instance with the
* given properties from the given factory. The factory implementation needs to
* be compatible to <tt>org.objectweb.jotm.Jotm</tt>. The method has been
* introduced to allow testing with mock objects.
*
* @param factoryClassName Class name of the factory copatibla with JOTM.
* @param properties The properties passed to the transaction manager.
* @return The transaction manager.
* @throws TransactionManagerAcquireException If any failure occured when loading
* the transaction manager.
*/
public TransactionManager getTransactionManager(
final String factoryClassName, final Properties properties)
throws TransactionManagerAcquireException {
TransactionManager transactionManager = null;
try {
Class factory = Class.forName(factoryClassName);
- Class[] types = new Class[] {Boolean.class, Boolean.class};
+ Class[] types = new Class[] {boolean.class, boolean.class};
Object[] params = new Object[] {Boolean.TRUE, Boolean.FALSE};
Object jotm = factory.getConstructor(types).newInstance(params);
- Method method = factory.getMethod("getTransactionmanager", (Class[]) null);
+ Method method = factory.getMethod("getTransactionManager", (Class[]) null);
Object obj = method.invoke(jotm, (Object[]) null);
transactionManager = (TransactionManager) obj;
} catch (Exception ex) {
String msg = "Unable to acquire instance of "
+ "javax.transaction.TransactionManager: " + NAME;
LOG.error(msg);
throw new TransactionManagerAcquireException(msg, ex);
}
if (transactionManager == null) {
String msg = "Unable to acquire instance of "
+ "javax.transaction.TransactionManager: " + NAME;
LOG.error(msg);
throw new TransactionManagerAcquireException(msg);
}
return transactionManager;
}
//--------------------------------------------------------------------------
}
| false | true | public TransactionManager getTransactionManager(
final String factoryClassName, final Properties properties)
throws TransactionManagerAcquireException {
TransactionManager transactionManager = null;
try {
Class factory = Class.forName(factoryClassName);
Class[] types = new Class[] {Boolean.class, Boolean.class};
Object[] params = new Object[] {Boolean.TRUE, Boolean.FALSE};
Object jotm = factory.getConstructor(types).newInstance(params);
Method method = factory.getMethod("getTransactionmanager", (Class[]) null);
Object obj = method.invoke(jotm, (Object[]) null);
transactionManager = (TransactionManager) obj;
} catch (Exception ex) {
String msg = "Unable to acquire instance of "
+ "javax.transaction.TransactionManager: " + NAME;
LOG.error(msg);
throw new TransactionManagerAcquireException(msg, ex);
}
if (transactionManager == null) {
String msg = "Unable to acquire instance of "
+ "javax.transaction.TransactionManager: " + NAME;
LOG.error(msg);
throw new TransactionManagerAcquireException(msg);
}
return transactionManager;
}
| public TransactionManager getTransactionManager(
final String factoryClassName, final Properties properties)
throws TransactionManagerAcquireException {
TransactionManager transactionManager = null;
try {
Class factory = Class.forName(factoryClassName);
Class[] types = new Class[] {boolean.class, boolean.class};
Object[] params = new Object[] {Boolean.TRUE, Boolean.FALSE};
Object jotm = factory.getConstructor(types).newInstance(params);
Method method = factory.getMethod("getTransactionManager", (Class[]) null);
Object obj = method.invoke(jotm, (Object[]) null);
transactionManager = (TransactionManager) obj;
} catch (Exception ex) {
String msg = "Unable to acquire instance of "
+ "javax.transaction.TransactionManager: " + NAME;
LOG.error(msg);
throw new TransactionManagerAcquireException(msg, ex);
}
if (transactionManager == null) {
String msg = "Unable to acquire instance of "
+ "javax.transaction.TransactionManager: " + NAME;
LOG.error(msg);
throw new TransactionManagerAcquireException(msg);
}
return transactionManager;
}
|
diff --git a/core/sail/rdbms/src/main/java/org/openrdf/sail/rdbms/schema/ValueTable.java b/core/sail/rdbms/src/main/java/org/openrdf/sail/rdbms/schema/ValueTable.java
index 758b5db92..42c838ffe 100644
--- a/core/sail/rdbms/src/main/java/org/openrdf/sail/rdbms/schema/ValueTable.java
+++ b/core/sail/rdbms/src/main/java/org/openrdf/sail/rdbms/schema/ValueTable.java
@@ -1,314 +1,314 @@
/*
* Copyright Aduna (http://www.aduna-software.com/) (c) 2008.
*
* Licensed under the Aduna BSD-style license.
*/
package org.openrdf.sail.rdbms.schema;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
/**
* Manages the rows in a value table. These tables have two columns: an internal
* id column and a value column.
*
* @author James Leigh
*
*/
public class ValueTable {
public static int BATCH_SIZE = 8 * 1024;
public static final long NIL_ID = 0; // TODO
private static final String[] PKEY = { "id" };
private static final String[] VALUE_INDEX = { "value" };
private int length = -1;
private int sqlType;
private int idType;
private String INSERT;
private String INSERT_SELECT;
private String EXPUNGE;
private RdbmsTable table;
private RdbmsTable temporary;
private int removedStatementsSinceExpunge;
private ValueBatch batch;
private BlockingQueue<Batch> queue;
private boolean indexingValues;
public void setQueue(BlockingQueue<Batch> queue) {
this.queue = queue;
}
public boolean isIndexingValues() {
return indexingValues;
}
public void setIndexingValues(boolean indexingValues) {
this.indexingValues = indexingValues;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getSqlType() {
return sqlType;
}
public void setSqlType(int sqlType) {
this.sqlType = sqlType;
}
public int getIdType() {
return idType;
}
public void setIdType(int sqlType) {
this.idType = sqlType;
}
public RdbmsTable getRdbmsTable() {
return table;
}
public void setRdbmsTable(RdbmsTable table) {
this.table = table;
}
public RdbmsTable getTemporaryTable() {
return temporary;
}
public void setTemporaryTable(RdbmsTable temporary) {
this.temporary = temporary;
}
public String getName() {
return table.getName();
}
public long size() {
return table.size();
}
public int getBatchSize() {
return BATCH_SIZE;
}
public void initialize() throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
if (temporary == null) {
sb.append(table.getName());
} else {
sb.append(temporary.getName());
}
sb.append(" (id, value) VALUES (?, ?)");
INSERT = sb.toString();
- if (temporary != null) {
- sb.delete(0, sb.length());
- sb.append("INSERT INTO ").append(table.getName());
- sb.append(" (id, value) SELECT DISTINCT id, value FROM ");
- sb.append(temporary.getName()).append(" tmp\n");
- sb.append("WHERE NOT EXISTS (SELECT id FROM ").append(table.getName());
- sb.append(" val WHERE val.id = tmp.id)");
- INSERT_SELECT = sb.toString();
sb.delete(0, sb.length());
sb.append("DELETE FROM ").append(table.getName()).append("\n");
sb.append("WHERE 1=1 ");
EXPUNGE = sb.toString();
+ if (temporary != null) {
+ sb.delete(0, sb.length());
+ sb.append("INSERT INTO ").append(table.getName());
+ sb.append(" (id, value) SELECT DISTINCT id, value FROM ");
+ sb.append(temporary.getName()).append(" tmp\n");
+ sb.append("WHERE NOT EXISTS (SELECT id FROM ").append(table.getName());
+ sb.append(" val WHERE val.id = tmp.id)");
+ INSERT_SELECT = sb.toString();
}
if (!table.isCreated()) {
createTable(table);
table.index(PKEY);
if (isIndexingValues()) {
table.index(VALUE_INDEX);
}
} else {
table.count();
}
if (temporary != null && !temporary.isCreated()) {
createTemporaryTable(temporary);
}
}
public void close() throws SQLException {
if (temporary != null) {
temporary.close();
}
table.close();
}
public synchronized void insert(Number id, Object value) throws SQLException, InterruptedException {
ValueBatch batch = getValueBatch();
if (isExpired(batch)) {
batch = newValueBatch();
initBatch(batch);
}
batch.setObject(1, id);
batch.setObject(2, value);
batch.addBatch();
queue(batch);
}
public ValueBatch getValueBatch() {
return this.batch;
}
public boolean isExpired(ValueBatch batch) {
if (batch == null || batch.isFull())
return true;
return queue == null || !queue.remove(batch);
}
public ValueBatch newValueBatch() {
return new ValueBatch();
}
public void initBatch(ValueBatch batch)
throws SQLException
{
batch.setTable(table);
batch.setBatchStatement(prepareInsert(INSERT));
batch.setMaxBatchSize(getBatchSize());
if (temporary != null) {
batch.setTemporary(temporary);
batch.setInsertStatement(prepareInsertSelect(INSERT_SELECT));
}
}
public void queue(ValueBatch batch)
throws SQLException, InterruptedException
{
this.batch = batch;
if (queue == null) {
batch.flush();
} else {
queue.put(batch);
}
}
public void optimize() throws SQLException {
table.optimize();
}
public boolean expungeRemovedStatements(int count, String condition)
throws SQLException {
removedStatementsSinceExpunge += count;
if (condition != null && timeToExpunge()) {
expunge(condition);
removedStatementsSinceExpunge = 0;
return true;
}
return false;
}
public List<Long> maxIds(int shift, int mod) throws SQLException {
String column = "id";
StringBuilder expr = new StringBuilder();
expr.append("MOD((").append(column);
expr.append(" >> ").append(shift);
expr.append(") + ").append(mod).append(", ");
expr.append(mod);
expr.append(")");
StringBuilder sb = new StringBuilder();
sb.append("SELECT ").append(expr);
sb.append(", MAX(").append(column);
sb.append(")\nFROM ").append(getName());
sb.append("\nGROUP BY ").append(expr);
String query = sb.toString();
PreparedStatement st = table.prepareStatement(query);
try {
ResultSet rs = st.executeQuery();
try {
List<Long> result = new ArrayList<Long>();
while (rs.next()) {
result.add(rs.getLong(2));
}
return result;
} finally {
rs.close();
}
} finally {
st.close();
}
}
public String sql(int type, int length) {
switch (type) {
case Types.VARCHAR:
if (length > 0)
return "VARCHAR(" + length + ")";
return "TEXT";
case Types.LONGVARCHAR:
if (length > 0)
return "LONGVARCHAR(" + length + ")";
return "TEXT";
case Types.BIGINT:
return "BIGINT";
case Types.INTEGER:
return "INTEGER";
case Types.SMALLINT:
return "SMALLINT";
case Types.FLOAT:
return "FLOAT";
case Types.DOUBLE:
return "DOUBLE";
case Types.DECIMAL:
return "DECIMAL";
case Types.BOOLEAN:
return "BOOLEAN";
case Types.TIMESTAMP:
return "TIMESTAMP";
default:
throw new AssertionError("Unsupported SQL Type: " + type);
}
}
@Override
public String toString() {
return getName();
}
protected void expunge(String condition) throws SQLException {
synchronized (table) {
int count = table.executeUpdate(EXPUNGE + condition);
table.modified(0, count);
}
}
protected boolean timeToExpunge() {
return removedStatementsSinceExpunge > table.size() / 4;
}
protected PreparedStatement prepareInsert(String sql) throws SQLException {
return table.prepareStatement(sql);
}
protected PreparedStatement prepareInsertSelect(String sql) throws SQLException {
return table.prepareStatement(sql);
}
protected void createTable(RdbmsTable table) throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append(" id ").append(sql(idType, -1)).append(" NOT NULL,\n");
sb.append(" value ").append(sql(sqlType, length));
sb.append(" NOT NULL\n");
table.createTable(sb);
}
protected void createTemporaryTable(RdbmsTable table) throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append(" id ").append(sql(idType, -1)).append(" NOT NULL,\n");
sb.append(" value ").append(sql(sqlType, length));
sb.append(" NOT NULL\n");
table.createTemporaryTable(sb);
}
}
| false | true | public void initialize() throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
if (temporary == null) {
sb.append(table.getName());
} else {
sb.append(temporary.getName());
}
sb.append(" (id, value) VALUES (?, ?)");
INSERT = sb.toString();
if (temporary != null) {
sb.delete(0, sb.length());
sb.append("INSERT INTO ").append(table.getName());
sb.append(" (id, value) SELECT DISTINCT id, value FROM ");
sb.append(temporary.getName()).append(" tmp\n");
sb.append("WHERE NOT EXISTS (SELECT id FROM ").append(table.getName());
sb.append(" val WHERE val.id = tmp.id)");
INSERT_SELECT = sb.toString();
sb.delete(0, sb.length());
sb.append("DELETE FROM ").append(table.getName()).append("\n");
sb.append("WHERE 1=1 ");
EXPUNGE = sb.toString();
}
if (!table.isCreated()) {
createTable(table);
table.index(PKEY);
if (isIndexingValues()) {
table.index(VALUE_INDEX);
}
} else {
table.count();
}
if (temporary != null && !temporary.isCreated()) {
createTemporaryTable(temporary);
}
}
| public void initialize() throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
if (temporary == null) {
sb.append(table.getName());
} else {
sb.append(temporary.getName());
}
sb.append(" (id, value) VALUES (?, ?)");
INSERT = sb.toString();
sb.delete(0, sb.length());
sb.append("DELETE FROM ").append(table.getName()).append("\n");
sb.append("WHERE 1=1 ");
EXPUNGE = sb.toString();
if (temporary != null) {
sb.delete(0, sb.length());
sb.append("INSERT INTO ").append(table.getName());
sb.append(" (id, value) SELECT DISTINCT id, value FROM ");
sb.append(temporary.getName()).append(" tmp\n");
sb.append("WHERE NOT EXISTS (SELECT id FROM ").append(table.getName());
sb.append(" val WHERE val.id = tmp.id)");
INSERT_SELECT = sb.toString();
}
if (!table.isCreated()) {
createTable(table);
table.index(PKEY);
if (isIndexingValues()) {
table.index(VALUE_INDEX);
}
} else {
table.count();
}
if (temporary != null && !temporary.isCreated()) {
createTemporaryTable(temporary);
}
}
|
diff --git a/deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/OldStyleMapService.java b/deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/OldStyleMapService.java
index 8c4509eb01..a3094346a7 100644
--- a/deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/OldStyleMapService.java
+++ b/deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/OldStyleMapService.java
@@ -1,401 +1,400 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2012 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
and
- Occam Labs UG (haftungsbeschränkt) -
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 information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
Occam Labs UG (haftungsbeschränkt)
Godesberger Allee 139, 53175 Bonn
Germany
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.wms;
import static org.deegree.commons.utils.CollectionUtils.AND;
import static org.deegree.commons.utils.CollectionUtils.addAllUncontained;
import static org.deegree.commons.utils.CollectionUtils.map;
import static org.deegree.commons.utils.CollectionUtils.reduce;
import static org.deegree.commons.utils.MapUtils.DEFAULT_PIXEL_SIZE;
import static org.deegree.rendering.r2d.RenderHelper.calcScaleWMS130;
import static org.deegree.rendering.r2d.context.Java2DHelper.applyHints;
import static org.deegree.services.wms.model.layers.Layer.render;
import static org.deegree.style.utils.ImageUtils.postprocessPng8bit;
import static org.slf4j.LoggerFactory.getLogger;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.deegree.commons.utils.CollectionUtils;
import org.deegree.commons.utils.CollectionUtils.Mapper;
import org.deegree.commons.utils.DoublePair;
import org.deegree.commons.utils.Pair;
import org.deegree.feature.Feature;
import org.deegree.feature.FeatureCollection;
import org.deegree.feature.Features;
import org.deegree.feature.GenericFeatureCollection;
import org.deegree.feature.persistence.FeatureStore;
import org.deegree.feature.persistence.FeatureStoreException;
import org.deegree.feature.persistence.query.Query;
import org.deegree.feature.stream.FeatureInputStream;
import org.deegree.feature.stream.ThreadedFeatureInputStream;
import org.deegree.feature.xpath.TypedObjectNodeXPathEvaluator;
import org.deegree.filter.FilterEvaluationException;
import org.deegree.filter.XPathEvaluator;
import org.deegree.protocol.wms.WMSException.InvalidDimensionValue;
import org.deegree.protocol.wms.WMSException.MissingDimensionValue;
import org.deegree.protocol.wms.filter.ScaleFunction;
import org.deegree.rendering.r2d.Java2DRenderer;
import org.deegree.rendering.r2d.Java2DTextRenderer;
import org.deegree.services.wms.controller.ops.GetFeatureInfo;
import org.deegree.services.wms.controller.ops.GetMap;
import org.deegree.services.wms.model.layers.FeatureLayer;
import org.deegree.services.wms.model.layers.Layer;
import org.deegree.style.se.unevaluated.Style;
import org.slf4j.Logger;
/**
* Factored out old style map service methods (using old configuration, old architecture).
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author: stranger $
*
* @version $Revision: $, $Date: $
*/
class OldStyleMapService {
private static final Logger LOG = getLogger( OldStyleMapService.class );
private MapService service;
OldStyleMapService( MapService service ) {
this.service = service;
}
/**
* @param gm
* @return a rendered image, containing the requested maps
* @throws InvalidDimensionValue
* @throws MissingDimensionValue
*/
Pair<BufferedImage, LinkedList<String>> getMapImage( GetMap gm )
throws MissingDimensionValue, InvalidDimensionValue {
LinkedList<String> warnings = new LinkedList<String>();
ScaleFunction.getCurrentScaleValue().set( gm.getScale() );
BufferedImage img = MapService.prepareImage( gm );
Graphics2D g = img.createGraphics();
paintMap( g, gm, warnings );
g.dispose();
// 8 bit png color map support copied from deegree 2, to be optimized
if ( gm.getFormat().equals( "image/png; mode=8bit" ) || gm.getFormat().equals( "image/png; subtype=8bit" )
|| gm.getFormat().equals( "image/gif" ) ) {
img = postprocessPng8bit( img );
}
ScaleFunction.getCurrentScaleValue().remove();
return new Pair<BufferedImage, LinkedList<String>>( img, warnings );
}
/**
* Paints the map on a graphics object.
*
* @param g
* @param gm
* @param warnings
* @throws InvalidDimensionValue
* @throws MissingDimensionValue
*/
private void paintMap( Graphics2D g, GetMap gm, LinkedList<String> warnings )
throws MissingDimensionValue, InvalidDimensionValue {
Iterator<Layer> layers = gm.getLayers().iterator();
Iterator<Style> styles = gm.getStyles().iterator();
if ( reduce( true, map( gm.getLayers(), CollectionUtils.<Layer> getInstanceofMapper( FeatureLayer.class ) ),
AND ) ) {
LinkedList<FeatureLayer> fls = new LinkedList<FeatureLayer>();
Map<FeatureStore, LinkedList<Query>> queries = new HashMap<FeatureStore, LinkedList<Query>>();
HashMap<QName, FeatureLayer> ftToLayer = new HashMap<QName, FeatureLayer>();
HashMap<QName, Style> ftToStyle = new HashMap<QName, Style>();
double scale = gm.getScale();
if ( reduce( true, map( gm.getLayers(), getFeatureLayerCollector( fls ) ), AND ) ) {
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
s = s.filter( scale );
DoublePair scales = l.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale || ( !s.isDefault() && s.getRules().isEmpty() ) ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
l.getName() == null ? l.getTitle() : l.getName() );
continue;
}
LinkedList<String> otherWarns = collectFeatureQueries( queries, (FeatureLayer) l, s, gm, ftToLayer,
ftToStyle );
if ( otherWarns == null ) {
queries.clear();
break;
}
warnings.addAll( otherWarns );
}
}
if ( queries.size() == 1 ) {
handleCollectedQueries( queries, ftToLayer, ftToStyle, gm, g );
return;
}
if ( queries.isEmpty() ) {
- LOG.debug( "No queries found when collecting, probably due to scale constraints in the layers/styles." );
- return;
+ LOG.debug( "No queries found when collecting, trying without collected queries." );
}
LOG.debug( "Not using collected queries." );
layers = gm.getLayers().iterator();
styles = gm.getStyles().iterator();
}
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions );
warnings.addAll( paintLayer( l, s, g, gm ) );
}
}
// must ensure that subtree consists of feature layers only
// returns null if not all styles contain distinct feature type names
private LinkedList<String> collectFeatureQueries( Map<FeatureStore, LinkedList<Query>> queries, FeatureLayer l,
Style style, GetMap gm, HashMap<QName, FeatureLayer> ftToLayer,
HashMap<QName, Style> ftToStyle )
throws MissingDimensionValue, InvalidDimensionValue {
if ( !l.getClass().equals( FeatureLayer.class ) ) {
return null;
}
LinkedList<String> warns = new LinkedList<String>();
LinkedList<Query> list = queries.get( l.getDataStore() );
if ( list == null ) {
list = new LinkedList<Query>();
queries.put( l.getDataStore(), list );
}
warns.addAll( l.collectQueries( style, gm, list ) );
QName name = style == null ? null : style.getFeatureType();
if ( name == null || ftToLayer.containsKey( name ) ) {
return null;
}
ftToLayer.put( name, l );
ftToStyle.put( name, style );
for ( Layer child : l.getChildren() ) {
LinkedList<String> otherWarns = collectFeatureQueries( queries,
(FeatureLayer) child,
service.registry.get( child.getInternalName(), null ),
gm, ftToLayer, ftToStyle );
if ( otherWarns == null ) {
return null;
}
warns.addAll( otherWarns );
}
return warns;
}
private void handleCollectedQueries( Map<FeatureStore, LinkedList<Query>> queries,
HashMap<QName, FeatureLayer> ftToLayer, HashMap<QName, Style> ftToStyle,
GetMap gm, Graphics2D g ) {
LOG.debug( "Using collected queries for better performance." );
Java2DRenderer renderer = new Java2DRenderer( g, gm.getWidth(), gm.getHeight(), gm.getBoundingBox(),
gm.getPixelSize() );
Java2DTextRenderer textRenderer = new Java2DTextRenderer( renderer );
// TODO
XPathEvaluator<?> evaluator = new TypedObjectNodeXPathEvaluator();
Collection<LinkedList<Query>> qs = queries.values();
FeatureInputStream rs = null;
try {
FeatureStore store = queries.keySet().iterator().next();
LinkedList<Query> queriesList = qs.iterator().next();
if ( !queriesList.isEmpty() ) {
rs = store.query( queriesList.toArray( new Query[queriesList.size()] ) );
// TODO Should this always be done on this level? What about min and maxFill values?
rs = new ThreadedFeatureInputStream( rs, 100, 20 );
for ( Feature f : rs ) {
QName name = f.getType().getName();
FeatureLayer l = ftToLayer.get( name );
applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions );
render( f, (XPathEvaluator<Feature>) evaluator, ftToStyle.get( name ), renderer, textRenderer,
gm.getScale(), gm.getResolution() );
}
} else {
LOG.warn( "No queries were found for the requested layers." );
}
} catch ( FilterEvaluationException e ) {
LOG.error( "A filter could not be evaluated. The error was '{}'.", e.getLocalizedMessage() );
LOG.trace( "Stack trace:", e );
} catch ( FeatureStoreException e ) {
LOG.error( "Data could not be fetched from the feature store. The error was '{}'.", e.getLocalizedMessage() );
LOG.trace( "Stack trace:", e );
} finally {
if ( rs != null ) {
rs.close();
}
}
}
private static Mapper<Boolean, Layer> getFeatureLayerCollector( final LinkedList<FeatureLayer> list ) {
return new Mapper<Boolean, Layer>() {
@Override
public Boolean apply( Layer u ) {
return collectFeatureLayers( u, list );
}
};
}
/**
* @param l
* @param list
* @return true, if all sub layers were feature layers and its style had a distinct feature type name
*/
static boolean collectFeatureLayers( Layer l, final LinkedList<FeatureLayer> list ) {
if ( l instanceof FeatureLayer ) {
list.add( (FeatureLayer) l );
return reduce( true, map( l.getChildren(), getFeatureLayerCollector( list ) ), AND );
}
return false;
}
protected LinkedList<String> paintLayer( Layer l, Style s, Graphics2D g, GetMap gm )
throws MissingDimensionValue, InvalidDimensionValue {
LinkedList<String> warnings = new LinkedList<String>();
double scale = gm.getScale();
DoublePair scales = l.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.", l.getName() == null ? l.getTitle()
: l.getName() );
return warnings;
}
warnings.addAll( l.paintMap( g, gm, s ) );
for ( Layer child : l.getChildren() ) {
warnings.addAll( paintLayer( child, service.registry.get( child.getInternalName(), null ), g, gm ) );
}
return warnings;
}
/**
* @param fi
* @return a collection of feature values for the selected area, and warning headers
* @throws InvalidDimensionValue
* @throws MissingDimensionValue
*/
Pair<FeatureCollection, LinkedList<String>> getFeatures( GetFeatureInfo fi )
throws MissingDimensionValue, InvalidDimensionValue {
List<Feature> list = new LinkedList<Feature>();
LinkedList<String> warnings = new LinkedList<String>();
Iterator<Style> styles = fi.getStyles().iterator();
double scale = calcScaleWMS130( fi.getWidth(), fi.getHeight(), fi.getEnvelope(), fi.getCoordinateSystem(),
DEFAULT_PIXEL_SIZE );
for ( Layer layer : fi.getQueryLayers() ) {
DoublePair scales = layer.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
layer.getName() == null ? layer.getTitle() : layer.getName() );
continue;
}
warnings.addAll( getFeatures( list, layer, fi, styles.next() ) );
}
list = Features.clearDuplicates( list );
if ( list.size() > fi.getFeatureCount() ) {
list = list.subList( 0, fi.getFeatureCount() );
}
GenericFeatureCollection col = new GenericFeatureCollection();
col.addAll( list );
return new Pair<FeatureCollection, LinkedList<String>>( col, warnings );
}
private LinkedList<String> getFeatures( Collection<Feature> feats, Layer l, GetFeatureInfo fi, Style s )
throws MissingDimensionValue, InvalidDimensionValue {
LinkedList<String> warnings = new LinkedList<String>();
if ( l.isQueryable() ) {
Pair<FeatureCollection, LinkedList<String>> pair = l.getFeatures( fi, s );
if ( pair != null ) {
if ( pair.first != null ) {
addAllUncontained( feats, pair.first );
}
warnings.addAll( pair.second );
}
}
double scale = calcScaleWMS130( fi.getWidth(), fi.getHeight(), fi.getEnvelope(), fi.getCoordinateSystem(),
DEFAULT_PIXEL_SIZE );
for ( Layer c : l.getChildren() ) {
DoublePair scales = c.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
c.getName() == null ? c.getTitle() : c.getName() );
continue;
}
if ( c.getName() != null ) {
s = service.registry.get( c.getName(), null );
}
warnings.addAll( getFeatures( feats, c, fi, s ) );
}
return warnings;
}
}
| true | true | private void paintMap( Graphics2D g, GetMap gm, LinkedList<String> warnings )
throws MissingDimensionValue, InvalidDimensionValue {
Iterator<Layer> layers = gm.getLayers().iterator();
Iterator<Style> styles = gm.getStyles().iterator();
if ( reduce( true, map( gm.getLayers(), CollectionUtils.<Layer> getInstanceofMapper( FeatureLayer.class ) ),
AND ) ) {
LinkedList<FeatureLayer> fls = new LinkedList<FeatureLayer>();
Map<FeatureStore, LinkedList<Query>> queries = new HashMap<FeatureStore, LinkedList<Query>>();
HashMap<QName, FeatureLayer> ftToLayer = new HashMap<QName, FeatureLayer>();
HashMap<QName, Style> ftToStyle = new HashMap<QName, Style>();
double scale = gm.getScale();
if ( reduce( true, map( gm.getLayers(), getFeatureLayerCollector( fls ) ), AND ) ) {
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
s = s.filter( scale );
DoublePair scales = l.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale || ( !s.isDefault() && s.getRules().isEmpty() ) ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
l.getName() == null ? l.getTitle() : l.getName() );
continue;
}
LinkedList<String> otherWarns = collectFeatureQueries( queries, (FeatureLayer) l, s, gm, ftToLayer,
ftToStyle );
if ( otherWarns == null ) {
queries.clear();
break;
}
warnings.addAll( otherWarns );
}
}
if ( queries.size() == 1 ) {
handleCollectedQueries( queries, ftToLayer, ftToStyle, gm, g );
return;
}
if ( queries.isEmpty() ) {
LOG.debug( "No queries found when collecting, probably due to scale constraints in the layers/styles." );
return;
}
LOG.debug( "Not using collected queries." );
layers = gm.getLayers().iterator();
styles = gm.getStyles().iterator();
}
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions );
warnings.addAll( paintLayer( l, s, g, gm ) );
}
}
| private void paintMap( Graphics2D g, GetMap gm, LinkedList<String> warnings )
throws MissingDimensionValue, InvalidDimensionValue {
Iterator<Layer> layers = gm.getLayers().iterator();
Iterator<Style> styles = gm.getStyles().iterator();
if ( reduce( true, map( gm.getLayers(), CollectionUtils.<Layer> getInstanceofMapper( FeatureLayer.class ) ),
AND ) ) {
LinkedList<FeatureLayer> fls = new LinkedList<FeatureLayer>();
Map<FeatureStore, LinkedList<Query>> queries = new HashMap<FeatureStore, LinkedList<Query>>();
HashMap<QName, FeatureLayer> ftToLayer = new HashMap<QName, FeatureLayer>();
HashMap<QName, Style> ftToStyle = new HashMap<QName, Style>();
double scale = gm.getScale();
if ( reduce( true, map( gm.getLayers(), getFeatureLayerCollector( fls ) ), AND ) ) {
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
s = s.filter( scale );
DoublePair scales = l.getScaleHint();
LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale );
if ( scales.first > scale || scales.second < scale || ( !s.isDefault() && s.getRules().isEmpty() ) ) {
LOG.debug( "Not showing layer '{}' because of its scale constraint.",
l.getName() == null ? l.getTitle() : l.getName() );
continue;
}
LinkedList<String> otherWarns = collectFeatureQueries( queries, (FeatureLayer) l, s, gm, ftToLayer,
ftToStyle );
if ( otherWarns == null ) {
queries.clear();
break;
}
warnings.addAll( otherWarns );
}
}
if ( queries.size() == 1 ) {
handleCollectedQueries( queries, ftToLayer, ftToStyle, gm, g );
return;
}
if ( queries.isEmpty() ) {
LOG.debug( "No queries found when collecting, trying without collected queries." );
}
LOG.debug( "Not using collected queries." );
layers = gm.getLayers().iterator();
styles = gm.getStyles().iterator();
}
while ( layers.hasNext() ) {
Layer l = layers.next();
Style s = styles.next();
applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions );
warnings.addAll( paintLayer( l, s, g, gm ) );
}
}
|
diff --git a/src/com/android/browser/FetchUrlMimeType.java b/src/com/android/browser/FetchUrlMimeType.java
index 33b58086..6556b380 100644
--- a/src/com/android/browser/FetchUrlMimeType.java
+++ b/src/com/android/browser/FetchUrlMimeType.java
@@ -1,139 +1,143 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.conn.params.ConnRouteParams;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Proxy;
import android.net.http.AndroidHttpClient;
import android.os.Environment;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import java.io.IOException;
/**
* This class is used to pull down the http headers of a given URL so that
* we can analyse the mimetype and make any correction needed before we give
* the URL to the download manager.
* This operation is needed when the user long-clicks on a link or image and
* we don't know the mimetype. If the user just clicks on the link, we will
* do the same steps of correcting the mimetype down in
* android.os.webkit.LoadListener rather than handling it here.
*
*/
class FetchUrlMimeType extends Thread {
private final static String LOGTAG = "FetchUrlMimeType";
private Context mContext;
private DownloadManager.Request mRequest;
private String mUri;
private String mCookies;
private String mUserAgent;
public FetchUrlMimeType(Context context, DownloadManager.Request request,
String uri, String cookies, String userAgent) {
mContext = context.getApplicationContext();
mRequest = request;
mUri = uri;
mCookies = cookies;
mUserAgent = userAgent;
}
@Override
public void run() {
// User agent is likely to be null, though the AndroidHttpClient
// seems ok with that.
AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
HttpHost httpHost;
try {
httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
if (httpHost != null) {
ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
}
} catch (IllegalArgumentException ex) {
Log.e(LOGTAG,"Download failed: " + ex);
client.close();
return;
}
HttpHead request = new HttpHead(mUri);
if (mCookies != null && mCookies.length() > 0) {
request.addHeader("Cookie", mCookies);
}
HttpResponse response;
String mimeType = null;
String contentDisposition = null;
try {
response = client.execute(request);
// We could get a redirect here, but if we do lets let
// the download manager take care of it, and thus trust that
// the server sends the right mimetype
if (response.getStatusLine().getStatusCode() == 200) {
Header header = response.getFirstHeader("Content-Type");
if (header != null) {
mimeType = header.getValue();
final int semicolonIndex = mimeType.indexOf(';');
if (semicolonIndex != -1) {
mimeType = mimeType.substring(0, semicolonIndex);
}
}
Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
if (contentDispositionHeader != null) {
contentDisposition = contentDispositionHeader.getValue();
}
}
} catch (IllegalArgumentException ex) {
- request.abort();
+ if (request != null) {
+ request.abort();
+ }
} catch (IOException ex) {
- request.abort();
+ if (request != null) {
+ request.abort();
+ }
} finally {
client.close();
}
if (mimeType != null) {
if (mimeType.equalsIgnoreCase("text/plain") ||
mimeType.equalsIgnoreCase("application/octet-stream")) {
String newMimeType =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(mUri));
if (newMimeType != null) {
mimeType = newMimeType;
mRequest.setMimeType(newMimeType);
}
}
String filename = URLUtil.guessFileName(mUri, contentDisposition,
mimeType);
mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
}
// Start the download
DownloadManager manager = (DownloadManager) mContext.getSystemService(
Context.DOWNLOAD_SERVICE);
manager.enqueue(mRequest);
}
}
| false | true | public void run() {
// User agent is likely to be null, though the AndroidHttpClient
// seems ok with that.
AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
HttpHost httpHost;
try {
httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
if (httpHost != null) {
ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
}
} catch (IllegalArgumentException ex) {
Log.e(LOGTAG,"Download failed: " + ex);
client.close();
return;
}
HttpHead request = new HttpHead(mUri);
if (mCookies != null && mCookies.length() > 0) {
request.addHeader("Cookie", mCookies);
}
HttpResponse response;
String mimeType = null;
String contentDisposition = null;
try {
response = client.execute(request);
// We could get a redirect here, but if we do lets let
// the download manager take care of it, and thus trust that
// the server sends the right mimetype
if (response.getStatusLine().getStatusCode() == 200) {
Header header = response.getFirstHeader("Content-Type");
if (header != null) {
mimeType = header.getValue();
final int semicolonIndex = mimeType.indexOf(';');
if (semicolonIndex != -1) {
mimeType = mimeType.substring(0, semicolonIndex);
}
}
Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
if (contentDispositionHeader != null) {
contentDisposition = contentDispositionHeader.getValue();
}
}
} catch (IllegalArgumentException ex) {
request.abort();
} catch (IOException ex) {
request.abort();
} finally {
client.close();
}
if (mimeType != null) {
if (mimeType.equalsIgnoreCase("text/plain") ||
mimeType.equalsIgnoreCase("application/octet-stream")) {
String newMimeType =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(mUri));
if (newMimeType != null) {
mimeType = newMimeType;
mRequest.setMimeType(newMimeType);
}
}
String filename = URLUtil.guessFileName(mUri, contentDisposition,
mimeType);
mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
}
// Start the download
DownloadManager manager = (DownloadManager) mContext.getSystemService(
Context.DOWNLOAD_SERVICE);
manager.enqueue(mRequest);
}
| public void run() {
// User agent is likely to be null, though the AndroidHttpClient
// seems ok with that.
AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
HttpHost httpHost;
try {
httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
if (httpHost != null) {
ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
}
} catch (IllegalArgumentException ex) {
Log.e(LOGTAG,"Download failed: " + ex);
client.close();
return;
}
HttpHead request = new HttpHead(mUri);
if (mCookies != null && mCookies.length() > 0) {
request.addHeader("Cookie", mCookies);
}
HttpResponse response;
String mimeType = null;
String contentDisposition = null;
try {
response = client.execute(request);
// We could get a redirect here, but if we do lets let
// the download manager take care of it, and thus trust that
// the server sends the right mimetype
if (response.getStatusLine().getStatusCode() == 200) {
Header header = response.getFirstHeader("Content-Type");
if (header != null) {
mimeType = header.getValue();
final int semicolonIndex = mimeType.indexOf(';');
if (semicolonIndex != -1) {
mimeType = mimeType.substring(0, semicolonIndex);
}
}
Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
if (contentDispositionHeader != null) {
contentDisposition = contentDispositionHeader.getValue();
}
}
} catch (IllegalArgumentException ex) {
if (request != null) {
request.abort();
}
} catch (IOException ex) {
if (request != null) {
request.abort();
}
} finally {
client.close();
}
if (mimeType != null) {
if (mimeType.equalsIgnoreCase("text/plain") ||
mimeType.equalsIgnoreCase("application/octet-stream")) {
String newMimeType =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(mUri));
if (newMimeType != null) {
mimeType = newMimeType;
mRequest.setMimeType(newMimeType);
}
}
String filename = URLUtil.guessFileName(mUri, contentDisposition,
mimeType);
mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
}
// Start the download
DownloadManager manager = (DownloadManager) mContext.getSystemService(
Context.DOWNLOAD_SERVICE);
manager.enqueue(mRequest);
}
|
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java
index fc803330..a4257c3e 100644
--- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java
+++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java
@@ -1,718 +1,718 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* 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.
******************************************************************************/
package de.tuilmenau.ics.fog.routing.hierarchical.management;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.LinkedList;
import de.tuilmenau.ics.fog.facade.Name;
import de.tuilmenau.ics.fog.facade.Namespace;
import de.tuilmenau.ics.fog.facade.properties.PropertyException;
import de.tuilmenau.ics.fog.packets.hierarchical.NeighborClusterAnnounce;
import de.tuilmenau.ics.fog.packets.hierarchical.election.BullyAnnounce;
import de.tuilmenau.ics.fog.packets.hierarchical.election.BullyPriorityUpdate;
import de.tuilmenau.ics.fog.routing.hierarchical.election.BullyPriority;
import de.tuilmenau.ics.fog.routing.hierarchical.election.Elector;
import de.tuilmenau.ics.fog.routing.hierarchical.HRMController;
import de.tuilmenau.ics.fog.routing.hierarchical.HRMConfig;
import de.tuilmenau.ics.fog.routing.hierarchical.RoutingServiceLinkVector;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMName;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.L2Address;
import de.tuilmenau.ics.fog.topology.IElementDecorator;
import de.tuilmenau.ics.fog.ui.Logging;
/**
* This class represents a clusters on a defined hierarchy level.
*
*/
public class Cluster extends ControlEntity implements ICluster, IElementDecorator
{
/**
* For using this class within (de-)serialization.
*/
private static final long serialVersionUID = -7486131336574637721L;
/**
* This is the cluster counter, which allows for globally (related to a physical simulation machine) unique cluster IDs.
*/
private static long sNextClusterFreeID = 0;
/**
* Stores the physical simulation machine specific multiplier, which is used to create unique cluster IDs even if multiple physical simulation machines are connected by FoGSiEm instances
* The value "-1" is important for initialization!
*/
private static long sClusterIDMachineMultiplier = -1;
/**
* Stores the unique cluster ID
*/
private Long mClusterID;
/**
* Stores the elector which is responsible for coordinator elections for this cluster.
*/
private Elector mElector = null;
/**
* Counter about how many times a coordinator was defined
*/
private int mCoordinatorUpdateCounter = 0;
/**
* Stores a descriptive string about the elected coordinator
*/
private String mCoordinatorDescription = null;
private ComChannel mChannelToCoordinator = null;
private BullyPriority mHighestPriority = null;
private BullyPriority mCoordinatorPriority;
private Name mCoordName;
private Name mCoordAddress;
private LinkedList<NeighborClusterAnnounce> mReceivedAnnounces = null;
private int mToken;
/**
* Stores a reference to the local coordinator instance if the local router is also the coordinator for this cluster
*/
private Coordinator mCoordinator = null;
private ComChannelMuxer mMux = null;
/**
* This is the constructor of a cluster object. At first such a cluster is identified by its cluster
* ID and the hierarchical level. Later on - once a coordinator is found, it is additionally identified
* by a token the coordinator sends to all participants. In contrast to the cluster token the identity is used
* to filter potential participants that may be used for the election of a coordinator.
*
* @param ptHRMController a reference to the HRMController instance
* @param pClusterID the cluster ID
* @param pHierarchyLevel the hierarchy level
*/
public Cluster(HRMController pHRMController, Long pClusterID, HierarchyLevel pHierarchyLevel)
{
super(pHRMController, pHierarchyLevel);
// set the ClusterID
if (pClusterID < 0){
// create an ID for the cluster
mClusterID = createClusterID();
}else{
// use the ClusterID from outside
mClusterID = pClusterID;
}
// creates new elector object, which is responsible for Bully based election processes
mElector = new Elector(this);
mReceivedAnnounces = new LinkedList<NeighborClusterAnnounce>();
for(ICluster tCluster : getHRMController().getRoutingTargets())
{
Logging.log(this, "Found already known neighbor: " + tCluster);
if ((tCluster.getHierarchyLevel().equals(getHierarchyLevel())) && (tCluster != this))
{
if (!(tCluster instanceof Cluster)){
Logging.err(this, "Routing target should be a cluster, but it is " + tCluster);
}
tCluster.addNeighborCluster(this);
// increase Bully priority because of changed connectivity (topology depending)
getPriority().increaseConnectivity();
}
}
mMux = new ComChannelMuxer(this, getHRMController());
// register at HRMController's internal database
getHRMController().registerCluster(this);
Logging.log(this, "CREATED");
}
/**
* Determines the physical simulation machine specific ClusterID multiplier
*
* @return the generated multiplier
*/
private long clusterIDMachineMultiplier()
{
if (sClusterIDMachineMultiplier < 0){
String tHostName = HRMController.getHostName();
if (tHostName != null){
sClusterIDMachineMultiplier = (tHostName.hashCode() % 10000) * 10000;
}else{
Logging.err(this, "Unable to determine the machine-specific ClusterID multiplier because host name couldn't be indentified");
}
}
return sClusterIDMachineMultiplier;
}
/**
* Generates a new ClusterID
*
* @return the ClusterID
*/
private long createClusterID()
{
// get the current unique ID counter
long tResult = sNextClusterFreeID * clusterIDMachineMultiplier();
// make sure the next ID isn't equal
sNextClusterFreeID++;
return tResult;
}
/**
* Returns the elector of this cluster
*
* @return the elector
*/
public Elector getElector()
{
return mElector;
}
/**
* Returns a descriptive string about the elected coordinator
*
* @return the descriptive string
*/
public String getCoordinatorDescription()
{
return mCoordinatorDescription;
}
/**
* Returns a descriptive string about the cluster
*
* @return the descriptive string
*/
public String getClusterDescription()
{
return toLocation();
//getHRMController().getPhysicalNode() + ":" + mClusterID + "@" + getHierarchyLevel() + "(" + mCoordSignature + ")";
}
/**
* Determines the coordinator of this cluster. It is "null" if the election was lost or hasn't finished yet.
*
* @return the cluster's coordinator
*/
public Coordinator getCoordinator()
{
return mCoordinator;
}
/**
* Determines if a coordinator is known.
*
* @return true if the coordinator is elected and known, otherwise false
*/
public boolean hasLocalCoordinator()
{
return (mCoordinator != null);
}
/**
* Set the new coordinator, which was elected by the Elector instance.
*
* @param pCoordinator the new coordinator
*/
public void setCoordinator(Coordinator pCoordinator)
{
Logging.log(this, "Updating the coordinator from " + mCoordinator + " to " + pCoordinator);
// set the coordinator
mCoordinator = pCoordinator;
// update the descriptive string about the coordinator
mCoordinatorDescription = mCoordinator.toLocation();
}
/**
* Returns the full ClusterID (including the machine specific multiplier)
*
* @return the full ClusterID
*/
public Long getClusterID()
{
return mClusterID;
}
/**
* Returns the machine-local ClusterID (excluding the machine specific multiplier)
*
* @return the machine-local ClusterID
*/
public long getGUIClusterID()
{
return mClusterID / clusterIDMachineMultiplier();
}
public void handleBullyAnnounce(BullyAnnounce pBullyAnnounce, ComChannel pCEP)
{
// update the description about the elected coordinator
mCoordinatorDescription = pBullyAnnounce.getCoordinatorDescription();
setSuperiorCoordinatorCEP(pCEP, pBullyAnnounce.getSenderName(), pBullyAnnounce.getToken(), pCEP.getPeerL2Address());
getHRMController().setClusterWithCoordinator(getHierarchyLevel(), this);
}
- public void setSuperiorCoordinatorCEP(ComChannel pCoordinatorChannel, Name pCoordName, int pCoordToken, HRMName pAddress)
+ public void setSuperiorCoordinatorCEP(ComChannel pComChannel, Name pCoordName, int pCoordToken, HRMName pAddress)
{
setToken(pCoordToken);
- Logging.log(this, "Setting " + (++mCoordinatorUpdateCounter) + " time a new coordinator: " + pCoordName + "/" + pCoordinatorChannel + " with routing address " + pAddress);
- mChannelToCoordinator = pCoordinatorChannel;
+ Logging.log(this, "Setting " + (++mCoordinatorUpdateCounter) + " time a new coordinator: " + pCoordName + "/" + pComChannel + " with routing address " + pAddress);
+ mChannelToCoordinator = pComChannel;
mCoordName = pCoordName;
if(mChannelToCoordinator == null) {
synchronized(this) {
mCoordAddress = getHRMController().getNode().getRoutingService().getNameFor(getHRMController().getNode().getCentralFN());
notifyAll();
}
setCoordinatorPriority(getPriority());
} else {
synchronized(this) {
mCoordAddress = pAddress;
notifyAll();
}
- setCoordinatorPriority(pCoordinatorChannel.getPeerPriority());
+ setCoordinatorPriority(pComChannel.getPeerPriority());
try {
getHRMController().getHRS().mapFoGNameToL2Address(pCoordName, pAddress);
} catch (RemoteException tExc) {
Logging.err(this, "Unable to register " + pCoordName, tExc);
}
- if(pCoordinatorChannel.getRouteToPeer() != null && !pCoordinatorChannel.getRouteToPeer().isEmpty()) {
+ if(pComChannel.getRouteToPeer() != null && !pComChannel.getRouteToPeer().isEmpty()) {
if(pAddress instanceof L2Address) {
getHRMController().getHRS().registerNode((L2Address) pAddress, false);
}
- getHRMController().getHRS().registerRoute(pCoordinatorChannel.getSourceName(), pCoordinatorChannel.getPeerL2Address(), pCoordinatorChannel.getRouteToPeer());
+ getHRMController().getHRS().registerRoute(pComChannel.getSourceName(), pComChannel.getPeerL2Address(), pComChannel.getRouteToPeer());
}
}
Logging.log(this, "This cluster has the following neighbors: " + getNeighbors());
for(ICluster tCluster : getNeighbors()) {
if(tCluster instanceof Cluster) {
Logging.log(this, "CLUSTER-CEP - found already known neighbor cluster: " + tCluster);
Logging.log(this, "Preparing neighbor zone announcement");
NeighborClusterAnnounce tAnnounce = new NeighborClusterAnnounce(pCoordName, getHierarchyLevel(), pAddress, getToken(), mClusterID);
tAnnounce.setCoordinatorsPriority(getPriority()); //TODO : ???
- if(pCoordinatorChannel != null) {
- tAnnounce.addRoutingVector(new RoutingServiceLinkVector(pCoordinatorChannel.getRouteToPeer(), pCoordinatorChannel.getSourceName(), pCoordinatorChannel.getPeerL2Address()));
+ if(pComChannel != null) {
+ tAnnounce.addRoutingVector(new RoutingServiceLinkVector(pComChannel.getRouteToPeer(), pComChannel.getSourceName(), pComChannel.getPeerL2Address()));
}
- ((Cluster)tCluster).announceNeighborCoord(tAnnounce, pCoordinatorChannel);
+ ((Cluster)tCluster).announceNeighborCoord(tAnnounce, pComChannel);
}
}
if(mReceivedAnnounces.isEmpty()) {
Logging.log(this, "No announces came in while no coordinator was set");
} else {
Logging.log(this, "sending old announces");
while(!mReceivedAnnounces.isEmpty()) {
if(mChannelToCoordinator != null)
{
// OK, we have to notify the other node via socket communication, so this cluster has to be at least one hop away
mChannelToCoordinator.sendPacket(mReceivedAnnounces.removeFirst());
} else {
/*
* in this case this announcement came from a neighbor intermediate cluster
*/
- handleNeighborAnnouncement(mReceivedAnnounces.removeFirst(), pCoordinatorChannel);
+ handleNeighborAnnouncement(mReceivedAnnounces.removeFirst(), pComChannel);
}
}
}
}
private ICluster addAnnouncedCluster(NeighborClusterAnnounce pAnnounce, ComChannel pCEP)
{
if(pAnnounce.getRoutingVectors() != null) {
for(RoutingServiceLinkVector tVector : pAnnounce.getRoutingVectors()) {
getHRMController().getHRS().registerRoute(tVector.getSource(), tVector.getDestination(), tVector.getPath());
}
}
ICluster tCluster = getHRMController().getCluster(new ClusterName(pAnnounce.getToken(), pAnnounce.getClusterID(), pAnnounce.getLevel()));
if(tCluster == null) {
tCluster = new NeighborCluster(pAnnounce.getClusterID(), pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress(), pAnnounce.getToken(), getHierarchyLevel(), getHRMController());
getHRMController().setSourceIntermediateCluster(tCluster, this);
((NeighborCluster)tCluster).addAnnouncedCEP(pCEP);
((NeighborCluster)tCluster).setSourceIntermediate(this);
tCluster.setPriority(pAnnounce.getCoordinatorsPriority());
tCluster.setToken(pAnnounce.getToken());
try {
getHRMController().getHRS().mapFoGNameToL2Address(tCluster.getCoordinatorName(), tCluster.getCoordinatorsAddress());
} catch (RemoteException tExc) {
Logging.err(this, "Unable to fulfill requirements", tExc);
}
} else {
Logging.log(this, "Cluster announced by " + pAnnounce + " is an intermediate neighbor ");
}
/*if(tCluster instanceof AttachedCluster) {
((AttachedCluster)tCluster).setNegotiatingHost(pAnnounce.getAnnouncersAddress());
}*/
/*
* function checks whether neighbor relation was established earlier
*/
addNeighborCluster(tCluster);
if(pAnnounce.getCoordinatorName() != null) {
// Description tDescription = new Description();
try {
getHRMController().getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress());
} catch (RemoteException tExc) {
Logging.warn(this, "Unable to register " + pAnnounce.getCoordinatorName(), tExc);
}
}
return tCluster;
}
public void handleNeighborAnnouncement(NeighborClusterAnnounce pAnnounce, ComChannel pCEP)
{
if(!pAnnounce.getCoordinatorName().equals(getHRMController().getNodeName())) {
Logging.log(this, "Received announcement of foreign cluster");
}
if(getHierarchyLevel().isBaseLevel()) {
if(pCEP != null) {
if(!pCEP.getSourceName().equals(pCEP.getPeerL2Address()) && pCEP.getRouteToPeer() != null) {
RoutingServiceLinkVector tLink = new RoutingServiceLinkVector(pCEP.getRouteToPeer().clone(), pCEP.getSourceName(), pCEP.getPeerL2Address());
pAnnounce.addRoutingVector(tLink);
Logging.log(this, "Added routing vector " + tLink);
}
pAnnounce.isForeignAnnouncement();
}
} else {
if(getHRMController().getClusterWithCoordinatorOnLevel(getHierarchyLevel().getValue()) == null) {
/*
* no coordinator set -> find cluster that is neighbor of the predecessor, so routes are correct
*/
for(Coordinator tManager : getHRMController().getCoordinator(getHierarchyLevel())) {
if(tManager.getNeighbors().contains(pAnnounce.getNegotiatorIdentification())) {
tManager.storeAnnouncement(pAnnounce);
}
}
} else {
/*
* coordinator set -> find cluster that is neighbor of the predecessor, so routes are correct
*/
for(Coordinator tManager : getHRMController().getCoordinator(getHierarchyLevel())) {
if(tManager.getNeighbors().contains(pAnnounce.getNegotiatorIdentification())) {
if(tManager.getSuperiorCoordinatorCEP() != null) {
tManager.getSuperiorCoordinatorCEP().sendPacket(pAnnounce);
}
}
}
}
if(pAnnounce.getCoveringClusterEntry() != null) {
// Cluster tForwardingCluster = null;
if(pAnnounce.isRejected()) {
// Cluster tMultiplex = this;
// tForwardingCluster = (Cluster) ((Cluster) getCoordinator().getLastUncovered(tMultiplex, pCEP.getRemoteCluster()) == null ? pCEP.getRemoteCluster() : getCoordinator().getLastUncovered(tMultiplex, pCEP.getRemoteCluster())) ;
//pAnnounce.setAnnouncer( (tForwardingCluster.getCoordinatorsAddress() != null ? tForwardingCluster.getCoordinatorsAddress() : null ));
Logging.log(this, "Removing " + this + " as participating CEP from " + this);
getComChannels().remove(this);
}
try {
addNeighborCluster(getHRMController().getCluster(pCEP.handleDiscoveryEntry(pAnnounce.getCoveringClusterEntry())));
} catch (PropertyException tExc) {
Logging.log(this, "Unable to fulfill requirements");
}
Logging.log(this, "new negotiating cluster will be " + getHRMController().getCluster(pAnnounce.getNegotiatorIdentification()));
} else if(pCEP != null) {
Logging.log(this, "new negotiating cluster will be " + getHRMController().getCluster(pAnnounce.getNegotiatorIdentification()));
}
}
}
public ComChannel getSuperiorCoordinatorCEP()
{
return mChannelToCoordinator;
}
public void addNeighborCluster(ICluster pNeighbor)
{
LinkedList<ICluster> tNeighbors = getNeighbors();
if(!tNeighbors.contains(pNeighbor))
{
if(pNeighbor instanceof Cluster) {
RoutableClusterGraphLink tLink = new RoutableClusterGraphLink(RoutableClusterGraphLink.LinkType.PHYSICAL_LINK);
getHRMController().getRoutableClusterGraph().storeLink(pNeighbor, this, tLink);
} else {
RoutableClusterGraphLink tLink = new RoutableClusterGraphLink(RoutableClusterGraphLink.LinkType.LOGICAL_LINK);
getHRMController().getRoutableClusterGraph().storeLink(pNeighbor, this, tLink);
}
if(pNeighbor instanceof Cluster) {
Logging.log(this, "CLUSTER - adding neighbor cluster: " + pNeighbor);
// increase Bully priority because of changed connectivity (topology depending)
getPriority().increaseConnectivity();
Logging.log(this, "Informing " + getComChannels() + " about change in priority and initiating new election");
sendClusterBroadcast(new BullyPriorityUpdate(getHRMController().getNodeName(), getPriority()));
Logging.log(this, "Informed other clients about change of priority - it is now " + getPriority().getValue());
}
}
}
private void announceNeighborCoord(NeighborClusterAnnounce pAnnouncement, ComChannel pCEP)
{
Logging.log(this, "Handling " + pAnnouncement);
if(mCoordName != null)
{
if(getHRMController().getNodeName().equals(mCoordName))
{
handleNeighborAnnouncement(pAnnouncement, pCEP);
} else {
mChannelToCoordinator.sendPacket(pAnnouncement);
}
} else {
mReceivedAnnounces.add(pAnnouncement);
}
}
public BullyPriority getHighestPriority()
{
if (mHighestPriority == null){
mHighestPriority = new BullyPriority(this);
}
return mHighestPriority;
}
public BullyPriority getCoordinatorPriority()
{
return mCoordinatorPriority;
}
public void setCoordinatorPriority(BullyPriority pCoordinatorPriority)
{
mCoordinatorPriority = pCoordinatorPriority;
}
public LinkedList<ICluster> getNeighbors()
{
LinkedList<ICluster> tList = new LinkedList<ICluster>();
for(HRMGraphNodeName tNode : getHRMController().getRoutableClusterGraph().getNeighbors(this)) {
if(tNode instanceof ICluster) {
tList.add((ICluster)tNode);
}
}
return tList;
}
public int getToken()
{
return mToken;
}
public L2Address getCoordinatorsAddress()
{
return (L2Address) mCoordAddress;
}
public void setCoordinatorName(Name pCoordName)
{
mCoordName = pCoordName;
}
public void sendClusterBroadcast(Serializable pData)
{
Logging.log(this, "Sending CLUSTER BROADCAST " + pData);
if(pData instanceof BullyPriorityUpdate)
{
Logging.log(this, "Will send priority update to" + getComChannels());
}
for(ComChannel tComChannel : getComChannels())
{
Logging.log(this, " BROADCAST TO " + tComChannel);
tComChannel.sendPacket(pData);
}
}
public Name getCoordinatorName()
{
return mCoordName;
}
@Override
public void setToken(int pToken) {
Logging.log(this, "Updating token from " + mToken + " to " + pToken);
mToken = pToken;
}
@Override
public void setHighestPriority(BullyPriority pHighestPriority) {
mHighestPriority = pHighestPriority;
}
@Override
public Namespace getNamespace() {
return new Namespace("cluster");
}
@Override
public int getSerialisedSize() {
return 0;
}
@Override
public boolean equals(Object pObj)
{
if(pObj instanceof Coordinator) {
return false;
}
if(pObj instanceof Cluster) {
ICluster tCluster = (ICluster) pObj;
if (tCluster.getClusterID().equals(getClusterID()) && (tCluster.getToken() == getToken()) && (tCluster.getHierarchyLevel() == getHierarchyLevel())) {
return true;
} else if(tCluster.getClusterID().equals(getClusterID()) && tCluster.getHierarchyLevel() == getHierarchyLevel()) {
return false;
} else if (tCluster.getClusterID().equals(getClusterID())) {
return false;
}
}
if(pObj instanceof ClusterName) {
ClusterName tClusterName = (ClusterName) pObj;
if (tClusterName.getClusterID().equals(getClusterID()) && (tClusterName.getToken() == getToken()) && (tClusterName.getHierarchyLevel() == getHierarchyLevel())) {
return true;
} else if(tClusterName.getClusterID().equals(getClusterID()) && tClusterName.getHierarchyLevel() == getHierarchyLevel()) {
return false;
} else if (tClusterName.getClusterID().equals(getClusterID())) {
return false;
}
}
return false;
}
@Override
public synchronized ComChannelMuxer getMultiplexer()
{
return mMux;
}
/**
* This method is specific for the handling of RouteRequests.
*
* @param pCluster
* @return
*/
// public CoordinatorCEPChannel getCEPOfCluster(ICluster pCluster)
// {
// for(CoordinatorCEPChannel tCEP : getParticipatingCEPs()) {
// if(tCEP.getRemoteClusterName().equals(pCluster)) {
// return tCEP;
// }
// }
// return null;
// }
@Override
public Object getDecorationParameter()
{
return IElementDecorator.Color.GREEN;
}
@Override
public void setDecorationParameter(Object pDecoration)
{
// not used, but have to be implemented for implementing interface IElementDecorator
}
@Override
public Object getDecorationValue()
{
return Float.valueOf(0.8f);
}
@Override
public void setDecorationValue(Object tLabal)
{
// not used, but have to be implemented for implementing interface IElementDecorator
}
public int hashCode()
{
return mClusterID.intValue();
}
/**
* Returns a descriptive string about this object
*
* @return the descriptive string
*/
@SuppressWarnings("unused")
public String toString()
{
HRMID tHRMID = getHRMID();
if(tHRMID != null && HRMConfig.Debugging.PRINT_HRMIDS_AS_CLUSTER_IDS) {
return tHRMID.toString();
} else {
return toLocation() + "(" + idToString() + ")";
}
}
/**
* Returns a location description about this instance
*/
@Override
public String toLocation()
{
String tResult = getClass().getSimpleName() + getGUIClusterID() + "@" + getHRMController().getNodeGUIName() + "@" + getHierarchyLevel().getValue();
return tResult;
}
/**
* Returns a string including the ClusterID, the token, and the node priority
*
* @return the complex string
*/
private String idToString()
{
if (getHRMID() == null){
return "ID=" + getClusterID() + ", Tok=" + mToken + ", NodePrio=" + getPriority().getValue();
}else{
return "HRMID=" + getHRMID().toString();
}
}
}
| false | true | public void setSuperiorCoordinatorCEP(ComChannel pCoordinatorChannel, Name pCoordName, int pCoordToken, HRMName pAddress)
{
setToken(pCoordToken);
Logging.log(this, "Setting " + (++mCoordinatorUpdateCounter) + " time a new coordinator: " + pCoordName + "/" + pCoordinatorChannel + " with routing address " + pAddress);
mChannelToCoordinator = pCoordinatorChannel;
mCoordName = pCoordName;
if(mChannelToCoordinator == null) {
synchronized(this) {
mCoordAddress = getHRMController().getNode().getRoutingService().getNameFor(getHRMController().getNode().getCentralFN());
notifyAll();
}
setCoordinatorPriority(getPriority());
} else {
synchronized(this) {
mCoordAddress = pAddress;
notifyAll();
}
setCoordinatorPriority(pCoordinatorChannel.getPeerPriority());
try {
getHRMController().getHRS().mapFoGNameToL2Address(pCoordName, pAddress);
} catch (RemoteException tExc) {
Logging.err(this, "Unable to register " + pCoordName, tExc);
}
if(pCoordinatorChannel.getRouteToPeer() != null && !pCoordinatorChannel.getRouteToPeer().isEmpty()) {
if(pAddress instanceof L2Address) {
getHRMController().getHRS().registerNode((L2Address) pAddress, false);
}
getHRMController().getHRS().registerRoute(pCoordinatorChannel.getSourceName(), pCoordinatorChannel.getPeerL2Address(), pCoordinatorChannel.getRouteToPeer());
}
}
Logging.log(this, "This cluster has the following neighbors: " + getNeighbors());
for(ICluster tCluster : getNeighbors()) {
if(tCluster instanceof Cluster) {
Logging.log(this, "CLUSTER-CEP - found already known neighbor cluster: " + tCluster);
Logging.log(this, "Preparing neighbor zone announcement");
NeighborClusterAnnounce tAnnounce = new NeighborClusterAnnounce(pCoordName, getHierarchyLevel(), pAddress, getToken(), mClusterID);
tAnnounce.setCoordinatorsPriority(getPriority()); //TODO : ???
if(pCoordinatorChannel != null) {
tAnnounce.addRoutingVector(new RoutingServiceLinkVector(pCoordinatorChannel.getRouteToPeer(), pCoordinatorChannel.getSourceName(), pCoordinatorChannel.getPeerL2Address()));
}
((Cluster)tCluster).announceNeighborCoord(tAnnounce, pCoordinatorChannel);
}
}
if(mReceivedAnnounces.isEmpty()) {
Logging.log(this, "No announces came in while no coordinator was set");
} else {
Logging.log(this, "sending old announces");
while(!mReceivedAnnounces.isEmpty()) {
if(mChannelToCoordinator != null)
{
// OK, we have to notify the other node via socket communication, so this cluster has to be at least one hop away
mChannelToCoordinator.sendPacket(mReceivedAnnounces.removeFirst());
} else {
/*
* in this case this announcement came from a neighbor intermediate cluster
*/
handleNeighborAnnouncement(mReceivedAnnounces.removeFirst(), pCoordinatorChannel);
}
}
}
}
| public void setSuperiorCoordinatorCEP(ComChannel pComChannel, Name pCoordName, int pCoordToken, HRMName pAddress)
{
setToken(pCoordToken);
Logging.log(this, "Setting " + (++mCoordinatorUpdateCounter) + " time a new coordinator: " + pCoordName + "/" + pComChannel + " with routing address " + pAddress);
mChannelToCoordinator = pComChannel;
mCoordName = pCoordName;
if(mChannelToCoordinator == null) {
synchronized(this) {
mCoordAddress = getHRMController().getNode().getRoutingService().getNameFor(getHRMController().getNode().getCentralFN());
notifyAll();
}
setCoordinatorPriority(getPriority());
} else {
synchronized(this) {
mCoordAddress = pAddress;
notifyAll();
}
setCoordinatorPriority(pComChannel.getPeerPriority());
try {
getHRMController().getHRS().mapFoGNameToL2Address(pCoordName, pAddress);
} catch (RemoteException tExc) {
Logging.err(this, "Unable to register " + pCoordName, tExc);
}
if(pComChannel.getRouteToPeer() != null && !pComChannel.getRouteToPeer().isEmpty()) {
if(pAddress instanceof L2Address) {
getHRMController().getHRS().registerNode((L2Address) pAddress, false);
}
getHRMController().getHRS().registerRoute(pComChannel.getSourceName(), pComChannel.getPeerL2Address(), pComChannel.getRouteToPeer());
}
}
Logging.log(this, "This cluster has the following neighbors: " + getNeighbors());
for(ICluster tCluster : getNeighbors()) {
if(tCluster instanceof Cluster) {
Logging.log(this, "CLUSTER-CEP - found already known neighbor cluster: " + tCluster);
Logging.log(this, "Preparing neighbor zone announcement");
NeighborClusterAnnounce tAnnounce = new NeighborClusterAnnounce(pCoordName, getHierarchyLevel(), pAddress, getToken(), mClusterID);
tAnnounce.setCoordinatorsPriority(getPriority()); //TODO : ???
if(pComChannel != null) {
tAnnounce.addRoutingVector(new RoutingServiceLinkVector(pComChannel.getRouteToPeer(), pComChannel.getSourceName(), pComChannel.getPeerL2Address()));
}
((Cluster)tCluster).announceNeighborCoord(tAnnounce, pComChannel);
}
}
if(mReceivedAnnounces.isEmpty()) {
Logging.log(this, "No announces came in while no coordinator was set");
} else {
Logging.log(this, "sending old announces");
while(!mReceivedAnnounces.isEmpty()) {
if(mChannelToCoordinator != null)
{
// OK, we have to notify the other node via socket communication, so this cluster has to be at least one hop away
mChannelToCoordinator.sendPacket(mReceivedAnnounces.removeFirst());
} else {
/*
* in this case this announcement came from a neighbor intermediate cluster
*/
handleNeighborAnnouncement(mReceivedAnnounces.removeFirst(), pComChannel);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.